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