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