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