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