xref: /netbsd-src/sys/kern/kern_exec.c (revision c505c4429840c353a86d4eb53b5e2bfc0092264e)
1 /*	$NetBSD: kern_exec.c,v 1.299 2010/07/07 01:30:37 chs Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*-
30  * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou
31  * Copyright (C) 1992 Wolfgang Solfrank.
32  * Copyright (C) 1992 TooLs GmbH.
33  * All rights reserved.
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgement:
45  *	This product includes software developed by TooLs GmbH.
46  * 4. The name of TooLs GmbH may not be used to endorse or promote products
47  *    derived from this software without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
50  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
51  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
52  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
53  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
54  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
55  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
56  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
57  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
58  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60 
61 #include <sys/cdefs.h>
62 __KERNEL_RCSID(0, "$NetBSD: kern_exec.c,v 1.299 2010/07/07 01:30:37 chs Exp $");
63 
64 #include "opt_ktrace.h"
65 #include "opt_modular.h"
66 #include "opt_syscall_debug.h"
67 #include "veriexec.h"
68 #include "opt_pax.h"
69 #include "opt_sa.h"
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/filedesc.h>
74 #include <sys/kernel.h>
75 #include <sys/proc.h>
76 #include <sys/mount.h>
77 #include <sys/malloc.h>
78 #include <sys/kmem.h>
79 #include <sys/namei.h>
80 #include <sys/vnode.h>
81 #include <sys/file.h>
82 #include <sys/acct.h>
83 #include <sys/exec.h>
84 #include <sys/ktrace.h>
85 #include <sys/uidinfo.h>
86 #include <sys/wait.h>
87 #include <sys/mman.h>
88 #include <sys/ras.h>
89 #include <sys/signalvar.h>
90 #include <sys/stat.h>
91 #include <sys/syscall.h>
92 #include <sys/kauth.h>
93 #include <sys/lwpctl.h>
94 #include <sys/pax.h>
95 #include <sys/cpu.h>
96 #include <sys/module.h>
97 #include <sys/sa.h>
98 #include <sys/savar.h>
99 #include <sys/syscallvar.h>
100 #include <sys/syscallargs.h>
101 #if NVERIEXEC > 0
102 #include <sys/verified_exec.h>
103 #endif /* NVERIEXEC > 0 */
104 #include <sys/sdt.h>
105 
106 #include <uvm/uvm_extern.h>
107 
108 #include <machine/reg.h>
109 
110 #include <compat/common/compat_util.h>
111 
112 static int exec_sigcode_map(struct proc *, const struct emul *);
113 
114 #ifdef DEBUG_EXEC
115 #define DPRINTF(a) uprintf a
116 #else
117 #define DPRINTF(a)
118 #endif /* DEBUG_EXEC */
119 
120 /*
121  * DTrace SDT provider definitions
122  */
123 SDT_PROBE_DEFINE(proc,,,exec,
124 	    "char *", NULL,
125 	    NULL, NULL, NULL, NULL,
126 	    NULL, NULL, NULL, NULL);
127 SDT_PROBE_DEFINE(proc,,,exec_success,
128 	    "char *", NULL,
129 	    NULL, NULL, NULL, NULL,
130 	    NULL, NULL, NULL, NULL);
131 SDT_PROBE_DEFINE(proc,,,exec_failure,
132 	    "int", NULL,
133 	    NULL, NULL, NULL, NULL,
134 	    NULL, NULL, NULL, NULL);
135 
136 /*
137  * Exec function switch:
138  *
139  * Note that each makecmds function is responsible for loading the
140  * exec package with the necessary functions for any exec-type-specific
141  * handling.
142  *
143  * Functions for specific exec types should be defined in their own
144  * header file.
145  */
146 static const struct execsw	**execsw = NULL;
147 static int			nexecs;
148 
149 u_int	exec_maxhdrsz;	 /* must not be static - used by netbsd32 */
150 
151 /* list of dynamically loaded execsw entries */
152 static LIST_HEAD(execlist_head, exec_entry) ex_head =
153     LIST_HEAD_INITIALIZER(ex_head);
154 struct exec_entry {
155 	LIST_ENTRY(exec_entry)	ex_list;
156 	SLIST_ENTRY(exec_entry)	ex_slist;
157 	const struct execsw	*ex_sw;
158 };
159 
160 #ifndef __HAVE_SYSCALL_INTERN
161 void	syscall(void);
162 #endif
163 
164 #ifdef KERN_SA
165 static struct sa_emul saemul_netbsd = {
166 	sizeof(ucontext_t),
167 	sizeof(struct sa_t),
168 	sizeof(struct sa_t *),
169 	NULL,
170 	NULL,
171 	cpu_upcall,
172 	(void (*)(struct lwp *, void *))getucontext_sa,
173 	sa_ucsp
174 };
175 #endif /* KERN_SA */
176 
177 /* NetBSD emul struct */
178 struct emul emul_netbsd = {
179 	.e_name =		"netbsd",
180 	.e_path =		NULL,
181 #ifndef __HAVE_MINIMAL_EMUL
182 	.e_flags =		EMUL_HAS_SYS___syscall,
183 	.e_errno =		NULL,
184 	.e_nosys =		SYS_syscall,
185 	.e_nsysent =		SYS_NSYSENT,
186 #endif
187 	.e_sysent =		sysent,
188 #ifdef SYSCALL_DEBUG
189 	.e_syscallnames =	syscallnames,
190 #else
191 	.e_syscallnames =	NULL,
192 #endif
193 	.e_sendsig =		sendsig,
194 	.e_trapsignal =		trapsignal,
195 	.e_tracesig =		NULL,
196 	.e_sigcode =		NULL,
197 	.e_esigcode =		NULL,
198 	.e_sigobject =		NULL,
199 	.e_setregs =		setregs,
200 	.e_proc_exec =		NULL,
201 	.e_proc_fork =		NULL,
202 	.e_proc_exit =		NULL,
203 	.e_lwp_fork =		NULL,
204 	.e_lwp_exit =		NULL,
205 #ifdef __HAVE_SYSCALL_INTERN
206 	.e_syscall_intern =	syscall_intern,
207 #else
208 	.e_syscall =		syscall,
209 #endif
210 	.e_sysctlovly =		NULL,
211 	.e_fault =		NULL,
212 	.e_vm_default_addr =	uvm_default_mapaddr,
213 	.e_usertrap =		NULL,
214 #ifdef KERN_SA
215 	.e_sa =			&saemul_netbsd,
216 #else
217 	.e_sa =			NULL,
218 #endif
219 	.e_ucsize =		sizeof(ucontext_t),
220 	.e_startlwp =		startlwp
221 };
222 
223 /*
224  * Exec lock. Used to control access to execsw[] structures.
225  * This must not be static so that netbsd32 can access it, too.
226  */
227 krwlock_t exec_lock;
228 
229 static kmutex_t sigobject_lock;
230 
231 static void *
232 exec_pool_alloc(struct pool *pp, int flags)
233 {
234 
235 	return (void *)uvm_km_alloc(kernel_map, NCARGS, 0,
236 	    UVM_KMF_PAGEABLE | UVM_KMF_WAITVA);
237 }
238 
239 static void
240 exec_pool_free(struct pool *pp, void *addr)
241 {
242 
243 	uvm_km_free(kernel_map, (vaddr_t)addr, NCARGS, UVM_KMF_PAGEABLE);
244 }
245 
246 static struct pool exec_pool;
247 
248 static struct pool_allocator exec_palloc = {
249 	.pa_alloc = exec_pool_alloc,
250 	.pa_free = exec_pool_free,
251 	.pa_pagesz = NCARGS
252 };
253 
254 /*
255  * check exec:
256  * given an "executable" described in the exec package's namei info,
257  * see what we can do with it.
258  *
259  * ON ENTRY:
260  *	exec package with appropriate namei info
261  *	lwp pointer of exec'ing lwp
262  *	NO SELF-LOCKED VNODES
263  *
264  * ON EXIT:
265  *	error:	nothing held, etc.  exec header still allocated.
266  *	ok:	filled exec package, executable's vnode (unlocked).
267  *
268  * EXEC SWITCH ENTRY:
269  * 	Locked vnode to check, exec package, proc.
270  *
271  * EXEC SWITCH EXIT:
272  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
273  *	error:	destructive:
274  *			everything deallocated execept exec header.
275  *		non-destructive:
276  *			error code, executable's vnode (unlocked),
277  *			exec header unmodified.
278  */
279 int
280 /*ARGSUSED*/
281 check_exec(struct lwp *l, struct exec_package *epp, const char *kpath)
282 {
283 	int		error, i;
284 	struct vnode	*vp;
285 	struct nameidata nd;
286 	size_t		resid;
287 
288 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | SAVENAME | TRYEMULROOT,
289 	       UIO_SYSSPACE, kpath);
290 
291 	/* first get the vnode */
292 	if ((error = namei(&nd)) != 0)
293 		return error;
294 	epp->ep_vp = vp = nd.ni_vp;
295 	/* this cannot overflow as both are size PATH_MAX */
296 	strcpy(epp->ep_resolvedname, nd.ni_cnd.cn_pnbuf);
297 
298 	/* dump this right away */
299 #ifdef DIAGNOSTIC
300 	/* paranoia (take this out once namei stuff stabilizes) */
301 	memset(nd.ni_cnd.cn_pnbuf, '~', PATH_MAX);
302 #endif
303 	PNBUF_PUT(nd.ni_cnd.cn_pnbuf);
304 
305 	/* check access and type */
306 	if (vp->v_type != VREG) {
307 		error = EACCES;
308 		goto bad1;
309 	}
310 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
311 		goto bad1;
312 
313 	/* get attributes */
314 	if ((error = VOP_GETATTR(vp, epp->ep_vap, l->l_cred)) != 0)
315 		goto bad1;
316 
317 	/* Check mount point */
318 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
319 		error = EACCES;
320 		goto bad1;
321 	}
322 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
323 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
324 
325 	/* try to open it */
326 	if ((error = VOP_OPEN(vp, FREAD, l->l_cred)) != 0)
327 		goto bad1;
328 
329 	/* unlock vp, since we need it unlocked from here on out. */
330 	VOP_UNLOCK(vp);
331 
332 #if NVERIEXEC > 0
333 	error = veriexec_verify(l, vp, epp->ep_resolvedname,
334 	    epp->ep_flags & EXEC_INDIR ? VERIEXEC_INDIRECT : VERIEXEC_DIRECT,
335 	    NULL);
336 	if (error)
337 		goto bad2;
338 #endif /* NVERIEXEC > 0 */
339 
340 #ifdef PAX_SEGVGUARD
341 	error = pax_segvguard(l, vp, epp->ep_resolvedname, false);
342 	if (error)
343 		goto bad2;
344 #endif /* PAX_SEGVGUARD */
345 
346 	/* now we have the file, get the exec header */
347 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
348 			UIO_SYSSPACE, 0, l->l_cred, &resid, NULL);
349 	if (error)
350 		goto bad2;
351 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
352 
353 	/*
354 	 * Set up default address space limits.  Can be overridden
355 	 * by individual exec packages.
356 	 *
357 	 * XXX probably should be all done in the exec packages.
358 	 */
359 	epp->ep_vm_minaddr = VM_MIN_ADDRESS;
360 	epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
361 	/*
362 	 * set up the vmcmds for creation of the process
363 	 * address space
364 	 */
365 	error = ENOEXEC;
366 	for (i = 0; i < nexecs; i++) {
367 		int newerror;
368 
369 		epp->ep_esch = execsw[i];
370 		newerror = (*execsw[i]->es_makecmds)(l, epp);
371 
372 		if (!newerror) {
373 			/* Seems ok: check that entry point is sane */
374 			if (epp->ep_entry > VM_MAXUSER_ADDRESS) {
375 				error = ENOEXEC;
376 				break;
377 			}
378 
379 			/* check limits */
380 			if ((epp->ep_tsize > MAXTSIZ) ||
381 			    (epp->ep_dsize > (u_quad_t)l->l_proc->p_rlimit
382 						    [RLIMIT_DATA].rlim_cur)) {
383 				error = ENOMEM;
384 				break;
385 			}
386 			return 0;
387 		}
388 
389 		if (epp->ep_emul_root != NULL) {
390 			vrele(epp->ep_emul_root);
391 			epp->ep_emul_root = NULL;
392 		}
393 		if (epp->ep_interp != NULL) {
394 			vrele(epp->ep_interp);
395 			epp->ep_interp = NULL;
396 		}
397 
398 		/* make sure the first "interesting" error code is saved. */
399 		if (error == ENOEXEC)
400 			error = newerror;
401 
402 		if (epp->ep_flags & EXEC_DESTR)
403 			/* Error from "#!" code, tidied up by recursive call */
404 			return error;
405 	}
406 
407 	/* not found, error */
408 
409 	/*
410 	 * free any vmspace-creation commands,
411 	 * and release their references
412 	 */
413 	kill_vmcmds(&epp->ep_vmcmds);
414 
415 bad2:
416 	/*
417 	 * close and release the vnode, restore the old one, free the
418 	 * pathname buf, and punt.
419 	 */
420 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
421 	VOP_CLOSE(vp, FREAD, l->l_cred);
422 	vput(vp);
423 	return error;
424 
425 bad1:
426 	/*
427 	 * free the namei pathname buffer, and put the vnode
428 	 * (which we don't yet have open).
429 	 */
430 	vput(vp);				/* was still locked */
431 	return error;
432 }
433 
434 #ifdef __MACHINE_STACK_GROWS_UP
435 #define STACK_PTHREADSPACE NBPG
436 #else
437 #define STACK_PTHREADSPACE 0
438 #endif
439 
440 static int
441 execve_fetch_element(char * const *array, size_t index, char **value)
442 {
443 	return copyin(array + index, value, sizeof(*value));
444 }
445 
446 /*
447  * exec system call
448  */
449 /* ARGSUSED */
450 int
451 sys_execve(struct lwp *l, const struct sys_execve_args *uap, register_t *retval)
452 {
453 	/* {
454 		syscallarg(const char *)	path;
455 		syscallarg(char * const *)	argp;
456 		syscallarg(char * const *)	envp;
457 	} */
458 
459 	return execve1(l, SCARG(uap, path), SCARG(uap, argp),
460 	    SCARG(uap, envp), execve_fetch_element);
461 }
462 
463 /*
464  * Load modules to try and execute an image that we do not understand.
465  * If no execsw entries are present, we load those likely to be needed
466  * in order to run native images only.  Otherwise, we autoload all
467  * possible modules that could let us run the binary.  XXX lame
468  */
469 static void
470 exec_autoload(void)
471 {
472 #ifdef MODULAR
473 	static const char * const native[] = {
474 		"exec_elf32",
475 		"exec_elf64",
476 		"exec_script",
477 		NULL
478 	};
479 	static const char * const compat[] = {
480 		"exec_elf32",
481 		"exec_elf64",
482 		"exec_script",
483 		"exec_aout",
484 		"exec_coff",
485 		"exec_ecoff",
486 		"compat_aoutm68k",
487 		"compat_freebsd",
488 		"compat_ibcs2",
489 		"compat_irix",
490 		"compat_linux",
491 		"compat_linux32",
492 		"compat_netbsd32",
493 		"compat_sunos",
494 		"compat_sunos32",
495 		"compat_svr4",
496 		"compat_svr4_32",
497 		"compat_ultrix",
498 		NULL
499 	};
500 	char const * const *list;
501 	int i;
502 
503 	mutex_enter(&module_lock);
504 	list = (nexecs == 0 ? native : compat);
505 	for (i = 0; list[i] != NULL; i++) {
506 		if (module_autoload(list[i], MODULE_CLASS_MISC) != 0) {
507 		    	continue;
508 		}
509 		mutex_exit(&module_lock);
510 	   	yield();
511 		mutex_enter(&module_lock);
512 	}
513 	mutex_exit(&module_lock);
514 #endif
515 }
516 
517 int
518 execve1(struct lwp *l, const char *path, char * const *args,
519     char * const *envs, execve_fetch_element_t fetch_element)
520 {
521 	int			error;
522 	struct exec_package	pack;
523 	struct vattr		attr;
524 	struct proc		*p;
525 	char			*argp;
526 	char			*dp, *sp;
527 	long			argc, envc;
528 	size_t			i, len;
529 	char			*stack;
530 	struct ps_strings	arginfo;
531 	struct ps_strings	*aip = &arginfo;
532 	struct vmspace		*vm;
533 	struct exec_fakearg	*tmpfap;
534 	int			szsigcode;
535 	struct exec_vmcmd	*base_vcp;
536 	int			oldlwpflags;
537 	ksiginfo_t		ksi;
538 	ksiginfoq_t		kq;
539 	char			*pathbuf;
540 	char			*resolvedpathbuf;
541 	const char		*commandname;
542 	u_int			modgen;
543 
544 	p = l->l_proc;
545  	modgen = 0;
546 
547 	SDT_PROBE(proc,,,exec, path, 0, 0, 0, 0);
548 
549 	/*
550 	 * Check if we have exceeded our number of processes limit.
551 	 * This is so that we handle the case where a root daemon
552 	 * forked, ran setuid to become the desired user and is trying
553 	 * to exec. The obvious place to do the reference counting check
554 	 * is setuid(), but we don't do the reference counting check there
555 	 * like other OS's do because then all the programs that use setuid()
556 	 * must be modified to check the return code of setuid() and exit().
557 	 * It is dangerous to make setuid() fail, because it fails open and
558 	 * the program will continue to run as root. If we make it succeed
559 	 * and return an error code, again we are not enforcing the limit.
560 	 * The best place to enforce the limit is here, when the process tries
561 	 * to execute a new image, because eventually the process will need
562 	 * to call exec in order to do something useful.
563 	 */
564  retry:
565 	if ((p->p_flag & PK_SUGID) && kauth_authorize_generic(l->l_cred,
566 	    KAUTH_GENERIC_ISSUSER, NULL) != 0 && chgproccnt(kauth_cred_getuid(
567 	    l->l_cred), 0) > p->p_rlimit[RLIMIT_NPROC].rlim_cur)
568 		return EAGAIN;
569 
570 	oldlwpflags = l->l_flag & (LW_SA | LW_SA_UPCALL);
571 	if (l->l_flag & LW_SA) {
572 		lwp_lock(l);
573 		l->l_flag &= ~(LW_SA | LW_SA_UPCALL);
574 		lwp_unlock(l);
575 	}
576 
577 	/*
578 	 * Drain existing references and forbid new ones.  The process
579 	 * should be left alone until we're done here.  This is necessary
580 	 * to avoid race conditions - e.g. in ptrace() - that might allow
581 	 * a local user to illicitly obtain elevated privileges.
582 	 */
583 	rw_enter(&p->p_reflock, RW_WRITER);
584 
585 	base_vcp = NULL;
586 	/*
587 	 * Init the namei data to point the file user's program name.
588 	 * This is done here rather than in check_exec(), so that it's
589 	 * possible to override this settings if any of makecmd/probe
590 	 * functions call check_exec() recursively - for example,
591 	 * see exec_script_makecmds().
592 	 */
593 	pathbuf = PNBUF_GET();
594 	error = copyinstr(path, pathbuf, MAXPATHLEN, NULL);
595 	if (error) {
596 		DPRINTF(("execve: copyinstr path %d", error));
597 		goto clrflg;
598 	}
599 	resolvedpathbuf = PNBUF_GET();
600 #ifdef DIAGNOSTIC
601 	strcpy(resolvedpathbuf, "/wrong");
602 #endif
603 
604 	/*
605 	 * initialize the fields of the exec package.
606 	 */
607 	pack.ep_name = path;
608 	pack.ep_kname = pathbuf;
609 	pack.ep_resolvedname = resolvedpathbuf;
610 	pack.ep_hdr = kmem_alloc(exec_maxhdrsz, KM_SLEEP);
611 	pack.ep_hdrlen = exec_maxhdrsz;
612 	pack.ep_hdrvalid = 0;
613 	pack.ep_emul_arg = NULL;
614 	pack.ep_vmcmds.evs_cnt = 0;
615 	pack.ep_vmcmds.evs_used = 0;
616 	pack.ep_vap = &attr;
617 	pack.ep_flags = 0;
618 	pack.ep_emul_root = NULL;
619 	pack.ep_interp = NULL;
620 	pack.ep_esch = NULL;
621 	pack.ep_pax_flags = 0;
622 
623 	rw_enter(&exec_lock, RW_READER);
624 
625 	/* see if we can run it. */
626 	if ((error = check_exec(l, &pack, pathbuf)) != 0) {
627 		if (error != ENOENT) {
628 			DPRINTF(("execve: check exec failed %d\n", error));
629 		}
630 		goto freehdr;
631 	}
632 
633 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
634 
635 	/* allocate an argument buffer */
636 	argp = pool_get(&exec_pool, PR_WAITOK);
637 	KASSERT(argp != NULL);
638 	dp = argp;
639 	argc = 0;
640 
641 	/* copy the fake args list, if there's one, freeing it as we go */
642 	if (pack.ep_flags & EXEC_HASARGL) {
643 		tmpfap = pack.ep_fa;
644 		while (tmpfap->fa_arg != NULL) {
645 			const char *cp;
646 
647 			cp = tmpfap->fa_arg;
648 			while (*cp)
649 				*dp++ = *cp++;
650 			*dp++ = '\0';
651 			ktrexecarg(tmpfap->fa_arg, cp - tmpfap->fa_arg);
652 
653 			kmem_free(tmpfap->fa_arg, tmpfap->fa_len);
654 			tmpfap++; argc++;
655 		}
656 		kmem_free(pack.ep_fa, pack.ep_fa_len);
657 		pack.ep_flags &= ~EXEC_HASARGL;
658 	}
659 
660 	/* Now get argv & environment */
661 	if (args == NULL) {
662 		DPRINTF(("execve: null args\n"));
663 		error = EINVAL;
664 		goto bad;
665 	}
666 	/* 'i' will index the argp/envp element to be retrieved */
667 	i = 0;
668 	if (pack.ep_flags & EXEC_SKIPARG)
669 		i++;
670 
671 	while (1) {
672 		len = argp + ARG_MAX - dp;
673 		if ((error = (*fetch_element)(args, i, &sp)) != 0) {
674 			DPRINTF(("execve: fetch_element args %d\n", error));
675 			goto bad;
676 		}
677 		if (!sp)
678 			break;
679 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
680 			DPRINTF(("execve: copyinstr args %d\n", error));
681 			if (error == ENAMETOOLONG)
682 				error = E2BIG;
683 			goto bad;
684 		}
685 		ktrexecarg(dp, len - 1);
686 		dp += len;
687 		i++;
688 		argc++;
689 	}
690 
691 	envc = 0;
692 	/* environment need not be there */
693 	if (envs != NULL) {
694 		i = 0;
695 		while (1) {
696 			len = argp + ARG_MAX - dp;
697 			if ((error = (*fetch_element)(envs, i, &sp)) != 0) {
698 				DPRINTF(("execve: fetch_element env %d\n", error));
699 				goto bad;
700 			}
701 			if (!sp)
702 				break;
703 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
704 				DPRINTF(("execve: copyinstr env %d\n", error));
705 				if (error == ENAMETOOLONG)
706 					error = E2BIG;
707 				goto bad;
708 			}
709 			ktrexecenv(dp, len - 1);
710 			dp += len;
711 			i++;
712 			envc++;
713 		}
714 	}
715 
716 	dp = (char *) ALIGN(dp);
717 
718 	szsigcode = pack.ep_esch->es_emul->e_esigcode -
719 	    pack.ep_esch->es_emul->e_sigcode;
720 
721 #ifdef __MACHINE_STACK_GROWS_UP
722 /* See big comment lower down */
723 #define	RTLD_GAP	32
724 #else
725 #define	RTLD_GAP	0
726 #endif
727 
728 	/* Now check if args & environ fit into new stack */
729 	if (pack.ep_flags & EXEC_32)
730 		len = ((argc + envc + 2 + pack.ep_esch->es_arglen) *
731 		    sizeof(int) + sizeof(int) + dp + RTLD_GAP +
732 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
733 		    - argp;
734 	else
735 		len = ((argc + envc + 2 + pack.ep_esch->es_arglen) *
736 		    sizeof(char *) + sizeof(int) + dp + RTLD_GAP +
737 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
738 		    - argp;
739 
740 #ifdef PAX_ASLR
741 	if (pax_aslr_active(l))
742 		len += (arc4random() % PAGE_SIZE);
743 #endif /* PAX_ASLR */
744 
745 #ifdef STACKLALIGN	/* arm, etc. */
746 	len = STACKALIGN(len);	/* make the stack "safely" aligned */
747 #else
748 	len = ALIGN(len);	/* make the stack "safely" aligned */
749 #endif
750 
751 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
752 		DPRINTF(("execve: stack limit exceeded %zu\n", len));
753 		error = ENOMEM;
754 		goto bad;
755 	}
756 
757 	/* Get rid of other LWPs. */
758 	if (p->p_sa || p->p_nlwps > 1) {
759 		mutex_enter(p->p_lock);
760 		exit_lwps(l);
761 		mutex_exit(p->p_lock);
762 	}
763 	KDASSERT(p->p_nlwps == 1);
764 
765 	/* Destroy any lwpctl info. */
766 	if (p->p_lwpctl != NULL)
767 		lwp_ctl_exit();
768 
769 #ifdef KERN_SA
770 	/* Release any SA state. */
771 	if (p->p_sa)
772 		sa_release(p);
773 #endif /* KERN_SA */
774 
775 	/* Remove POSIX timers */
776 	timers_free(p, TIMERS_POSIX);
777 
778 	/* adjust "active stack depth" for process VSZ */
779 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
780 
781 	/*
782 	 * Do whatever is necessary to prepare the address space
783 	 * for remapping.  Note that this might replace the current
784 	 * vmspace with another!
785 	 */
786 	uvmspace_exec(l, pack.ep_vm_minaddr, pack.ep_vm_maxaddr);
787 
788 	/* record proc's vnode, for use by procfs and others */
789         if (p->p_textvp)
790                 vrele(p->p_textvp);
791 	vref(pack.ep_vp);
792 	p->p_textvp = pack.ep_vp;
793 
794 	/* Now map address space */
795 	vm = p->p_vmspace;
796 	vm->vm_taddr = (void *)pack.ep_taddr;
797 	vm->vm_tsize = btoc(pack.ep_tsize);
798 	vm->vm_daddr = (void*)pack.ep_daddr;
799 	vm->vm_dsize = btoc(pack.ep_dsize);
800 	vm->vm_ssize = btoc(pack.ep_ssize);
801 	vm->vm_issize = 0;
802 	vm->vm_maxsaddr = (void *)pack.ep_maxsaddr;
803 	vm->vm_minsaddr = (void *)pack.ep_minsaddr;
804 
805 #ifdef PAX_ASLR
806 	pax_aslr_init(l, vm);
807 #endif /* PAX_ASLR */
808 
809 	/* create the new process's VM space by running the vmcmds */
810 #ifdef DIAGNOSTIC
811 	if (pack.ep_vmcmds.evs_used == 0)
812 		panic("execve: no vmcmds");
813 #endif
814 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
815 		struct exec_vmcmd *vcp;
816 
817 		vcp = &pack.ep_vmcmds.evs_cmds[i];
818 		if (vcp->ev_flags & VMCMD_RELATIVE) {
819 #ifdef DIAGNOSTIC
820 			if (base_vcp == NULL)
821 				panic("execve: relative vmcmd with no base");
822 			if (vcp->ev_flags & VMCMD_BASE)
823 				panic("execve: illegal base & relative vmcmd");
824 #endif
825 			vcp->ev_addr += base_vcp->ev_addr;
826 		}
827 		error = (*vcp->ev_proc)(l, vcp);
828 #ifdef DEBUG_EXEC
829 		if (error) {
830 			size_t j;
831 			struct exec_vmcmd *vp = &pack.ep_vmcmds.evs_cmds[0];
832 			for (j = 0; j <= i; j++)
833 				uprintf(
834 			"vmcmd[%zu] = %#lx/%#lx fd@%#lx prot=0%o flags=%d\n",
835 				    j, vp[j].ev_addr, vp[j].ev_len,
836 				    vp[j].ev_offset, vp[j].ev_prot,
837 				    vp[j].ev_flags);
838 		}
839 #endif /* DEBUG_EXEC */
840 		if (vcp->ev_flags & VMCMD_BASE)
841 			base_vcp = vcp;
842 	}
843 
844 	/* free the vmspace-creation commands, and release their references */
845 	kill_vmcmds(&pack.ep_vmcmds);
846 
847 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
848 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred);
849 	vput(pack.ep_vp);
850 
851 	/* if an error happened, deallocate and punt */
852 	if (error) {
853 		DPRINTF(("execve: vmcmd %zu failed: %d\n", i - 1, error));
854 		goto exec_abort;
855 	}
856 
857 	/* remember information about the process */
858 	arginfo.ps_nargvstr = argc;
859 	arginfo.ps_nenvstr = envc;
860 
861 	/* set command name & other accounting info */
862 	commandname = strrchr(pack.ep_resolvedname, '/');
863 	if (commandname != NULL) {
864 		commandname++;
865 	} else {
866 		commandname = pack.ep_resolvedname;
867 	}
868 	i = min(strlen(commandname), MAXCOMLEN);
869 	(void)memcpy(p->p_comm, commandname, i);
870 	p->p_comm[i] = '\0';
871 
872 	dp = PNBUF_GET();
873 	/*
874 	 * If the path starts with /, we don't need to do any work.
875 	 * This handles the majority of the cases.
876 	 * In the future perhaps we could canonicalize it?
877 	 */
878 	if (pathbuf[0] == '/')
879 		(void)strlcpy(pack.ep_path = dp, pathbuf, MAXPATHLEN);
880 #ifdef notyet
881 	/*
882 	 * Although this works most of the time [since the entry was just
883 	 * entered in the cache] we don't use it because it theoretically
884 	 * can fail and it is not the cleanest interface, because there
885 	 * could be races. When the namei cache is re-written, this can
886 	 * be changed to use the appropriate function.
887 	 */
888 	else if (!(error = vnode_to_path(dp, MAXPATHLEN, p->p_textvp, l, p)))
889 		pack.ep_path = dp;
890 #endif
891 	else {
892 #ifdef notyet
893 		printf("Cannot get path for pid %d [%s] (error %d)",
894 		    (int)p->p_pid, p->p_comm, error);
895 #endif
896 		pack.ep_path = NULL;
897 		PNBUF_PUT(dp);
898 	}
899 
900 	stack = (char *)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
901 		STACK_PTHREADSPACE + sizeof(struct ps_strings) + szsigcode),
902 		len - (sizeof(struct ps_strings) + szsigcode));
903 
904 #ifdef __MACHINE_STACK_GROWS_UP
905 	/*
906 	 * The copyargs call always copies into lower addresses
907 	 * first, moving towards higher addresses, starting with
908 	 * the stack pointer that we give.  When the stack grows
909 	 * down, this puts argc/argv/envp very shallow on the
910 	 * stack, right at the first user stack pointer.
911 	 * When the stack grows up, the situation is reversed.
912 	 *
913 	 * Normally, this is no big deal.  But the ld_elf.so _rtld()
914 	 * function expects to be called with a single pointer to
915 	 * a region that has a few words it can stash values into,
916 	 * followed by argc/argv/envp.  When the stack grows down,
917 	 * it's easy to decrement the stack pointer a little bit to
918 	 * allocate the space for these few words and pass the new
919 	 * stack pointer to _rtld.  When the stack grows up, however,
920 	 * a few words before argc is part of the signal trampoline, XXX
921 	 * so we have a problem.
922 	 *
923 	 * Instead of changing how _rtld works, we take the easy way
924 	 * out and steal 32 bytes before we call copyargs.
925 	 * This extra space was allowed for when 'len' was calculated.
926 	 */
927 	stack += RTLD_GAP;
928 #endif /* __MACHINE_STACK_GROWS_UP */
929 
930 	/* Now copy argc, args & environ to new stack */
931 	error = (*pack.ep_esch->es_copyargs)(l, &pack, &arginfo, &stack, argp);
932 	if (pack.ep_path) {
933 		PNBUF_PUT(pack.ep_path);
934 		pack.ep_path = NULL;
935 	}
936 	if (error) {
937 		DPRINTF(("execve: copyargs failed %d\n", error));
938 		goto exec_abort;
939 	}
940 	/* Move the stack back to original point */
941 	stack = (char *)STACK_GROW(vm->vm_minsaddr, len);
942 
943 	/* fill process ps_strings info */
944 	p->p_psstr = (struct ps_strings *)
945 	    STACK_ALLOC(STACK_GROW(vm->vm_minsaddr, STACK_PTHREADSPACE),
946 	    sizeof(struct ps_strings));
947 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
948 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
949 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
950 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
951 
952 	/* copy out the process's ps_strings structure */
953 	if ((error = copyout(aip, (char *)p->p_psstr,
954 	    sizeof(arginfo))) != 0) {
955 		DPRINTF(("execve: ps_strings copyout %p->%p size %ld failed\n",
956 		       aip, (char *)p->p_psstr, (long)sizeof(arginfo)));
957 		goto exec_abort;
958 	}
959 
960 	fd_closeexec();		/* handle close on exec */
961 	execsigs(p);		/* reset catched signals */
962 
963 	l->l_ctxlink = NULL;	/* reset ucontext link */
964 
965 
966 	p->p_acflag &= ~AFORK;
967 	mutex_enter(p->p_lock);
968 	p->p_flag |= PK_EXEC;
969 	mutex_exit(p->p_lock);
970 
971 	/*
972 	 * Stop profiling.
973 	 */
974 	if ((p->p_stflag & PST_PROFIL) != 0) {
975 		mutex_spin_enter(&p->p_stmutex);
976 		stopprofclock(p);
977 		mutex_spin_exit(&p->p_stmutex);
978 	}
979 
980 	/*
981 	 * It's OK to test PL_PPWAIT unlocked here, as other LWPs have
982 	 * exited and exec()/exit() are the only places it will be cleared.
983 	 */
984 	if ((p->p_lflag & PL_PPWAIT) != 0) {
985 		mutex_enter(proc_lock);
986 		p->p_lflag &= ~PL_PPWAIT;
987 		cv_broadcast(&p->p_pptr->p_waitcv);
988 		mutex_exit(proc_lock);
989 	}
990 
991 	/*
992 	 * Deal with set[ug]id.  MNT_NOSUID has already been used to disable
993 	 * s[ug]id.  It's OK to check for PSL_TRACED here as we have blocked
994 	 * out additional references on the process for the moment.
995 	 */
996 	if ((p->p_slflag & PSL_TRACED) == 0 &&
997 
998 	    (((attr.va_mode & S_ISUID) != 0 &&
999 	      kauth_cred_geteuid(l->l_cred) != attr.va_uid) ||
1000 
1001 	     ((attr.va_mode & S_ISGID) != 0 &&
1002 	      kauth_cred_getegid(l->l_cred) != attr.va_gid))) {
1003 		/*
1004 		 * Mark the process as SUGID before we do
1005 		 * anything that might block.
1006 		 */
1007 		proc_crmod_enter();
1008 		proc_crmod_leave(NULL, NULL, true);
1009 
1010 		/* Make sure file descriptors 0..2 are in use. */
1011 		if ((error = fd_checkstd()) != 0) {
1012 			DPRINTF(("execve: fdcheckstd failed %d\n", error));
1013 			goto exec_abort;
1014 		}
1015 
1016 		/*
1017 		 * Copy the credential so other references don't see our
1018 		 * changes.
1019 		 */
1020 		l->l_cred = kauth_cred_copy(l->l_cred);
1021 #ifdef KTRACE
1022 		/*
1023 		 * If the persistent trace flag isn't set, turn off.
1024 		 */
1025 		if (p->p_tracep) {
1026 			mutex_enter(&ktrace_lock);
1027 			if (!(p->p_traceflag & KTRFAC_PERSISTENT))
1028 				ktrderef(p);
1029 			mutex_exit(&ktrace_lock);
1030 		}
1031 #endif
1032 		if (attr.va_mode & S_ISUID)
1033 			kauth_cred_seteuid(l->l_cred, attr.va_uid);
1034 		if (attr.va_mode & S_ISGID)
1035 			kauth_cred_setegid(l->l_cred, attr.va_gid);
1036 	} else {
1037 		if (kauth_cred_geteuid(l->l_cred) ==
1038 		    kauth_cred_getuid(l->l_cred) &&
1039 		    kauth_cred_getegid(l->l_cred) ==
1040 		    kauth_cred_getgid(l->l_cred))
1041 			p->p_flag &= ~PK_SUGID;
1042 	}
1043 
1044 	/*
1045 	 * Copy the credential so other references don't see our changes.
1046 	 * Test to see if this is necessary first, since in the common case
1047 	 * we won't need a private reference.
1048 	 */
1049 	if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
1050 	    kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
1051 		l->l_cred = kauth_cred_copy(l->l_cred);
1052 		kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
1053 		kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
1054 	}
1055 
1056 	/* Update the master credentials. */
1057 	if (l->l_cred != p->p_cred) {
1058 		kauth_cred_t ocred;
1059 
1060 		kauth_cred_hold(l->l_cred);
1061 		mutex_enter(p->p_lock);
1062 		ocred = p->p_cred;
1063 		p->p_cred = l->l_cred;
1064 		mutex_exit(p->p_lock);
1065 		kauth_cred_free(ocred);
1066 	}
1067 
1068 #if defined(__HAVE_RAS)
1069 	/*
1070 	 * Remove all RASs from the address space.
1071 	 */
1072 	ras_purgeall();
1073 #endif
1074 
1075 	doexechooks(p);
1076 
1077 	/* setup new registers and do misc. setup. */
1078 	(*pack.ep_esch->es_emul->e_setregs)(l, &pack, (vaddr_t)stack);
1079 	if (pack.ep_esch->es_setregs)
1080 		(*pack.ep_esch->es_setregs)(l, &pack, (vaddr_t)stack);
1081 
1082 	/* map the process's signal trampoline code */
1083 	if (exec_sigcode_map(p, pack.ep_esch->es_emul)) {
1084 		DPRINTF(("execve: map sigcode failed %d\n", error));
1085 		goto exec_abort;
1086 	}
1087 
1088 	pool_put(&exec_pool, argp);
1089 
1090 	/* notify others that we exec'd */
1091 	KNOTE(&p->p_klist, NOTE_EXEC);
1092 
1093 	kmem_free(pack.ep_hdr, pack.ep_hdrlen);
1094 
1095 	SDT_PROBE(proc,,,exec_success, path, 0, 0, 0, 0);
1096 
1097 	/* The emulation root will usually have been found when we looked
1098 	 * for the elf interpreter (or similar), if not look now. */
1099 	if (pack.ep_esch->es_emul->e_path != NULL && pack.ep_emul_root == NULL)
1100 		emul_find_root(l, &pack);
1101 
1102 	/* Any old emulation root got removed by fdcloseexec */
1103 	rw_enter(&p->p_cwdi->cwdi_lock, RW_WRITER);
1104 	p->p_cwdi->cwdi_edir = pack.ep_emul_root;
1105 	rw_exit(&p->p_cwdi->cwdi_lock);
1106 	pack.ep_emul_root = NULL;
1107 	if (pack.ep_interp != NULL)
1108 		vrele(pack.ep_interp);
1109 
1110 	/*
1111 	 * Call emulation specific exec hook. This can setup per-process
1112 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
1113 	 *
1114 	 * If we are executing process of different emulation than the
1115 	 * original forked process, call e_proc_exit() of the old emulation
1116 	 * first, then e_proc_exec() of new emulation. If the emulation is
1117 	 * same, the exec hook code should deallocate any old emulation
1118 	 * resources held previously by this process.
1119 	 */
1120 	if (p->p_emul && p->p_emul->e_proc_exit
1121 	    && p->p_emul != pack.ep_esch->es_emul)
1122 		(*p->p_emul->e_proc_exit)(p);
1123 
1124 	/*
1125 	 * This is now LWP 1.
1126 	 */
1127 	mutex_enter(p->p_lock);
1128 	p->p_nlwpid = 1;
1129 	l->l_lid = 1;
1130 	mutex_exit(p->p_lock);
1131 
1132 	/*
1133 	 * Call exec hook. Emulation code may NOT store reference to anything
1134 	 * from &pack.
1135 	 */
1136         if (pack.ep_esch->es_emul->e_proc_exec)
1137                 (*pack.ep_esch->es_emul->e_proc_exec)(p, &pack);
1138 
1139 	/* update p_emul, the old value is no longer needed */
1140 	p->p_emul = pack.ep_esch->es_emul;
1141 
1142 	/* ...and the same for p_execsw */
1143 	p->p_execsw = pack.ep_esch;
1144 
1145 #ifdef __HAVE_SYSCALL_INTERN
1146 	(*p->p_emul->e_syscall_intern)(p);
1147 #endif
1148 	ktremul();
1149 
1150 	/* Allow new references from the debugger/procfs. */
1151 	rw_exit(&p->p_reflock);
1152 	rw_exit(&exec_lock);
1153 
1154 	mutex_enter(proc_lock);
1155 
1156 	if ((p->p_slflag & (PSL_TRACED|PSL_SYSCALL)) == PSL_TRACED) {
1157 		KSI_INIT_EMPTY(&ksi);
1158 		ksi.ksi_signo = SIGTRAP;
1159 		ksi.ksi_lid = l->l_lid;
1160 		kpsignal(p, &ksi, NULL);
1161 	}
1162 
1163 	if (p->p_sflag & PS_STOPEXEC) {
1164 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
1165 		p->p_pptr->p_nstopchild++;
1166 		p->p_pptr->p_waited = 0;
1167 		mutex_enter(p->p_lock);
1168 		ksiginfo_queue_init(&kq);
1169 		sigclearall(p, &contsigmask, &kq);
1170 		lwp_lock(l);
1171 		l->l_stat = LSSTOP;
1172 		p->p_stat = SSTOP;
1173 		p->p_nrlwps--;
1174 		mutex_exit(p->p_lock);
1175 		mutex_exit(proc_lock);
1176 		mi_switch(l);
1177 		ksiginfo_queue_drain(&kq);
1178 		KERNEL_LOCK(l->l_biglocks, l);
1179 	} else {
1180 		mutex_exit(proc_lock);
1181 	}
1182 
1183 	PNBUF_PUT(pathbuf);
1184 	PNBUF_PUT(resolvedpathbuf);
1185 	return (EJUSTRETURN);
1186 
1187  bad:
1188 	/* free the vmspace-creation commands, and release their references */
1189 	kill_vmcmds(&pack.ep_vmcmds);
1190 	/* kill any opened file descriptor, if necessary */
1191 	if (pack.ep_flags & EXEC_HASFD) {
1192 		pack.ep_flags &= ~EXEC_HASFD;
1193 		fd_close(pack.ep_fd);
1194 	}
1195 	/* close and put the exec'd file */
1196 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
1197 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred);
1198 	vput(pack.ep_vp);
1199 	pool_put(&exec_pool, argp);
1200 
1201  freehdr:
1202 	kmem_free(pack.ep_hdr, pack.ep_hdrlen);
1203 	if (pack.ep_emul_root != NULL)
1204 		vrele(pack.ep_emul_root);
1205 	if (pack.ep_interp != NULL)
1206 		vrele(pack.ep_interp);
1207 
1208 	rw_exit(&exec_lock);
1209 
1210 	PNBUF_PUT(resolvedpathbuf);
1211 
1212  clrflg:
1213 	lwp_lock(l);
1214 	l->l_flag |= oldlwpflags;
1215 	lwp_unlock(l);
1216 	rw_exit(&p->p_reflock);
1217 
1218 	PNBUF_PUT(pathbuf);
1219 
1220 	if (modgen != module_gen && error == ENOEXEC) {
1221 		modgen = module_gen;
1222 		exec_autoload();
1223 		goto retry;
1224 	}
1225 
1226 	SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
1227 	return error;
1228 
1229  exec_abort:
1230 	SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
1231 	rw_exit(&p->p_reflock);
1232 	rw_exit(&exec_lock);
1233 
1234 	PNBUF_PUT(pathbuf);
1235 	PNBUF_PUT(resolvedpathbuf);
1236 
1237 	/*
1238 	 * the old process doesn't exist anymore.  exit gracefully.
1239 	 * get rid of the (new) address space we have created, if any, get rid
1240 	 * of our namei data and vnode, and exit noting failure
1241 	 */
1242 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
1243 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
1244 	if (pack.ep_emul_arg)
1245 		free(pack.ep_emul_arg, M_TEMP);
1246 	pool_put(&exec_pool, argp);
1247 	kmem_free(pack.ep_hdr, pack.ep_hdrlen);
1248 	if (pack.ep_emul_root != NULL)
1249 		vrele(pack.ep_emul_root);
1250 	if (pack.ep_interp != NULL)
1251 		vrele(pack.ep_interp);
1252 
1253 	/* Acquire the sched-state mutex (exit1() will release it). */
1254 	mutex_enter(p->p_lock);
1255 	exit1(l, W_EXITCODE(error, SIGABRT));
1256 
1257 	/* NOTREACHED */
1258 	return 0;
1259 }
1260 
1261 
1262 int
1263 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
1264     char **stackp, void *argp)
1265 {
1266 	char	**cpp, *dp, *sp;
1267 	size_t	len;
1268 	void	*nullp;
1269 	long	argc, envc;
1270 	int	error;
1271 
1272 	cpp = (char **)*stackp;
1273 	nullp = NULL;
1274 	argc = arginfo->ps_nargvstr;
1275 	envc = arginfo->ps_nenvstr;
1276 	if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0)
1277 		return error;
1278 
1279 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_esch->es_arglen);
1280 	sp = argp;
1281 
1282 	/* XXX don't copy them out, remap them! */
1283 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
1284 
1285 	for (; --argc >= 0; sp += len, dp += len)
1286 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
1287 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
1288 			return error;
1289 
1290 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
1291 		return error;
1292 
1293 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
1294 
1295 	for (; --envc >= 0; sp += len, dp += len)
1296 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
1297 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
1298 			return error;
1299 
1300 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
1301 		return error;
1302 
1303 	*stackp = (char *)cpp;
1304 	return 0;
1305 }
1306 
1307 
1308 /*
1309  * Add execsw[] entries.
1310  */
1311 int
1312 exec_add(struct execsw *esp, int count)
1313 {
1314 	struct exec_entry	*it;
1315 	int			i;
1316 
1317 	if (count == 0) {
1318 		return 0;
1319 	}
1320 
1321 	/* Check for duplicates. */
1322 	rw_enter(&exec_lock, RW_WRITER);
1323 	for (i = 0; i < count; i++) {
1324 		LIST_FOREACH(it, &ex_head, ex_list) {
1325 			/* assume unique (makecmds, probe_func, emulation) */
1326 			if (it->ex_sw->es_makecmds == esp[i].es_makecmds &&
1327 			    it->ex_sw->u.elf_probe_func ==
1328 			    esp[i].u.elf_probe_func &&
1329 			    it->ex_sw->es_emul == esp[i].es_emul) {
1330 				rw_exit(&exec_lock);
1331 				return EEXIST;
1332 			}
1333 		}
1334 	}
1335 
1336 	/* Allocate new entries. */
1337 	for (i = 0; i < count; i++) {
1338 		it = kmem_alloc(sizeof(*it), KM_SLEEP);
1339 		it->ex_sw = &esp[i];
1340 		LIST_INSERT_HEAD(&ex_head, it, ex_list);
1341 	}
1342 
1343 	/* update execsw[] */
1344 	exec_init(0);
1345 	rw_exit(&exec_lock);
1346 	return 0;
1347 }
1348 
1349 /*
1350  * Remove execsw[] entry.
1351  */
1352 int
1353 exec_remove(struct execsw *esp, int count)
1354 {
1355 	struct exec_entry	*it, *next;
1356 	int			i;
1357 	const struct proclist_desc *pd;
1358 	proc_t			*p;
1359 
1360 	if (count == 0) {
1361 		return 0;
1362 	}
1363 
1364 	/* Abort if any are busy. */
1365 	rw_enter(&exec_lock, RW_WRITER);
1366 	for (i = 0; i < count; i++) {
1367 		mutex_enter(proc_lock);
1368 		for (pd = proclists; pd->pd_list != NULL; pd++) {
1369 			PROCLIST_FOREACH(p, pd->pd_list) {
1370 				if (p->p_execsw == &esp[i]) {
1371 					mutex_exit(proc_lock);
1372 					rw_exit(&exec_lock);
1373 					return EBUSY;
1374 				}
1375 			}
1376 		}
1377 		mutex_exit(proc_lock);
1378 	}
1379 
1380 	/* None are busy, so remove them all. */
1381 	for (i = 0; i < count; i++) {
1382 		for (it = LIST_FIRST(&ex_head); it != NULL; it = next) {
1383 			next = LIST_NEXT(it, ex_list);
1384 			if (it->ex_sw == &esp[i]) {
1385 				LIST_REMOVE(it, ex_list);
1386 				kmem_free(it, sizeof(*it));
1387 				break;
1388 			}
1389 		}
1390 	}
1391 
1392 	/* update execsw[] */
1393 	exec_init(0);
1394 	rw_exit(&exec_lock);
1395 	return 0;
1396 }
1397 
1398 /*
1399  * Initialize exec structures. If init_boot is true, also does necessary
1400  * one-time initialization (it's called from main() that way).
1401  * Once system is multiuser, this should be called with exec_lock held,
1402  * i.e. via exec_{add|remove}().
1403  */
1404 int
1405 exec_init(int init_boot)
1406 {
1407 	const struct execsw 	**sw;
1408 	struct exec_entry	*ex;
1409 	SLIST_HEAD(,exec_entry)	first;
1410 	SLIST_HEAD(,exec_entry)	any;
1411 	SLIST_HEAD(,exec_entry)	last;
1412 	int			i, sz;
1413 
1414 	if (init_boot) {
1415 		/* do one-time initializations */
1416 		rw_init(&exec_lock);
1417 		mutex_init(&sigobject_lock, MUTEX_DEFAULT, IPL_NONE);
1418 		pool_init(&exec_pool, NCARGS, 0, 0, PR_NOALIGN|PR_NOTOUCH,
1419 		    "execargs", &exec_palloc, IPL_NONE);
1420 		pool_sethardlimit(&exec_pool, maxexec, "should not happen", 0);
1421 	} else {
1422 		KASSERT(rw_write_held(&exec_lock));
1423 	}
1424 
1425 	/* Sort each entry onto the appropriate queue. */
1426 	SLIST_INIT(&first);
1427 	SLIST_INIT(&any);
1428 	SLIST_INIT(&last);
1429 	sz = 0;
1430 	LIST_FOREACH(ex, &ex_head, ex_list) {
1431 		switch(ex->ex_sw->es_prio) {
1432 		case EXECSW_PRIO_FIRST:
1433 			SLIST_INSERT_HEAD(&first, ex, ex_slist);
1434 			break;
1435 		case EXECSW_PRIO_ANY:
1436 			SLIST_INSERT_HEAD(&any, ex, ex_slist);
1437 			break;
1438 		case EXECSW_PRIO_LAST:
1439 			SLIST_INSERT_HEAD(&last, ex, ex_slist);
1440 			break;
1441 		default:
1442 			panic("exec_init");
1443 			break;
1444 		}
1445 		sz++;
1446 	}
1447 
1448 	/*
1449 	 * Create new execsw[].  Ensure we do not try a zero-sized
1450 	 * allocation.
1451 	 */
1452 	sw = kmem_alloc(sz * sizeof(struct execsw *) + 1, KM_SLEEP);
1453 	i = 0;
1454 	SLIST_FOREACH(ex, &first, ex_slist) {
1455 		sw[i++] = ex->ex_sw;
1456 	}
1457 	SLIST_FOREACH(ex, &any, ex_slist) {
1458 		sw[i++] = ex->ex_sw;
1459 	}
1460 	SLIST_FOREACH(ex, &last, ex_slist) {
1461 		sw[i++] = ex->ex_sw;
1462 	}
1463 
1464 	/* Replace old execsw[] and free used memory. */
1465 	if (execsw != NULL) {
1466 		kmem_free(__UNCONST(execsw),
1467 		    nexecs * sizeof(struct execsw *) + 1);
1468 	}
1469 	execsw = sw;
1470 	nexecs = sz;
1471 
1472 	/* Figure out the maximum size of an exec header. */
1473 	exec_maxhdrsz = sizeof(int);
1474 	for (i = 0; i < nexecs; i++) {
1475 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
1476 			exec_maxhdrsz = execsw[i]->es_hdrsz;
1477 	}
1478 
1479 	return 0;
1480 }
1481 
1482 static int
1483 exec_sigcode_map(struct proc *p, const struct emul *e)
1484 {
1485 	vaddr_t va;
1486 	vsize_t sz;
1487 	int error;
1488 	struct uvm_object *uobj;
1489 
1490 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
1491 
1492 	if (e->e_sigobject == NULL || sz == 0) {
1493 		return 0;
1494 	}
1495 
1496 	/*
1497 	 * If we don't have a sigobject for this emulation, create one.
1498 	 *
1499 	 * sigobject is an anonymous memory object (just like SYSV shared
1500 	 * memory) that we keep a permanent reference to and that we map
1501 	 * in all processes that need this sigcode. The creation is simple,
1502 	 * we create an object, add a permanent reference to it, map it in
1503 	 * kernel space, copy out the sigcode to it and unmap it.
1504 	 * We map it with PROT_READ|PROT_EXEC into the process just
1505 	 * the way sys_mmap() would map it.
1506 	 */
1507 
1508 	uobj = *e->e_sigobject;
1509 	if (uobj == NULL) {
1510 		mutex_enter(&sigobject_lock);
1511 		if ((uobj = *e->e_sigobject) == NULL) {
1512 			uobj = uao_create(sz, 0);
1513 			(*uobj->pgops->pgo_reference)(uobj);
1514 			va = vm_map_min(kernel_map);
1515 			if ((error = uvm_map(kernel_map, &va, round_page(sz),
1516 			    uobj, 0, 0,
1517 			    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
1518 			    UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
1519 				printf("kernel mapping failed %d\n", error);
1520 				(*uobj->pgops->pgo_detach)(uobj);
1521 				mutex_exit(&sigobject_lock);
1522 				return (error);
1523 			}
1524 			memcpy((void *)va, e->e_sigcode, sz);
1525 #ifdef PMAP_NEED_PROCWR
1526 			pmap_procwr(&proc0, va, sz);
1527 #endif
1528 			uvm_unmap(kernel_map, va, va + round_page(sz));
1529 			*e->e_sigobject = uobj;
1530 		}
1531 		mutex_exit(&sigobject_lock);
1532 	}
1533 
1534 	/* Just a hint to uvm_map where to put it. */
1535 	va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
1536 	    round_page(sz));
1537 
1538 #ifdef __alpha__
1539 	/*
1540 	 * Tru64 puts /sbin/loader at the end of user virtual memory,
1541 	 * which causes the above calculation to put the sigcode at
1542 	 * an invalid address.  Put it just below the text instead.
1543 	 */
1544 	if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
1545 		va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
1546 	}
1547 #endif
1548 
1549 	(*uobj->pgops->pgo_reference)(uobj);
1550 	error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
1551 			uobj, 0, 0,
1552 			UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
1553 				    UVM_ADV_RANDOM, 0));
1554 	if (error) {
1555 		(*uobj->pgops->pgo_detach)(uobj);
1556 		return (error);
1557 	}
1558 	p->p_sigctx.ps_sigcode = (void *)va;
1559 	return (0);
1560 }
1561