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