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