Home | History | Annotate | Line # | Download | only in kern
kern_exec.c revision 1.130
      1 /*	$NetBSD: kern_exec.c,v 1.130 2000/12/08 19:42:12 jdolecek 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 "opt_ktrace.h"
     36 #include "opt_syscall_debug.h"
     37 
     38 #include <sys/param.h>
     39 #include <sys/systm.h>
     40 #include <sys/filedesc.h>
     41 #include <sys/kernel.h>
     42 #include <sys/proc.h>
     43 #include <sys/mount.h>
     44 #include <sys/malloc.h>
     45 #include <sys/namei.h>
     46 #include <sys/vnode.h>
     47 #include <sys/file.h>
     48 #include <sys/acct.h>
     49 #include <sys/exec.h>
     50 #include <sys/ktrace.h>
     51 #include <sys/resourcevar.h>
     52 #include <sys/wait.h>
     53 #include <sys/mman.h>
     54 #include <sys/signalvar.h>
     55 #include <sys/stat.h>
     56 #include <sys/syscall.h>
     57 
     58 #include <sys/syscallargs.h>
     59 
     60 #include <uvm/uvm_extern.h>
     61 
     62 #include <machine/cpu.h>
     63 #include <machine/reg.h>
     64 
     65 /*
     66  * Exec function switch:
     67  *
     68  * Note that each makecmds function is responsible for loading the
     69  * exec package with the necessary functions for any exec-type-specific
     70  * handling.
     71  *
     72  * Functions for specific exec types should be defined in their own
     73  * header file.
     74  */
     75 extern const struct execsw execsw_builtin[];
     76 extern int nexecs_builtin;
     77 static const struct execsw **execsw = NULL;
     78 static int nexecs;
     79 int exec_maxhdrsz;		/* must not be static - netbsd32 needs it */
     80 
     81 #ifdef LKM
     82 /* list of supported emulations */
     83 static
     84 LIST_HEAD(emlist_head, emul_entry) el_head = LIST_HEAD_INITIALIZER(el_head);
     85 struct emul_entry {
     86 	LIST_ENTRY(emul_entry) el_list;
     87 	const struct emul *el_emul;
     88 	int ro_entry;
     89 };
     90 
     91 /* list of dynamically loaded execsw entries */
     92 static
     93 LIST_HEAD(execlist_head, exec_entry) ex_head = LIST_HEAD_INITIALIZER(ex_head);
     94 struct exec_entry {
     95 	LIST_ENTRY(exec_entry) ex_list;
     96 	const struct execsw *es;
     97 };
     98 
     99 /* structure used for building execw[] */
    100 struct execsw_entry {
    101 	struct execsw_entry *next;
    102 	const struct execsw *es;
    103 };
    104 #endif /* LKM */
    105 
    106 /* NetBSD emul struct */
    107 extern char sigcode[], esigcode[];
    108 #ifdef SYSCALL_DEBUG
    109 extern const char * const syscallnames[];
    110 #endif
    111 
    112 const struct emul emul_netbsd = {
    113 	"netbsd",
    114 	NULL,		/* emulation path */
    115 	NULL,
    116 	sendsig,
    117 	SYS_syscall,
    118 	SYS_MAXSYSCALL,
    119 	sysent,
    120 #ifdef SYSCALL_DEBUG
    121 	syscallnames,
    122 #else
    123 	NULL,
    124 #endif
    125 	sigcode,
    126 	esigcode,
    127 	NULL,
    128 	NULL,
    129 	NULL,
    130 	EMUL_HAS_SYS___syscall,
    131 };
    132 
    133 /*
    134  * Exec lock. Used to control access to execsw[] structures.
    135  * This must not be static so that netbsd32 can access it, too.
    136  */
    137 struct lock exec_lock;
    138 
    139 #ifdef LKM
    140 static const struct emul *	emul_search __P((const char *));
    141 static void link_es __P((struct execsw_entry **, const struct execsw *));
    142 #endif /* LKM */
    143 
    144 /*
    145  * check exec:
    146  * given an "executable" described in the exec package's namei info,
    147  * see what we can do with it.
    148  *
    149  * ON ENTRY:
    150  *	exec package with appropriate namei info
    151  *	proc pointer of exec'ing proc
    152  *	NO SELF-LOCKED VNODES
    153  *
    154  * ON EXIT:
    155  *	error:	nothing held, etc.  exec header still allocated.
    156  *	ok:	filled exec package, executable's vnode (unlocked).
    157  *
    158  * EXEC SWITCH ENTRY:
    159  * 	Locked vnode to check, exec package, proc.
    160  *
    161  * EXEC SWITCH EXIT:
    162  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
    163  *	error:	destructive:
    164  *			everything deallocated execept exec header.
    165  *		non-destructive:
    166  *			error code, executable's vnode (unlocked),
    167  *			exec header unmodified.
    168  */
    169 int
    170 check_exec(struct proc *p, struct exec_package *epp)
    171 {
    172 	int error, i;
    173 	struct vnode *vp;
    174 	struct nameidata *ndp;
    175 	size_t resid;
    176 
    177 	ndp = epp->ep_ndp;
    178 	ndp->ni_cnd.cn_nameiop = LOOKUP;
    179 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME;
    180 	/* first get the vnode */
    181 	if ((error = namei(ndp)) != 0)
    182 		return error;
    183 	epp->ep_vp = vp = ndp->ni_vp;
    184 
    185 	/* check access and type */
    186 	if (vp->v_type != VREG) {
    187 		error = EACCES;
    188 		goto bad1;
    189 	}
    190 	if ((error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p)) != 0)
    191 		goto bad1;
    192 
    193 	/* get attributes */
    194 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
    195 		goto bad1;
    196 
    197 	/* Check mount point */
    198 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
    199 		error = EACCES;
    200 		goto bad1;
    201 	}
    202 	if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
    203 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
    204 
    205 	/* try to open it */
    206 	if ((error = VOP_OPEN(vp, FREAD, p->p_ucred, p)) != 0)
    207 		goto bad1;
    208 
    209 	/* unlock vp, since we need it unlocked from here on out. */
    210 	VOP_UNLOCK(vp, 0);
    211 
    212 	/* now we have the file, get the exec header */
    213 	uvn_attach(vp, VM_PROT_READ);
    214 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
    215 			UIO_SYSSPACE, 0, p->p_ucred, &resid, p);
    216 	if (error)
    217 		goto bad2;
    218 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
    219 
    220 	/*
    221 	 * set up the vmcmds for creation of the process
    222 	 * address space
    223 	 */
    224 	error = ENOEXEC;
    225 	for (i = 0; i < nexecs && error != 0; i++) {
    226 		int newerror;
    227 
    228 		epp->ep_esch = execsw[i];
    229 		newerror = (*execsw[i]->es_check)(p, epp);
    230 		/* make sure the first "interesting" error code is saved. */
    231 		if (!newerror || error == ENOEXEC)
    232 			error = newerror;
    233 
    234 		/* if es_check call was successful, update epp->ep_es */
    235 		if (!newerror && (epp->ep_flags & EXEC_HASES) == 0)
    236 			epp->ep_es = execsw[i];
    237 
    238 		if (epp->ep_flags & EXEC_DESTR && error != 0)
    239 			return error;
    240 	}
    241 	if (!error) {
    242 		/* check that entry point is sane */
    243 		if (epp->ep_entry > VM_MAXUSER_ADDRESS)
    244 			error = ENOEXEC;
    245 
    246 		/* check limits */
    247 		if ((epp->ep_tsize > MAXTSIZ) ||
    248 		    (epp->ep_dsize > p->p_rlimit[RLIMIT_DATA].rlim_cur))
    249 			error = ENOMEM;
    250 
    251 		if (!error)
    252 			return (0);
    253 	}
    254 
    255 	/*
    256 	 * free any vmspace-creation commands,
    257 	 * and release their references
    258 	 */
    259 	kill_vmcmds(&epp->ep_vmcmds);
    260 
    261 bad2:
    262 	/*
    263 	 * close and release the vnode, restore the old one, free the
    264 	 * pathname buf, and punt.
    265 	 */
    266 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    267 	VOP_CLOSE(vp, FREAD, p->p_ucred, p);
    268 	vput(vp);
    269 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
    270 	return error;
    271 
    272 bad1:
    273 	/*
    274 	 * free the namei pathname buffer, and put the vnode
    275 	 * (which we don't yet have open).
    276 	 */
    277 	vput(vp);				/* was still locked */
    278 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
    279 	return error;
    280 }
    281 
    282 /*
    283  * exec system call
    284  */
    285 /* ARGSUSED */
    286 int
    287 sys_execve(struct proc *p, void *v, register_t *retval)
    288 {
    289 	struct sys_execve_args /* {
    290 		syscallarg(const char *) path;
    291 		syscallarg(char * const *) argp;
    292 		syscallarg(char * const *) envp;
    293 	} */ *uap = v;
    294 	int error, i;
    295 	struct exec_package pack;
    296 	struct nameidata nid;
    297 	struct vattr attr;
    298 	struct ucred *cred = p->p_ucred;
    299 	char *argp;
    300 	char * const *cpp;
    301 	char *dp, *sp;
    302 	long argc, envc;
    303 	size_t len;
    304 	char *stack;
    305 	struct ps_strings arginfo;
    306 	struct vmspace *vm;
    307 	char **tmpfap;
    308 	int szsigcode;
    309 	struct exec_vmcmd *base_vcp = NULL;
    310 
    311 	/*
    312 	 * Init the namei data to point the file user's program name.
    313 	 * This is done here rather than in check_exec(), so that it's
    314 	 * possible to override this settings if any of makecmd/probe
    315 	 * functions call check_exec() recursively - for example,
    316 	 * see exec_script_makecmds().
    317 	 */
    318 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path), p);
    319 
    320 	/*
    321 	 * initialize the fields of the exec package.
    322 	 */
    323 	pack.ep_name = SCARG(uap, path);
    324 	pack.ep_hdr = malloc(exec_maxhdrsz, M_EXEC, M_WAITOK);
    325 	pack.ep_hdrlen = exec_maxhdrsz;
    326 	pack.ep_hdrvalid = 0;
    327 	pack.ep_ndp = &nid;
    328 	pack.ep_emul_arg = NULL;
    329 	pack.ep_vmcmds.evs_cnt = 0;
    330 	pack.ep_vmcmds.evs_used = 0;
    331 	pack.ep_vap = &attr;
    332 	pack.ep_flags = 0;
    333 
    334 	lockmgr(&exec_lock, LK_SHARED, NULL);
    335 
    336 	/* see if we can run it. */
    337 	if ((error = check_exec(p, &pack)) != 0)
    338 		goto freehdr;
    339 
    340 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
    341 
    342 	/* allocate an argument buffer */
    343 	argp = (char *) uvm_km_valloc_wait(exec_map, NCARGS);
    344 #ifdef DIAGNOSTIC
    345 	if (argp == (vaddr_t) 0)
    346 		panic("execve: argp == NULL");
    347 #endif
    348 	dp = argp;
    349 	argc = 0;
    350 
    351 	/* copy the fake args list, if there's one, freeing it as we go */
    352 	if (pack.ep_flags & EXEC_HASARGL) {
    353 		tmpfap = pack.ep_fa;
    354 		while (*tmpfap != NULL) {
    355 			char *cp;
    356 
    357 			cp = *tmpfap;
    358 			while (*cp)
    359 				*dp++ = *cp++;
    360 			dp++;
    361 
    362 			FREE(*tmpfap, M_EXEC);
    363 			tmpfap++; argc++;
    364 		}
    365 		FREE(pack.ep_fa, M_EXEC);
    366 		pack.ep_flags &= ~EXEC_HASARGL;
    367 	}
    368 
    369 	/* Now get argv & environment */
    370 	if (!(cpp = SCARG(uap, argp))) {
    371 		error = EINVAL;
    372 		goto bad;
    373 	}
    374 
    375 	if (pack.ep_flags & EXEC_SKIPARG)
    376 		cpp++;
    377 
    378 	while (1) {
    379 		len = argp + ARG_MAX - dp;
    380 		if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
    381 			goto bad;
    382 		if (!sp)
    383 			break;
    384 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    385 			if (error == ENAMETOOLONG)
    386 				error = E2BIG;
    387 			goto bad;
    388 		}
    389 		dp += len;
    390 		cpp++;
    391 		argc++;
    392 	}
    393 
    394 	envc = 0;
    395 	/* environment need not be there */
    396 	if ((cpp = SCARG(uap, envp)) != NULL ) {
    397 		while (1) {
    398 			len = argp + ARG_MAX - dp;
    399 			if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
    400 				goto bad;
    401 			if (!sp)
    402 				break;
    403 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    404 				if (error == ENAMETOOLONG)
    405 					error = E2BIG;
    406 				goto bad;
    407 			}
    408 			dp += len;
    409 			cpp++;
    410 			envc++;
    411 		}
    412 	}
    413 
    414 	dp = (char *) ALIGN(dp);
    415 
    416 	szsigcode = pack.ep_es->es_emul->e_esigcode -
    417 	    pack.ep_es->es_emul->e_sigcode;
    418 
    419 	/* Now check if args & environ fit into new stack */
    420 	if (pack.ep_flags & EXEC_32)
    421 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
    422 		    sizeof(int) + sizeof(int) + dp + STACKGAPLEN +
    423 		    szsigcode + sizeof(struct ps_strings)) - argp;
    424 	else
    425 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
    426 		    sizeof(char *) + sizeof(int) + dp + STACKGAPLEN +
    427 		    szsigcode + sizeof(struct ps_strings)) - argp;
    428 
    429 	len = ALIGN(len);	/* make the stack "safely" aligned */
    430 
    431 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
    432 		error = ENOMEM;
    433 		goto bad;
    434 	}
    435 
    436 	/* adjust "active stack depth" for process VSZ */
    437 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
    438 
    439 	/*
    440 	 * Do whatever is necessary to prepare the address space
    441 	 * for remapping.  Note that this might replace the current
    442 	 * vmspace with another!
    443 	 */
    444 	uvmspace_exec(p);
    445 
    446 	/* Now map address space */
    447 	vm = p->p_vmspace;
    448 	vm->vm_taddr = (char *) pack.ep_taddr;
    449 	vm->vm_tsize = btoc(pack.ep_tsize);
    450 	vm->vm_daddr = (char *) pack.ep_daddr;
    451 	vm->vm_dsize = btoc(pack.ep_dsize);
    452 	vm->vm_ssize = btoc(pack.ep_ssize);
    453 	vm->vm_maxsaddr = (char *) pack.ep_maxsaddr;
    454 	vm->vm_minsaddr = (char *) pack.ep_minsaddr;
    455 
    456 	/* create the new process's VM space by running the vmcmds */
    457 #ifdef DIAGNOSTIC
    458 	if (pack.ep_vmcmds.evs_used == 0)
    459 		panic("execve: no vmcmds");
    460 #endif
    461 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
    462 		struct exec_vmcmd *vcp;
    463 
    464 		vcp = &pack.ep_vmcmds.evs_cmds[i];
    465 		if (vcp->ev_flags & VMCMD_RELATIVE) {
    466 #ifdef DIAGNOSTIC
    467 			if (base_vcp == NULL)
    468 				panic("execve: relative vmcmd with no base");
    469 			if (vcp->ev_flags & VMCMD_BASE)
    470 				panic("execve: illegal base & relative vmcmd");
    471 #endif
    472 			vcp->ev_addr += base_vcp->ev_addr;
    473 		}
    474 		error = (*vcp->ev_proc)(p, vcp);
    475 #ifdef DEBUG
    476 		if (error) {
    477 			if (i > 0)
    478 				printf("vmcmd[%d] = %#lx/%#lx @ %#lx\n", i-1,
    479 				       vcp[-1].ev_addr, vcp[-1].ev_len,
    480 				       vcp[-1].ev_offset);
    481 			printf("vmcmd[%d] = %#lx/%#lx @ %#lx\n", i,
    482 			       vcp->ev_addr, vcp->ev_len, vcp->ev_offset);
    483 		}
    484 #endif
    485 		if (vcp->ev_flags & VMCMD_BASE)
    486 			base_vcp = vcp;
    487 	}
    488 
    489 	/* free the vmspace-creation commands, and release their references */
    490 	kill_vmcmds(&pack.ep_vmcmds);
    491 
    492 	/* if an error happened, deallocate and punt */
    493 	if (error) {
    494 #ifdef DEBUG
    495 		printf("execve: vmcmd %i failed: %d\n", i-1, error);
    496 #endif
    497 		goto exec_abort;
    498 	}
    499 
    500 	/* remember information about the process */
    501 	arginfo.ps_nargvstr = argc;
    502 	arginfo.ps_nenvstr = envc;
    503 
    504 	stack = (char *) (vm->vm_minsaddr - len);
    505 	/* Now copy argc, args & environ to new stack */
    506 	if (!(*pack.ep_es->es_copyargs)(&pack, &arginfo, stack, argp)) {
    507 #ifdef DEBUG
    508 		printf("execve: copyargs failed\n");
    509 #endif
    510 		goto exec_abort;
    511 	}
    512 
    513 	/* fill process ps_strings info */
    514 	p->p_psstr = (struct ps_strings *)(vm->vm_minsaddr
    515 		- sizeof(struct ps_strings));
    516 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
    517 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
    518 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
    519 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
    520 
    521 	/* copy out the process's ps_strings structure */
    522 	if (copyout(&arginfo, (char *)p->p_psstr, sizeof(arginfo))) {
    523 #ifdef DEBUG
    524 		printf("execve: ps_strings copyout failed\n");
    525 #endif
    526 		goto exec_abort;
    527 	}
    528 
    529 	/* copy out the process's signal trapoline code */
    530 	if (szsigcode) {
    531 		if (copyout((char *)pack.ep_es->es_emul->e_sigcode,
    532 		    p->p_sigacts->ps_sigcode = (char *)p->p_psstr - szsigcode,
    533 		    szsigcode)) {
    534 #ifdef DEBUG
    535 			printf("execve: sig trampoline copyout failed\n");
    536 #endif
    537 			goto exec_abort;
    538 		}
    539 #ifdef PMAP_NEED_PROCWR
    540 		/* This is code. Let the pmap do what is needed. */
    541 		pmap_procwr(p, (vaddr_t)p->p_sigacts->ps_sigcode, szsigcode);
    542 #endif
    543 	}
    544 
    545 	stopprofclock(p);	/* stop profiling */
    546 	fdcloseexec(p);		/* handle close on exec */
    547 	execsigs(p);		/* reset catched signals */
    548 	p->p_ctxlink = NULL;	/* reset ucontext link */
    549 
    550 	/* set command name & other accounting info */
    551 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
    552 	memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, len);
    553 	p->p_comm[len] = 0;
    554 	p->p_acflag &= ~AFORK;
    555 
    556 	/* record proc's vnode, for use by procfs and others */
    557         if (p->p_textvp)
    558                 vrele(p->p_textvp);
    559 	VREF(pack.ep_vp);
    560 	p->p_textvp = pack.ep_vp;
    561 
    562 	p->p_flag |= P_EXEC;
    563 	if (p->p_flag & P_PPWAIT) {
    564 		p->p_flag &= ~P_PPWAIT;
    565 		wakeup((caddr_t) p->p_pptr);
    566 	}
    567 
    568 	/*
    569 	 * deal with set[ug]id.
    570 	 * MNT_NOSUID and P_TRACED have already been used to disable s[ug]id.
    571 	 */
    572 	if (((attr.va_mode & S_ISUID) != 0 && p->p_ucred->cr_uid != attr.va_uid)
    573 	 || ((attr.va_mode & S_ISGID) != 0 && p->p_ucred->cr_gid != attr.va_gid)){
    574 		p->p_ucred = crcopy(cred);
    575 #ifdef KTRACE
    576 		/*
    577 		 * If process is being ktraced, turn off - unless
    578 		 * root set it.
    579 		 */
    580 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT))
    581 			ktrderef(p);
    582 #endif
    583 		if (attr.va_mode & S_ISUID)
    584 			p->p_ucred->cr_uid = attr.va_uid;
    585 		if (attr.va_mode & S_ISGID)
    586 			p->p_ucred->cr_gid = attr.va_gid;
    587 		p_sugid(p);
    588 	} else
    589 		p->p_flag &= ~P_SUGID;
    590 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
    591 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
    592 
    593 	doexechooks(p);
    594 
    595 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
    596 
    597 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    598 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    599 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
    600 	vput(pack.ep_vp);
    601 
    602 	/* setup new registers and do misc. setup. */
    603 	(*pack.ep_es->es_setregs)(p, &pack, (u_long) stack);
    604 
    605 	if (p->p_flag & P_TRACED)
    606 		psignal(p, SIGTRAP);
    607 
    608 	free(pack.ep_hdr, M_EXEC);
    609 
    610 	/*
    611 	 * Call emulation specific exec hook. This can setup setup per-process
    612 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
    613 	 *
    614 	 * If we are executing process of different emulation than the
    615 	 * original forked process, call e_proc_exit() of the old emulation
    616 	 * first, then e_proc_exec() of new emulation. If the emulation is
    617 	 * same, the exec hook code should deallocate any old emulation
    618 	 * resources held previously by this process.
    619 	 */
    620 	if (p->p_emul && p->p_emul->e_proc_exit
    621 	    && p->p_emul != pack.ep_es->es_emul)
    622 		(*p->p_emul->e_proc_exit)(p);
    623 
    624 	/*
    625 	 * Call exec hook. Emulation code may NOT store reference to anything
    626 	 * from &pack.
    627 	 */
    628         if (pack.ep_es->es_emul->e_proc_exec)
    629                 (*pack.ep_es->es_emul->e_proc_exec)(p, &pack);
    630 
    631 	/* update p_emul, the old value is no longer needed */
    632 	p->p_emul = pack.ep_es->es_emul;
    633 
    634 #ifdef KTRACE
    635 	if (KTRPOINT(p, KTR_EMUL))
    636 		ktremul(p);
    637 #endif
    638 
    639 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    640 
    641 	return (EJUSTRETURN);
    642 
    643 bad:
    644 	/* free the vmspace-creation commands, and release their references */
    645 	kill_vmcmds(&pack.ep_vmcmds);
    646 	/* kill any opened file descriptor, if necessary */
    647 	if (pack.ep_flags & EXEC_HASFD) {
    648 		pack.ep_flags &= ~EXEC_HASFD;
    649 		(void) fdrelease(p, pack.ep_fd);
    650 	}
    651 	/* close and put the exec'd file */
    652 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    653 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
    654 	vput(pack.ep_vp);
    655 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    656 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
    657 
    658 freehdr:
    659 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    660 
    661 	free(pack.ep_hdr, M_EXEC);
    662 	return error;
    663 
    664 exec_abort:
    665 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    666 
    667 	/*
    668 	 * the old process doesn't exist anymore.  exit gracefully.
    669 	 * get rid of the (new) address space we have created, if any, get rid
    670 	 * of our namei data and vnode, and exit noting failure
    671 	 */
    672 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
    673 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
    674 	if (pack.ep_emul_arg)
    675 		FREE(pack.ep_emul_arg, M_TEMP);
    676 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
    677 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    678 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
    679 	vput(pack.ep_vp);
    680 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
    681 	free(pack.ep_hdr, M_EXEC);
    682 	exit1(p, W_EXITCODE(0, SIGABRT));
    683 	exit1(p, -1);
    684 
    685 	/* NOTREACHED */
    686 	return 0;
    687 }
    688 
    689 
    690 void *
    691 copyargs(struct exec_package *pack, struct ps_strings *arginfo,
    692     void *stack, void *argp)
    693 {
    694 	char **cpp = stack;
    695 	char *dp, *sp;
    696 	size_t len;
    697 	void *nullp = NULL;
    698 	long argc = arginfo->ps_nargvstr;
    699 	long envc = arginfo->ps_nenvstr;
    700 
    701 #ifdef __sparc_v9__
    702 	/* XXX Temporary hack for argc format conversion. */
    703 	argc <<= 32;
    704 #endif
    705 	if (copyout(&argc, cpp++, sizeof(argc)))
    706 		return NULL;
    707 #ifdef __sparc_v9__
    708 	/* XXX Temporary hack for argc format conversion. */
    709 	argc >>= 32;
    710 #endif
    711 
    712 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_es->es_arglen);
    713 	sp = argp;
    714 
    715 	/* XXX don't copy them out, remap them! */
    716 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
    717 
    718 	for (; --argc >= 0; sp += len, dp += len)
    719 		if (copyout(&dp, cpp++, sizeof(dp)) ||
    720 		    copyoutstr(sp, dp, ARG_MAX, &len))
    721 			return NULL;
    722 
    723 	if (copyout(&nullp, cpp++, sizeof(nullp)))
    724 		return NULL;
    725 
    726 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
    727 
    728 	for (; --envc >= 0; sp += len, dp += len)
    729 		if (copyout(&dp, cpp++, sizeof(dp)) ||
    730 		    copyoutstr(sp, dp, ARG_MAX, &len))
    731 			return NULL;
    732 
    733 	if (copyout(&nullp, cpp++, sizeof(nullp)))
    734 		return NULL;
    735 
    736 	return cpp;
    737 }
    738 
    739 #ifdef LKM
    740 /*
    741  * Find an emulation of given name in list of emulations.
    742  */
    743 static const struct emul *
    744 emul_search(name)
    745 	const char *name;
    746 {
    747 	struct emul_entry *it;
    748 
    749 	LIST_FOREACH(it, &el_head, el_list) {
    750 		if (strcmp(name, it->el_emul->e_name) == 0)
    751 			return it->el_emul;
    752 	}
    753 
    754 	return NULL;
    755 }
    756 
    757 /*
    758  * Add an emulation to list, if it's not there already.
    759  */
    760 int
    761 emul_register(emul, ro_entry)
    762 	const struct emul *emul;
    763 	int ro_entry;
    764 {
    765 	struct emul_entry *ee;
    766 	int error = 0;
    767 
    768 	lockmgr(&exec_lock, LK_SHARED, NULL);
    769 
    770 	if (emul_search(emul->e_name)) {
    771 		error = EEXIST;
    772 		goto out;
    773 	}
    774 
    775 	MALLOC(ee, struct emul_entry *, sizeof(struct emul_entry),
    776 		M_EXEC, M_WAITOK);
    777 	ee->el_emul = emul;
    778 	ee->ro_entry = ro_entry;
    779 	LIST_INSERT_HEAD(&el_head, ee, el_list);
    780 
    781     out:
    782 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    783 	return error;
    784 }
    785 
    786 /*
    787  * Remove emulation with name 'name' from list of supported emulations.
    788  */
    789 int
    790 emul_unregister(name)
    791 	const char *name;
    792 {
    793 	struct emul_entry *it;
    794 	int i, error = 0;
    795 	const struct proclist_desc *pd;
    796 	struct proc *ptmp;
    797 
    798 	lockmgr(&exec_lock, LK_SHARED, NULL);
    799 
    800 	LIST_FOREACH(it, &el_head, el_list) {
    801 		if (strcmp(it->el_emul->e_name, name) == 0)
    802 			break;
    803 	}
    804 
    805 	if (!it) {
    806 		error = ENOENT;
    807 		goto out;
    808 	}
    809 
    810 	if (it->ro_entry) {
    811 		error = EBUSY;
    812 		goto out;
    813 	}
    814 
    815 	/* test if any execw[] entry is still using this */
    816 	for(i=0; execsw[i]; i++) {
    817 		if (execsw[i]->es_emul == it->el_emul) {
    818 			error = EBUSY;
    819 			goto out;
    820 		}
    821 	}
    822 
    823 	/*
    824 	 * Test if any process is running under this emulation - since
    825 	 * emul_unregister() is running quite sendomly, it's better
    826 	 * to do expensive check here than to use any locking.
    827 	 */
    828 	proclist_lock_read();
    829 	for (pd = proclists; pd->pd_list != NULL && !error; pd++) {
    830 		LIST_FOREACH(ptmp, pd->pd_list, p_list) {
    831 			if (ptmp->p_emul == it->el_emul) {
    832 				error = EBUSY;
    833 				break;
    834 			}
    835 		}
    836 	}
    837 	proclist_unlock_read();
    838 
    839 	if (error)
    840 		goto out;
    841 
    842 
    843 	/* entry is not used, remove it */
    844 	LIST_REMOVE(it, el_list);
    845 	FREE(it, M_EXEC);
    846 
    847     out:
    848 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    849 	return error;
    850 }
    851 
    852 /*
    853  * Add execsw[] entry.
    854  */
    855 int
    856 exec_add(esp, e_name)
    857 	struct execsw *esp;
    858 	const char *e_name;
    859 {
    860 	struct exec_entry *it;
    861 	int error = 0;
    862 
    863 	lockmgr(&exec_lock, LK_EXCLUSIVE, NULL);
    864 
    865 	if (!esp->es_emul) {
    866 		esp->es_emul = emul_search(e_name);
    867 		if (!esp->es_emul) {
    868 			error = ENOENT;
    869 			goto out;
    870 		}
    871 	}
    872 
    873 	LIST_FOREACH(it, &ex_head, ex_list) {
    874 		/* assume tuple (makecmds, probe_func, emulation) is unique */
    875 		if (it->es->es_check == esp->es_check
    876 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
    877 		    && it->es->es_emul == esp->es_emul) {
    878 			error = EEXIST;
    879 			goto out;
    880 		}
    881 	}
    882 
    883 	/* if we got here, the entry doesn't exist yet */
    884 	MALLOC(it, struct exec_entry *, sizeof(struct exec_entry),
    885 		M_EXEC, M_WAITOK);
    886 	it->es = esp;
    887 	LIST_INSERT_HEAD(&ex_head, it, ex_list);
    888 
    889 	/* update execsw[] */
    890 	exec_init(0);
    891 
    892     out:
    893 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    894 	return error;
    895 }
    896 
    897 /*
    898  * Remove execsw[] entry.
    899  */
    900 int
    901 exec_remove(esp)
    902 	const struct execsw *esp;
    903 {
    904 	struct exec_entry *it;
    905 	int error = 0;
    906 
    907 	lockmgr(&exec_lock, LK_EXCLUSIVE, NULL);
    908 
    909 	LIST_FOREACH(it, &ex_head, ex_list) {
    910 		/* assume tuple (makecmds, probe_func, emulation) is unique */
    911 		if (it->es->es_check == esp->es_check
    912 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
    913 		    && it->es->es_emul == esp->es_emul)
    914 			break;
    915 	}
    916 	if (!it) {
    917 		error = ENOENT;
    918 		goto out;
    919 	}
    920 
    921 	/* remove item from list and free resources */
    922 	LIST_REMOVE(it, ex_list);
    923 	FREE(it, M_EXEC);
    924 
    925 	/* update execsw[] */
    926 	exec_init(0);
    927 
    928     out:
    929 	lockmgr(&exec_lock, LK_RELEASE, NULL);
    930 	return error;
    931 }
    932 
    933 static void
    934 link_es(listp, esp)
    935 	struct execsw_entry **listp;
    936 	const struct execsw *esp;
    937 {
    938 	struct execsw_entry *et, *e1;
    939 
    940 	MALLOC(et, struct execsw_entry *, sizeof(struct execsw_entry),
    941 			M_TEMP, M_WAITOK);
    942 	et->next = NULL;
    943 	et->es = esp;
    944 	if (*listp == NULL) {
    945 		*listp = et;
    946 		return;
    947 	}
    948 
    949 	switch(et->es->es_prio) {
    950 	case EXECSW_PRIO_FIRST:
    951 		/* put new entry as the first */
    952 		et->next = *listp;
    953 		*listp = et;
    954 		break;
    955 	case EXECSW_PRIO_ANY:
    956 		/* put new entry after all *_FIRST and *_ANY entries */
    957 		for(e1 = *listp; e1->next
    958 			&& e1->next->es->es_prio != EXECSW_PRIO_LAST;
    959 			e1 = e1->next);
    960 		et->next = e1->next;
    961 		e1->next = et;
    962 		break;
    963 	case EXECSW_PRIO_LAST:
    964 		/* put new entry as the last one */
    965 		for(e1 = *listp; e1->next; e1 = e1->next);
    966 		e1->next = et;
    967 		break;
    968 	default:
    969 #ifdef DIAGNOSTIC
    970 		panic("execw[] entry with unknown priority %d found\n",
    971 			et->es->es_prio);
    972 #endif
    973 		break;
    974 	}
    975 }
    976 
    977 /*
    978  * Initialize exec structures. If init_boot is true, also does necessary
    979  * one-time initialization (it's called from main() that way).
    980  * Once system is multiuser, this should be called with exec_lock hold,
    981  * i.e. via exec_{add|remove}().
    982  */
    983 int
    984 exec_init(init_boot)
    985 	int init_boot;
    986 {
    987 	const struct execsw **new_es, * const *old_es;
    988 	struct execsw_entry *list, *e1;
    989 	struct exec_entry *e2;
    990 	int i, es_sz;
    991 
    992 	if (init_boot) {
    993 		/* do one-time initializations */
    994 		lockinit(&exec_lock, PWAIT, "execlck", 0, 0);
    995 
    996 		/* register compiled-in emulations */
    997 		for(i=0; i < nexecs_builtin; i++) {
    998 			if (execsw_builtin[i].es_emul)
    999 				emul_register(execsw_builtin[i].es_emul, 1);
   1000 		}
   1001 #ifdef DIAGNOSTIC
   1002 		if (i == 0)
   1003 			panic("no emulations found in execsw_builtin[]\n");
   1004 #endif
   1005 	}
   1006 
   1007 	/*
   1008 	 * Build execsw[] array from builtin entries and entries added
   1009 	 * at runtime.
   1010 	 */
   1011 	list = NULL;
   1012 	for(i=0; i < nexecs_builtin; i++)
   1013 		link_es(&list, &execsw_builtin[i]);
   1014 
   1015 	/* Add dynamically loaded entries */
   1016 	es_sz = nexecs_builtin;
   1017 	LIST_FOREACH(e2, &ex_head, ex_list) {
   1018 		link_es(&list, e2->es);
   1019 		es_sz++;
   1020 	}
   1021 
   1022 	/*
   1023 	 * Now that we have sorted all execw entries, create new execsw[]
   1024 	 * and free no longer needed memory in the process.
   1025 	 */
   1026 	new_es = malloc(es_sz * sizeof(struct execsw *), M_EXEC, M_WAITOK);
   1027 	for(i=0; list; i++) {
   1028 		new_es[i] = list->es;
   1029 		e1 = list->next;
   1030 		FREE(list, M_TEMP);
   1031 		list = e1;
   1032 	}
   1033 
   1034 	/*
   1035 	 * New execsw[] array built, now replace old execsw[] and free
   1036 	 * used memory.
   1037 	 */
   1038 	old_es = execsw;
   1039 	execsw = new_es;
   1040 	nexecs = es_sz;
   1041 	if (old_es)
   1042 		free((void *)old_es, M_EXEC);
   1043 
   1044 	/*
   1045 	 * Figure out the maximum size of an exec header.
   1046 	 */
   1047 	exec_maxhdrsz = 0;
   1048 	for (i = 0; i < nexecs; i++) {
   1049 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
   1050 			exec_maxhdrsz = execsw[i]->es_hdrsz;
   1051 	}
   1052 
   1053 	return 0;
   1054 }
   1055 #endif
   1056 
   1057 #ifndef LKM
   1058 /*
   1059  * Simplified exec_init() for kernels without LKMs. Only initialize
   1060  * exec_maxhdrsz and execsw[].
   1061  */
   1062 int
   1063 exec_init(init_boot)
   1064 	int init_boot;
   1065 {
   1066 	int i;
   1067 
   1068 #ifdef DIAGNOSTIC
   1069 	if (!init_boot)
   1070 		panic("exec_init(): called with init_boot == 0");
   1071 #endif
   1072 
   1073 	/* do one-time initializations */
   1074 	lockinit(&exec_lock, PWAIT, "execlck", 0, 0);
   1075 
   1076 	nexecs = nexecs_builtin;
   1077 	execsw = malloc(nexecs*sizeof(struct execsw *), M_EXEC, M_WAITOK);
   1078 
   1079 	/*
   1080 	 * Fill in execsw[] and figure out the maximum size of an exec header.
   1081 	 */
   1082 	exec_maxhdrsz = 0;
   1083 	for(i=0; i < nexecs; i++) {
   1084 		execsw[i] = &execsw_builtin[i];
   1085 		if (execsw_builtin[i].es_hdrsz > exec_maxhdrsz)
   1086 			exec_maxhdrsz = execsw_builtin[i].es_hdrsz;
   1087 	}
   1088 
   1089 	return 0;
   1090 
   1091 }
   1092 #endif /* !LKM */
   1093