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