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