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