xref: /netbsd-src/sys/kern/kern_exec.c (revision 3cec974c61d7fac0a37c0377723a33214a458c8b)
1 /*	$NetBSD: kern_exec.c,v 1.138 2001/02/26 20:43:25 lukem 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 "opt_ktrace.h"
36 #include "opt_syscall_debug.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/filedesc.h>
41 #include <sys/kernel.h>
42 #include <sys/proc.h>
43 #include <sys/mount.h>
44 #include <sys/malloc.h>
45 #include <sys/namei.h>
46 #include <sys/vnode.h>
47 #include <sys/file.h>
48 #include <sys/acct.h>
49 #include <sys/exec.h>
50 #include <sys/ktrace.h>
51 #include <sys/resourcevar.h>
52 #include <sys/wait.h>
53 #include <sys/mman.h>
54 #include <sys/signalvar.h>
55 #include <sys/stat.h>
56 #include <sys/syscall.h>
57 
58 #include <sys/syscallargs.h>
59 
60 #include <uvm/uvm_extern.h>
61 
62 #include <machine/cpu.h>
63 #include <machine/reg.h>
64 
65 /*
66  * Exec function switch:
67  *
68  * Note that each makecmds function is responsible for loading the
69  * exec package with the necessary functions for any exec-type-specific
70  * handling.
71  *
72  * Functions for specific exec types should be defined in their own
73  * header file.
74  */
75 extern const struct execsw	execsw_builtin[];
76 extern int			nexecs_builtin;
77 static const struct execsw	**execsw = NULL;
78 static int			nexecs;
79 
80 int	exec_maxhdrsz;		/* must not be static - netbsd32 needs it */
81 
82 #ifdef LKM
83 /* list of supported emulations */
84 static
85 LIST_HEAD(emlist_head, emul_entry) el_head = LIST_HEAD_INITIALIZER(el_head);
86 struct emul_entry {
87 	LIST_ENTRY(emul_entry)	el_list;
88 	const struct emul	*el_emul;
89 	int			ro_entry;
90 };
91 
92 /* list of dynamically loaded execsw entries */
93 static
94 LIST_HEAD(execlist_head, exec_entry) ex_head = LIST_HEAD_INITIALIZER(ex_head);
95 struct exec_entry {
96 	LIST_ENTRY(exec_entry)	ex_list;
97 	const struct execsw	*es;
98 };
99 
100 /* structure used for building execw[] */
101 struct execsw_entry {
102 	struct execsw_entry	*next;
103 	const struct execsw	*es;
104 };
105 #endif /* LKM */
106 
107 /* NetBSD emul struct */
108 extern char	sigcode[], esigcode[];
109 #ifdef SYSCALL_DEBUG
110 extern const char * const syscallnames[];
111 #endif
112 #ifdef __HAVE_SYSCALL_INTERN
113 void syscall_intern(struct proc *);
114 #else
115 void syscall(void);
116 #endif
117 
118 const struct emul emul_netbsd = {
119 	"netbsd",
120 	NULL,		/* emulation path */
121 #ifndef __HAVE_MINIMAL_EMUL
122 	EMUL_HAS_SYS___syscall,
123 	NULL,
124 	SYS_syscall,
125 	SYS_MAXSYSCALL,
126 #endif
127 	sysent,
128 #ifdef SYSCALL_DEBUG
129 	syscallnames,
130 #else
131 	NULL,
132 #endif
133 	sendsig,
134 	sigcode,
135 	esigcode,
136 	NULL,
137 	NULL,
138 	NULL,
139 #ifdef __HAVE_SYSCALL_INTERN
140 	syscall_intern,
141 #else
142 	syscall,
143 #endif
144 };
145 
146 /*
147  * Exec lock. Used to control access to execsw[] structures.
148  * This must not be static so that netbsd32 can access it, too.
149  */
150 struct lock exec_lock;
151 
152 #ifdef LKM
153 static const struct emul * emul_search(const char *);
154 static void link_es(struct execsw_entry **, const struct execsw *);
155 #endif /* LKM */
156 
157 /*
158  * check exec:
159  * given an "executable" described in the exec package's namei info,
160  * see what we can do with it.
161  *
162  * ON ENTRY:
163  *	exec package with appropriate namei info
164  *	proc pointer of exec'ing proc
165  *	NO SELF-LOCKED VNODES
166  *
167  * ON EXIT:
168  *	error:	nothing held, etc.  exec header still allocated.
169  *	ok:	filled exec package, executable's vnode (unlocked).
170  *
171  * EXEC SWITCH ENTRY:
172  * 	Locked vnode to check, exec package, proc.
173  *
174  * EXEC SWITCH EXIT:
175  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
176  *	error:	destructive:
177  *			everything deallocated execept exec header.
178  *		non-destructive:
179  *			error code, executable's vnode (unlocked),
180  *			exec header unmodified.
181  */
182 int
183 check_exec(struct proc *p, struct exec_package *epp)
184 {
185 	int		error, i;
186 	struct vnode	*vp;
187 	struct nameidata *ndp;
188 	size_t		resid;
189 
190 	ndp = epp->ep_ndp;
191 	ndp->ni_cnd.cn_nameiop = LOOKUP;
192 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME;
193 	/* first get the vnode */
194 	if ((error = namei(ndp)) != 0)
195 		return error;
196 	epp->ep_vp = vp = ndp->ni_vp;
197 
198 	/* check access and type */
199 	if (vp->v_type != VREG) {
200 		error = EACCES;
201 		goto bad1;
202 	}
203 	if ((error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p)) != 0)
204 		goto bad1;
205 
206 	/* get attributes */
207 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
208 		goto bad1;
209 
210 	/* Check mount point */
211 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
212 		error = EACCES;
213 		goto bad1;
214 	}
215 	if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
216 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
217 
218 	/* try to open it */
219 	if ((error = VOP_OPEN(vp, FREAD, p->p_ucred, p)) != 0)
220 		goto bad1;
221 
222 	/* unlock vp, since we need it unlocked from here on out. */
223 	VOP_UNLOCK(vp, 0);
224 
225 	/* now we have the file, get the exec header */
226 	uvn_attach(vp, VM_PROT_READ);
227 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
228 			UIO_SYSSPACE, 0, p->p_ucred, &resid, p);
229 	if (error)
230 		goto bad2;
231 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
232 
233 	/*
234 	 * Set up default address space limits.  Can be overridden
235 	 * by individual exec packages.
236 	 *
237 	 * XXX probably shoul be all done in the exec pakages.
238 	 */
239 	epp->ep_vm_minaddr = VM_MIN_ADDRESS;
240 	epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
241 	/*
242 	 * set up the vmcmds for creation of the process
243 	 * address space
244 	 */
245 	error = ENOEXEC;
246 	for (i = 0; i < nexecs && error != 0; i++) {
247 		int newerror;
248 
249 		epp->ep_esch = execsw[i];
250 		newerror = (*execsw[i]->es_check)(p, epp);
251 		/* make sure the first "interesting" error code is saved. */
252 		if (!newerror || error == ENOEXEC)
253 			error = newerror;
254 
255 		/* if es_check call was successful, update epp->ep_es */
256 		if (!newerror && (epp->ep_flags & EXEC_HASES) == 0)
257 			epp->ep_es = execsw[i];
258 
259 		if (epp->ep_flags & EXEC_DESTR && error != 0)
260 			return error;
261 	}
262 	if (!error) {
263 		/* check that entry point is sane */
264 		if (epp->ep_entry > VM_MAXUSER_ADDRESS)
265 			error = ENOEXEC;
266 
267 		/* check limits */
268 		if ((epp->ep_tsize > MAXTSIZ) ||
269 		    (epp->ep_dsize > p->p_rlimit[RLIMIT_DATA].rlim_cur))
270 			error = ENOMEM;
271 
272 		if (!error)
273 			return (0);
274 	}
275 
276 	/*
277 	 * free any vmspace-creation commands,
278 	 * and release their references
279 	 */
280 	kill_vmcmds(&epp->ep_vmcmds);
281 
282 bad2:
283 	/*
284 	 * close and release the vnode, restore the old one, free the
285 	 * pathname buf, and punt.
286 	 */
287 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
288 	VOP_CLOSE(vp, FREAD, p->p_ucred, p);
289 	vput(vp);
290 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
291 	return error;
292 
293 bad1:
294 	/*
295 	 * free the namei pathname buffer, and put the vnode
296 	 * (which we don't yet have open).
297 	 */
298 	vput(vp);				/* was still locked */
299 	PNBUF_PUT(ndp->ni_cnd.cn_pnbuf);
300 	return error;
301 }
302 
303 /*
304  * exec system call
305  */
306 /* ARGSUSED */
307 int
308 sys_execve(struct proc *p, void *v, register_t *retval)
309 {
310 	struct sys_execve_args /* {
311 		syscallarg(const char *)	path;
312 		syscallarg(char * const *)	argp;
313 		syscallarg(char * const *)	envp;
314 	} */ *uap = v;
315 	int			error, i;
316 	struct exec_package	pack;
317 	struct nameidata	nid;
318 	struct vattr		attr;
319 	struct ucred		*cred;
320 	char			*argp;
321 	char * const		*cpp;
322 	char			*dp, *sp;
323 	long			argc, envc;
324 	size_t			len;
325 	char			*stack;
326 	struct ps_strings	arginfo;
327 	struct vmspace		*vm;
328 	char			**tmpfap;
329 	int			szsigcode;
330 	struct exec_vmcmd	*base_vcp;
331 
332 	cred = p->p_ucred;
333 	base_vcp = NULL;
334 	/*
335 	 * Init the namei data to point the file user's program name.
336 	 * This is done here rather than in check_exec(), so that it's
337 	 * possible to override this settings if any of makecmd/probe
338 	 * functions call check_exec() recursively - for example,
339 	 * see exec_script_makecmds().
340 	 */
341 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path), p);
342 
343 	/*
344 	 * initialize the fields of the exec package.
345 	 */
346 	pack.ep_name = SCARG(uap, path);
347 	pack.ep_hdr = malloc(exec_maxhdrsz, M_EXEC, M_WAITOK);
348 	pack.ep_hdrlen = exec_maxhdrsz;
349 	pack.ep_hdrvalid = 0;
350 	pack.ep_ndp = &nid;
351 	pack.ep_emul_arg = NULL;
352 	pack.ep_vmcmds.evs_cnt = 0;
353 	pack.ep_vmcmds.evs_used = 0;
354 	pack.ep_vap = &attr;
355 	pack.ep_flags = 0;
356 
357 	lockmgr(&exec_lock, LK_SHARED, NULL);
358 
359 	/* see if we can run it. */
360 	if ((error = check_exec(p, &pack)) != 0)
361 		goto freehdr;
362 
363 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
364 
365 	/* allocate an argument buffer */
366 	argp = (char *) uvm_km_valloc_wait(exec_map, NCARGS);
367 #ifdef DIAGNOSTIC
368 	if (argp == (vaddr_t) 0)
369 		panic("execve: argp == NULL");
370 #endif
371 	dp = argp;
372 	argc = 0;
373 
374 	/* copy the fake args list, if there's one, freeing it as we go */
375 	if (pack.ep_flags & EXEC_HASARGL) {
376 		tmpfap = pack.ep_fa;
377 		while (*tmpfap != NULL) {
378 			char *cp;
379 
380 			cp = *tmpfap;
381 			while (*cp)
382 				*dp++ = *cp++;
383 			dp++;
384 
385 			FREE(*tmpfap, M_EXEC);
386 			tmpfap++; argc++;
387 		}
388 		FREE(pack.ep_fa, M_EXEC);
389 		pack.ep_flags &= ~EXEC_HASARGL;
390 	}
391 
392 	/* Now get argv & environment */
393 	if (!(cpp = SCARG(uap, argp))) {
394 		error = EINVAL;
395 		goto bad;
396 	}
397 
398 	if (pack.ep_flags & EXEC_SKIPARG)
399 		cpp++;
400 
401 	while (1) {
402 		len = argp + ARG_MAX - dp;
403 		if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
404 			goto bad;
405 		if (!sp)
406 			break;
407 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
408 			if (error == ENAMETOOLONG)
409 				error = E2BIG;
410 			goto bad;
411 		}
412 		dp += len;
413 		cpp++;
414 		argc++;
415 	}
416 
417 	envc = 0;
418 	/* environment need not be there */
419 	if ((cpp = SCARG(uap, envp)) != NULL ) {
420 		while (1) {
421 			len = argp + ARG_MAX - dp;
422 			if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
423 				goto bad;
424 			if (!sp)
425 				break;
426 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
427 				if (error == ENAMETOOLONG)
428 					error = E2BIG;
429 				goto bad;
430 			}
431 			dp += len;
432 			cpp++;
433 			envc++;
434 		}
435 	}
436 
437 	dp = (char *) ALIGN(dp);
438 
439 	szsigcode = pack.ep_es->es_emul->e_esigcode -
440 	    pack.ep_es->es_emul->e_sigcode;
441 
442 	/* Now check if args & environ fit into new stack */
443 	if (pack.ep_flags & EXEC_32)
444 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
445 		    sizeof(int) + sizeof(int) + dp + STACKGAPLEN +
446 		    szsigcode + sizeof(struct ps_strings)) - argp;
447 	else
448 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
449 		    sizeof(char *) + sizeof(int) + dp + STACKGAPLEN +
450 		    szsigcode + sizeof(struct ps_strings)) - argp;
451 
452 	len = ALIGN(len);	/* make the stack "safely" aligned */
453 
454 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
455 		error = ENOMEM;
456 		goto bad;
457 	}
458 
459 	/* adjust "active stack depth" for process VSZ */
460 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
461 
462 	/*
463 	 * Do whatever is necessary to prepare the address space
464 	 * for remapping.  Note that this might replace the current
465 	 * vmspace with another!
466 	 */
467 	uvmspace_exec(p, pack.ep_vm_minaddr, pack.ep_vm_maxaddr);
468 
469 	/* Now map address space */
470 	vm = p->p_vmspace;
471 	vm->vm_taddr = (char *) pack.ep_taddr;
472 	vm->vm_tsize = btoc(pack.ep_tsize);
473 	vm->vm_daddr = (char *) pack.ep_daddr;
474 	vm->vm_dsize = btoc(pack.ep_dsize);
475 	vm->vm_ssize = btoc(pack.ep_ssize);
476 	vm->vm_maxsaddr = (char *) pack.ep_maxsaddr;
477 	vm->vm_minsaddr = (char *) pack.ep_minsaddr;
478 
479 	/* create the new process's VM space by running the vmcmds */
480 #ifdef DIAGNOSTIC
481 	if (pack.ep_vmcmds.evs_used == 0)
482 		panic("execve: no vmcmds");
483 #endif
484 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
485 		struct exec_vmcmd *vcp;
486 
487 		vcp = &pack.ep_vmcmds.evs_cmds[i];
488 		if (vcp->ev_flags & VMCMD_RELATIVE) {
489 #ifdef DIAGNOSTIC
490 			if (base_vcp == NULL)
491 				panic("execve: relative vmcmd with no base");
492 			if (vcp->ev_flags & VMCMD_BASE)
493 				panic("execve: illegal base & relative vmcmd");
494 #endif
495 			vcp->ev_addr += base_vcp->ev_addr;
496 		}
497 		error = (*vcp->ev_proc)(p, vcp);
498 #ifdef DEBUG
499 		if (error) {
500 			if (i > 0)
501 				printf("vmcmd[%d] = %#lx/%#lx @ %#lx\n", i-1,
502 				       vcp[-1].ev_addr, vcp[-1].ev_len,
503 				       vcp[-1].ev_offset);
504 			printf("vmcmd[%d] = %#lx/%#lx @ %#lx\n", i,
505 			       vcp->ev_addr, vcp->ev_len, vcp->ev_offset);
506 		}
507 #endif
508 		if (vcp->ev_flags & VMCMD_BASE)
509 			base_vcp = vcp;
510 	}
511 
512 	/* free the vmspace-creation commands, and release their references */
513 	kill_vmcmds(&pack.ep_vmcmds);
514 
515 	/* if an error happened, deallocate and punt */
516 	if (error) {
517 #ifdef DEBUG
518 		printf("execve: vmcmd %i failed: %d\n", i-1, error);
519 #endif
520 		goto exec_abort;
521 	}
522 
523 	/* remember information about the process */
524 	arginfo.ps_nargvstr = argc;
525 	arginfo.ps_nenvstr = envc;
526 
527 	stack = (char *) (vm->vm_minsaddr - len);
528 	/* Now copy argc, args & environ to new stack */
529 	if (!(*pack.ep_es->es_copyargs)(&pack, &arginfo, stack, argp)) {
530 #ifdef DEBUG
531 		printf("execve: copyargs failed\n");
532 #endif
533 		goto exec_abort;
534 	}
535 
536 	/* fill process ps_strings info */
537 	p->p_psstr = (struct ps_strings *)(vm->vm_minsaddr
538 		- sizeof(struct ps_strings));
539 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
540 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
541 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
542 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
543 
544 	/* copy out the process's ps_strings structure */
545 	if (copyout(&arginfo, (char *)p->p_psstr, sizeof(arginfo))) {
546 #ifdef DEBUG
547 		printf("execve: ps_strings copyout %p->%p size %ld failed\n",
548 		       &arginfo, (char *)p->p_psstr, (long)sizeof(arginfo));
549 #endif
550 		goto exec_abort;
551 	}
552 
553 	/* copy out the process's signal trapoline code */
554 	if (szsigcode) {
555 		if (copyout((char *)pack.ep_es->es_emul->e_sigcode,
556 		    p->p_sigctx.ps_sigcode = (char *)p->p_psstr - szsigcode,
557 		    szsigcode)) {
558 #ifdef DEBUG
559 			printf("execve: sig trampoline copyout failed\n");
560 #endif
561 			goto exec_abort;
562 		}
563 #ifdef PMAP_NEED_PROCWR
564 		/* This is code. Let the pmap do what is needed. */
565 		pmap_procwr(p, (vaddr_t)p->p_sigctx.ps_sigcode, szsigcode);
566 #endif
567 	}
568 
569 	stopprofclock(p);	/* stop profiling */
570 	fdcloseexec(p);		/* handle close on exec */
571 	execsigs(p);		/* reset catched signals */
572 	p->p_ctxlink = NULL;	/* reset ucontext link */
573 
574 	/* set command name & other accounting info */
575 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
576 	memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, len);
577 	p->p_comm[len] = 0;
578 	p->p_acflag &= ~AFORK;
579 
580 	/* record proc's vnode, for use by procfs and others */
581         if (p->p_textvp)
582                 vrele(p->p_textvp);
583 	VREF(pack.ep_vp);
584 	p->p_textvp = pack.ep_vp;
585 
586 	p->p_flag |= P_EXEC;
587 	if (p->p_flag & P_PPWAIT) {
588 		p->p_flag &= ~P_PPWAIT;
589 		wakeup((caddr_t) p->p_pptr);
590 	}
591 
592 	/*
593 	 * deal with set[ug]id.
594 	 * MNT_NOSUID and P_TRACED have already been used to disable s[ug]id.
595 	 */
596 	if (((attr.va_mode & S_ISUID) != 0 && p->p_ucred->cr_uid != attr.va_uid)
597 	 || ((attr.va_mode & S_ISGID) != 0 && p->p_ucred->cr_gid != attr.va_gid)){
598 		p->p_ucred = crcopy(cred);
599 #ifdef KTRACE
600 		/*
601 		 * If process is being ktraced, turn off - unless
602 		 * root set it.
603 		 */
604 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT))
605 			ktrderef(p);
606 #endif
607 		if (attr.va_mode & S_ISUID)
608 			p->p_ucred->cr_uid = attr.va_uid;
609 		if (attr.va_mode & S_ISGID)
610 			p->p_ucred->cr_gid = attr.va_gid;
611 		p_sugid(p);
612 	} else
613 		p->p_flag &= ~P_SUGID;
614 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
615 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
616 
617 	doexechooks(p);
618 
619 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
620 
621 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
622 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
623 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
624 	vput(pack.ep_vp);
625 
626 	/* setup new registers and do misc. setup. */
627 	(*pack.ep_es->es_setregs)(p, &pack, (u_long) stack);
628 
629 	if (p->p_flag & P_TRACED)
630 		psignal(p, SIGTRAP);
631 
632 	free(pack.ep_hdr, M_EXEC);
633 
634 	/*
635 	 * Call emulation specific exec hook. This can setup setup per-process
636 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
637 	 *
638 	 * If we are executing process of different emulation than the
639 	 * original forked process, call e_proc_exit() of the old emulation
640 	 * first, then e_proc_exec() of new emulation. If the emulation is
641 	 * same, the exec hook code should deallocate any old emulation
642 	 * resources held previously by this process.
643 	 */
644 	if (p->p_emul && p->p_emul->e_proc_exit
645 	    && p->p_emul != pack.ep_es->es_emul)
646 		(*p->p_emul->e_proc_exit)(p);
647 
648 	/*
649 	 * Call exec hook. Emulation code may NOT store reference to anything
650 	 * from &pack.
651 	 */
652         if (pack.ep_es->es_emul->e_proc_exec)
653                 (*pack.ep_es->es_emul->e_proc_exec)(p, &pack);
654 
655 	/* update p_emul, the old value is no longer needed */
656 	p->p_emul = pack.ep_es->es_emul;
657 #ifdef __HAVE_SYSCALL_INTERN
658 	(*p->p_emul->e_syscall_intern)(p);
659 #endif
660 #ifdef KTRACE
661 	if (KTRPOINT(p, KTR_EMUL))
662 		ktremul(p);
663 #endif
664 
665 	lockmgr(&exec_lock, LK_RELEASE, NULL);
666 
667 	return (EJUSTRETURN);
668 
669  bad:
670 	/* free the vmspace-creation commands, and release their references */
671 	kill_vmcmds(&pack.ep_vmcmds);
672 	/* kill any opened file descriptor, if necessary */
673 	if (pack.ep_flags & EXEC_HASFD) {
674 		pack.ep_flags &= ~EXEC_HASFD;
675 		(void) fdrelease(p, pack.ep_fd);
676 	}
677 	/* close and put the exec'd file */
678 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
679 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
680 	vput(pack.ep_vp);
681 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
682 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
683 
684  freehdr:
685 	lockmgr(&exec_lock, LK_RELEASE, NULL);
686 
687 	free(pack.ep_hdr, M_EXEC);
688 	return error;
689 
690  exec_abort:
691 	lockmgr(&exec_lock, LK_RELEASE, NULL);
692 
693 	/*
694 	 * the old process doesn't exist anymore.  exit gracefully.
695 	 * get rid of the (new) address space we have created, if any, get rid
696 	 * of our namei data and vnode, and exit noting failure
697 	 */
698 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
699 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
700 	if (pack.ep_emul_arg)
701 		FREE(pack.ep_emul_arg, M_TEMP);
702 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
703 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
704 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
705 	vput(pack.ep_vp);
706 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
707 	free(pack.ep_hdr, M_EXEC);
708 	exit1(p, W_EXITCODE(0, SIGABRT));
709 	exit1(p, -1);
710 
711 	/* NOTREACHED */
712 	return 0;
713 }
714 
715 
716 void *
717 copyargs(struct exec_package *pack, struct ps_strings *arginfo,
718 	void *stack, void *argp)
719 {
720 	char	**cpp, *dp, *sp;
721 	size_t	len;
722 	void	*nullp;
723 	long	argc, envc;
724 
725 	cpp = stack;
726 	nullp = NULL;
727 	argc = arginfo->ps_nargvstr;
728 	envc = arginfo->ps_nenvstr;
729 	if (copyout(&argc, cpp++, sizeof(argc)))
730 		return NULL;
731 
732 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_es->es_arglen);
733 	sp = argp;
734 
735 	/* XXX don't copy them out, remap them! */
736 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
737 
738 	for (; --argc >= 0; sp += len, dp += len)
739 		if (copyout(&dp, cpp++, sizeof(dp)) ||
740 		    copyoutstr(sp, dp, ARG_MAX, &len))
741 			return NULL;
742 
743 	if (copyout(&nullp, cpp++, sizeof(nullp)))
744 		return NULL;
745 
746 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
747 
748 	for (; --envc >= 0; sp += len, dp += len)
749 		if (copyout(&dp, cpp++, sizeof(dp)) ||
750 		    copyoutstr(sp, dp, ARG_MAX, &len))
751 			return NULL;
752 
753 	if (copyout(&nullp, cpp++, sizeof(nullp)))
754 		return NULL;
755 
756 	return cpp;
757 }
758 
759 #ifdef LKM
760 /*
761  * Find an emulation of given name in list of emulations.
762  */
763 static const struct emul *
764 emul_search(const char *name)
765 {
766 	struct emul_entry *it;
767 
768 	LIST_FOREACH(it, &el_head, el_list) {
769 		if (strcmp(name, it->el_emul->e_name) == 0)
770 			return it->el_emul;
771 	}
772 
773 	return NULL;
774 }
775 
776 /*
777  * Add an emulation to list, if it's not there already.
778  */
779 int
780 emul_register(const struct emul *emul, int ro_entry)
781 {
782 	struct emul_entry	*ee;
783 	int			error;
784 
785 	error = 0;
786 	lockmgr(&exec_lock, LK_SHARED, NULL);
787 
788 	if (emul_search(emul->e_name)) {
789 		error = EEXIST;
790 		goto out;
791 	}
792 
793 	MALLOC(ee, struct emul_entry *, sizeof(struct emul_entry),
794 		M_EXEC, M_WAITOK);
795 	ee->el_emul = emul;
796 	ee->ro_entry = ro_entry;
797 	LIST_INSERT_HEAD(&el_head, ee, el_list);
798 
799  out:
800 	lockmgr(&exec_lock, LK_RELEASE, NULL);
801 	return error;
802 }
803 
804 /*
805  * Remove emulation with name 'name' from list of supported emulations.
806  */
807 int
808 emul_unregister(const char *name)
809 {
810 	const struct proclist_desc *pd;
811 	struct emul_entry	*it;
812 	int			i, error;
813 	struct proc		*ptmp;
814 
815 	error = 0;
816 	lockmgr(&exec_lock, LK_SHARED, NULL);
817 
818 	LIST_FOREACH(it, &el_head, el_list) {
819 		if (strcmp(it->el_emul->e_name, name) == 0)
820 			break;
821 	}
822 
823 	if (!it) {
824 		error = ENOENT;
825 		goto out;
826 	}
827 
828 	if (it->ro_entry) {
829 		error = EBUSY;
830 		goto out;
831 	}
832 
833 	/* test if any execw[] entry is still using this */
834 	for(i=0; i < nexecs; i++) {
835 		if (execsw[i]->es_emul == it->el_emul) {
836 			error = EBUSY;
837 			goto out;
838 		}
839 	}
840 
841 	/*
842 	 * Test if any process is running under this emulation - since
843 	 * emul_unregister() is running quite sendomly, it's better
844 	 * to do expensive check here than to use any locking.
845 	 */
846 	proclist_lock_read();
847 	for (pd = proclists; pd->pd_list != NULL && !error; pd++) {
848 		LIST_FOREACH(ptmp, pd->pd_list, p_list) {
849 			if (ptmp->p_emul == it->el_emul) {
850 				error = EBUSY;
851 				break;
852 			}
853 		}
854 	}
855 	proclist_unlock_read();
856 
857 	if (error)
858 		goto out;
859 
860 
861 	/* entry is not used, remove it */
862 	LIST_REMOVE(it, el_list);
863 	FREE(it, M_EXEC);
864 
865  out:
866 	lockmgr(&exec_lock, LK_RELEASE, NULL);
867 	return error;
868 }
869 
870 /*
871  * Add execsw[] entry.
872  */
873 int
874 exec_add(struct execsw *esp, const char *e_name)
875 {
876 	struct exec_entry	*it;
877 	int			error;
878 
879 	error = 0;
880 	lockmgr(&exec_lock, LK_EXCLUSIVE, NULL);
881 
882 	if (!esp->es_emul) {
883 		esp->es_emul = emul_search(e_name);
884 		if (!esp->es_emul) {
885 			error = ENOENT;
886 			goto out;
887 		}
888 	}
889 
890 	LIST_FOREACH(it, &ex_head, ex_list) {
891 		/* assume tuple (makecmds, probe_func, emulation) is unique */
892 		if (it->es->es_check == esp->es_check
893 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
894 		    && it->es->es_emul == esp->es_emul) {
895 			error = EEXIST;
896 			goto out;
897 		}
898 	}
899 
900 	/* if we got here, the entry doesn't exist yet */
901 	MALLOC(it, struct exec_entry *, sizeof(struct exec_entry),
902 		M_EXEC, M_WAITOK);
903 	it->es = esp;
904 	LIST_INSERT_HEAD(&ex_head, it, ex_list);
905 
906 	/* update execsw[] */
907 	exec_init(0);
908 
909  out:
910 	lockmgr(&exec_lock, LK_RELEASE, NULL);
911 	return error;
912 }
913 
914 /*
915  * Remove execsw[] entry.
916  */
917 int
918 exec_remove(const struct execsw *esp)
919 {
920 	struct exec_entry	*it;
921 	int			error;
922 
923 	error = 0;
924 	lockmgr(&exec_lock, LK_EXCLUSIVE, NULL);
925 
926 	LIST_FOREACH(it, &ex_head, ex_list) {
927 		/* assume tuple (makecmds, probe_func, emulation) is unique */
928 		if (it->es->es_check == esp->es_check
929 		    && it->es->u.elf_probe_func == esp->u.elf_probe_func
930 		    && it->es->es_emul == esp->es_emul)
931 			break;
932 	}
933 	if (!it) {
934 		error = ENOENT;
935 		goto out;
936 	}
937 
938 	/* remove item from list and free resources */
939 	LIST_REMOVE(it, ex_list);
940 	FREE(it, M_EXEC);
941 
942 	/* update execsw[] */
943 	exec_init(0);
944 
945  out:
946 	lockmgr(&exec_lock, LK_RELEASE, NULL);
947 	return error;
948 }
949 
950 static void
951 link_es(struct execsw_entry **listp, const struct execsw *esp)
952 {
953 	struct execsw_entry *et, *e1;
954 
955 	MALLOC(et, struct execsw_entry *, sizeof(struct execsw_entry),
956 			M_TEMP, M_WAITOK);
957 	et->next = NULL;
958 	et->es = esp;
959 	if (*listp == NULL) {
960 		*listp = et;
961 		return;
962 	}
963 
964 	switch(et->es->es_prio) {
965 	case EXECSW_PRIO_FIRST:
966 		/* put new entry as the first */
967 		et->next = *listp;
968 		*listp = et;
969 		break;
970 	case EXECSW_PRIO_ANY:
971 		/* put new entry after all *_FIRST and *_ANY entries */
972 		for(e1 = *listp; e1->next
973 			&& e1->next->es->es_prio != EXECSW_PRIO_LAST;
974 			e1 = e1->next);
975 		et->next = e1->next;
976 		e1->next = et;
977 		break;
978 	case EXECSW_PRIO_LAST:
979 		/* put new entry as the last one */
980 		for(e1 = *listp; e1->next; e1 = e1->next);
981 		e1->next = et;
982 		break;
983 	default:
984 #ifdef DIAGNOSTIC
985 		panic("execw[] entry with unknown priority %d found\n",
986 			et->es->es_prio);
987 #endif
988 		break;
989 	}
990 }
991 
992 /*
993  * Initialize exec structures. If init_boot is true, also does necessary
994  * one-time initialization (it's called from main() that way).
995  * Once system is multiuser, this should be called with exec_lock hold,
996  * i.e. via exec_{add|remove}().
997  */
998 int
999 exec_init(int init_boot)
1000 {
1001 	const struct execsw	**new_es, * const *old_es;
1002 	struct execsw_entry	*list, *e1;
1003 	struct exec_entry	*e2;
1004 	int			i, es_sz;
1005 
1006 	if (init_boot) {
1007 		/* do one-time initializations */
1008 		lockinit(&exec_lock, PWAIT, "execlck", 0, 0);
1009 
1010 		/* register compiled-in emulations */
1011 		for(i=0; i < nexecs_builtin; i++) {
1012 			if (execsw_builtin[i].es_emul)
1013 				emul_register(execsw_builtin[i].es_emul, 1);
1014 		}
1015 #ifdef DIAGNOSTIC
1016 		if (i == 0)
1017 			panic("no emulations found in execsw_builtin[]\n");
1018 #endif
1019 	}
1020 
1021 	/*
1022 	 * Build execsw[] array from builtin entries and entries added
1023 	 * at runtime.
1024 	 */
1025 	list = NULL;
1026 	for(i=0; i < nexecs_builtin; i++)
1027 		link_es(&list, &execsw_builtin[i]);
1028 
1029 	/* Add dynamically loaded entries */
1030 	es_sz = nexecs_builtin;
1031 	LIST_FOREACH(e2, &ex_head, ex_list) {
1032 		link_es(&list, e2->es);
1033 		es_sz++;
1034 	}
1035 
1036 	/*
1037 	 * Now that we have sorted all execw entries, create new execsw[]
1038 	 * and free no longer needed memory in the process.
1039 	 */
1040 	new_es = malloc(es_sz * sizeof(struct execsw *), M_EXEC, M_WAITOK);
1041 	for(i=0; list; i++) {
1042 		new_es[i] = list->es;
1043 		e1 = list->next;
1044 		FREE(list, M_TEMP);
1045 		list = e1;
1046 	}
1047 
1048 	/*
1049 	 * New execsw[] array built, now replace old execsw[] and free
1050 	 * used memory.
1051 	 */
1052 	old_es = execsw;
1053 	execsw = new_es;
1054 	nexecs = es_sz;
1055 	if (old_es)
1056 		free((void *)old_es, M_EXEC);
1057 
1058 	/*
1059 	 * Figure out the maximum size of an exec header.
1060 	 */
1061 	exec_maxhdrsz = 0;
1062 	for (i = 0; i < nexecs; i++) {
1063 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
1064 			exec_maxhdrsz = execsw[i]->es_hdrsz;
1065 	}
1066 
1067 	return 0;
1068 }
1069 #endif
1070 
1071 #ifndef LKM
1072 /*
1073  * Simplified exec_init() for kernels without LKMs. Only initialize
1074  * exec_maxhdrsz and execsw[].
1075  */
1076 int
1077 exec_init(int init_boot)
1078 {
1079 	int i;
1080 
1081 #ifdef DIAGNOSTIC
1082 	if (!init_boot)
1083 		panic("exec_init(): called with init_boot == 0");
1084 #endif
1085 
1086 	/* do one-time initializations */
1087 	lockinit(&exec_lock, PWAIT, "execlck", 0, 0);
1088 
1089 	nexecs = nexecs_builtin;
1090 	execsw = malloc(nexecs*sizeof(struct execsw *), M_EXEC, M_WAITOK);
1091 
1092 	/*
1093 	 * Fill in execsw[] and figure out the maximum size of an exec header.
1094 	 */
1095 	exec_maxhdrsz = 0;
1096 	for(i=0; i < nexecs; i++) {
1097 		execsw[i] = &execsw_builtin[i];
1098 		if (execsw_builtin[i].es_hdrsz > exec_maxhdrsz)
1099 			exec_maxhdrsz = execsw_builtin[i].es_hdrsz;
1100 	}
1101 
1102 	return 0;
1103 
1104 }
1105 #endif /* !LKM */
1106