Home | History | Annotate | Line # | Download | only in kern
kern_exec.c revision 1.234
      1 /*	$NetBSD: kern_exec.c,v 1.234 2006/12/23 17:23:51 elad Exp $	*/
      2 
      3 /*-
      4  * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou
      5  * Copyright (C) 1992 Wolfgang Solfrank.
      6  * Copyright (C) 1992 TooLs GmbH.
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *	This product includes software developed by TooLs GmbH.
     20  * 4. The name of TooLs GmbH may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: kern_exec.c,v 1.234 2006/12/23 17:23:51 elad Exp $");
     37 
     38 #include "opt_ktrace.h"
     39 #include "opt_syscall_debug.h"
     40 #include "opt_compat_netbsd.h"
     41 #include "veriexec.h"
     42 #include "opt_pax.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/systm.h>
     46 #include <sys/filedesc.h>
     47 #include <sys/kernel.h>
     48 #include <sys/proc.h>
     49 #include <sys/mount.h>
     50 #include <sys/malloc.h>
     51 #include <sys/namei.h>
     52 #include <sys/vnode.h>
     53 #include <sys/file.h>
     54 #include <sys/acct.h>
     55 #include <sys/exec.h>
     56 #include <sys/ktrace.h>
     57 #include <sys/resourcevar.h>
     58 #include <sys/wait.h>
     59 #include <sys/mman.h>
     60 #include <sys/ras.h>
     61 #include <sys/signalvar.h>
     62 #include <sys/stat.h>
     63 #include <sys/syscall.h>
     64 #include <sys/kauth.h>
     65 
     66 #include <sys/sa.h>
     67 #include <sys/savar.h>
     68 #include <sys/syscallargs.h>
     69 #if NVERIEXEC > 0
     70 #include <sys/verified_exec.h>
     71 #endif /* NVERIEXEC > 0 */
     72 
     73 #ifdef SYSTRACE
     74 #include <sys/systrace.h>
     75 #endif /* SYSTRACE */
     76 
     77 #ifdef PAX_SEGVGUARD
     78 #include <sys/pax.h>
     79 #endif /* PAX_SEGVGUARD */
     80 
     81 #include <uvm/uvm_extern.h>
     82 
     83 #include <machine/cpu.h>
     84 #include <machine/reg.h>
     85 
     86 static int exec_sigcode_map(struct proc *, const struct emul *);
     87 
     88 #ifdef DEBUG_EXEC
     89 #define DPRINTF(a) uprintf a
     90 #else
     91 #define DPRINTF(a)
     92 #endif /* DEBUG_EXEC */
     93 
     94 MALLOC_DEFINE(M_EXEC, "exec", "argument lists & other mem used by exec");
     95 
     96 /*
     97  * Exec function switch:
     98  *
     99  * Note that each makecmds function is responsible for loading the
    100  * exec package with the necessary functions for any exec-type-specific
    101  * handling.
    102  *
    103  * Functions for specific exec types should be defined in their own
    104  * header file.
    105  */
    106 extern const struct execsw	execsw_builtin[];
    107 extern int			nexecs_builtin;
    108 static const struct execsw	**execsw = NULL;
    109 static int			nexecs;
    110 
    111 u_int	exec_maxhdrsz;		/* must not be static - netbsd32 needs it */
    112 
    113 #ifdef LKM
    114 /* list of supported emulations */
    115 static
    116 LIST_HEAD(emlist_head, emul_entry) el_head = LIST_HEAD_INITIALIZER(el_head);
    117 struct emul_entry {
    118 	LIST_ENTRY(emul_entry)	el_list;
    119 	const struct emul	*el_emul;
    120 	int			ro_entry;
    121 };
    122 
    123 /* list of dynamically loaded execsw entries */
    124 static
    125 LIST_HEAD(execlist_head, exec_entry) ex_head = LIST_HEAD_INITIALIZER(ex_head);
    126 struct exec_entry {
    127 	LIST_ENTRY(exec_entry)	ex_list;
    128 	const struct execsw	*es;
    129 };
    130 
    131 /* structure used for building execw[] */
    132 struct execsw_entry {
    133 	struct execsw_entry	*next;
    134 	const struct execsw	*es;
    135 };
    136 #endif /* LKM */
    137 
    138 #ifdef SYSCALL_DEBUG
    139 extern const char * const syscallnames[];
    140 #endif
    141 
    142 #ifdef COMPAT_16
    143 extern char	sigcode[], esigcode[];
    144 struct uvm_object *emul_netbsd_object;
    145 #endif
    146 
    147 #ifndef __HAVE_SYSCALL_INTERN
    148 void	syscall(void);
    149 #endif
    150 
    151 static const struct sa_emul saemul_netbsd = {
    152 	sizeof(ucontext_t),
    153 	sizeof(struct sa_t),
    154 	sizeof(struct sa_t *),
    155 	NULL,
    156 	NULL,
    157 	cpu_upcall,
    158 	(void (*)(struct lwp *, void *))getucontext,
    159 	sa_ucsp
    160 };
    161 
    162 /* NetBSD emul struct */
    163 const struct emul emul_netbsd = {
    164 	"netbsd",
    165 	NULL,		/* emulation path */
    166 #ifndef __HAVE_MINIMAL_EMUL
    167 	EMUL_HAS_SYS___syscall,
    168 	NULL,
    169 	SYS_syscall,
    170 	SYS_NSYSENT,
    171 #endif
    172 	sysent,
    173 #ifdef SYSCALL_DEBUG
    174 	syscallnames,
    175 #else
    176 	NULL,
    177 #endif
    178 	sendsig,
    179 	trapsignal,
    180 	NULL,
    181 #ifdef COMPAT_16
    182 	sigcode,
    183 	esigcode,
    184 	&emul_netbsd_object,
    185 #else
    186 	NULL,
    187 	NULL,
    188 	NULL,
    189 #endif
    190 	setregs,
    191 	NULL,
    192 	NULL,
    193 	NULL,
    194 	NULL,
    195 	NULL,
    196 #ifdef __HAVE_SYSCALL_INTERN
    197 	syscall_intern,
    198 #else
    199 	syscall,
    200 #endif
    201 	NULL,
    202 	NULL,
    203 
    204 	uvm_default_mapaddr,
    205 	NULL,
    206 	&saemul_netbsd,
    207 };
    208 
    209 #ifdef LKM
    210 /*
    211  * Exec lock. Used to control access to execsw[] structures.
    212  * This must not be static so that netbsd32 can access it, too.
    213  */
    214 struct lock exec_lock;
    215 
    216 static void link_es(struct execsw_entry **, const struct execsw *);
    217 #endif /* LKM */
    218 
    219 /*
    220  * check exec:
    221  * given an "executable" described in the exec package's namei info,
    222  * see what we can do with it.
    223  *
    224  * ON ENTRY:
    225  *	exec package with appropriate namei info
    226  *	lwp pointer of exec'ing lwp
    227  *	NO SELF-LOCKED VNODES
    228  *
    229  * ON EXIT:
    230  *	error:	nothing held, etc.  exec header still allocated.
    231  *	ok:	filled exec package, executable's vnode (unlocked).
    232  *
    233  * EXEC SWITCH ENTRY:
    234  * 	Locked vnode to check, exec package, proc.
    235  *
    236  * EXEC SWITCH EXIT:
    237  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
    238  *	error:	destructive:
    239  *			everything deallocated execept exec header.
    240  *		non-destructive:
    241  *			error code, executable's vnode (unlocked),
    242  *			exec header unmodified.
    243  */
    244 int
    245 /*ARGSUSED*/
    246 check_exec(struct lwp *l, struct exec_package *epp)
    247 {
    248 	int		error, i;
    249 	struct vnode	*vp;
    250 	struct nameidata *ndp;
    251 	size_t		resid;
    252 
    253 	ndp = epp->ep_ndp;
    254 	ndp->ni_cnd.cn_nameiop = LOOKUP;
    255 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME;
    256 	/* first get the vnode */
    257 	if ((error = namei(ndp)) != 0)
    258 		return error;
    259 	epp->ep_vp = vp = ndp->ni_vp;
    260 
    261 	/* check access and type */
    262 	if (vp->v_type != VREG) {
    263 		error = EACCES;
    264 		goto bad1;
    265 	}
    266 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred, l)) != 0)
    267 		goto bad1;
    268 
    269 	/* get attributes */
    270 	if ((error = VOP_GETATTR(vp, epp->ep_vap, l->l_cred, l)) != 0)
    271 		goto bad1;
    272 
    273 	/* Check mount point */
    274 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
    275 		error = EACCES;
    276 		goto bad1;
    277 	}
    278 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
    279 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
    280 
    281 	/* try to open it */
    282 	if ((error = VOP_OPEN(vp, FREAD, l->l_cred, l)) != 0)
    283 		goto bad1;
    284 
    285 	/* unlock vp, since we need it unlocked from here on out. */
    286 	VOP_UNLOCK(vp, 0);
    287 
    288 #if NVERIEXEC > 0
    289 	if ((error = veriexec_verify(l, vp, ndp->ni_cnd.cn_pnbuf,
    290 	    epp->ep_flags & EXEC_INDIR ? VERIEXEC_INDIRECT : VERIEXEC_DIRECT,
    291 	    NULL)) != 0)
    292 		goto bad2;
    293 #endif /* NVERIEXEC > 0 */
    294 
    295 #ifdef PAX_SEGVGUARD
    296 	error = pax_segvguard(l, vp, ndp->ni_cnd.cn_pnbuf, FALSE);
    297 	if (error)
    298 		goto bad2;
    299 #endif /* PAX_SEGVGUARD */
    300 
    301 	/* now we have the file, get the exec header */
    302 	uvn_attach(vp, VM_PROT_READ);
    303 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
    304 			UIO_SYSSPACE, 0, l->l_cred, &resid, NULL);
    305 	if (error)
    306 		goto bad2;
    307 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
    308 
    309 	/*
    310 	 * Set up default address space limits.  Can be overridden
    311 	 * by individual exec packages.
    312 	 *
    313 	 * XXX probably should be all done in the exec pakages.
    314 	 */
    315 	epp->ep_vm_minaddr = VM_MIN_ADDRESS;
    316 	epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
    317 	/*
    318 	 * set up the vmcmds for creation of the process
    319 	 * address space
    320 	 */
    321 	error = ENOEXEC;
    322 	for (i = 0; i < nexecs && error != 0; i++) {
    323 		int newerror;
    324 
    325 		epp->ep_esch = execsw[i];
    326 		newerror = (*execsw[i]->es_makecmds)(l, epp);
    327 		/* make sure the first "interesting" error code is saved. */
    328 		if (!newerror || error == ENOEXEC)
    329 			error = newerror;
    330 
    331 		/* if es_makecmds call was successful, update epp->ep_es */
    332 		if (!newerror && (epp->ep_flags & EXEC_HASES) == 0)
    333 			epp->ep_es = execsw[i];
    334 
    335 		if (epp->ep_flags & EXEC_DESTR && error != 0)
    336 			return error;
    337 	}
    338 	if (!error) {
    339 		/* check that entry point is sane */
    340 		if (epp->ep_entry > VM_MAXUSER_ADDRESS)
    341 			error = ENOEXEC;
    342 
    343 		/* check limits */
    344 		if ((epp->ep_tsize > MAXTSIZ) ||
    345 		    (epp->ep_dsize >
    346 		     (u_quad_t)l->l_proc->p_rlimit[RLIMIT_DATA].rlim_cur))
    347 			error = ENOMEM;
    348 
    349 		if (!error)
    350 			return (0);
    351 	}
    352 
    353 	/*
    354 	 * free any vmspace-creation commands,
    355 	 * and release their references
    356 	 */
    357 	kill_vmcmds(&epp->ep_vmcmds);
    358 
    359 bad2:
    360 	/*
    361 	 * close and release the vnode, restore the old one, free the
    362 	 * pathname buf, and punt.
    363 	 */
    364 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    365 	VOP_CLOSE(vp, FREAD, l->l_cred, l);
    366 	vput(vp);
    367 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
    368 	return error;
    369 
    370 bad1:
    371 	/*
    372 	 * free the namei pathname buffer, and put the vnode
    373 	 * (which we don't yet have open).
    374 	 */
    375 	vput(vp);				/* was still locked */
    376 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
    377 	return error;
    378 }
    379 
    380 #ifdef __MACHINE_STACK_GROWS_UP
    381 #define STACK_PTHREADSPACE NBPG
    382 #else
    383 #define STACK_PTHREADSPACE 0
    384 #endif
    385 
    386 static int
    387 execve_fetch_element(char * const *array, size_t index, char **value)
    388 {
    389 	return copyin(array + index, value, sizeof(*value));
    390 }
    391 
    392 /*
    393  * exec system call
    394  */
    395 /* ARGSUSED */
    396 int
    397 sys_execve(struct lwp *l, void *v, register_t *retval)
    398 {
    399 	struct sys_execve_args /* {
    400 		syscallarg(const char *)	path;
    401 		syscallarg(char * const *)	argp;
    402 		syscallarg(char * const *)	envp;
    403 	} */ *uap = v;
    404 
    405 	return execve1(l, SCARG(uap, path), SCARG(uap, argp),
    406 	    SCARG(uap, envp), execve_fetch_element);
    407 }
    408 
    409 int
    410 execve1(struct lwp *l, const char *path, char * const *args,
    411     char * const *envs, execve_fetch_element_t fetch_element)
    412 {
    413 	int			error;
    414 	u_int			i;
    415 	struct exec_package	pack;
    416 	struct nameidata	nid;
    417 	struct vattr		attr;
    418 	struct proc		*p;
    419 	char			*argp;
    420 	char			*dp, *sp;
    421 	long			argc, envc;
    422 	size_t			len;
    423 	char			*stack;
    424 	struct ps_strings	arginfo;
    425 	struct ps_strings	*aip = &arginfo;
    426 	struct vmspace		*vm;
    427 	char			**tmpfap;
    428 	int			szsigcode;
    429 	struct exec_vmcmd	*base_vcp;
    430 	int			oldlwpflags;
    431 #ifdef SYSTRACE
    432 	int			wassugid = ISSET(p->p_flag, P_SUGID);
    433 	char			pathbuf[MAXPATHLEN];
    434 	size_t			pathbuflen;
    435 #endif /* SYSTRACE */
    436 
    437 	/* Disable scheduler activation upcalls. */
    438 	oldlwpflags = l->l_flag & (L_SA | L_SA_UPCALL);
    439 	if (l->l_flag & L_SA)
    440 		l->l_flag &= ~(L_SA | L_SA_UPCALL);
    441 
    442 	p = l->l_proc;
    443 	/*
    444 	 * Lock the process and set the P_INEXEC flag to indicate that
    445 	 * it should be left alone until we're done here.  This is
    446 	 * necessary to avoid race conditions - e.g. in ptrace() -
    447 	 * that might allow a local user to illicitly obtain elevated
    448 	 * privileges.
    449 	 */
    450 	p->p_flag |= P_INEXEC;
    451 
    452 	base_vcp = NULL;
    453 	/*
    454 	 * Init the namei data to point the file user's program name.
    455 	 * This is done here rather than in check_exec(), so that it's
    456 	 * possible to override this settings if any of makecmd/probe
    457 	 * functions call check_exec() recursively - for example,
    458 	 * see exec_script_makecmds().
    459 	 */
    460 #ifdef SYSTRACE
    461 	if (ISSET(p->p_flag, P_SYSTRACE))
    462 		systrace_execve0(p);
    463 
    464 	error = copyinstr(path, pathbuf, sizeof(pathbuf),
    465 			  &pathbuflen);
    466 	if (error)
    467 		goto clrflg;
    468 
    469 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, l);
    470 #else
    471 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, path, l);
    472 #endif /* SYSTRACE */
    473 
    474 	/*
    475 	 * initialize the fields of the exec package.
    476 	 */
    477 #ifdef SYSTRACE
    478 	pack.ep_name = pathbuf;
    479 #else
    480 	pack.ep_name = path;
    481 #endif /* SYSTRACE */
    482 	pack.ep_hdr = malloc(exec_maxhdrsz, M_EXEC, M_WAITOK);
    483 	pack.ep_hdrlen = exec_maxhdrsz;
    484 	pack.ep_hdrvalid = 0;
    485 	pack.ep_ndp = &nid;
    486 	pack.ep_emul_arg = NULL;
    487 	pack.ep_vmcmds.evs_cnt = 0;
    488 	pack.ep_vmcmds.evs_used = 0;
    489 	pack.ep_vap = &attr;
    490 	pack.ep_flags = 0;
    491 
    492 #ifdef LKM
    493 	lockmgr(&exec_lock, LK_SHARED, NULL);
    494 #endif
    495 
    496 	/* see if we can run it. */
    497         if ((error = check_exec(l, &pack)) != 0)
    498 		goto freehdr;
    499 
    500 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
    501 
    502 	/* allocate an argument buffer */
    503 	argp = (char *) uvm_km_alloc(exec_map, NCARGS, 0,
    504 	    UVM_KMF_PAGEABLE|UVM_KMF_WAITVA);
    505 #ifdef DIAGNOSTIC
    506 	if (argp == NULL)
    507 		panic("execve: argp == NULL");
    508 #endif
    509 	dp = argp;
    510 	argc = 0;
    511 
    512 	/* copy the fake args list, if there's one, freeing it as we go */
    513 	if (pack.ep_flags & EXEC_HASARGL) {
    514 		tmpfap = pack.ep_fa;
    515 		while (*tmpfap != NULL) {
    516 			char *cp;
    517 
    518 			cp = *tmpfap;
    519 			while (*cp)
    520 				*dp++ = *cp++;
    521 			dp++;
    522 
    523 			FREE(*tmpfap, M_EXEC);
    524 			tmpfap++; argc++;
    525 		}
    526 		FREE(pack.ep_fa, M_EXEC);
    527 		pack.ep_flags &= ~EXEC_HASARGL;
    528 	}
    529 
    530 	/* Now get argv & environment */
    531 	if (args == NULL) {
    532 		error = EINVAL;
    533 		goto bad;
    534 	}
    535 	/* 'i' will index the argp/envp element to be retrieved */
    536 	i = 0;
    537 	if (pack.ep_flags & EXEC_SKIPARG)
    538 		i++;
    539 
    540 	while (1) {
    541 		len = argp + ARG_MAX - dp;
    542 		if ((error = (*fetch_element)(args, i, &sp)) != 0)
    543 			goto bad;
    544 		if (!sp)
    545 			break;
    546 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    547 			if (error == ENAMETOOLONG)
    548 				error = E2BIG;
    549 			goto bad;
    550 		}
    551 #ifdef KTRACE
    552 		if (KTRPOINT(p, KTR_EXEC_ARG))
    553 			ktrkmem(l, KTR_EXEC_ARG, dp, len - 1);
    554 #endif
    555 		dp += len;
    556 		i++;
    557 		argc++;
    558 	}
    559 
    560 	envc = 0;
    561 	/* environment need not be there */
    562 	if (envs != NULL) {
    563 		i = 0;
    564 		while (1) {
    565 			len = argp + ARG_MAX - dp;
    566 			if ((error = (*fetch_element)(envs, i, &sp)) != 0)
    567 				goto bad;
    568 			if (!sp)
    569 				break;
    570 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    571 				if (error == ENAMETOOLONG)
    572 					error = E2BIG;
    573 				goto bad;
    574 			}
    575 #ifdef KTRACE
    576 			if (KTRPOINT(p, KTR_EXEC_ENV))
    577 				ktrkmem(l, KTR_EXEC_ENV, dp, len - 1);
    578 #endif
    579 			dp += len;
    580 			i++;
    581 			envc++;
    582 		}
    583 	}
    584 
    585 	dp = (char *) ALIGN(dp);
    586 
    587 	szsigcode = pack.ep_es->es_emul->e_esigcode -
    588 	    pack.ep_es->es_emul->e_sigcode;
    589 
    590 	/* Now check if args & environ fit into new stack */
    591 	if (pack.ep_flags & EXEC_32)
    592 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
    593 		    sizeof(int) + sizeof(int) + dp + STACKGAPLEN +
    594 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
    595 		    - argp;
    596 	else
    597 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
    598 		    sizeof(char *) + sizeof(int) + dp + STACKGAPLEN +
    599 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
    600 		    - argp;
    601 
    602 	len = ALIGN(len);	/* make the stack "safely" aligned */
    603 
    604 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
    605 		error = ENOMEM;
    606 		goto bad;
    607 	}
    608 
    609 	/* Get rid of other LWPs/ */
    610 	p->p_flag |= P_WEXIT; /* XXX hack. lwp-exit stuff wants to see it. */
    611 	exit_lwps(l);
    612 	p->p_flag &= ~P_WEXIT;
    613 	KDASSERT(p->p_nlwps == 1);
    614 
    615 	/* This is now LWP 1 */
    616 	l->l_lid = 1;
    617 	p->p_nlwpid = 1;
    618 
    619 	/* Release any SA state. */
    620 	if (p->p_sa)
    621 		sa_release(p);
    622 
    623 	/* Remove POSIX timers */
    624 	timers_free(p, TIMERS_POSIX);
    625 
    626 	/* adjust "active stack depth" for process VSZ */
    627 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
    628 
    629 	/*
    630 	 * Do whatever is necessary to prepare the address space
    631 	 * for remapping.  Note that this might replace the current
    632 	 * vmspace with another!
    633 	 */
    634 	uvmspace_exec(l, pack.ep_vm_minaddr, pack.ep_vm_maxaddr);
    635 
    636 	/* record proc's vnode, for use by procfs and others */
    637         if (p->p_textvp)
    638                 vrele(p->p_textvp);
    639 	VREF(pack.ep_vp);
    640 	p->p_textvp = pack.ep_vp;
    641 
    642 	/* Now map address space */
    643 	vm = p->p_vmspace;
    644 	vm->vm_taddr = (caddr_t) pack.ep_taddr;
    645 	vm->vm_tsize = btoc(pack.ep_tsize);
    646 	vm->vm_daddr = (caddr_t) pack.ep_daddr;
    647 	vm->vm_dsize = btoc(pack.ep_dsize);
    648 	vm->vm_ssize = btoc(pack.ep_ssize);
    649 	vm->vm_maxsaddr = (caddr_t) pack.ep_maxsaddr;
    650 	vm->vm_minsaddr = (caddr_t) pack.ep_minsaddr;
    651 
    652 	/* create the new process's VM space by running the vmcmds */
    653 #ifdef DIAGNOSTIC
    654 	if (pack.ep_vmcmds.evs_used == 0)
    655 		panic("execve: no vmcmds");
    656 #endif
    657 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
    658 		struct exec_vmcmd *vcp;
    659 
    660 		vcp = &pack.ep_vmcmds.evs_cmds[i];
    661 		if (vcp->ev_flags & VMCMD_RELATIVE) {
    662 #ifdef DIAGNOSTIC
    663 			if (base_vcp == NULL)
    664 				panic("execve: relative vmcmd with no base");
    665 			if (vcp->ev_flags & VMCMD_BASE)
    666 				panic("execve: illegal base & relative vmcmd");
    667 #endif
    668 			vcp->ev_addr += base_vcp->ev_addr;
    669 		}
    670 		error = (*vcp->ev_proc)(l, vcp);
    671 #ifdef DEBUG_EXEC
    672 		if (error) {
    673 			int j;
    674 			struct exec_vmcmd *vp = &pack.ep_vmcmds.evs_cmds[0];
    675 			for (j = 0; j <= i; j++)
    676 				uprintf(
    677 			    "vmcmd[%d] = %#lx/%#lx fd@%#lx prot=0%o flags=%d\n",
    678 				    j, vp[j].ev_addr, vp[j].ev_len,
    679 				    vp[j].ev_offset, vp[j].ev_prot,
    680 				    vp[j].ev_flags);
    681 		}
    682 #endif /* DEBUG_EXEC */
    683 		if (vcp->ev_flags & VMCMD_BASE)
    684 			base_vcp = vcp;
    685 	}
    686 
    687 	/* free the vmspace-creation commands, and release their references */
    688 	kill_vmcmds(&pack.ep_vmcmds);
    689 
    690 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    691 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred, l);
    692 	vput(pack.ep_vp);
    693 
    694 	/* if an error happened, deallocate and punt */
    695 	if (error) {
    696 		DPRINTF(("execve: vmcmd %i failed: %d\n", i - 1, error));
    697 		goto exec_abort;
    698 	}
    699 
    700 	/* remember information about the process */
    701 	arginfo.ps_nargvstr = argc;
    702 	arginfo.ps_nenvstr = envc;
    703 
    704 	stack = (char *)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
    705 		STACK_PTHREADSPACE + sizeof(struct ps_strings) + szsigcode),
    706 		len - (sizeof(struct ps_strings) + szsigcode));
    707 #ifdef __MACHINE_STACK_GROWS_UP
    708 	/*
    709 	 * The copyargs call always copies into lower addresses
    710 	 * first, moving towards higher addresses, starting with
    711 	 * the stack pointer that we give.  When the stack grows
    712 	 * down, this puts argc/argv/envp very shallow on the
    713 	 * stack, right at the first user stack pointer, and puts
    714 	 * STACKGAPLEN very deep in the stack.  When the stack
    715 	 * grows up, the situation is reversed.
    716 	 *
    717 	 * Normally, this is no big deal.  But the ld_elf.so _rtld()
    718 	 * function expects to be called with a single pointer to
    719 	 * a region that has a few words it can stash values into,
    720 	 * followed by argc/argv/envp.  When the stack grows down,
    721 	 * it's easy to decrement the stack pointer a little bit to
    722 	 * allocate the space for these few words and pass the new
    723 	 * stack pointer to _rtld.  When the stack grows up, however,
    724 	 * a few words before argc is part of the signal trampoline, XXX
    725 	 * so we have a problem.
    726 	 *
    727 	 * Instead of changing how _rtld works, we take the easy way
    728 	 * out and steal 32 bytes before we call copyargs.  This
    729 	 * space is effectively stolen from STACKGAPLEN.
    730 	 */
    731 	stack += 32;
    732 #endif /* __MACHINE_STACK_GROWS_UP */
    733 
    734 	/* Now copy argc, args & environ to new stack */
    735 	error = (*pack.ep_es->es_copyargs)(l, &pack, &arginfo, &stack, argp);
    736 	if (error) {
    737 		DPRINTF(("execve: copyargs failed %d\n", error));
    738 		goto exec_abort;
    739 	}
    740 	/* Move the stack back to original point */
    741 	stack = (char *)STACK_GROW(vm->vm_minsaddr, len);
    742 
    743 	/* fill process ps_strings info */
    744 	p->p_psstr = (struct ps_strings *)
    745 	    STACK_ALLOC(STACK_GROW(vm->vm_minsaddr, STACK_PTHREADSPACE),
    746 	    sizeof(struct ps_strings));
    747 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
    748 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
    749 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
    750 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
    751 
    752 	/* copy out the process's ps_strings structure */
    753 	if ((error = copyout(aip, (char *)p->p_psstr,
    754 	    sizeof(arginfo))) != 0) {
    755 		DPRINTF(("execve: ps_strings copyout %p->%p size %ld failed\n",
    756 		       aip, (char *)p->p_psstr, (long)sizeof(arginfo)));
    757 		goto exec_abort;
    758 	}
    759 
    760 	stopprofclock(p);	/* stop profiling */
    761 	fdcloseexec(l);		/* handle close on exec */
    762 	execsigs(p);		/* reset catched signals */
    763 
    764 	l->l_ctxlink = NULL;	/* reset ucontext link */
    765 
    766 	/* set command name & other accounting info */
    767 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
    768 	memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, len);
    769 	p->p_comm[len] = 0;
    770 	p->p_acflag &= ~AFORK;
    771 
    772 	p->p_flag |= P_EXEC;
    773 	if (p->p_flag & P_PPWAIT) {
    774 		p->p_flag &= ~P_PPWAIT;
    775 		wakeup((caddr_t) p->p_pptr);
    776 	}
    777 
    778 	/*
    779 	 * deal with set[ug]id.
    780 	 * MNT_NOSUID has already been used to disable s[ug]id.
    781 	 */
    782 	if ((p->p_flag & P_TRACED) == 0 &&
    783 
    784 	    (((attr.va_mode & S_ISUID) != 0 &&
    785 	      kauth_cred_geteuid(l->l_cred) != attr.va_uid) ||
    786 
    787 	     ((attr.va_mode & S_ISGID) != 0 &&
    788 	      kauth_cred_getegid(l->l_cred) != attr.va_gid))) {
    789 		/*
    790 		 * Mark the process as SUGID before we do
    791 		 * anything that might block.
    792 		 */
    793 		p_sugid(p);
    794 
    795 		/* Make sure file descriptors 0..2 are in use. */
    796 		if ((error = fdcheckstd(l)) != 0) {
    797 			DPRINTF(("execve: fdcheckstd failed %d\n", error));
    798 			goto exec_abort;
    799 		}
    800 
    801 		/*
    802 		 * Copy the credential so other references don't see our
    803 		 * changes.
    804 		 */
    805 		l->l_cred = kauth_cred_copy(l->l_cred);
    806 #ifdef KTRACE
    807 		/*
    808 		 * If process is being ktraced, turn off - unless
    809 		 * root set it.
    810 		 */
    811 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT))
    812 			ktrderef(p);
    813 #endif
    814 		if (attr.va_mode & S_ISUID)
    815 			kauth_cred_seteuid(l->l_cred, attr.va_uid);
    816 		if (attr.va_mode & S_ISGID)
    817 			kauth_cred_setegid(l->l_cred, attr.va_gid);
    818 	} else {
    819 		if (kauth_cred_geteuid(l->l_cred) ==
    820 		    kauth_cred_getuid(l->l_cred) &&
    821 		    kauth_cred_getegid(l->l_cred) ==
    822 		    kauth_cred_getgid(l->l_cred))
    823 			p->p_flag &= ~P_SUGID;
    824 	}
    825 
    826 	/*
    827 	 * Copy the credential so other references don't see our changes.
    828 	 * Test to see if this is necessary first, since in the common case
    829 	 * we won't need a private reference.
    830 	 */
    831 	if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
    832 	    kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
    833 		l->l_cred = kauth_cred_copy(l->l_cred);
    834 		kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
    835 		kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
    836 	}
    837 
    838 	/* Update the master credentials. */
    839 	if (l->l_cred != p->p_cred) {
    840 		kauth_cred_t ocred;
    841 
    842 		kauth_cred_hold(l->l_cred);
    843 		simple_lock(&p->p_lock);
    844 		ocred = p->p_cred;
    845 		p->p_cred = l->l_cred;
    846 		simple_unlock(&p->p_lock);
    847 		kauth_cred_free(ocred);
    848 	}
    849 
    850 #if defined(__HAVE_RAS)
    851 	/*
    852 	 * Remove all RASs from the address space.
    853 	 */
    854 	ras_purgeall(p);
    855 #endif
    856 
    857 	doexechooks(p);
    858 
    859 	uvm_km_free(exec_map, (vaddr_t) argp, NCARGS, UVM_KMF_PAGEABLE);
    860 
    861 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    862 
    863 	/* notify others that we exec'd */
    864 	KNOTE(&p->p_klist, NOTE_EXEC);
    865 
    866 	/* setup new registers and do misc. setup. */
    867 	(*pack.ep_es->es_emul->e_setregs)(l, &pack, (u_long) stack);
    868 	if (pack.ep_es->es_setregs)
    869 		(*pack.ep_es->es_setregs)(l, &pack, (u_long) stack);
    870 
    871 	/* map the process's signal trampoline code */
    872 	if (exec_sigcode_map(p, pack.ep_es->es_emul)) {
    873 		DPRINTF(("execve: map sigcode failed %d\n", error));
    874 		goto exec_abort;
    875 	}
    876 
    877 	if ((p->p_flag & (P_TRACED|P_SYSCALL)) == P_TRACED)
    878 		psignal(p, SIGTRAP);
    879 
    880 	free(pack.ep_hdr, M_EXEC);
    881 
    882 	/*
    883 	 * Call emulation specific exec hook. This can setup per-process
    884 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
    885 	 *
    886 	 * If we are executing process of different emulation than the
    887 	 * original forked process, call e_proc_exit() of the old emulation
    888 	 * first, then e_proc_exec() of new emulation. If the emulation is
    889 	 * same, the exec hook code should deallocate any old emulation
    890 	 * resources held previously by this process.
    891 	 */
    892 	if (p->p_emul && p->p_emul->e_proc_exit
    893 	    && p->p_emul != pack.ep_es->es_emul)
    894 		(*p->p_emul->e_proc_exit)(p);
    895 
    896 	/*
    897 	 * Call exec hook. Emulation code may NOT store reference to anything
    898 	 * from &pack.
    899 	 */
    900         if (pack.ep_es->es_emul->e_proc_exec)
    901                 (*pack.ep_es->es_emul->e_proc_exec)(p, &pack);
    902 
    903 	/* update p_emul, the old value is no longer needed */
    904 	p->p_emul = pack.ep_es->es_emul;
    905 
    906 	/* ...and the same for p_execsw */
    907 	p->p_execsw = pack.ep_es;
    908 
    909 #ifdef __HAVE_SYSCALL_INTERN
    910 	(*p->p_emul->e_syscall_intern)(p);
    911 #endif
    912 #ifdef KTRACE
    913 	if (KTRPOINT(p, KTR_EMUL))
    914 		ktremul(l);
    915 #endif
    916 
    917 #ifdef LKM
    918 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    919 #endif
    920 	p->p_flag &= ~P_INEXEC;
    921 
    922 	if (p->p_flag & P_STOPEXEC) {
    923 		int s;
    924 
    925 		sigminusset(&contsigmask, &p->p_sigctx.ps_siglist);
    926 		SCHED_LOCK(s);
    927 		p->p_pptr->p_nstopchild++;
    928 		p->p_stat = SSTOP;
    929 		l->l_stat = LSSTOP;
    930 		p->p_nrlwps--;
    931 		mi_switch(l, NULL);
    932 		SCHED_ASSERT_UNLOCKED();
    933 		splx(s);
    934 	}
    935 
    936 #ifdef SYSTRACE
    937 	if (ISSET(p->p_flag, P_SYSTRACE) &&
    938 	    wassugid && !ISSET(p->p_flag, P_SUGID))
    939 		systrace_execve1(pathbuf, p);
    940 #endif /* SYSTRACE */
    941 
    942 	return (EJUSTRETURN);
    943 
    944  bad:
    945 	p->p_flag &= ~P_INEXEC;
    946 	/* free the vmspace-creation commands, and release their references */
    947 	kill_vmcmds(&pack.ep_vmcmds);
    948 	/* kill any opened file descriptor, if necessary */
    949 	if (pack.ep_flags & EXEC_HASFD) {
    950 		pack.ep_flags &= ~EXEC_HASFD;
    951 		(void) fdrelease(l, pack.ep_fd);
    952 	}
    953 	/* close and put the exec'd file */
    954 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    955 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred, l);
    956 	vput(pack.ep_vp);
    957 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    958 	uvm_km_free(exec_map, (vaddr_t) argp, NCARGS, UVM_KMF_PAGEABLE);
    959 
    960  freehdr:
    961 	free(pack.ep_hdr, M_EXEC);
    962 
    963 #ifdef SYSTRACE
    964  clrflg:
    965 #endif /* SYSTRACE */
    966 	l->l_flag |= oldlwpflags;
    967 	p->p_flag &= ~P_INEXEC;
    968 #ifdef LKM
    969 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    970 #endif
    971 
    972 	return error;
    973 
    974  exec_abort:
    975 	p->p_flag &= ~P_INEXEC;
    976 #ifdef LKM
    977 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    978 #endif
    979 
    980 	/*
    981 	 * the old process doesn't exist anymore.  exit gracefully.
    982 	 * get rid of the (new) address space we have created, if any, get rid
    983 	 * of our namei data and vnode, and exit noting failure
    984 	 */
    985 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
    986 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
    987 	if (pack.ep_emul_arg)
    988 		FREE(pack.ep_emul_arg, M_TEMP);
    989 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    990 	uvm_km_free(exec_map, (vaddr_t) argp, NCARGS, UVM_KMF_PAGEABLE);
    991 	free(pack.ep_hdr, M_EXEC);
    992 	exit1(l, W_EXITCODE(error, SIGABRT));
    993 
    994 	/* NOTREACHED */
    995 	return 0;
    996 }
    997 
    998 
    999 int
   1000 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
   1001     char **stackp, void *argp)
   1002 {
   1003 	char	**cpp, *dp, *sp;
   1004 	size_t	len;
   1005 	void	*nullp;
   1006 	long	argc, envc;
   1007 	int	error;
   1008 
   1009 	cpp = (char **)*stackp;
   1010 	nullp = NULL;
   1011 	argc = arginfo->ps_nargvstr;
   1012 	envc = arginfo->ps_nenvstr;
   1013 	if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0)
   1014 		return error;
   1015 
   1016 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_es->es_arglen);
   1017 	sp = argp;
   1018 
   1019 	/* XXX don't copy them out, remap them! */
   1020 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
   1021 
   1022 	for (; --argc >= 0; sp += len, dp += len)
   1023 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
   1024 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
   1025 			return error;
   1026 
   1027 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
   1028 		return error;
   1029 
   1030 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
   1031 
   1032 	for (; --envc >= 0; sp += len, dp += len)
   1033 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
   1034 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
   1035 			return error;
   1036 
   1037 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
   1038 		return error;
   1039 
   1040 	*stackp = (char *)cpp;
   1041 	return 0;
   1042 }
   1043 
   1044 #ifdef LKM
   1045 /*
   1046  * Find an emulation of given name in list of emulations.
   1047  * Needs to be called with the exec_lock held.
   1048  */
   1049 const struct emul *
   1050 emul_search(const char *name)
   1051 {
   1052 	struct emul_entry *it;
   1053 
   1054 	LIST_FOREACH(it, &el_head, el_list) {
   1055 		if (strcmp(name, it->el_emul->e_name) == 0)
   1056 			return it->el_emul;
   1057 	}
   1058 
   1059 	return NULL;
   1060 }
   1061 
   1062 /*
   1063  * Add an emulation to list, if it's not there already.
   1064  */
   1065 int
   1066 emul_register(const struct emul *emul, int ro_entry)
   1067 {
   1068 	struct emul_entry	*ee;
   1069 	int			error;
   1070 
   1071 	error = 0;
   1072 	lockmgr(&exec_lock, LK_SHARED, NULL);
   1073 
   1074 	if (emul_search(emul->e_name)) {
   1075 		error = EEXIST;
   1076 		goto out;
   1077 	}
   1078 
   1079 	MALLOC(ee, struct emul_entry *, sizeof(struct emul_entry),
   1080 		M_EXEC, M_WAITOK);
   1081 	ee->el_emul = emul;
   1082 	ee->ro_entry = ro_entry;
   1083 	LIST_INSERT_HEAD(&el_head, ee, el_list);
   1084 
   1085  out:
   1086 	lockmgr(&exec_lock, LK_RELEASE, NULL);
   1087 	return error;
   1088 }
   1089 
   1090 /*
   1091  * Remove emulation with name 'name' from list of supported emulations.
   1092  */
   1093 int
   1094 emul_unregister(const char *name)
   1095 {
   1096 	const struct proclist_desc *pd;
   1097 	struct emul_entry	*it;
   1098 	int			i, error;
   1099 	struct proc		*ptmp;
   1100 
   1101 	error = 0;
   1102 	lockmgr(&exec_lock, LK_SHARED, NULL);
   1103 
   1104 	LIST_FOREACH(it, &el_head, el_list) {
   1105 		if (strcmp(it->el_emul->e_name, name) == 0)
   1106 			break;
   1107 	}
   1108 
   1109 	if (!it) {
   1110 		error = ENOENT;
   1111 		goto out;
   1112 	}
   1113 
   1114 	if (it->ro_entry) {
   1115 		error = EBUSY;
   1116 		goto out;
   1117 	}
   1118 
   1119 	/* test if any execw[] entry is still using this */
   1120 	for(i=0; i < nexecs; i++) {
   1121 		if (execsw[i]->es_emul == it->el_emul) {
   1122 			error = EBUSY;
   1123 			goto out;
   1124 		}
   1125 	}
   1126 
   1127 	/*
   1128 	 * Test if any process is running under this emulation - since
   1129 	 * emul_unregister() is running quite sendomly, it's better
   1130 	 * to do expensive check here than to use any locking.
   1131 	 */
   1132 	proclist_lock_read();
   1133 	for (pd = proclists; pd->pd_list != NULL && !error; pd++) {
   1134 		PROCLIST_FOREACH(ptmp, pd->pd_list) {
   1135 			if (ptmp->p_emul == it->el_emul) {
   1136 				error = EBUSY;
   1137 				break;
   1138 			}
   1139 		}
   1140 	}
   1141 	proclist_unlock_read();
   1142 
   1143 	if (error)
   1144 		goto out;
   1145 
   1146 
   1147 	/* entry is not used, remove it */
   1148 	LIST_REMOVE(it, el_list);
   1149 	FREE(it, M_EXEC);
   1150 
   1151  out:
   1152 	lockmgr(&exec_lock, LK_RELEASE, NULL);
   1153 	return error;
   1154 }
   1155 
   1156 /*
   1157  * Add execsw[] entry.
   1158  */
   1159 int
   1160 exec_add(struct execsw *esp, const char *e_name)
   1161 {
   1162 	struct exec_entry	*it;
   1163 	int			error;
   1164 
   1165 	error = 0;
   1166 	lockmgr(&exec_lock, LK_EXCLUSIVE, NULL);
   1167 
   1168 	if (!esp->es_emul) {
   1169 		esp->es_emul = emul_search(e_name);
   1170 		if (!esp->es_emul) {
   1171 			error = ENOENT;
   1172 			goto out;
   1173 		}
   1174 	}
   1175 
   1176 	LIST_FOREACH(it, &ex_head, ex_list) {
   1177 		/* assume tuple (makecmds, probe_func, emulation) is unique */
   1178 		if (it->es->es_makecmds == esp->es_makecmds
   1179 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
   1180 		    && it->es->es_emul == esp->es_emul) {
   1181 			error = EEXIST;
   1182 			goto out;
   1183 		}
   1184 	}
   1185 
   1186 	/* if we got here, the entry doesn't exist yet */
   1187 	MALLOC(it, struct exec_entry *, sizeof(struct exec_entry),
   1188 		M_EXEC, M_WAITOK);
   1189 	it->es = esp;
   1190 	LIST_INSERT_HEAD(&ex_head, it, ex_list);
   1191 
   1192 	/* update execsw[] */
   1193 	exec_init(0);
   1194 
   1195  out:
   1196 	lockmgr(&exec_lock, LK_RELEASE, NULL);
   1197 	return error;
   1198 }
   1199 
   1200 /*
   1201  * Remove execsw[] entry.
   1202  */
   1203 int
   1204 exec_remove(const struct execsw *esp)
   1205 {
   1206 	struct exec_entry	*it;
   1207 	int			error;
   1208 
   1209 	error = 0;
   1210 	lockmgr(&exec_lock, LK_EXCLUSIVE, NULL);
   1211 
   1212 	LIST_FOREACH(it, &ex_head, ex_list) {
   1213 		/* assume tuple (makecmds, probe_func, emulation) is unique */
   1214 		if (it->es->es_makecmds == esp->es_makecmds
   1215 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
   1216 		    && it->es->es_emul == esp->es_emul)
   1217 			break;
   1218 	}
   1219 	if (!it) {
   1220 		error = ENOENT;
   1221 		goto out;
   1222 	}
   1223 
   1224 	/* remove item from list and free resources */
   1225 	LIST_REMOVE(it, ex_list);
   1226 	FREE(it, M_EXEC);
   1227 
   1228 	/* update execsw[] */
   1229 	exec_init(0);
   1230 
   1231  out:
   1232 	lockmgr(&exec_lock, LK_RELEASE, NULL);
   1233 	return error;
   1234 }
   1235 
   1236 static void
   1237 link_es(struct execsw_entry **listp, const struct execsw *esp)
   1238 {
   1239 	struct execsw_entry *et, *e1;
   1240 
   1241 	et = (struct execsw_entry *) malloc(sizeof(struct execsw_entry),
   1242 			M_TEMP, M_WAITOK);
   1243 	et->next = NULL;
   1244 	et->es = esp;
   1245 	if (*listp == NULL) {
   1246 		*listp = et;
   1247 		return;
   1248 	}
   1249 
   1250 	switch(et->es->es_prio) {
   1251 	case EXECSW_PRIO_FIRST:
   1252 		/* put new entry as the first */
   1253 		et->next = *listp;
   1254 		*listp = et;
   1255 		break;
   1256 	case EXECSW_PRIO_ANY:
   1257 		/* put new entry after all *_FIRST and *_ANY entries */
   1258 		for(e1 = *listp; e1->next
   1259 			&& e1->next->es->es_prio != EXECSW_PRIO_LAST;
   1260 			e1 = e1->next);
   1261 		et->next = e1->next;
   1262 		e1->next = et;
   1263 		break;
   1264 	case EXECSW_PRIO_LAST:
   1265 		/* put new entry as the last one */
   1266 		for(e1 = *listp; e1->next; e1 = e1->next);
   1267 		e1->next = et;
   1268 		break;
   1269 	default:
   1270 #ifdef DIAGNOSTIC
   1271 		panic("execw[] entry with unknown priority %d found",
   1272 			et->es->es_prio);
   1273 #else
   1274 		free(et, M_TEMP);
   1275 #endif
   1276 		break;
   1277 	}
   1278 }
   1279 
   1280 /*
   1281  * Initialize exec structures. If init_boot is true, also does necessary
   1282  * one-time initialization (it's called from main() that way).
   1283  * Once system is multiuser, this should be called with exec_lock held,
   1284  * i.e. via exec_{add|remove}().
   1285  */
   1286 int
   1287 exec_init(int init_boot)
   1288 {
   1289 	const struct execsw	**new_es, * const *old_es;
   1290 	struct execsw_entry	*list, *e1;
   1291 	struct exec_entry	*e2;
   1292 	int			i, es_sz;
   1293 
   1294 	if (init_boot) {
   1295 		/* do one-time initializations */
   1296 		lockinit(&exec_lock, PWAIT, "execlck", 0, 0);
   1297 
   1298 		/* register compiled-in emulations */
   1299 		for(i=0; i < nexecs_builtin; i++) {
   1300 			if (execsw_builtin[i].es_emul)
   1301 				emul_register(execsw_builtin[i].es_emul, 1);
   1302 		}
   1303 #ifdef DIAGNOSTIC
   1304 		if (i == 0)
   1305 			panic("no emulations found in execsw_builtin[]");
   1306 #endif
   1307 	}
   1308 
   1309 	/*
   1310 	 * Build execsw[] array from builtin entries and entries added
   1311 	 * at runtime.
   1312 	 */
   1313 	list = NULL;
   1314 	for(i=0; i < nexecs_builtin; i++)
   1315 		link_es(&list, &execsw_builtin[i]);
   1316 
   1317 	/* Add dynamically loaded entries */
   1318 	es_sz = nexecs_builtin;
   1319 	LIST_FOREACH(e2, &ex_head, ex_list) {
   1320 		link_es(&list, e2->es);
   1321 		es_sz++;
   1322 	}
   1323 
   1324 	/*
   1325 	 * Now that we have sorted all execw entries, create new execsw[]
   1326 	 * and free no longer needed memory in the process.
   1327 	 */
   1328 	new_es = malloc(es_sz * sizeof(struct execsw *), M_EXEC, M_WAITOK);
   1329 	for(i=0; list; i++) {
   1330 		new_es[i] = list->es;
   1331 		e1 = list->next;
   1332 		free(list, M_TEMP);
   1333 		list = e1;
   1334 	}
   1335 
   1336 	/*
   1337 	 * New execsw[] array built, now replace old execsw[] and free
   1338 	 * used memory.
   1339 	 */
   1340 	old_es = execsw;
   1341 	execsw = new_es;
   1342 	nexecs = es_sz;
   1343 	if (old_es)
   1344 		/*XXXUNCONST*/
   1345 		free(__UNCONST(old_es), M_EXEC);
   1346 
   1347 	/*
   1348 	 * Figure out the maximum size of an exec header.
   1349 	 */
   1350 	exec_maxhdrsz = 0;
   1351 	for (i = 0; i < nexecs; i++) {
   1352 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
   1353 			exec_maxhdrsz = execsw[i]->es_hdrsz;
   1354 	}
   1355 
   1356 	return 0;
   1357 }
   1358 #endif
   1359 
   1360 #ifndef LKM
   1361 /*
   1362  * Simplified exec_init() for kernels without LKMs. Only initialize
   1363  * exec_maxhdrsz and execsw[].
   1364  */
   1365 int
   1366 exec_init(int init_boot)
   1367 {
   1368 	int i;
   1369 
   1370 #ifdef DIAGNOSTIC
   1371 	if (!init_boot)
   1372 		panic("exec_init(): called with init_boot == 0");
   1373 #endif
   1374 
   1375 	/* do one-time initializations */
   1376 	nexecs = nexecs_builtin;
   1377 	execsw = malloc(nexecs*sizeof(struct execsw *), M_EXEC, M_WAITOK);
   1378 
   1379 	/*
   1380 	 * Fill in execsw[] and figure out the maximum size of an exec header.
   1381 	 */
   1382 	exec_maxhdrsz = 0;
   1383 	for(i=0; i < nexecs; i++) {
   1384 		execsw[i] = &execsw_builtin[i];
   1385 		if (execsw_builtin[i].es_hdrsz > exec_maxhdrsz)
   1386 			exec_maxhdrsz = execsw_builtin[i].es_hdrsz;
   1387 	}
   1388 
   1389 	return 0;
   1390 
   1391 }
   1392 #endif /* !LKM */
   1393 
   1394 static int
   1395 exec_sigcode_map(struct proc *p, const struct emul *e)
   1396 {
   1397 	vaddr_t va;
   1398 	vsize_t sz;
   1399 	int error;
   1400 	struct uvm_object *uobj;
   1401 
   1402 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
   1403 
   1404 	if (e->e_sigobject == NULL || sz == 0) {
   1405 		return 0;
   1406 	}
   1407 
   1408 	/*
   1409 	 * If we don't have a sigobject for this emulation, create one.
   1410 	 *
   1411 	 * sigobject is an anonymous memory object (just like SYSV shared
   1412 	 * memory) that we keep a permanent reference to and that we map
   1413 	 * in all processes that need this sigcode. The creation is simple,
   1414 	 * we create an object, add a permanent reference to it, map it in
   1415 	 * kernel space, copy out the sigcode to it and unmap it.
   1416 	 * We map it with PROT_READ|PROT_EXEC into the process just
   1417 	 * the way sys_mmap() would map it.
   1418 	 */
   1419 
   1420 	uobj = *e->e_sigobject;
   1421 	if (uobj == NULL) {
   1422 		uobj = uao_create(sz, 0);
   1423 		(*uobj->pgops->pgo_reference)(uobj);
   1424 		va = vm_map_min(kernel_map);
   1425 		if ((error = uvm_map(kernel_map, &va, round_page(sz),
   1426 		    uobj, 0, 0,
   1427 		    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
   1428 		    UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
   1429 			printf("kernel mapping failed %d\n", error);
   1430 			(*uobj->pgops->pgo_detach)(uobj);
   1431 			return (error);
   1432 		}
   1433 		memcpy((void *)va, e->e_sigcode, sz);
   1434 #ifdef PMAP_NEED_PROCWR
   1435 		pmap_procwr(&proc0, va, sz);
   1436 #endif
   1437 		uvm_unmap(kernel_map, va, va + round_page(sz));
   1438 		*e->e_sigobject = uobj;
   1439 	}
   1440 
   1441 	/* Just a hint to uvm_map where to put it. */
   1442 	va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
   1443 	    round_page(sz));
   1444 
   1445 #ifdef __alpha__
   1446 	/*
   1447 	 * Tru64 puts /sbin/loader at the end of user virtual memory,
   1448 	 * which causes the above calculation to put the sigcode at
   1449 	 * an invalid address.  Put it just below the text instead.
   1450 	 */
   1451 	if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
   1452 		va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
   1453 	}
   1454 #endif
   1455 
   1456 	(*uobj->pgops->pgo_reference)(uobj);
   1457 	error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
   1458 			uobj, 0, 0,
   1459 			UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
   1460 				    UVM_ADV_RANDOM, 0));
   1461 	if (error) {
   1462 		(*uobj->pgops->pgo_detach)(uobj);
   1463 		return (error);
   1464 	}
   1465 	p->p_sigctx.ps_sigcode = (void *)va;
   1466 	return (0);
   1467 }
   1468