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