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