Home | History | Annotate | Line # | Download | only in kern
kern_exec.c revision 1.244
      1 /*	$NetBSD: kern_exec.c,v 1.244 2007/04/22 08:30:00 dsl Exp $	*/
      2 
      3 /*-
      4  * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou
      5  * Copyright (C) 1992 Wolfgang Solfrank.
      6  * Copyright (C) 1992 TooLs GmbH.
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *	This product includes software developed by TooLs GmbH.
     20  * 4. The name of TooLs GmbH may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: kern_exec.c,v 1.244 2007/04/22 08:30:00 dsl Exp $");
     37 
     38 #include "opt_ktrace.h"
     39 #include "opt_syscall_debug.h"
     40 #include "opt_compat_netbsd.h"
     41 #include "veriexec.h"
     42 #include "opt_pax.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/systm.h>
     46 #include <sys/filedesc.h>
     47 #include <sys/kernel.h>
     48 #include <sys/proc.h>
     49 #include <sys/mount.h>
     50 #include <sys/malloc.h>
     51 #include <sys/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 #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 	uvn_attach(vp, VM_PROT_READ);
    294 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
    295 			UIO_SYSSPACE, 0, l->l_cred, &resid, NULL);
    296 	if (error)
    297 		goto bad2;
    298 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
    299 
    300 	/*
    301 	 * Set up default address space limits.  Can be overridden
    302 	 * by individual exec packages.
    303 	 *
    304 	 * XXX probably should be all done in the exec packages.
    305 	 */
    306 	epp->ep_vm_minaddr = VM_MIN_ADDRESS;
    307 	epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
    308 	/*
    309 	 * set up the vmcmds for creation of the process
    310 	 * address space
    311 	 */
    312 	error = ENOEXEC;
    313 	for (i = 0; i < nexecs; i++) {
    314 		int newerror;
    315 
    316 		epp->ep_esch = execsw[i];
    317 		newerror = (*execsw[i]->es_makecmds)(l, epp);
    318 
    319 		if (!newerror) {
    320 			/* Seems ok: check that entry point is sane */
    321 			if (epp->ep_entry > VM_MAXUSER_ADDRESS) {
    322 				error = ENOEXEC;
    323 				break;
    324 			}
    325 
    326 			/* check limits */
    327 			if ((epp->ep_tsize > MAXTSIZ) ||
    328 			    (epp->ep_dsize > (u_quad_t)l->l_proc->p_rlimit
    329 						    [RLIMIT_DATA].rlim_cur)) {
    330 				error = ENOMEM;
    331 				break;
    332 			}
    333 			return 0;
    334 		}
    335 
    336 		if (epp->ep_emul_root != NULL) {
    337 			vrele(epp->ep_emul_root);
    338 			epp->ep_emul_root = NULL;
    339 		}
    340 		if (epp->ep_interp != NULL) {
    341 			vrele(epp->ep_interp);
    342 			epp->ep_interp = NULL;
    343 		}
    344 
    345 		/* make sure the first "interesting" error code is saved. */
    346 		if (error == ENOEXEC)
    347 			error = newerror;
    348 
    349 		if (epp->ep_flags & EXEC_DESTR)
    350 			/* Error from "#!" code, tidied up by recursive call */
    351 			return error;
    352 	}
    353 
    354 	/*
    355 	 * free any vmspace-creation commands,
    356 	 * and release their references
    357 	 */
    358 	kill_vmcmds(&epp->ep_vmcmds);
    359 
    360 bad2:
    361 	/*
    362 	 * close and release the vnode, restore the old one, free the
    363 	 * pathname buf, and punt.
    364 	 */
    365 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    366 	VOP_CLOSE(vp, FREAD, l->l_cred, l);
    367 	vput(vp);
    368 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
    369 	return error;
    370 
    371 bad1:
    372 	/*
    373 	 * free the namei pathname buffer, and put the vnode
    374 	 * (which we don't yet have open).
    375 	 */
    376 	vput(vp);				/* was still locked */
    377 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
    378 	return error;
    379 }
    380 
    381 #ifdef __MACHINE_STACK_GROWS_UP
    382 #define STACK_PTHREADSPACE NBPG
    383 #else
    384 #define STACK_PTHREADSPACE 0
    385 #endif
    386 
    387 static int
    388 execve_fetch_element(char * const *array, size_t index, char **value)
    389 {
    390 	return copyin(array + index, value, sizeof(*value));
    391 }
    392 
    393 /*
    394  * exec system call
    395  */
    396 /* ARGSUSED */
    397 int
    398 sys_execve(struct lwp *l, void *v, register_t *retval)
    399 {
    400 	struct sys_execve_args /* {
    401 		syscallarg(const char *)	path;
    402 		syscallarg(char * const *)	argp;
    403 		syscallarg(char * const *)	envp;
    404 	} */ *uap = v;
    405 
    406 	return execve1(l, SCARG(uap, path), SCARG(uap, argp),
    407 	    SCARG(uap, envp), execve_fetch_element);
    408 }
    409 
    410 int
    411 execve1(struct lwp *l, const char *path, char * const *args,
    412     char * const *envs, execve_fetch_element_t fetch_element)
    413 {
    414 	int			error;
    415 	u_int			i;
    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			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 	mutex_enter(&p->p_mutex);
    448 	proc_drainrefs(p);
    449 	mutex_exit(&p->p_mutex);
    450 
    451 	base_vcp = NULL;
    452 	/*
    453 	 * Init the namei data to point the file user's program name.
    454 	 * This is done here rather than in check_exec(), so that it's
    455 	 * possible to override this settings if any of makecmd/probe
    456 	 * functions call check_exec() recursively - for example,
    457 	 * see exec_script_makecmds().
    458 	 */
    459 #ifdef SYSTRACE
    460 	if (ISSET(p->p_flag, PK_SYSTRACE))
    461 		systrace_execve0(p);
    462 
    463 	error = copyinstr(path, pathbuf, sizeof(pathbuf),
    464 			  &pathbuflen);
    465 	if (error)
    466 		goto clrflg;
    467 
    468 	NDINIT(&nid, LOOKUP, NOFOLLOW | TRYEMULROOT, UIO_SYSSPACE, pathbuf, l);
    469 #else
    470 	NDINIT(&nid, LOOKUP, NOFOLLOW | TRYEMULROOT, UIO_USERSPACE, path, l);
    471 #endif /* SYSTRACE */
    472 
    473 	/*
    474 	 * initialize the fields of the exec package.
    475 	 */
    476 #ifdef SYSTRACE
    477 	pack.ep_name = pathbuf;
    478 #else
    479 	pack.ep_name = path;
    480 #endif /* SYSTRACE */
    481 	pack.ep_hdr = malloc(exec_maxhdrsz, M_EXEC, M_WAITOK);
    482 	pack.ep_hdrlen = exec_maxhdrsz;
    483 	pack.ep_hdrvalid = 0;
    484 	pack.ep_ndp = &nid;
    485 	pack.ep_emul_arg = NULL;
    486 	pack.ep_vmcmds.evs_cnt = 0;
    487 	pack.ep_vmcmds.evs_used = 0;
    488 	pack.ep_vap = &attr;
    489 	pack.ep_flags = 0;
    490 	pack.ep_emul_root = NULL;
    491 	pack.ep_interp = NULL;
    492 	pack.ep_esch = NULL;
    493 
    494 #ifdef LKM
    495 	rw_enter(&exec_lock, RW_READER);
    496 #endif
    497 
    498 	/* see if we can run it. */
    499         if ((error = check_exec(l, &pack)) != 0)
    500 		goto freehdr;
    501 
    502 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
    503 
    504 	/* allocate an argument buffer */
    505 	argp = (char *) uvm_km_alloc(exec_map, NCARGS, 0,
    506 	    UVM_KMF_PAGEABLE|UVM_KMF_WAITVA);
    507 #ifdef DIAGNOSTIC
    508 	if (argp == NULL)
    509 		panic("execve: argp == NULL");
    510 #endif
    511 	dp = argp;
    512 	argc = 0;
    513 
    514 	/* copy the fake args list, if there's one, freeing it as we go */
    515 	if (pack.ep_flags & EXEC_HASARGL) {
    516 		tmpfap = pack.ep_fa;
    517 		while (*tmpfap != NULL) {
    518 			char *cp;
    519 
    520 			cp = *tmpfap;
    521 			while (*cp)
    522 				*dp++ = *cp++;
    523 			dp++;
    524 
    525 			FREE(*tmpfap, M_EXEC);
    526 			tmpfap++; argc++;
    527 		}
    528 		FREE(pack.ep_fa, M_EXEC);
    529 		pack.ep_flags &= ~EXEC_HASARGL;
    530 	}
    531 
    532 	/* Now get argv & environment */
    533 	if (args == NULL) {
    534 		error = EINVAL;
    535 		goto bad;
    536 	}
    537 	/* 'i' will index the argp/envp element to be retrieved */
    538 	i = 0;
    539 	if (pack.ep_flags & EXEC_SKIPARG)
    540 		i++;
    541 
    542 	while (1) {
    543 		len = argp + ARG_MAX - dp;
    544 		if ((error = (*fetch_element)(args, i, &sp)) != 0)
    545 			goto bad;
    546 		if (!sp)
    547 			break;
    548 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    549 			if (error == ENAMETOOLONG)
    550 				error = E2BIG;
    551 			goto bad;
    552 		}
    553 #ifdef KTRACE
    554 		if (KTRPOINT(p, KTR_EXEC_ARG))
    555 			ktrkmem(l, KTR_EXEC_ARG, dp, len - 1);
    556 #endif
    557 		dp += len;
    558 		i++;
    559 		argc++;
    560 	}
    561 
    562 	envc = 0;
    563 	/* environment need not be there */
    564 	if (envs != NULL) {
    565 		i = 0;
    566 		while (1) {
    567 			len = argp + ARG_MAX - dp;
    568 			if ((error = (*fetch_element)(envs, i, &sp)) != 0)
    569 				goto bad;
    570 			if (!sp)
    571 				break;
    572 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    573 				if (error == ENAMETOOLONG)
    574 					error = E2BIG;
    575 				goto bad;
    576 			}
    577 #ifdef KTRACE
    578 			if (KTRPOINT(p, KTR_EXEC_ENV))
    579 				ktrkmem(l, KTR_EXEC_ENV, dp, len - 1);
    580 #endif
    581 			dp += len;
    582 			i++;
    583 			envc++;
    584 		}
    585 	}
    586 
    587 	dp = (char *) ALIGN(dp);
    588 
    589 	szsigcode = pack.ep_esch->es_emul->e_esigcode -
    590 	    pack.ep_esch->es_emul->e_sigcode;
    591 
    592 	/* Now check if args & environ fit into new stack */
    593 	if (pack.ep_flags & EXEC_32)
    594 		len = ((argc + envc + 2 + pack.ep_esch->es_arglen) *
    595 		    sizeof(int) + sizeof(int) + dp + STACKGAPLEN +
    596 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
    597 		    - argp;
    598 	else
    599 		len = ((argc + envc + 2 + pack.ep_esch->es_arglen) *
    600 		    sizeof(char *) + sizeof(int) + dp + STACKGAPLEN +
    601 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
    602 		    - argp;
    603 
    604 #ifdef STACKLALIGN	/* arm, etc. */
    605 	len = STACKALIGN(len);	/* make the stack "safely" aligned */
    606 #else
    607 	len = ALIGN(len);	/* make the stack "safely" aligned */
    608 #endif
    609 
    610 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
    611 		error = ENOMEM;
    612 		goto bad;
    613 	}
    614 
    615 	/* Get rid of other LWPs. */
    616 	if (p->p_nlwps > 1) {
    617 		mutex_enter(&p->p_smutex);
    618 		exit_lwps(l);
    619 		mutex_exit(&p->p_smutex);
    620 	}
    621 	KDASSERT(p->p_nlwps == 1);
    622 
    623 	/* This is now LWP 1 */
    624 	l->l_lid = 1;
    625 	p->p_nlwpid = 1;
    626 
    627 	/* Remove POSIX timers */
    628 	timers_free(p, TIMERS_POSIX);
    629 
    630 	/* adjust "active stack depth" for process VSZ */
    631 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
    632 
    633 	/*
    634 	 * Do whatever is necessary to prepare the address space
    635 	 * for remapping.  Note that this might replace the current
    636 	 * vmspace with another!
    637 	 */
    638 	uvmspace_exec(l, pack.ep_vm_minaddr, pack.ep_vm_maxaddr);
    639 
    640 	/* record proc's vnode, for use by procfs and others */
    641         if (p->p_textvp)
    642                 vrele(p->p_textvp);
    643 	VREF(pack.ep_vp);
    644 	p->p_textvp = pack.ep_vp;
    645 
    646 	/* Now map address space */
    647 	vm = p->p_vmspace;
    648 	vm->vm_taddr = (void *)pack.ep_taddr;
    649 	vm->vm_tsize = btoc(pack.ep_tsize);
    650 	vm->vm_daddr = (void*)pack.ep_daddr;
    651 	vm->vm_dsize = btoc(pack.ep_dsize);
    652 	vm->vm_ssize = btoc(pack.ep_ssize);
    653 	vm->vm_maxsaddr = (void *)pack.ep_maxsaddr;
    654 	vm->vm_minsaddr = (void *)pack.ep_minsaddr;
    655 
    656 	/* create the new process's VM space by running the vmcmds */
    657 #ifdef DIAGNOSTIC
    658 	if (pack.ep_vmcmds.evs_used == 0)
    659 		panic("execve: no vmcmds");
    660 #endif
    661 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
    662 		struct exec_vmcmd *vcp;
    663 
    664 		vcp = &pack.ep_vmcmds.evs_cmds[i];
    665 		if (vcp->ev_flags & VMCMD_RELATIVE) {
    666 #ifdef DIAGNOSTIC
    667 			if (base_vcp == NULL)
    668 				panic("execve: relative vmcmd with no base");
    669 			if (vcp->ev_flags & VMCMD_BASE)
    670 				panic("execve: illegal base & relative vmcmd");
    671 #endif
    672 			vcp->ev_addr += base_vcp->ev_addr;
    673 		}
    674 		error = (*vcp->ev_proc)(l, vcp);
    675 #ifdef DEBUG_EXEC
    676 		if (error) {
    677 			int j;
    678 			struct exec_vmcmd *vp = &pack.ep_vmcmds.evs_cmds[0];
    679 			for (j = 0; j <= i; j++)
    680 				uprintf(
    681 			    "vmcmd[%d] = %#lx/%#lx fd@%#lx prot=0%o flags=%d\n",
    682 				    j, vp[j].ev_addr, vp[j].ev_len,
    683 				    vp[j].ev_offset, vp[j].ev_prot,
    684 				    vp[j].ev_flags);
    685 		}
    686 #endif /* DEBUG_EXEC */
    687 		if (vcp->ev_flags & VMCMD_BASE)
    688 			base_vcp = vcp;
    689 	}
    690 
    691 	/* free the vmspace-creation commands, and release their references */
    692 	kill_vmcmds(&pack.ep_vmcmds);
    693 
    694 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    695 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred, l);
    696 	vput(pack.ep_vp);
    697 
    698 	/* if an error happened, deallocate and punt */
    699 	if (error) {
    700 		DPRINTF(("execve: vmcmd %i failed: %d\n", i - 1, error));
    701 		goto exec_abort;
    702 	}
    703 
    704 	/* remember information about the process */
    705 	arginfo.ps_nargvstr = argc;
    706 	arginfo.ps_nenvstr = envc;
    707 
    708 	stack = (char *)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
    709 		STACK_PTHREADSPACE + sizeof(struct ps_strings) + szsigcode),
    710 		len - (sizeof(struct ps_strings) + szsigcode));
    711 #ifdef __MACHINE_STACK_GROWS_UP
    712 	/*
    713 	 * The copyargs call always copies into lower addresses
    714 	 * first, moving towards higher addresses, starting with
    715 	 * the stack pointer that we give.  When the stack grows
    716 	 * down, this puts argc/argv/envp very shallow on the
    717 	 * stack, right at the first user stack pointer, and puts
    718 	 * STACKGAPLEN very deep in the stack.  When the stack
    719 	 * grows up, the situation is reversed.
    720 	 *
    721 	 * Normally, this is no big deal.  But the ld_elf.so _rtld()
    722 	 * function expects to be called with a single pointer to
    723 	 * a region that has a few words it can stash values into,
    724 	 * followed by argc/argv/envp.  When the stack grows down,
    725 	 * it's easy to decrement the stack pointer a little bit to
    726 	 * allocate the space for these few words and pass the new
    727 	 * stack pointer to _rtld.  When the stack grows up, however,
    728 	 * a few words before argc is part of the signal trampoline, XXX
    729 	 * so we have a problem.
    730 	 *
    731 	 * Instead of changing how _rtld works, we take the easy way
    732 	 * out and steal 32 bytes before we call copyargs.  This
    733 	 * space is effectively stolen from STACKGAPLEN.
    734 	 */
    735 	stack += 32;
    736 #endif /* __MACHINE_STACK_GROWS_UP */
    737 
    738 	/* Now copy argc, args & environ to new stack */
    739 	error = (*pack.ep_esch->es_copyargs)(l, &pack, &arginfo, &stack, argp);
    740 	if (error) {
    741 		DPRINTF(("execve: copyargs failed %d\n", error));
    742 		goto exec_abort;
    743 	}
    744 	/* Move the stack back to original point */
    745 	stack = (char *)STACK_GROW(vm->vm_minsaddr, len);
    746 
    747 	/* fill process ps_strings info */
    748 	p->p_psstr = (struct ps_strings *)
    749 	    STACK_ALLOC(STACK_GROW(vm->vm_minsaddr, STACK_PTHREADSPACE),
    750 	    sizeof(struct ps_strings));
    751 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
    752 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
    753 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
    754 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
    755 
    756 	/* copy out the process's ps_strings structure */
    757 	if ((error = copyout(aip, (char *)p->p_psstr,
    758 	    sizeof(arginfo))) != 0) {
    759 		DPRINTF(("execve: ps_strings copyout %p->%p size %ld failed\n",
    760 		       aip, (char *)p->p_psstr, (long)sizeof(arginfo)));
    761 		goto exec_abort;
    762 	}
    763 
    764 	fdcloseexec(l);		/* handle close on exec */
    765 	execsigs(p);		/* reset catched signals */
    766 
    767 	l->l_ctxlink = NULL;	/* reset ucontext link */
    768 
    769 	/* set command name & other accounting info */
    770 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
    771 	memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, len);
    772 	p->p_comm[len] = 0;
    773 	p->p_acflag &= ~AFORK;
    774 
    775 	p->p_flag |= PK_EXEC;
    776 
    777 	/*
    778 	 * Stop profiling.
    779 	 */
    780 	if ((p->p_stflag & PST_PROFIL) != 0) {
    781 		mutex_spin_enter(&p->p_stmutex);
    782 		stopprofclock(p);
    783 		mutex_spin_exit(&p->p_stmutex);
    784 	}
    785 
    786 	/*
    787 	 * It's OK to test PS_PPWAIT unlocked here, as other LWPs have
    788 	 * exited and exec()/exit() are the only places it will be cleared.
    789 	 */
    790 	if ((p->p_sflag & PS_PPWAIT) != 0) {
    791 		mutex_enter(&proclist_lock);
    792 		mutex_enter(&p->p_smutex);
    793 		p->p_sflag &= ~PS_PPWAIT;
    794 		cv_broadcast(&p->p_pptr->p_waitcv);
    795 		mutex_exit(&p->p_smutex);
    796 		mutex_exit(&proclist_lock);
    797 	}
    798 
    799 	/*
    800 	 * Deal with set[ug]id.  MNT_NOSUID has already been used to disable
    801 	 * s[ug]id.  It's OK to check for PSL_TRACED here as we have blocked
    802 	 * out additional references on the process for the moment.
    803 	 */
    804 	if ((p->p_slflag & PSL_TRACED) == 0 &&
    805 
    806 	    (((attr.va_mode & S_ISUID) != 0 &&
    807 	      kauth_cred_geteuid(l->l_cred) != attr.va_uid) ||
    808 
    809 	     ((attr.va_mode & S_ISGID) != 0 &&
    810 	      kauth_cred_getegid(l->l_cred) != attr.va_gid))) {
    811 		/*
    812 		 * Mark the process as SUGID before we do
    813 		 * anything that might block.
    814 		 */
    815 		proc_crmod_enter();
    816 		proc_crmod_leave(NULL, NULL, true);
    817 
    818 		/* Make sure file descriptors 0..2 are in use. */
    819 		if ((error = fdcheckstd(l)) != 0) {
    820 			DPRINTF(("execve: fdcheckstd failed %d\n", error));
    821 			goto exec_abort;
    822 		}
    823 
    824 		/*
    825 		 * Copy the credential so other references don't see our
    826 		 * changes.
    827 		 */
    828 		l->l_cred = kauth_cred_copy(l->l_cred);
    829 #ifdef KTRACE
    830 		/*
    831 		 * If process is being ktraced, turn off - unless
    832 		 * root set it.
    833 		 */
    834 		if (p->p_tracep) {
    835 			mutex_enter(&ktrace_mutex);
    836 			if (!(p->p_traceflag & KTRFAC_ROOT))
    837 				ktrderef(p);
    838 			mutex_exit(&ktrace_mutex);
    839 		}
    840 #endif
    841 		if (attr.va_mode & S_ISUID)
    842 			kauth_cred_seteuid(l->l_cred, attr.va_uid);
    843 		if (attr.va_mode & S_ISGID)
    844 			kauth_cred_setegid(l->l_cred, attr.va_gid);
    845 	} else {
    846 		if (kauth_cred_geteuid(l->l_cred) ==
    847 		    kauth_cred_getuid(l->l_cred) &&
    848 		    kauth_cred_getegid(l->l_cred) ==
    849 		    kauth_cred_getgid(l->l_cred))
    850 			p->p_flag &= ~PK_SUGID;
    851 	}
    852 
    853 	/*
    854 	 * Copy the credential so other references don't see our changes.
    855 	 * Test to see if this is necessary first, since in the common case
    856 	 * we won't need a private reference.
    857 	 */
    858 	if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
    859 	    kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
    860 		l->l_cred = kauth_cred_copy(l->l_cred);
    861 		kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
    862 		kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
    863 	}
    864 
    865 	/* Update the master credentials. */
    866 	if (l->l_cred != p->p_cred) {
    867 		kauth_cred_t ocred;
    868 
    869 		kauth_cred_hold(l->l_cred);
    870 		mutex_enter(&p->p_mutex);
    871 		ocred = p->p_cred;
    872 		p->p_cred = l->l_cred;
    873 		mutex_exit(&p->p_mutex);
    874 		kauth_cred_free(ocred);
    875 	}
    876 
    877 #if defined(__HAVE_RAS)
    878 	/*
    879 	 * Remove all RASs from the address space.
    880 	 */
    881 	ras_purgeall(p);
    882 #endif
    883 
    884 	doexechooks(p);
    885 
    886 	uvm_km_free(exec_map, (vaddr_t) argp, NCARGS, UVM_KMF_PAGEABLE);
    887 
    888 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    889 
    890 	/* notify others that we exec'd */
    891 	KNOTE(&p->p_klist, NOTE_EXEC);
    892 
    893 	/* setup new registers and do misc. setup. */
    894 	(*pack.ep_esch->es_emul->e_setregs)(l, &pack, (u_long) stack);
    895 	if (pack.ep_esch->es_setregs)
    896 		(*pack.ep_esch->es_setregs)(l, &pack, (u_long) stack);
    897 
    898 	/* map the process's signal trampoline code */
    899 	if (exec_sigcode_map(p, pack.ep_esch->es_emul)) {
    900 		DPRINTF(("execve: map sigcode failed %d\n", error));
    901 		goto exec_abort;
    902 	}
    903 
    904 	free(pack.ep_hdr, M_EXEC);
    905 
    906 	/* The emulation root will usually have been found when we looked
    907 	 * for the elf interpreter (or similar), if not look now. */
    908 	if (pack.ep_esch->es_emul->e_path != NULL && pack.ep_emul_root == NULL)
    909 		emul_find_root(l, &pack);
    910 
    911 	/* Any old emulation root got removed by fdcloseexec */
    912 	p->p_cwdi->cwdi_edir = pack.ep_emul_root;
    913 	pack.ep_emul_root = NULL;
    914 	if (pack.ep_interp != NULL)
    915 		vrele(pack.ep_interp);
    916 
    917 	/*
    918 	 * Call emulation specific exec hook. This can setup per-process
    919 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
    920 	 *
    921 	 * If we are executing process of different emulation than the
    922 	 * original forked process, call e_proc_exit() of the old emulation
    923 	 * first, then e_proc_exec() of new emulation. If the emulation is
    924 	 * same, the exec hook code should deallocate any old emulation
    925 	 * resources held previously by this process.
    926 	 */
    927 	if (p->p_emul && p->p_emul->e_proc_exit
    928 	    && p->p_emul != pack.ep_esch->es_emul)
    929 		(*p->p_emul->e_proc_exit)(p);
    930 
    931 	/*
    932 	 * Call exec hook. Emulation code may NOT store reference to anything
    933 	 * from &pack.
    934 	 */
    935         if (pack.ep_esch->es_emul->e_proc_exec)
    936                 (*pack.ep_esch->es_emul->e_proc_exec)(p, &pack);
    937 
    938 	/* update p_emul, the old value is no longer needed */
    939 	p->p_emul = pack.ep_esch->es_emul;
    940 
    941 	/* ...and the same for p_execsw */
    942 	p->p_execsw = pack.ep_esch;
    943 
    944 #ifdef __HAVE_SYSCALL_INTERN
    945 	(*p->p_emul->e_syscall_intern)(p);
    946 #endif
    947 #ifdef KTRACE
    948 	if (KTRPOINT(p, KTR_EMUL))
    949 		ktremul(l);
    950 #endif
    951 
    952 #ifdef LKM
    953 	rw_exit(&exec_lock);
    954 #endif
    955 
    956 	mutex_enter(&proclist_mutex);
    957 
    958 	if ((p->p_slflag & (PSL_TRACED|PSL_SYSCALL)) == PSL_TRACED) {
    959 		KSI_INIT_EMPTY(&ksi);
    960 		ksi.ksi_signo = SIGTRAP;
    961 		ksi.ksi_lid = l->l_lid;
    962 		kpsignal(p, &ksi, NULL);
    963 	}
    964 
    965 	if (p->p_sflag & PS_STOPEXEC) {
    966 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    967 		p->p_pptr->p_nstopchild++;
    968 		p->p_pptr->p_waited = 0;
    969 		mutex_enter(&p->p_smutex);
    970 		ksiginfo_queue_init(&kq);
    971 		sigclearall(p, &contsigmask, &kq);
    972 		lwp_lock(l);
    973 		p->p_refcnt = 1;
    974 		l->l_stat = LSSTOP;
    975 		p->p_stat = SSTOP;
    976 		p->p_nrlwps--;
    977 		mutex_exit(&p->p_smutex);
    978 		mutex_exit(&proclist_mutex);
    979 		mi_switch(l, NULL);
    980 		ksiginfo_queue_drain(&kq);
    981 		KERNEL_LOCK(l->l_biglocks, l);
    982 	} else {
    983 		mutex_exit(&proclist_mutex);
    984 
    985 		/* Unlock the process. */
    986 		mb_write();
    987 		p->p_refcnt = 1;
    988 	}
    989 
    990 #ifdef SYSTRACE
    991 	/* XXXSMP */
    992 	if (ISSET(p->p_flag, PK_SYSTRACE) &&
    993 	    wassugid && !ISSET(p->p_flag, PK_SUGID))
    994 		systrace_execve1(pathbuf, p);
    995 #endif /* SYSTRACE */
    996 
    997 	return (EJUSTRETURN);
    998 
    999  bad:
   1000 	/* free the vmspace-creation commands, and release their references */
   1001 	kill_vmcmds(&pack.ep_vmcmds);
   1002 	/* kill any opened file descriptor, if necessary */
   1003 	if (pack.ep_flags & EXEC_HASFD) {
   1004 		pack.ep_flags &= ~EXEC_HASFD;
   1005 		(void) fdrelease(l, pack.ep_fd);
   1006 	}
   1007 	/* close and put the exec'd file */
   1008 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
   1009 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred, l);
   1010 	vput(pack.ep_vp);
   1011 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
   1012 	uvm_km_free(exec_map, (vaddr_t) argp, NCARGS, UVM_KMF_PAGEABLE);
   1013 
   1014  freehdr:
   1015 	free(pack.ep_hdr, M_EXEC);
   1016 	if (pack.ep_emul_root != NULL)
   1017 		vrele(pack.ep_emul_root);
   1018 	if (pack.ep_interp != NULL)
   1019 		vrele(pack.ep_interp);
   1020 
   1021 #ifdef SYSTRACE
   1022  clrflg:
   1023 #endif /* SYSTRACE */
   1024 	/* Unlock the process. */
   1025 	mb_write();
   1026 	p->p_refcnt = 1;
   1027 
   1028 #ifdef LKM
   1029 	rw_exit(&exec_lock);
   1030 #endif
   1031 
   1032 	return error;
   1033 
   1034  exec_abort:
   1035 #ifdef LKM
   1036 	rw_exit(&exec_lock);
   1037 #endif
   1038 
   1039 	/*
   1040 	 * the old process doesn't exist anymore.  exit gracefully.
   1041 	 * get rid of the (new) address space we have created, if any, get rid
   1042 	 * of our namei data and vnode, and exit noting failure
   1043 	 */
   1044 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
   1045 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
   1046 	if (pack.ep_emul_arg)
   1047 		FREE(pack.ep_emul_arg, M_TEMP);
   1048 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
   1049 	uvm_km_free(exec_map, (vaddr_t) argp, NCARGS, UVM_KMF_PAGEABLE);
   1050 	free(pack.ep_hdr, M_EXEC);
   1051 	if (pack.ep_emul_root != NULL)
   1052 		vrele(pack.ep_emul_root);
   1053 	if (pack.ep_interp != NULL)
   1054 		vrele(pack.ep_interp);
   1055 
   1056 	/*
   1057 	 * Acquire the sched-state mutex (exit1() will release it).  Since
   1058 	 * this is a failed exec and we are exiting, keep the process locked
   1059 	 * (p->p_refcnt == 0) through exit1().
   1060 	 */
   1061 	mutex_enter(&p->p_smutex);
   1062 	exit1(l, W_EXITCODE(error, SIGABRT));
   1063 
   1064 	/* NOTREACHED */
   1065 	return 0;
   1066 }
   1067 
   1068 
   1069 int
   1070 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
   1071     char **stackp, void *argp)
   1072 {
   1073 	char	**cpp, *dp, *sp;
   1074 	size_t	len;
   1075 	void	*nullp;
   1076 	long	argc, envc;
   1077 	int	error;
   1078 
   1079 	cpp = (char **)*stackp;
   1080 	nullp = NULL;
   1081 	argc = arginfo->ps_nargvstr;
   1082 	envc = arginfo->ps_nenvstr;
   1083 	if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0)
   1084 		return error;
   1085 
   1086 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_esch->es_arglen);
   1087 	sp = argp;
   1088 
   1089 	/* XXX don't copy them out, remap them! */
   1090 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
   1091 
   1092 	for (; --argc >= 0; sp += len, dp += len)
   1093 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
   1094 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
   1095 			return error;
   1096 
   1097 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
   1098 		return error;
   1099 
   1100 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
   1101 
   1102 	for (; --envc >= 0; sp += len, dp += len)
   1103 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
   1104 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
   1105 			return error;
   1106 
   1107 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
   1108 		return error;
   1109 
   1110 	*stackp = (char *)cpp;
   1111 	return 0;
   1112 }
   1113 
   1114 #ifdef LKM
   1115 /*
   1116  * Find an emulation of given name in list of emulations.
   1117  * Needs to be called with the exec_lock held.
   1118  */
   1119 const struct emul *
   1120 emul_search(const char *name)
   1121 {
   1122 	struct emul_entry *it;
   1123 
   1124 	LIST_FOREACH(it, &el_head, el_list) {
   1125 		if (strcmp(name, it->el_emul->e_name) == 0)
   1126 			return it->el_emul;
   1127 	}
   1128 
   1129 	return NULL;
   1130 }
   1131 
   1132 /*
   1133  * Add an emulation to list, if it's not there already.
   1134  */
   1135 int
   1136 emul_register(const struct emul *emul, int ro_entry)
   1137 {
   1138 	struct emul_entry	*ee;
   1139 	int			error;
   1140 
   1141 	error = 0;
   1142 	rw_enter(&exec_lock, RW_WRITER);
   1143 
   1144 	if (emul_search(emul->e_name)) {
   1145 		error = EEXIST;
   1146 		goto out;
   1147 	}
   1148 
   1149 	MALLOC(ee, struct emul_entry *, sizeof(struct emul_entry),
   1150 		M_EXEC, M_WAITOK);
   1151 	ee->el_emul = emul;
   1152 	ee->ro_entry = ro_entry;
   1153 	LIST_INSERT_HEAD(&el_head, ee, el_list);
   1154 
   1155  out:
   1156 	rw_exit(&exec_lock);
   1157 	return error;
   1158 }
   1159 
   1160 /*
   1161  * Remove emulation with name 'name' from list of supported emulations.
   1162  */
   1163 int
   1164 emul_unregister(const char *name)
   1165 {
   1166 	const struct proclist_desc *pd;
   1167 	struct emul_entry	*it;
   1168 	int			i, error;
   1169 	struct proc		*ptmp;
   1170 
   1171 	error = 0;
   1172 	rw_enter(&exec_lock, RW_WRITER);
   1173 
   1174 	LIST_FOREACH(it, &el_head, el_list) {
   1175 		if (strcmp(it->el_emul->e_name, name) == 0)
   1176 			break;
   1177 	}
   1178 
   1179 	if (!it) {
   1180 		error = ENOENT;
   1181 		goto out;
   1182 	}
   1183 
   1184 	if (it->ro_entry) {
   1185 		error = EBUSY;
   1186 		goto out;
   1187 	}
   1188 
   1189 	/* test if any execw[] entry is still using this */
   1190 	for(i=0; i < nexecs; i++) {
   1191 		if (execsw[i]->es_emul == it->el_emul) {
   1192 			error = EBUSY;
   1193 			goto out;
   1194 		}
   1195 	}
   1196 
   1197 	/*
   1198 	 * Test if any process is running under this emulation - since
   1199 	 * emul_unregister() is running quite sendomly, it's better
   1200 	 * to do expensive check here than to use any locking.
   1201 	 */
   1202 	mutex_enter(&proclist_lock);
   1203 	for (pd = proclists; pd->pd_list != NULL && !error; pd++) {
   1204 		PROCLIST_FOREACH(ptmp, pd->pd_list) {
   1205 			if (ptmp->p_emul == it->el_emul) {
   1206 				error = EBUSY;
   1207 				break;
   1208 			}
   1209 		}
   1210 	}
   1211 	mutex_exit(&proclist_lock);
   1212 
   1213 	if (error)
   1214 		goto out;
   1215 
   1216 
   1217 	/* entry is not used, remove it */
   1218 	LIST_REMOVE(it, el_list);
   1219 	FREE(it, M_EXEC);
   1220 
   1221  out:
   1222 	rw_exit(&exec_lock);
   1223 	return error;
   1224 }
   1225 
   1226 /*
   1227  * Add execsw[] entry.
   1228  */
   1229 int
   1230 exec_add(struct execsw *esp, const char *e_name)
   1231 {
   1232 	struct exec_entry	*it;
   1233 	int			error;
   1234 
   1235 	error = 0;
   1236 	rw_enter(&exec_lock, RW_WRITER);
   1237 
   1238 	if (!esp->es_emul) {
   1239 		esp->es_emul = emul_search(e_name);
   1240 		if (!esp->es_emul) {
   1241 			error = ENOENT;
   1242 			goto out;
   1243 		}
   1244 	}
   1245 
   1246 	LIST_FOREACH(it, &ex_head, ex_list) {
   1247 		/* assume tuple (makecmds, probe_func, emulation) is unique */
   1248 		if (it->es->es_makecmds == esp->es_makecmds
   1249 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
   1250 		    && it->es->es_emul == esp->es_emul) {
   1251 			error = EEXIST;
   1252 			goto out;
   1253 		}
   1254 	}
   1255 
   1256 	/* if we got here, the entry doesn't exist yet */
   1257 	MALLOC(it, struct exec_entry *, sizeof(struct exec_entry),
   1258 		M_EXEC, M_WAITOK);
   1259 	it->es = esp;
   1260 	LIST_INSERT_HEAD(&ex_head, it, ex_list);
   1261 
   1262 	/* update execsw[] */
   1263 	exec_init(0);
   1264 
   1265  out:
   1266 	rw_exit(&exec_lock);
   1267 	return error;
   1268 }
   1269 
   1270 /*
   1271  * Remove execsw[] entry.
   1272  */
   1273 int
   1274 exec_remove(const struct execsw *esp)
   1275 {
   1276 	struct exec_entry	*it;
   1277 	int			error;
   1278 
   1279 	error = 0;
   1280 	rw_enter(&exec_lock, RW_WRITER);
   1281 
   1282 	LIST_FOREACH(it, &ex_head, ex_list) {
   1283 		/* assume tuple (makecmds, probe_func, emulation) is unique */
   1284 		if (it->es->es_makecmds == esp->es_makecmds
   1285 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
   1286 		    && it->es->es_emul == esp->es_emul)
   1287 			break;
   1288 	}
   1289 	if (!it) {
   1290 		error = ENOENT;
   1291 		goto out;
   1292 	}
   1293 
   1294 	/* remove item from list and free resources */
   1295 	LIST_REMOVE(it, ex_list);
   1296 	FREE(it, M_EXEC);
   1297 
   1298 	/* update execsw[] */
   1299 	exec_init(0);
   1300 
   1301  out:
   1302 	rw_exit(&exec_lock);
   1303 	return error;
   1304 }
   1305 
   1306 static void
   1307 link_es(struct execsw_entry **listp, const struct execsw *esp)
   1308 {
   1309 	struct execsw_entry *et, *e1;
   1310 
   1311 	et = (struct execsw_entry *) malloc(sizeof(struct execsw_entry),
   1312 			M_TEMP, M_WAITOK);
   1313 	et->next = NULL;
   1314 	et->es = esp;
   1315 	if (*listp == NULL) {
   1316 		*listp = et;
   1317 		return;
   1318 	}
   1319 
   1320 	switch(et->es->es_prio) {
   1321 	case EXECSW_PRIO_FIRST:
   1322 		/* put new entry as the first */
   1323 		et->next = *listp;
   1324 		*listp = et;
   1325 		break;
   1326 	case EXECSW_PRIO_ANY:
   1327 		/* put new entry after all *_FIRST and *_ANY entries */
   1328 		for(e1 = *listp; e1->next
   1329 			&& e1->next->es->es_prio != EXECSW_PRIO_LAST;
   1330 			e1 = e1->next);
   1331 		et->next = e1->next;
   1332 		e1->next = et;
   1333 		break;
   1334 	case EXECSW_PRIO_LAST:
   1335 		/* put new entry as the last one */
   1336 		for(e1 = *listp; e1->next; e1 = e1->next);
   1337 		e1->next = et;
   1338 		break;
   1339 	default:
   1340 #ifdef DIAGNOSTIC
   1341 		panic("execw[] entry with unknown priority %d found",
   1342 			et->es->es_prio);
   1343 #else
   1344 		free(et, M_TEMP);
   1345 #endif
   1346 		break;
   1347 	}
   1348 }
   1349 
   1350 /*
   1351  * Initialize exec structures. If init_boot is true, also does necessary
   1352  * one-time initialization (it's called from main() that way).
   1353  * Once system is multiuser, this should be called with exec_lock held,
   1354  * i.e. via exec_{add|remove}().
   1355  */
   1356 int
   1357 exec_init(int init_boot)
   1358 {
   1359 	const struct execsw	**new_es, * const *old_es;
   1360 	struct execsw_entry	*list, *e1;
   1361 	struct exec_entry	*e2;
   1362 	int			i, es_sz;
   1363 
   1364 	if (init_boot) {
   1365 		/* do one-time initializations */
   1366 		rw_init(&exec_lock);
   1367 
   1368 		/* register compiled-in emulations */
   1369 		for(i=0; i < nexecs_builtin; i++) {
   1370 			if (execsw_builtin[i].es_emul)
   1371 				emul_register(execsw_builtin[i].es_emul, 1);
   1372 		}
   1373 #ifdef DIAGNOSTIC
   1374 		if (i == 0)
   1375 			panic("no emulations found in execsw_builtin[]");
   1376 #endif
   1377 	}
   1378 
   1379 	/*
   1380 	 * Build execsw[] array from builtin entries and entries added
   1381 	 * at runtime.
   1382 	 */
   1383 	list = NULL;
   1384 	for(i=0; i < nexecs_builtin; i++)
   1385 		link_es(&list, &execsw_builtin[i]);
   1386 
   1387 	/* Add dynamically loaded entries */
   1388 	es_sz = nexecs_builtin;
   1389 	LIST_FOREACH(e2, &ex_head, ex_list) {
   1390 		link_es(&list, e2->es);
   1391 		es_sz++;
   1392 	}
   1393 
   1394 	/*
   1395 	 * Now that we have sorted all execw entries, create new execsw[]
   1396 	 * and free no longer needed memory in the process.
   1397 	 */
   1398 	new_es = malloc(es_sz * sizeof(struct execsw *), M_EXEC, M_WAITOK);
   1399 	for(i=0; list; i++) {
   1400 		new_es[i] = list->es;
   1401 		e1 = list->next;
   1402 		free(list, M_TEMP);
   1403 		list = e1;
   1404 	}
   1405 
   1406 	/*
   1407 	 * New execsw[] array built, now replace old execsw[] and free
   1408 	 * used memory.
   1409 	 */
   1410 	old_es = execsw;
   1411 	execsw = new_es;
   1412 	nexecs = es_sz;
   1413 	if (old_es)
   1414 		/*XXXUNCONST*/
   1415 		free(__UNCONST(old_es), M_EXEC);
   1416 
   1417 	/*
   1418 	 * Figure out the maximum size of an exec header.
   1419 	 */
   1420 	exec_maxhdrsz = 0;
   1421 	for (i = 0; i < nexecs; i++) {
   1422 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
   1423 			exec_maxhdrsz = execsw[i]->es_hdrsz;
   1424 	}
   1425 
   1426 	return 0;
   1427 }
   1428 #endif
   1429 
   1430 #ifndef LKM
   1431 /*
   1432  * Simplified exec_init() for kernels without LKMs. Only initialize
   1433  * exec_maxhdrsz and execsw[].
   1434  */
   1435 int
   1436 exec_init(int init_boot)
   1437 {
   1438 	int i;
   1439 
   1440 #ifdef DIAGNOSTIC
   1441 	if (!init_boot)
   1442 		panic("exec_init(): called with init_boot == 0");
   1443 #endif
   1444 
   1445 	/* do one-time initializations */
   1446 	nexecs = nexecs_builtin;
   1447 	execsw = malloc(nexecs*sizeof(struct execsw *), M_EXEC, M_WAITOK);
   1448 
   1449 	/*
   1450 	 * Fill in execsw[] and figure out the maximum size of an exec header.
   1451 	 */
   1452 	exec_maxhdrsz = 0;
   1453 	for(i=0; i < nexecs; i++) {
   1454 		execsw[i] = &execsw_builtin[i];
   1455 		if (execsw_builtin[i].es_hdrsz > exec_maxhdrsz)
   1456 			exec_maxhdrsz = execsw_builtin[i].es_hdrsz;
   1457 	}
   1458 
   1459 	return 0;
   1460 
   1461 }
   1462 #endif /* !LKM */
   1463 
   1464 static int
   1465 exec_sigcode_map(struct proc *p, const struct emul *e)
   1466 {
   1467 	vaddr_t va;
   1468 	vsize_t sz;
   1469 	int error;
   1470 	struct uvm_object *uobj;
   1471 
   1472 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
   1473 
   1474 	if (e->e_sigobject == NULL || sz == 0) {
   1475 		return 0;
   1476 	}
   1477 
   1478 	/*
   1479 	 * If we don't have a sigobject for this emulation, create one.
   1480 	 *
   1481 	 * sigobject is an anonymous memory object (just like SYSV shared
   1482 	 * memory) that we keep a permanent reference to and that we map
   1483 	 * in all processes that need this sigcode. The creation is simple,
   1484 	 * we create an object, add a permanent reference to it, map it in
   1485 	 * kernel space, copy out the sigcode to it and unmap it.
   1486 	 * We map it with PROT_READ|PROT_EXEC into the process just
   1487 	 * the way sys_mmap() would map it.
   1488 	 */
   1489 
   1490 	uobj = *e->e_sigobject;
   1491 	if (uobj == NULL) {
   1492 		uobj = uao_create(sz, 0);
   1493 		(*uobj->pgops->pgo_reference)(uobj);
   1494 		va = vm_map_min(kernel_map);
   1495 		if ((error = uvm_map(kernel_map, &va, round_page(sz),
   1496 		    uobj, 0, 0,
   1497 		    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
   1498 		    UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
   1499 			printf("kernel mapping failed %d\n", error);
   1500 			(*uobj->pgops->pgo_detach)(uobj);
   1501 			return (error);
   1502 		}
   1503 		memcpy((void *)va, e->e_sigcode, sz);
   1504 #ifdef PMAP_NEED_PROCWR
   1505 		pmap_procwr(&proc0, va, sz);
   1506 #endif
   1507 		uvm_unmap(kernel_map, va, va + round_page(sz));
   1508 		*e->e_sigobject = uobj;
   1509 	}
   1510 
   1511 	/* Just a hint to uvm_map where to put it. */
   1512 	va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
   1513 	    round_page(sz));
   1514 
   1515 #ifdef __alpha__
   1516 	/*
   1517 	 * Tru64 puts /sbin/loader at the end of user virtual memory,
   1518 	 * which causes the above calculation to put the sigcode at
   1519 	 * an invalid address.  Put it just below the text instead.
   1520 	 */
   1521 	if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
   1522 		va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
   1523 	}
   1524 #endif
   1525 
   1526 	(*uobj->pgops->pgo_reference)(uobj);
   1527 	error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
   1528 			uobj, 0, 0,
   1529 			UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
   1530 				    UVM_ADV_RANDOM, 0));
   1531 	if (error) {
   1532 		(*uobj->pgops->pgo_detach)(uobj);
   1533 		return (error);
   1534 	}
   1535 	p->p_sigctx.ps_sigcode = (void *)va;
   1536 	return (0);
   1537 }
   1538