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