xref: /netbsd-src/sys/kern/kern_exec.c (revision 62a8debe1dc62962e18a1c918def78666141273b)
1 /*	$NetBSD: kern_exec.c,v 1.294 2010/03/01 21:10:15 darran 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.294 2010/03/01 21:10:15 darran 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)
282 {
283 	int		error, i;
284 	struct vnode	*vp;
285 	struct nameidata *ndp;
286 	size_t		resid;
287 
288 	ndp = epp->ep_ndp;
289 	ndp->ni_cnd.cn_nameiop = LOOKUP;
290 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME | TRYEMULROOT;
291 	/* first get the vnode */
292 	if ((error = namei(ndp)) != 0)
293 		return error;
294 	epp->ep_vp = vp = ndp->ni_vp;
295 
296 	/* check access and type */
297 	if (vp->v_type != VREG) {
298 		error = EACCES;
299 		goto bad1;
300 	}
301 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
302 		goto bad1;
303 
304 	/* get attributes */
305 	if ((error = VOP_GETATTR(vp, epp->ep_vap, l->l_cred)) != 0)
306 		goto bad1;
307 
308 	/* Check mount point */
309 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
310 		error = EACCES;
311 		goto bad1;
312 	}
313 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
314 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
315 
316 	/* try to open it */
317 	if ((error = VOP_OPEN(vp, FREAD, l->l_cred)) != 0)
318 		goto bad1;
319 
320 	/* unlock vp, since we need it unlocked from here on out. */
321 	VOP_UNLOCK(vp, 0);
322 
323 #if NVERIEXEC > 0
324 	error = veriexec_verify(l, vp, ndp->ni_cnd.cn_pnbuf,
325 	    epp->ep_flags & EXEC_INDIR ? VERIEXEC_INDIRECT : VERIEXEC_DIRECT,
326 	    NULL);
327 	if (error)
328 		goto bad2;
329 #endif /* NVERIEXEC > 0 */
330 
331 #ifdef PAX_SEGVGUARD
332 	error = pax_segvguard(l, vp, ndp->ni_cnd.cn_pnbuf, false);
333 	if (error)
334 		goto bad2;
335 #endif /* PAX_SEGVGUARD */
336 
337 	/* now we have the file, get the exec header */
338 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
339 			UIO_SYSSPACE, 0, l->l_cred, &resid, NULL);
340 	if (error)
341 		goto bad2;
342 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
343 
344 	/*
345 	 * Set up default address space limits.  Can be overridden
346 	 * by individual exec packages.
347 	 *
348 	 * XXX probably should be all done in the exec packages.
349 	 */
350 	epp->ep_vm_minaddr = VM_MIN_ADDRESS;
351 	epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
352 	/*
353 	 * set up the vmcmds for creation of the process
354 	 * address space
355 	 */
356 	error = ENOEXEC;
357 	for (i = 0; i < nexecs; i++) {
358 		int newerror;
359 
360 		epp->ep_esch = execsw[i];
361 		newerror = (*execsw[i]->es_makecmds)(l, epp);
362 
363 		if (!newerror) {
364 			/* Seems ok: check that entry point is sane */
365 			if (epp->ep_entry > VM_MAXUSER_ADDRESS) {
366 				error = ENOEXEC;
367 				break;
368 			}
369 
370 			/* check limits */
371 			if ((epp->ep_tsize > MAXTSIZ) ||
372 			    (epp->ep_dsize > (u_quad_t)l->l_proc->p_rlimit
373 						    [RLIMIT_DATA].rlim_cur)) {
374 				error = ENOMEM;
375 				break;
376 			}
377 			return 0;
378 		}
379 
380 		if (epp->ep_emul_root != NULL) {
381 			vrele(epp->ep_emul_root);
382 			epp->ep_emul_root = NULL;
383 		}
384 		if (epp->ep_interp != NULL) {
385 			vrele(epp->ep_interp);
386 			epp->ep_interp = NULL;
387 		}
388 
389 		/* make sure the first "interesting" error code is saved. */
390 		if (error == ENOEXEC)
391 			error = newerror;
392 
393 		if (epp->ep_flags & EXEC_DESTR)
394 			/* Error from "#!" code, tidied up by recursive call */
395 			return error;
396 	}
397 
398 	/* not found, error */
399 
400 	/*
401 	 * free any vmspace-creation commands,
402 	 * and release their references
403 	 */
404 	kill_vmcmds(&epp->ep_vmcmds);
405 
406 bad2:
407 	/*
408 	 * close and release the vnode, restore the old one, free the
409 	 * pathname buf, and punt.
410 	 */
411 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
412 	VOP_CLOSE(vp, FREAD, l->l_cred);
413 	vput(vp);
414 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
415 	return error;
416 
417 bad1:
418 	/*
419 	 * free the namei pathname buffer, and put the vnode
420 	 * (which we don't yet have open).
421 	 */
422 	vput(vp);				/* was still locked */
423 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
424 	return error;
425 }
426 
427 #ifdef __MACHINE_STACK_GROWS_UP
428 #define STACK_PTHREADSPACE NBPG
429 #else
430 #define STACK_PTHREADSPACE 0
431 #endif
432 
433 static int
434 execve_fetch_element(char * const *array, size_t index, char **value)
435 {
436 	return copyin(array + index, value, sizeof(*value));
437 }
438 
439 /*
440  * exec system call
441  */
442 /* ARGSUSED */
443 int
444 sys_execve(struct lwp *l, const struct sys_execve_args *uap, register_t *retval)
445 {
446 	/* {
447 		syscallarg(const char *)	path;
448 		syscallarg(char * const *)	argp;
449 		syscallarg(char * const *)	envp;
450 	} */
451 
452 	return execve1(l, SCARG(uap, path), SCARG(uap, argp),
453 	    SCARG(uap, envp), execve_fetch_element);
454 }
455 
456 /*
457  * Load modules to try and execute an image that we do not understand.
458  * If no execsw entries are present, we load those likely to be needed
459  * in order to run native images only.  Otherwise, we autoload all
460  * possible modules that could let us run the binary.  XXX lame
461  */
462 static void
463 exec_autoload(void)
464 {
465 #ifdef MODULAR
466 	static const char * const native[] = {
467 		"exec_elf32",
468 		"exec_elf64",
469 		"exec_script",
470 		NULL
471 	};
472 	static const char * const compat[] = {
473 		"exec_elf32",
474 		"exec_elf64",
475 		"exec_script",
476 		"exec_aout",
477 		"exec_coff",
478 		"exec_ecoff",
479 		"compat_aoutm68k",
480 		"compat_freebsd",
481 		"compat_ibcs2",
482 		"compat_irix",
483 		"compat_linux",
484 		"compat_linux32",
485 		"compat_netbsd32",
486 		"compat_sunos",
487 		"compat_sunos32",
488 		"compat_svr4",
489 		"compat_svr4_32",
490 		"compat_ultrix",
491 		NULL
492 	};
493 	char const * const *list;
494 	int i;
495 
496 	mutex_enter(&module_lock);
497 	list = (nexecs == 0 ? native : compat);
498 	for (i = 0; list[i] != NULL; i++) {
499 		if (module_autoload(list[i], MODULE_CLASS_MISC) != 0) {
500 		    	continue;
501 		}
502 		mutex_exit(&module_lock);
503 	   	yield();
504 		mutex_enter(&module_lock);
505 	}
506 	mutex_exit(&module_lock);
507 #endif
508 }
509 
510 int
511 execve1(struct lwp *l, const char *path, char * const *args,
512     char * const *envs, execve_fetch_element_t fetch_element)
513 {
514 	int			error;
515 	struct exec_package	pack;
516 	struct nameidata	nid;
517 	struct vattr		attr;
518 	struct proc		*p;
519 	char			*argp;
520 	char			*dp, *sp;
521 	long			argc, envc;
522 	size_t			i, len;
523 	char			*stack;
524 	struct ps_strings	arginfo;
525 	struct ps_strings	*aip = &arginfo;
526 	struct vmspace		*vm;
527 	struct exec_fakearg	*tmpfap;
528 	int			szsigcode;
529 	struct exec_vmcmd	*base_vcp;
530 	int			oldlwpflags;
531 	ksiginfo_t		ksi;
532 	ksiginfoq_t		kq;
533 	char			*pathbuf;
534 	size_t			pathbuflen;
535 	u_int			modgen;
536 
537 	p = l->l_proc;
538  	modgen = 0;
539 
540 	SDT_PROBE(proc,,,exec, path, 0, 0, 0, 0);
541 
542 	/*
543 	 * Check if we have exceeded our number of processes limit.
544 	 * This is so that we handle the case where a root daemon
545 	 * forked, ran setuid to become the desired user and is trying
546 	 * to exec. The obvious place to do the reference counting check
547 	 * is setuid(), but we don't do the reference counting check there
548 	 * like other OS's do because then all the programs that use setuid()
549 	 * must be modified to check the return code of setuid() and exit().
550 	 * It is dangerous to make setuid() fail, because it fails open and
551 	 * the program will continue to run as root. If we make it succeed
552 	 * and return an error code, again we are not enforcing the limit.
553 	 * The best place to enforce the limit is here, when the process tries
554 	 * to execute a new image, because eventually the process will need
555 	 * to call exec in order to do something useful.
556 	 */
557  retry:
558 	if ((p->p_flag & PK_SUGID) && kauth_authorize_generic(l->l_cred,
559 	    KAUTH_GENERIC_ISSUSER, NULL) != 0 && chgproccnt(kauth_cred_getuid(
560 	    l->l_cred), 0) > p->p_rlimit[RLIMIT_NPROC].rlim_cur)
561 		return EAGAIN;
562 
563 	oldlwpflags = l->l_flag & (LW_SA | LW_SA_UPCALL);
564 	if (l->l_flag & LW_SA) {
565 		lwp_lock(l);
566 		l->l_flag &= ~(LW_SA | LW_SA_UPCALL);
567 		lwp_unlock(l);
568 	}
569 
570 	/*
571 	 * Drain existing references and forbid new ones.  The process
572 	 * should be left alone until we're done here.  This is necessary
573 	 * to avoid race conditions - e.g. in ptrace() - that might allow
574 	 * a local user to illicitly obtain elevated privileges.
575 	 */
576 	rw_enter(&p->p_reflock, RW_WRITER);
577 
578 	base_vcp = NULL;
579 	/*
580 	 * Init the namei data to point the file user's program name.
581 	 * This is done here rather than in check_exec(), so that it's
582 	 * possible to override this settings if any of makecmd/probe
583 	 * functions call check_exec() recursively - for example,
584 	 * see exec_script_makecmds().
585 	 */
586 	pathbuf = PNBUF_GET();
587 	error = copyinstr(path, pathbuf, MAXPATHLEN, &pathbuflen);
588 	if (error) {
589 		DPRINTF(("execve: copyinstr path %d", error));
590 		goto clrflg;
591 	}
592 
593 	NDINIT(&nid, LOOKUP, NOFOLLOW | TRYEMULROOT, UIO_SYSSPACE, pathbuf);
594 
595 	/*
596 	 * initialize the fields of the exec package.
597 	 */
598 	pack.ep_name = path;
599 	pack.ep_hdr = kmem_alloc(exec_maxhdrsz, KM_SLEEP);
600 	pack.ep_hdrlen = exec_maxhdrsz;
601 	pack.ep_hdrvalid = 0;
602 	pack.ep_ndp = &nid;
603 	pack.ep_emul_arg = NULL;
604 	pack.ep_vmcmds.evs_cnt = 0;
605 	pack.ep_vmcmds.evs_used = 0;
606 	pack.ep_vap = &attr;
607 	pack.ep_flags = 0;
608 	pack.ep_emul_root = NULL;
609 	pack.ep_interp = NULL;
610 	pack.ep_esch = NULL;
611 	pack.ep_pax_flags = 0;
612 
613 	rw_enter(&exec_lock, RW_READER);
614 
615 	/* see if we can run it. */
616 	if ((error = check_exec(l, &pack)) != 0) {
617 		if (error != ENOENT) {
618 			DPRINTF(("execve: check exec failed %d\n", error));
619 		}
620 		goto freehdr;
621 	}
622 
623 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
624 
625 	/* allocate an argument buffer */
626 	argp = pool_get(&exec_pool, PR_WAITOK);
627 	KASSERT(argp != NULL);
628 	dp = argp;
629 	argc = 0;
630 
631 	/* copy the fake args list, if there's one, freeing it as we go */
632 	if (pack.ep_flags & EXEC_HASARGL) {
633 		tmpfap = pack.ep_fa;
634 		while (tmpfap->fa_arg != NULL) {
635 			const char *cp;
636 
637 			cp = tmpfap->fa_arg;
638 			while (*cp)
639 				*dp++ = *cp++;
640 			*dp++ = '\0';
641 			ktrexecarg(tmpfap->fa_arg, cp - tmpfap->fa_arg);
642 
643 			kmem_free(tmpfap->fa_arg, tmpfap->fa_len);
644 			tmpfap++; argc++;
645 		}
646 		kmem_free(pack.ep_fa, pack.ep_fa_len);
647 		pack.ep_flags &= ~EXEC_HASARGL;
648 	}
649 
650 	/* Now get argv & environment */
651 	if (args == NULL) {
652 		DPRINTF(("execve: null args\n"));
653 		error = EINVAL;
654 		goto bad;
655 	}
656 	/* 'i' will index the argp/envp element to be retrieved */
657 	i = 0;
658 	if (pack.ep_flags & EXEC_SKIPARG)
659 		i++;
660 
661 	while (1) {
662 		len = argp + ARG_MAX - dp;
663 		if ((error = (*fetch_element)(args, i, &sp)) != 0) {
664 			DPRINTF(("execve: fetch_element args %d\n", error));
665 			goto bad;
666 		}
667 		if (!sp)
668 			break;
669 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
670 			DPRINTF(("execve: copyinstr args %d\n", error));
671 			if (error == ENAMETOOLONG)
672 				error = E2BIG;
673 			goto bad;
674 		}
675 		ktrexecarg(dp, len - 1);
676 		dp += len;
677 		i++;
678 		argc++;
679 	}
680 
681 	envc = 0;
682 	/* environment need not be there */
683 	if (envs != NULL) {
684 		i = 0;
685 		while (1) {
686 			len = argp + ARG_MAX - dp;
687 			if ((error = (*fetch_element)(envs, i, &sp)) != 0) {
688 				DPRINTF(("execve: fetch_element env %d\n", error));
689 				goto bad;
690 			}
691 			if (!sp)
692 				break;
693 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
694 				DPRINTF(("execve: copyinstr env %d\n", error));
695 				if (error == ENAMETOOLONG)
696 					error = E2BIG;
697 				goto bad;
698 			}
699 			ktrexecenv(dp, len - 1);
700 			dp += len;
701 			i++;
702 			envc++;
703 		}
704 	}
705 
706 	dp = (char *) ALIGN(dp);
707 
708 	szsigcode = pack.ep_esch->es_emul->e_esigcode -
709 	    pack.ep_esch->es_emul->e_sigcode;
710 
711 #ifdef __MACHINE_STACK_GROWS_UP
712 /* See big comment lower down */
713 #define	RTLD_GAP	32
714 #else
715 #define	RTLD_GAP	0
716 #endif
717 
718 	/* Now check if args & environ fit into new stack */
719 	if (pack.ep_flags & EXEC_32)
720 		len = ((argc + envc + 2 + pack.ep_esch->es_arglen) *
721 		    sizeof(int) + sizeof(int) + dp + RTLD_GAP +
722 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
723 		    - argp;
724 	else
725 		len = ((argc + envc + 2 + pack.ep_esch->es_arglen) *
726 		    sizeof(char *) + sizeof(int) + dp + RTLD_GAP +
727 		    szsigcode + sizeof(struct ps_strings) + STACK_PTHREADSPACE)
728 		    - argp;
729 
730 #ifdef PAX_ASLR
731 	if (pax_aslr_active(l))
732 		len += (arc4random() % PAGE_SIZE);
733 #endif /* PAX_ASLR */
734 
735 #ifdef STACKLALIGN	/* arm, etc. */
736 	len = STACKALIGN(len);	/* make the stack "safely" aligned */
737 #else
738 	len = ALIGN(len);	/* make the stack "safely" aligned */
739 #endif
740 
741 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
742 		DPRINTF(("execve: stack limit exceeded %zu\n", len));
743 		error = ENOMEM;
744 		goto bad;
745 	}
746 
747 	/* Get rid of other LWPs. */
748 	if (p->p_sa || p->p_nlwps > 1) {
749 		mutex_enter(p->p_lock);
750 		exit_lwps(l);
751 		mutex_exit(p->p_lock);
752 	}
753 	KDASSERT(p->p_nlwps == 1);
754 
755 	/* Destroy any lwpctl info. */
756 	if (p->p_lwpctl != NULL)
757 		lwp_ctl_exit();
758 
759 	/* This is now LWP 1 */
760 	l->l_lid = 1;
761 	p->p_nlwpid = 1;
762 
763 #ifdef KERN_SA
764 	/* Release any SA state. */
765 	if (p->p_sa)
766 		sa_release(p);
767 #endif /* KERN_SA */
768 
769 	/* Remove POSIX timers */
770 	timers_free(p, TIMERS_POSIX);
771 
772 	/* adjust "active stack depth" for process VSZ */
773 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
774 
775 	/*
776 	 * Do whatever is necessary to prepare the address space
777 	 * for remapping.  Note that this might replace the current
778 	 * vmspace with another!
779 	 */
780 	uvmspace_exec(l, pack.ep_vm_minaddr, pack.ep_vm_maxaddr);
781 
782 	/* record proc's vnode, for use by procfs and others */
783         if (p->p_textvp)
784                 vrele(p->p_textvp);
785 	vref(pack.ep_vp);
786 	p->p_textvp = pack.ep_vp;
787 
788 	/* Now map address space */
789 	vm = p->p_vmspace;
790 	vm->vm_taddr = (void *)pack.ep_taddr;
791 	vm->vm_tsize = btoc(pack.ep_tsize);
792 	vm->vm_daddr = (void*)pack.ep_daddr;
793 	vm->vm_dsize = btoc(pack.ep_dsize);
794 	vm->vm_ssize = btoc(pack.ep_ssize);
795 	vm->vm_issize = 0;
796 	vm->vm_maxsaddr = (void *)pack.ep_maxsaddr;
797 	vm->vm_minsaddr = (void *)pack.ep_minsaddr;
798 
799 #ifdef PAX_ASLR
800 	pax_aslr_init(l, vm);
801 #endif /* PAX_ASLR */
802 
803 	/* create the new process's VM space by running the vmcmds */
804 #ifdef DIAGNOSTIC
805 	if (pack.ep_vmcmds.evs_used == 0)
806 		panic("execve: no vmcmds");
807 #endif
808 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
809 		struct exec_vmcmd *vcp;
810 
811 		vcp = &pack.ep_vmcmds.evs_cmds[i];
812 		if (vcp->ev_flags & VMCMD_RELATIVE) {
813 #ifdef DIAGNOSTIC
814 			if (base_vcp == NULL)
815 				panic("execve: relative vmcmd with no base");
816 			if (vcp->ev_flags & VMCMD_BASE)
817 				panic("execve: illegal base & relative vmcmd");
818 #endif
819 			vcp->ev_addr += base_vcp->ev_addr;
820 		}
821 		error = (*vcp->ev_proc)(l, vcp);
822 #ifdef DEBUG_EXEC
823 		if (error) {
824 			size_t j;
825 			struct exec_vmcmd *vp = &pack.ep_vmcmds.evs_cmds[0];
826 			for (j = 0; j <= i; j++)
827 				uprintf(
828 			"vmcmd[%zu] = %#lx/%#lx fd@%#lx prot=0%o flags=%d\n",
829 				    j, vp[j].ev_addr, vp[j].ev_len,
830 				    vp[j].ev_offset, vp[j].ev_prot,
831 				    vp[j].ev_flags);
832 		}
833 #endif /* DEBUG_EXEC */
834 		if (vcp->ev_flags & VMCMD_BASE)
835 			base_vcp = vcp;
836 	}
837 
838 	/* free the vmspace-creation commands, and release their references */
839 	kill_vmcmds(&pack.ep_vmcmds);
840 
841 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
842 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred);
843 	vput(pack.ep_vp);
844 
845 	/* if an error happened, deallocate and punt */
846 	if (error) {
847 		DPRINTF(("execve: vmcmd %zu failed: %d\n", i - 1, error));
848 		goto exec_abort;
849 	}
850 
851 	/* remember information about the process */
852 	arginfo.ps_nargvstr = argc;
853 	arginfo.ps_nenvstr = envc;
854 
855 	/* set command name & other accounting info */
856 	i = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
857 	(void)memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, i);
858 	p->p_comm[i] = '\0';
859 
860 	dp = PNBUF_GET();
861 	/*
862 	 * If the path starts with /, we don't need to do any work.
863 	 * This handles the majority of the cases.
864 	 * In the future perhaps we could canonicalize it?
865 	 */
866 	if (pathbuf[0] == '/')
867 		(void)strlcpy(pack.ep_path = dp, pathbuf, MAXPATHLEN);
868 #ifdef notyet
869 	/*
870 	 * Although this works most of the time [since the entry was just
871 	 * entered in the cache] we don't use it because it theoretically
872 	 * can fail and it is not the cleanest interface, because there
873 	 * could be races. When the namei cache is re-written, this can
874 	 * be changed to use the appropriate function.
875 	 */
876 	else if (!(error = vnode_to_path(dp, MAXPATHLEN, p->p_textvp, l, p)))
877 		pack.ep_path = dp;
878 #endif
879 	else {
880 #ifdef notyet
881 		printf("Cannot get path for pid %d [%s] (error %d)",
882 		    (int)p->p_pid, p->p_comm, error);
883 #endif
884 		pack.ep_path = NULL;
885 		PNBUF_PUT(dp);
886 	}
887 
888 	stack = (char *)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
889 		STACK_PTHREADSPACE + sizeof(struct ps_strings) + szsigcode),
890 		len - (sizeof(struct ps_strings) + szsigcode));
891 
892 #ifdef __MACHINE_STACK_GROWS_UP
893 	/*
894 	 * The copyargs call always copies into lower addresses
895 	 * first, moving towards higher addresses, starting with
896 	 * the stack pointer that we give.  When the stack grows
897 	 * down, this puts argc/argv/envp very shallow on the
898 	 * stack, right at the first user stack pointer.
899 	 * When the stack grows up, the situation is reversed.
900 	 *
901 	 * Normally, this is no big deal.  But the ld_elf.so _rtld()
902 	 * function expects to be called with a single pointer to
903 	 * a region that has a few words it can stash values into,
904 	 * followed by argc/argv/envp.  When the stack grows down,
905 	 * it's easy to decrement the stack pointer a little bit to
906 	 * allocate the space for these few words and pass the new
907 	 * stack pointer to _rtld.  When the stack grows up, however,
908 	 * a few words before argc is part of the signal trampoline, XXX
909 	 * so we have a problem.
910 	 *
911 	 * Instead of changing how _rtld works, we take the easy way
912 	 * out and steal 32 bytes before we call copyargs.
913 	 * This extra space was allowed for when 'len' was calculated.
914 	 */
915 	stack += RTLD_GAP;
916 #endif /* __MACHINE_STACK_GROWS_UP */
917 
918 	/* Now copy argc, args & environ to new stack */
919 	error = (*pack.ep_esch->es_copyargs)(l, &pack, &arginfo, &stack, argp);
920 	if (pack.ep_path) {
921 		PNBUF_PUT(pack.ep_path);
922 		pack.ep_path = NULL;
923 	}
924 	if (error) {
925 		DPRINTF(("execve: copyargs failed %d\n", error));
926 		goto exec_abort;
927 	}
928 	/* Move the stack back to original point */
929 	stack = (char *)STACK_GROW(vm->vm_minsaddr, len);
930 
931 	/* fill process ps_strings info */
932 	p->p_psstr = (struct ps_strings *)
933 	    STACK_ALLOC(STACK_GROW(vm->vm_minsaddr, STACK_PTHREADSPACE),
934 	    sizeof(struct ps_strings));
935 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
936 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
937 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
938 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
939 
940 	/* copy out the process's ps_strings structure */
941 	if ((error = copyout(aip, (char *)p->p_psstr,
942 	    sizeof(arginfo))) != 0) {
943 		DPRINTF(("execve: ps_strings copyout %p->%p size %ld failed\n",
944 		       aip, (char *)p->p_psstr, (long)sizeof(arginfo)));
945 		goto exec_abort;
946 	}
947 
948 	fd_closeexec();		/* handle close on exec */
949 	execsigs(p);		/* reset catched signals */
950 
951 	l->l_ctxlink = NULL;	/* reset ucontext link */
952 
953 
954 	p->p_acflag &= ~AFORK;
955 	mutex_enter(p->p_lock);
956 	p->p_flag |= PK_EXEC;
957 	mutex_exit(p->p_lock);
958 
959 	/*
960 	 * Stop profiling.
961 	 */
962 	if ((p->p_stflag & PST_PROFIL) != 0) {
963 		mutex_spin_enter(&p->p_stmutex);
964 		stopprofclock(p);
965 		mutex_spin_exit(&p->p_stmutex);
966 	}
967 
968 	/*
969 	 * It's OK to test PL_PPWAIT unlocked here, as other LWPs have
970 	 * exited and exec()/exit() are the only places it will be cleared.
971 	 */
972 	if ((p->p_lflag & PL_PPWAIT) != 0) {
973 		mutex_enter(proc_lock);
974 		p->p_lflag &= ~PL_PPWAIT;
975 		cv_broadcast(&p->p_pptr->p_waitcv);
976 		mutex_exit(proc_lock);
977 	}
978 
979 	/*
980 	 * Deal with set[ug]id.  MNT_NOSUID has already been used to disable
981 	 * s[ug]id.  It's OK to check for PSL_TRACED here as we have blocked
982 	 * out additional references on the process for the moment.
983 	 */
984 	if ((p->p_slflag & PSL_TRACED) == 0 &&
985 
986 	    (((attr.va_mode & S_ISUID) != 0 &&
987 	      kauth_cred_geteuid(l->l_cred) != attr.va_uid) ||
988 
989 	     ((attr.va_mode & S_ISGID) != 0 &&
990 	      kauth_cred_getegid(l->l_cred) != attr.va_gid))) {
991 		/*
992 		 * Mark the process as SUGID before we do
993 		 * anything that might block.
994 		 */
995 		proc_crmod_enter();
996 		proc_crmod_leave(NULL, NULL, true);
997 
998 		/* Make sure file descriptors 0..2 are in use. */
999 		if ((error = fd_checkstd()) != 0) {
1000 			DPRINTF(("execve: fdcheckstd failed %d\n", error));
1001 			goto exec_abort;
1002 		}
1003 
1004 		/*
1005 		 * Copy the credential so other references don't see our
1006 		 * changes.
1007 		 */
1008 		l->l_cred = kauth_cred_copy(l->l_cred);
1009 #ifdef KTRACE
1010 		/*
1011 		 * If the persistent trace flag isn't set, turn off.
1012 		 */
1013 		if (p->p_tracep) {
1014 			mutex_enter(&ktrace_lock);
1015 			if (!(p->p_traceflag & KTRFAC_PERSISTENT))
1016 				ktrderef(p);
1017 			mutex_exit(&ktrace_lock);
1018 		}
1019 #endif
1020 		if (attr.va_mode & S_ISUID)
1021 			kauth_cred_seteuid(l->l_cred, attr.va_uid);
1022 		if (attr.va_mode & S_ISGID)
1023 			kauth_cred_setegid(l->l_cred, attr.va_gid);
1024 	} else {
1025 		if (kauth_cred_geteuid(l->l_cred) ==
1026 		    kauth_cred_getuid(l->l_cred) &&
1027 		    kauth_cred_getegid(l->l_cred) ==
1028 		    kauth_cred_getgid(l->l_cred))
1029 			p->p_flag &= ~PK_SUGID;
1030 	}
1031 
1032 	/*
1033 	 * Copy the credential so other references don't see our changes.
1034 	 * Test to see if this is necessary first, since in the common case
1035 	 * we won't need a private reference.
1036 	 */
1037 	if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
1038 	    kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
1039 		l->l_cred = kauth_cred_copy(l->l_cred);
1040 		kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
1041 		kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
1042 	}
1043 
1044 	/* Update the master credentials. */
1045 	if (l->l_cred != p->p_cred) {
1046 		kauth_cred_t ocred;
1047 
1048 		kauth_cred_hold(l->l_cred);
1049 		mutex_enter(p->p_lock);
1050 		ocred = p->p_cred;
1051 		p->p_cred = l->l_cred;
1052 		mutex_exit(p->p_lock);
1053 		kauth_cred_free(ocred);
1054 	}
1055 
1056 #if defined(__HAVE_RAS)
1057 	/*
1058 	 * Remove all RASs from the address space.
1059 	 */
1060 	ras_purgeall();
1061 #endif
1062 
1063 	doexechooks(p);
1064 
1065 	/* setup new registers and do misc. setup. */
1066 	(*pack.ep_esch->es_emul->e_setregs)(l, &pack, (vaddr_t)stack);
1067 	if (pack.ep_esch->es_setregs)
1068 		(*pack.ep_esch->es_setregs)(l, &pack, (vaddr_t)stack);
1069 
1070 	/* map the process's signal trampoline code */
1071 	if (exec_sigcode_map(p, pack.ep_esch->es_emul)) {
1072 		DPRINTF(("execve: map sigcode failed %d\n", error));
1073 		goto exec_abort;
1074 	}
1075 
1076 	pool_put(&exec_pool, argp);
1077 
1078 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
1079 
1080 	/* notify others that we exec'd */
1081 	KNOTE(&p->p_klist, NOTE_EXEC);
1082 
1083 	kmem_free(pack.ep_hdr, pack.ep_hdrlen);
1084 
1085 	SDT_PROBE(proc,,,exec_success, path, 0, 0, 0, 0);
1086 
1087 	/* The emulation root will usually have been found when we looked
1088 	 * for the elf interpreter (or similar), if not look now. */
1089 	if (pack.ep_esch->es_emul->e_path != NULL && pack.ep_emul_root == NULL)
1090 		emul_find_root(l, &pack);
1091 
1092 	/* Any old emulation root got removed by fdcloseexec */
1093 	rw_enter(&p->p_cwdi->cwdi_lock, RW_WRITER);
1094 	p->p_cwdi->cwdi_edir = pack.ep_emul_root;
1095 	rw_exit(&p->p_cwdi->cwdi_lock);
1096 	pack.ep_emul_root = NULL;
1097 	if (pack.ep_interp != NULL)
1098 		vrele(pack.ep_interp);
1099 
1100 	/*
1101 	 * Call emulation specific exec hook. This can setup per-process
1102 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
1103 	 *
1104 	 * If we are executing process of different emulation than the
1105 	 * original forked process, call e_proc_exit() of the old emulation
1106 	 * first, then e_proc_exec() of new emulation. If the emulation is
1107 	 * same, the exec hook code should deallocate any old emulation
1108 	 * resources held previously by this process.
1109 	 */
1110 	if (p->p_emul && p->p_emul->e_proc_exit
1111 	    && p->p_emul != pack.ep_esch->es_emul)
1112 		(*p->p_emul->e_proc_exit)(p);
1113 
1114 	/*
1115 	 * Call exec hook. Emulation code may NOT store reference to anything
1116 	 * from &pack.
1117 	 */
1118         if (pack.ep_esch->es_emul->e_proc_exec)
1119                 (*pack.ep_esch->es_emul->e_proc_exec)(p, &pack);
1120 
1121 	/* update p_emul, the old value is no longer needed */
1122 	p->p_emul = pack.ep_esch->es_emul;
1123 
1124 	/* ...and the same for p_execsw */
1125 	p->p_execsw = pack.ep_esch;
1126 
1127 #ifdef __HAVE_SYSCALL_INTERN
1128 	(*p->p_emul->e_syscall_intern)(p);
1129 #endif
1130 	ktremul();
1131 
1132 	/* Allow new references from the debugger/procfs. */
1133 	rw_exit(&p->p_reflock);
1134 	rw_exit(&exec_lock);
1135 
1136 	mutex_enter(proc_lock);
1137 
1138 	if ((p->p_slflag & (PSL_TRACED|PSL_SYSCALL)) == PSL_TRACED) {
1139 		KSI_INIT_EMPTY(&ksi);
1140 		ksi.ksi_signo = SIGTRAP;
1141 		ksi.ksi_lid = l->l_lid;
1142 		kpsignal(p, &ksi, NULL);
1143 	}
1144 
1145 	if (p->p_sflag & PS_STOPEXEC) {
1146 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
1147 		p->p_pptr->p_nstopchild++;
1148 		p->p_pptr->p_waited = 0;
1149 		mutex_enter(p->p_lock);
1150 		ksiginfo_queue_init(&kq);
1151 		sigclearall(p, &contsigmask, &kq);
1152 		lwp_lock(l);
1153 		l->l_stat = LSSTOP;
1154 		p->p_stat = SSTOP;
1155 		p->p_nrlwps--;
1156 		mutex_exit(p->p_lock);
1157 		mutex_exit(proc_lock);
1158 		mi_switch(l);
1159 		ksiginfo_queue_drain(&kq);
1160 		KERNEL_LOCK(l->l_biglocks, l);
1161 	} else {
1162 		mutex_exit(proc_lock);
1163 	}
1164 
1165 	PNBUF_PUT(pathbuf);
1166 	return (EJUSTRETURN);
1167 
1168  bad:
1169 	/* free the vmspace-creation commands, and release their references */
1170 	kill_vmcmds(&pack.ep_vmcmds);
1171 	/* kill any opened file descriptor, if necessary */
1172 	if (pack.ep_flags & EXEC_HASFD) {
1173 		pack.ep_flags &= ~EXEC_HASFD;
1174 		fd_close(pack.ep_fd);
1175 	}
1176 	/* close and put the exec'd file */
1177 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
1178 	VOP_CLOSE(pack.ep_vp, FREAD, l->l_cred);
1179 	vput(pack.ep_vp);
1180 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
1181 	pool_put(&exec_pool, argp);
1182 
1183  freehdr:
1184 	kmem_free(pack.ep_hdr, pack.ep_hdrlen);
1185 	if (pack.ep_emul_root != NULL)
1186 		vrele(pack.ep_emul_root);
1187 	if (pack.ep_interp != NULL)
1188 		vrele(pack.ep_interp);
1189 
1190 	rw_exit(&exec_lock);
1191 
1192  clrflg:
1193 	lwp_lock(l);
1194 	l->l_flag |= oldlwpflags;
1195 	lwp_unlock(l);
1196 	PNBUF_PUT(pathbuf);
1197 	rw_exit(&p->p_reflock);
1198 
1199 	if (modgen != module_gen && error == ENOEXEC) {
1200 		modgen = module_gen;
1201 		exec_autoload();
1202 		goto retry;
1203 	}
1204 
1205 	SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
1206 	return error;
1207 
1208  exec_abort:
1209 	SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
1210 	PNBUF_PUT(pathbuf);
1211 	rw_exit(&p->p_reflock);
1212 	rw_exit(&exec_lock);
1213 
1214 	/*
1215 	 * the old process doesn't exist anymore.  exit gracefully.
1216 	 * get rid of the (new) address space we have created, if any, get rid
1217 	 * of our namei data and vnode, and exit noting failure
1218 	 */
1219 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
1220 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
1221 	if (pack.ep_emul_arg)
1222 		free(pack.ep_emul_arg, M_TEMP);
1223 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
1224 	pool_put(&exec_pool, argp);
1225 	kmem_free(pack.ep_hdr, pack.ep_hdrlen);
1226 	if (pack.ep_emul_root != NULL)
1227 		vrele(pack.ep_emul_root);
1228 	if (pack.ep_interp != NULL)
1229 		vrele(pack.ep_interp);
1230 
1231 	/* Acquire the sched-state mutex (exit1() will release it). */
1232 	mutex_enter(p->p_lock);
1233 	exit1(l, W_EXITCODE(error, SIGABRT));
1234 
1235 	/* NOTREACHED */
1236 	return 0;
1237 }
1238 
1239 
1240 int
1241 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
1242     char **stackp, void *argp)
1243 {
1244 	char	**cpp, *dp, *sp;
1245 	size_t	len;
1246 	void	*nullp;
1247 	long	argc, envc;
1248 	int	error;
1249 
1250 	cpp = (char **)*stackp;
1251 	nullp = NULL;
1252 	argc = arginfo->ps_nargvstr;
1253 	envc = arginfo->ps_nenvstr;
1254 	if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0)
1255 		return error;
1256 
1257 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_esch->es_arglen);
1258 	sp = argp;
1259 
1260 	/* XXX don't copy them out, remap them! */
1261 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
1262 
1263 	for (; --argc >= 0; sp += len, dp += len)
1264 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
1265 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
1266 			return error;
1267 
1268 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
1269 		return error;
1270 
1271 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
1272 
1273 	for (; --envc >= 0; sp += len, dp += len)
1274 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0 ||
1275 		    (error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0)
1276 			return error;
1277 
1278 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0)
1279 		return error;
1280 
1281 	*stackp = (char *)cpp;
1282 	return 0;
1283 }
1284 
1285 
1286 /*
1287  * Add execsw[] entries.
1288  */
1289 int
1290 exec_add(struct execsw *esp, int count)
1291 {
1292 	struct exec_entry	*it;
1293 	int			i;
1294 
1295 	if (count == 0) {
1296 		return 0;
1297 	}
1298 
1299 	/* Check for duplicates. */
1300 	rw_enter(&exec_lock, RW_WRITER);
1301 	for (i = 0; i < count; i++) {
1302 		LIST_FOREACH(it, &ex_head, ex_list) {
1303 			/* assume unique (makecmds, probe_func, emulation) */
1304 			if (it->ex_sw->es_makecmds == esp[i].es_makecmds &&
1305 			    it->ex_sw->u.elf_probe_func ==
1306 			    esp[i].u.elf_probe_func &&
1307 			    it->ex_sw->es_emul == esp[i].es_emul) {
1308 				rw_exit(&exec_lock);
1309 				return EEXIST;
1310 			}
1311 		}
1312 	}
1313 
1314 	/* Allocate new entries. */
1315 	for (i = 0; i < count; i++) {
1316 		it = kmem_alloc(sizeof(*it), KM_SLEEP);
1317 		it->ex_sw = &esp[i];
1318 		LIST_INSERT_HEAD(&ex_head, it, ex_list);
1319 	}
1320 
1321 	/* update execsw[] */
1322 	exec_init(0);
1323 	rw_exit(&exec_lock);
1324 	return 0;
1325 }
1326 
1327 /*
1328  * Remove execsw[] entry.
1329  */
1330 int
1331 exec_remove(struct execsw *esp, int count)
1332 {
1333 	struct exec_entry	*it, *next;
1334 	int			i;
1335 	const struct proclist_desc *pd;
1336 	proc_t			*p;
1337 
1338 	if (count == 0) {
1339 		return 0;
1340 	}
1341 
1342 	/* Abort if any are busy. */
1343 	rw_enter(&exec_lock, RW_WRITER);
1344 	for (i = 0; i < count; i++) {
1345 		mutex_enter(proc_lock);
1346 		for (pd = proclists; pd->pd_list != NULL; pd++) {
1347 			PROCLIST_FOREACH(p, pd->pd_list) {
1348 				if (p->p_execsw == &esp[i]) {
1349 					mutex_exit(proc_lock);
1350 					rw_exit(&exec_lock);
1351 					return EBUSY;
1352 				}
1353 			}
1354 		}
1355 		mutex_exit(proc_lock);
1356 	}
1357 
1358 	/* None are busy, so remove them all. */
1359 	for (i = 0; i < count; i++) {
1360 		for (it = LIST_FIRST(&ex_head); it != NULL; it = next) {
1361 			next = LIST_NEXT(it, ex_list);
1362 			if (it->ex_sw == &esp[i]) {
1363 				LIST_REMOVE(it, ex_list);
1364 				kmem_free(it, sizeof(*it));
1365 				break;
1366 			}
1367 		}
1368 	}
1369 
1370 	/* update execsw[] */
1371 	exec_init(0);
1372 	rw_exit(&exec_lock);
1373 	return 0;
1374 }
1375 
1376 /*
1377  * Initialize exec structures. If init_boot is true, also does necessary
1378  * one-time initialization (it's called from main() that way).
1379  * Once system is multiuser, this should be called with exec_lock held,
1380  * i.e. via exec_{add|remove}().
1381  */
1382 int
1383 exec_init(int init_boot)
1384 {
1385 	const struct execsw 	**sw;
1386 	struct exec_entry	*ex;
1387 	SLIST_HEAD(,exec_entry)	first;
1388 	SLIST_HEAD(,exec_entry)	any;
1389 	SLIST_HEAD(,exec_entry)	last;
1390 	int			i, sz;
1391 
1392 	if (init_boot) {
1393 		/* do one-time initializations */
1394 		rw_init(&exec_lock);
1395 		mutex_init(&sigobject_lock, MUTEX_DEFAULT, IPL_NONE);
1396 		pool_init(&exec_pool, NCARGS, 0, 0, PR_NOALIGN|PR_NOTOUCH,
1397 		    "execargs", &exec_palloc, IPL_NONE);
1398 		pool_sethardlimit(&exec_pool, maxexec, "should not happen", 0);
1399 	} else {
1400 		KASSERT(rw_write_held(&exec_lock));
1401 	}
1402 
1403 	/* Sort each entry onto the appropriate queue. */
1404 	SLIST_INIT(&first);
1405 	SLIST_INIT(&any);
1406 	SLIST_INIT(&last);
1407 	sz = 0;
1408 	LIST_FOREACH(ex, &ex_head, ex_list) {
1409 		switch(ex->ex_sw->es_prio) {
1410 		case EXECSW_PRIO_FIRST:
1411 			SLIST_INSERT_HEAD(&first, ex, ex_slist);
1412 			break;
1413 		case EXECSW_PRIO_ANY:
1414 			SLIST_INSERT_HEAD(&any, ex, ex_slist);
1415 			break;
1416 		case EXECSW_PRIO_LAST:
1417 			SLIST_INSERT_HEAD(&last, ex, ex_slist);
1418 			break;
1419 		default:
1420 			panic("exec_init");
1421 			break;
1422 		}
1423 		sz++;
1424 	}
1425 
1426 	/*
1427 	 * Create new execsw[].  Ensure we do not try a zero-sized
1428 	 * allocation.
1429 	 */
1430 	sw = kmem_alloc(sz * sizeof(struct execsw *) + 1, KM_SLEEP);
1431 	i = 0;
1432 	SLIST_FOREACH(ex, &first, ex_slist) {
1433 		sw[i++] = ex->ex_sw;
1434 	}
1435 	SLIST_FOREACH(ex, &any, ex_slist) {
1436 		sw[i++] = ex->ex_sw;
1437 	}
1438 	SLIST_FOREACH(ex, &last, ex_slist) {
1439 		sw[i++] = ex->ex_sw;
1440 	}
1441 
1442 	/* Replace old execsw[] and free used memory. */
1443 	if (execsw != NULL) {
1444 		kmem_free(__UNCONST(execsw),
1445 		    nexecs * sizeof(struct execsw *) + 1);
1446 	}
1447 	execsw = sw;
1448 	nexecs = sz;
1449 
1450 	/* Figure out the maximum size of an exec header. */
1451 	exec_maxhdrsz = sizeof(int);
1452 	for (i = 0; i < nexecs; i++) {
1453 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
1454 			exec_maxhdrsz = execsw[i]->es_hdrsz;
1455 	}
1456 
1457 	return 0;
1458 }
1459 
1460 static int
1461 exec_sigcode_map(struct proc *p, const struct emul *e)
1462 {
1463 	vaddr_t va;
1464 	vsize_t sz;
1465 	int error;
1466 	struct uvm_object *uobj;
1467 
1468 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
1469 
1470 	if (e->e_sigobject == NULL || sz == 0) {
1471 		return 0;
1472 	}
1473 
1474 	/*
1475 	 * If we don't have a sigobject for this emulation, create one.
1476 	 *
1477 	 * sigobject is an anonymous memory object (just like SYSV shared
1478 	 * memory) that we keep a permanent reference to and that we map
1479 	 * in all processes that need this sigcode. The creation is simple,
1480 	 * we create an object, add a permanent reference to it, map it in
1481 	 * kernel space, copy out the sigcode to it and unmap it.
1482 	 * We map it with PROT_READ|PROT_EXEC into the process just
1483 	 * the way sys_mmap() would map it.
1484 	 */
1485 
1486 	uobj = *e->e_sigobject;
1487 	if (uobj == NULL) {
1488 		mutex_enter(&sigobject_lock);
1489 		if ((uobj = *e->e_sigobject) == NULL) {
1490 			uobj = uao_create(sz, 0);
1491 			(*uobj->pgops->pgo_reference)(uobj);
1492 			va = vm_map_min(kernel_map);
1493 			if ((error = uvm_map(kernel_map, &va, round_page(sz),
1494 			    uobj, 0, 0,
1495 			    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
1496 			    UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
1497 				printf("kernel mapping failed %d\n", error);
1498 				(*uobj->pgops->pgo_detach)(uobj);
1499 				mutex_exit(&sigobject_lock);
1500 				return (error);
1501 			}
1502 			memcpy((void *)va, e->e_sigcode, sz);
1503 #ifdef PMAP_NEED_PROCWR
1504 			pmap_procwr(&proc0, va, sz);
1505 #endif
1506 			uvm_unmap(kernel_map, va, va + round_page(sz));
1507 			*e->e_sigobject = uobj;
1508 		}
1509 		mutex_exit(&sigobject_lock);
1510 	}
1511 
1512 	/* Just a hint to uvm_map where to put it. */
1513 	va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
1514 	    round_page(sz));
1515 
1516 #ifdef __alpha__
1517 	/*
1518 	 * Tru64 puts /sbin/loader at the end of user virtual memory,
1519 	 * which causes the above calculation to put the sigcode at
1520 	 * an invalid address.  Put it just below the text instead.
1521 	 */
1522 	if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
1523 		va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
1524 	}
1525 #endif
1526 
1527 	(*uobj->pgops->pgo_reference)(uobj);
1528 	error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
1529 			uobj, 0, 0,
1530 			UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
1531 				    UVM_ADV_RANDOM, 0));
1532 	if (error) {
1533 		(*uobj->pgops->pgo_detach)(uobj);
1534 		return (error);
1535 	}
1536 	p->p_sigctx.ps_sigcode = (void *)va;
1537 	return (0);
1538 }
1539