xref: /freebsd/sys/kern/kern_exec.c (revision 0f2bd1e89db1a2f09268edea21e0ead329e092df)
1 /*-
2  * Copyright (c) 1993, David Greenman
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_hwpmc_hooks.h"
31 #include "opt_kdtrace.h"
32 #include "opt_ktrace.h"
33 #include "opt_vm.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/eventhandler.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/sysproto.h>
41 #include <sys/signalvar.h>
42 #include <sys/kernel.h>
43 #include <sys/mount.h>
44 #include <sys/filedesc.h>
45 #include <sys/fcntl.h>
46 #include <sys/acct.h>
47 #include <sys/exec.h>
48 #include <sys/imgact.h>
49 #include <sys/imgact_elf.h>
50 #include <sys/wait.h>
51 #include <sys/malloc.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/pioctl.h>
55 #include <sys/namei.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sdt.h>
58 #include <sys/sf_buf.h>
59 #include <sys/syscallsubr.h>
60 #include <sys/sysent.h>
61 #include <sys/shm.h>
62 #include <sys/sysctl.h>
63 #include <sys/vnode.h>
64 #include <sys/stat.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_kern.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_pager.h>
78 
79 #ifdef	HWPMC_HOOKS
80 #include <sys/pmckern.h>
81 #endif
82 
83 #include <machine/reg.h>
84 
85 #include <security/audit/audit.h>
86 #include <security/mac/mac_framework.h>
87 
88 #ifdef KDTRACE_HOOKS
89 #include <sys/dtrace_bsd.h>
90 dtrace_execexit_func_t	dtrace_fasttrap_exec;
91 #endif
92 
93 SDT_PROVIDER_DECLARE(proc);
94 SDT_PROBE_DEFINE(proc, kernel, , exec);
95 SDT_PROBE_ARGTYPE(proc, kernel, , exec, 0, "char *");
96 SDT_PROBE_DEFINE(proc, kernel, , exec_failure);
97 SDT_PROBE_ARGTYPE(proc, kernel, , exec_failure, 0, "int");
98 SDT_PROBE_DEFINE(proc, kernel, , exec_success);
99 SDT_PROBE_ARGTYPE(proc, kernel, , exec_success, 0, "char *");
100 
101 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
102 
103 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
104 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
105 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
106 static int do_execve(struct thread *td, struct image_args *args,
107     struct mac *mac_p);
108 
109 /* XXX This should be vm_size_t. */
110 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
111     NULL, 0, sysctl_kern_ps_strings, "LU", "");
112 
113 /* XXX This should be vm_size_t. */
114 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD,
115     NULL, 0, sysctl_kern_usrstack, "LU", "");
116 
117 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
118     NULL, 0, sysctl_kern_stackprot, "I", "");
119 
120 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
121 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
122     &ps_arg_cache_limit, 0, "");
123 
124 static int map_at_zero = 0;
125 TUNABLE_INT("security.bsd.map_at_zero", &map_at_zero);
126 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RW, &map_at_zero, 0,
127     "Permit processes to map an object at virtual address 0.");
128 
129 static int
130 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
131 {
132 	struct proc *p;
133 	int error;
134 
135 	p = curproc;
136 #ifdef SCTL_MASK32
137 	if (req->flags & SCTL_MASK32) {
138 		unsigned int val;
139 		val = (unsigned int)p->p_sysent->sv_psstrings;
140 		error = SYSCTL_OUT(req, &val, sizeof(val));
141 	} else
142 #endif
143 		error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
144 		   sizeof(p->p_sysent->sv_psstrings));
145 	return error;
146 }
147 
148 static int
149 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
150 {
151 	struct proc *p;
152 	int error;
153 
154 	p = curproc;
155 #ifdef SCTL_MASK32
156 	if (req->flags & SCTL_MASK32) {
157 		unsigned int val;
158 		val = (unsigned int)p->p_sysent->sv_usrstack;
159 		error = SYSCTL_OUT(req, &val, sizeof(val));
160 	} else
161 #endif
162 		error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
163 		    sizeof(p->p_sysent->sv_usrstack));
164 	return error;
165 }
166 
167 static int
168 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
169 {
170 	struct proc *p;
171 
172 	p = curproc;
173 	return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
174 	    sizeof(p->p_sysent->sv_stackprot)));
175 }
176 
177 /*
178  * Each of the items is a pointer to a `const struct execsw', hence the
179  * double pointer here.
180  */
181 static const struct execsw **execsw;
182 
183 #ifndef _SYS_SYSPROTO_H_
184 struct execve_args {
185 	char    *fname;
186 	char    **argv;
187 	char    **envv;
188 };
189 #endif
190 
191 int
192 execve(td, uap)
193 	struct thread *td;
194 	struct execve_args /* {
195 		char *fname;
196 		char **argv;
197 		char **envv;
198 	} */ *uap;
199 {
200 	int error;
201 	struct image_args args;
202 
203 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
204 	    uap->argv, uap->envv);
205 	if (error == 0)
206 		error = kern_execve(td, &args, NULL);
207 	return (error);
208 }
209 
210 #ifndef _SYS_SYSPROTO_H_
211 struct fexecve_args {
212 	int	fd;
213 	char	**argv;
214 	char	**envv;
215 }
216 #endif
217 int
218 fexecve(struct thread *td, struct fexecve_args *uap)
219 {
220 	int error;
221 	struct image_args args;
222 
223 	error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
224 	    uap->argv, uap->envv);
225 	if (error == 0) {
226 		args.fd = uap->fd;
227 		error = kern_execve(td, &args, NULL);
228 	}
229 	return (error);
230 }
231 
232 #ifndef _SYS_SYSPROTO_H_
233 struct __mac_execve_args {
234 	char	*fname;
235 	char	**argv;
236 	char	**envv;
237 	struct mac	*mac_p;
238 };
239 #endif
240 
241 int
242 __mac_execve(td, uap)
243 	struct thread *td;
244 	struct __mac_execve_args /* {
245 		char *fname;
246 		char **argv;
247 		char **envv;
248 		struct mac *mac_p;
249 	} */ *uap;
250 {
251 #ifdef MAC
252 	int error;
253 	struct image_args args;
254 
255 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
256 	    uap->argv, uap->envv);
257 	if (error == 0)
258 		error = kern_execve(td, &args, uap->mac_p);
259 	return (error);
260 #else
261 	return (ENOSYS);
262 #endif
263 }
264 
265 /*
266  * XXX: kern_execve has the astonishing property of not always returning to
267  * the caller.  If sufficiently bad things happen during the call to
268  * do_execve(), it can end up calling exit1(); as a result, callers must
269  * avoid doing anything which they might need to undo (e.g., allocating
270  * memory).
271  */
272 int
273 kern_execve(td, args, mac_p)
274 	struct thread *td;
275 	struct image_args *args;
276 	struct mac *mac_p;
277 {
278 	struct proc *p = td->td_proc;
279 	int error;
280 
281 	AUDIT_ARG_ARGV(args->begin_argv, args->argc,
282 	    args->begin_envv - args->begin_argv);
283 	AUDIT_ARG_ENVV(args->begin_envv, args->envc,
284 	    args->endp - args->begin_envv);
285 	if (p->p_flag & P_HADTHREADS) {
286 		PROC_LOCK(p);
287 		if (thread_single(SINGLE_BOUNDARY)) {
288 			PROC_UNLOCK(p);
289 	       		exec_free_args(args);
290 			return (ERESTART);	/* Try again later. */
291 		}
292 		PROC_UNLOCK(p);
293 	}
294 
295 	error = do_execve(td, args, mac_p);
296 
297 	if (p->p_flag & P_HADTHREADS) {
298 		PROC_LOCK(p);
299 		/*
300 		 * If success, we upgrade to SINGLE_EXIT state to
301 		 * force other threads to suicide.
302 		 */
303 		if (error == 0)
304 			thread_single(SINGLE_EXIT);
305 		else
306 			thread_single_end();
307 		PROC_UNLOCK(p);
308 	}
309 
310 	return (error);
311 }
312 
313 /*
314  * In-kernel implementation of execve().  All arguments are assumed to be
315  * userspace pointers from the passed thread.
316  */
317 static int
318 do_execve(td, args, mac_p)
319 	struct thread *td;
320 	struct image_args *args;
321 	struct mac *mac_p;
322 {
323 	struct proc *p = td->td_proc;
324 	struct nameidata nd;
325 	struct ucred *newcred = NULL, *oldcred;
326 	struct uidinfo *euip;
327 	register_t *stack_base;
328 	int error, i;
329 	struct image_params image_params, *imgp;
330 	struct vattr attr;
331 	int (*img_first)(struct image_params *);
332 	struct pargs *oldargs = NULL, *newargs = NULL;
333 	struct sigacts *oldsigacts, *newsigacts;
334 #ifdef KTRACE
335 	struct vnode *tracevp = NULL;
336 	struct ucred *tracecred = NULL;
337 #endif
338 	struct vnode *textvp = NULL, *binvp = NULL;
339 	int credential_changing;
340 	int vfslocked;
341 	int textset;
342 #ifdef MAC
343 	struct label *interpvplabel = NULL;
344 	int will_transition;
345 #endif
346 #ifdef HWPMC_HOOKS
347 	struct pmckern_procexec pe;
348 #endif
349 	static const char fexecv_proc_title[] = "(fexecv)";
350 
351 	vfslocked = 0;
352 	imgp = &image_params;
353 
354 	/*
355 	 * Lock the process and set the P_INEXEC flag to indicate that
356 	 * it should be left alone until we're done here.  This is
357 	 * necessary to avoid race conditions - e.g. in ptrace() -
358 	 * that might allow a local user to illicitly obtain elevated
359 	 * privileges.
360 	 */
361 	PROC_LOCK(p);
362 	KASSERT((p->p_flag & P_INEXEC) == 0,
363 	    ("%s(): process already has P_INEXEC flag", __func__));
364 	p->p_flag |= P_INEXEC;
365 	PROC_UNLOCK(p);
366 
367 	/*
368 	 * Initialize part of the common data
369 	 */
370 	imgp->proc = p;
371 	imgp->execlabel = NULL;
372 	imgp->attr = &attr;
373 	imgp->entry_addr = 0;
374 	imgp->reloc_base = 0;
375 	imgp->vmspace_destroyed = 0;
376 	imgp->interpreted = 0;
377 	imgp->opened = 0;
378 	imgp->interpreter_name = NULL;
379 	imgp->auxargs = NULL;
380 	imgp->vp = NULL;
381 	imgp->object = NULL;
382 	imgp->firstpage = NULL;
383 	imgp->ps_strings = 0;
384 	imgp->auxarg_size = 0;
385 	imgp->args = args;
386 	imgp->execpath = imgp->freepath = NULL;
387 	imgp->execpathp = 0;
388 	imgp->canary = 0;
389 	imgp->canarylen = 0;
390 	imgp->pagesizes = 0;
391 	imgp->pagesizeslen = 0;
392 
393 #ifdef MAC
394 	error = mac_execve_enter(imgp, mac_p);
395 	if (error)
396 		goto exec_fail;
397 #endif
398 
399 	imgp->image_header = NULL;
400 
401 	/*
402 	 * Translate the file name. namei() returns a vnode pointer
403 	 *	in ni_vp amoung other things.
404 	 *
405 	 * XXXAUDIT: It would be desirable to also audit the name of the
406 	 * interpreter if this is an interpreted binary.
407 	 */
408 	if (args->fname != NULL) {
409 		NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
410 		    | MPSAFE | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
411 	}
412 
413 	SDT_PROBE(proc, kernel, , exec, args->fname, 0, 0, 0, 0 );
414 
415 interpret:
416 	if (args->fname != NULL) {
417 		error = namei(&nd);
418 		if (error)
419 			goto exec_fail;
420 
421 		vfslocked = NDHASGIANT(&nd);
422 		binvp  = nd.ni_vp;
423 		imgp->vp = binvp;
424 	} else {
425 		AUDIT_ARG_FD(args->fd);
426 		error = fgetvp(td, args->fd, &binvp);
427 		if (error)
428 			goto exec_fail;
429 		vfslocked = VFS_LOCK_GIANT(binvp->v_mount);
430 		vn_lock(binvp, LK_EXCLUSIVE | LK_RETRY);
431 		AUDIT_ARG_VNODE1(binvp);
432 		imgp->vp = binvp;
433 	}
434 
435 	/*
436 	 * Check file permissions (also 'opens' file)
437 	 */
438 	error = exec_check_permissions(imgp);
439 	if (error)
440 		goto exec_fail_dealloc;
441 
442 	imgp->object = imgp->vp->v_object;
443 	if (imgp->object != NULL)
444 		vm_object_reference(imgp->object);
445 
446 	/*
447 	 * Set VV_TEXT now so no one can write to the executable while we're
448 	 * activating it.
449 	 *
450 	 * Remember if this was set before and unset it in case this is not
451 	 * actually an executable image.
452 	 */
453 	textset = imgp->vp->v_vflag & VV_TEXT;
454 	imgp->vp->v_vflag |= VV_TEXT;
455 
456 	error = exec_map_first_page(imgp);
457 	if (error)
458 		goto exec_fail_dealloc;
459 
460 	imgp->proc->p_osrel = 0;
461 	/*
462 	 *	If the current process has a special image activator it
463 	 *	wants to try first, call it.   For example, emulating shell
464 	 *	scripts differently.
465 	 */
466 	error = -1;
467 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
468 		error = img_first(imgp);
469 
470 	/*
471 	 *	Loop through the list of image activators, calling each one.
472 	 *	An activator returns -1 if there is no match, 0 on success,
473 	 *	and an error otherwise.
474 	 */
475 	for (i = 0; error == -1 && execsw[i]; ++i) {
476 		if (execsw[i]->ex_imgact == NULL ||
477 		    execsw[i]->ex_imgact == img_first) {
478 			continue;
479 		}
480 		error = (*execsw[i]->ex_imgact)(imgp);
481 	}
482 
483 	if (error) {
484 		if (error == -1) {
485 			if (textset == 0)
486 				imgp->vp->v_vflag &= ~VV_TEXT;
487 			error = ENOEXEC;
488 		}
489 		goto exec_fail_dealloc;
490 	}
491 
492 	/*
493 	 * Special interpreter operation, cleanup and loop up to try to
494 	 * activate the interpreter.
495 	 */
496 	if (imgp->interpreted) {
497 		exec_unmap_first_page(imgp);
498 		/*
499 		 * VV_TEXT needs to be unset for scripts.  There is a short
500 		 * period before we determine that something is a script where
501 		 * VV_TEXT will be set. The vnode lock is held over this
502 		 * entire period so nothing should illegitimately be blocked.
503 		 */
504 		imgp->vp->v_vflag &= ~VV_TEXT;
505 		/* free name buffer and old vnode */
506 		if (args->fname != NULL)
507 			NDFREE(&nd, NDF_ONLY_PNBUF);
508 #ifdef MAC
509 		mac_execve_interpreter_enter(binvp, &interpvplabel);
510 #endif
511 		if (imgp->opened) {
512 			VOP_CLOSE(binvp, FREAD, td->td_ucred, td);
513 			imgp->opened = 0;
514 		}
515 		vput(binvp);
516 		vm_object_deallocate(imgp->object);
517 		imgp->object = NULL;
518 		VFS_UNLOCK_GIANT(vfslocked);
519 		vfslocked = 0;
520 		/* set new name to that of the interpreter */
521 		NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME | MPSAFE,
522 		    UIO_SYSSPACE, imgp->interpreter_name, td);
523 		args->fname = imgp->interpreter_name;
524 		goto interpret;
525 	}
526 
527 	/*
528 	 * NB: We unlock the vnode here because it is believed that none
529 	 * of the sv_copyout_strings/sv_fixup operations require the vnode.
530 	 */
531 	VOP_UNLOCK(imgp->vp, 0);
532 
533 	/*
534 	 * Do the best to calculate the full path to the image file.
535 	 */
536 	if (imgp->auxargs != NULL &&
537 	    ((args->fname != NULL && args->fname[0] == '/') ||
538 	     vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
539 		imgp->execpath = args->fname;
540 
541 	/*
542 	 * Copy out strings (args and env) and initialize stack base
543 	 */
544 	if (p->p_sysent->sv_copyout_strings)
545 		stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
546 	else
547 		stack_base = exec_copyout_strings(imgp);
548 
549 	/*
550 	 * If custom stack fixup routine present for this process
551 	 * let it do the stack setup.
552 	 * Else stuff argument count as first item on stack
553 	 */
554 	if (p->p_sysent->sv_fixup != NULL)
555 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
556 	else
557 		suword(--stack_base, imgp->args->argc);
558 
559 	/*
560 	 * For security and other reasons, the file descriptor table cannot
561 	 * be shared after an exec.
562 	 */
563 	fdunshare(p, td);
564 
565 	/*
566 	 * Malloc things before we need locks.
567 	 */
568 	newcred = crget();
569 	euip = uifind(attr.va_uid);
570 	i = imgp->args->begin_envv - imgp->args->begin_argv;
571 	/* Cache arguments if they fit inside our allowance */
572 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
573 		newargs = pargs_alloc(i);
574 		bcopy(imgp->args->begin_argv, newargs->ar_args, i);
575 	}
576 
577 	/* close files on exec */
578 	fdcloseexec(td);
579 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
580 
581 	/* Get a reference to the vnode prior to locking the proc */
582 	VREF(binvp);
583 
584 	/*
585 	 * For security and other reasons, signal handlers cannot
586 	 * be shared after an exec. The new process gets a copy of the old
587 	 * handlers. In execsigs(), the new process will have its signals
588 	 * reset.
589 	 */
590 	PROC_LOCK(p);
591 	oldcred = crcopysafe(p, newcred);
592 	if (sigacts_shared(p->p_sigacts)) {
593 		oldsigacts = p->p_sigacts;
594 		PROC_UNLOCK(p);
595 		newsigacts = sigacts_alloc();
596 		sigacts_copy(newsigacts, oldsigacts);
597 		PROC_LOCK(p);
598 		p->p_sigacts = newsigacts;
599 	} else
600 		oldsigacts = NULL;
601 
602 	/* Stop profiling */
603 	stopprofclock(p);
604 
605 	/* reset caught signals */
606 	execsigs(p);
607 
608 	/* name this process - nameiexec(p, ndp) */
609 	bzero(p->p_comm, sizeof(p->p_comm));
610 	if (args->fname)
611 		bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
612 		    min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
613 	else if (vn_commname(binvp, p->p_comm, sizeof(p->p_comm)) != 0)
614 		bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
615 	bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
616 
617 	/*
618 	 * mark as execed, wakeup the process that vforked (if any) and tell
619 	 * it that it now has its own resources back
620 	 */
621 	p->p_flag |= P_EXEC;
622 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
623 		p->p_flag &= ~P_PPWAIT;
624 		cv_broadcast(&p->p_pwait);
625 	}
626 
627 	/*
628 	 * Implement image setuid/setgid.
629 	 *
630 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
631 	 * the process is being traced.
632 	 *
633 	 * XXXMAC: For the time being, use NOSUID to also prohibit
634 	 * transitions on the file system.
635 	 */
636 	credential_changing = 0;
637 	credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
638 	    attr.va_uid;
639 	credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
640 	    attr.va_gid;
641 #ifdef MAC
642 	will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
643 	    interpvplabel, imgp);
644 	credential_changing |= will_transition;
645 #endif
646 
647 	if (credential_changing &&
648 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
649 	    (p->p_flag & P_TRACED) == 0) {
650 		/*
651 		 * Turn off syscall tracing for set-id programs, except for
652 		 * root.  Record any set-id flags first to make sure that
653 		 * we do not regain any tracing during a possible block.
654 		 */
655 		setsugid(p);
656 
657 #ifdef KTRACE
658 		if (p->p_tracevp != NULL &&
659 		    priv_check_cred(oldcred, PRIV_DEBUG_DIFFCRED, 0)) {
660 			mtx_lock(&ktrace_mtx);
661 			p->p_traceflag = 0;
662 			tracevp = p->p_tracevp;
663 			p->p_tracevp = NULL;
664 			tracecred = p->p_tracecred;
665 			p->p_tracecred = NULL;
666 			mtx_unlock(&ktrace_mtx);
667 		}
668 #endif
669 		/*
670 		 * Close any file descriptors 0..2 that reference procfs,
671 		 * then make sure file descriptors 0..2 are in use.
672 		 *
673 		 * setugidsafety() may call closef() and then pfind()
674 		 * which may grab the process lock.
675 		 * fdcheckstd() may call falloc() which may block to
676 		 * allocate memory, so temporarily drop the process lock.
677 		 */
678 		PROC_UNLOCK(p);
679 		VOP_UNLOCK(imgp->vp, 0);
680 		setugidsafety(td);
681 		error = fdcheckstd(td);
682 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
683 		if (error != 0)
684 			goto done1;
685 		PROC_LOCK(p);
686 		/*
687 		 * Set the new credentials.
688 		 */
689 		if (attr.va_mode & S_ISUID)
690 			change_euid(newcred, euip);
691 		if (attr.va_mode & S_ISGID)
692 			change_egid(newcred, attr.va_gid);
693 #ifdef MAC
694 		if (will_transition) {
695 			mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
696 			    interpvplabel, imgp);
697 		}
698 #endif
699 		/*
700 		 * Implement correct POSIX saved-id behavior.
701 		 *
702 		 * XXXMAC: Note that the current logic will save the
703 		 * uid and gid if a MAC domain transition occurs, even
704 		 * though maybe it shouldn't.
705 		 */
706 		change_svuid(newcred, newcred->cr_uid);
707 		change_svgid(newcred, newcred->cr_gid);
708 		p->p_ucred = newcred;
709 		newcred = NULL;
710 	} else {
711 		if (oldcred->cr_uid == oldcred->cr_ruid &&
712 		    oldcred->cr_gid == oldcred->cr_rgid)
713 			p->p_flag &= ~P_SUGID;
714 		/*
715 		 * Implement correct POSIX saved-id behavior.
716 		 *
717 		 * XXX: It's not clear that the existing behavior is
718 		 * POSIX-compliant.  A number of sources indicate that the
719 		 * saved uid/gid should only be updated if the new ruid is
720 		 * not equal to the old ruid, or the new euid is not equal
721 		 * to the old euid and the new euid is not equal to the old
722 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
723 		 * Also, this code uses the new (replaced) euid and egid as
724 		 * the source, which may or may not be the right ones to use.
725 		 */
726 		if (oldcred->cr_svuid != oldcred->cr_uid ||
727 		    oldcred->cr_svgid != oldcred->cr_gid) {
728 			change_svuid(newcred, newcred->cr_uid);
729 			change_svgid(newcred, newcred->cr_gid);
730 			p->p_ucred = newcred;
731 			newcred = NULL;
732 		}
733 	}
734 
735 	/*
736 	 * Store the vp for use in procfs.  This vnode was referenced prior
737 	 * to locking the proc lock.
738 	 */
739 	textvp = p->p_textvp;
740 	p->p_textvp = binvp;
741 
742 #ifdef KDTRACE_HOOKS
743 	/*
744 	 * Tell the DTrace fasttrap provider about the exec if it
745 	 * has declared an interest.
746 	 */
747 	if (dtrace_fasttrap_exec)
748 		dtrace_fasttrap_exec(p);
749 #endif
750 
751 	/*
752 	 * Notify others that we exec'd, and clear the P_INEXEC flag
753 	 * as we're now a bona fide freshly-execed process.
754 	 */
755 	KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
756 	p->p_flag &= ~P_INEXEC;
757 
758 	/*
759 	 * If tracing the process, trap to the debugger so that
760 	 * breakpoints can be set before the program executes.  We
761 	 * have to use tdsignal() to deliver the signal to the current
762 	 * thread since any other threads in this process will exit if
763 	 * execve() succeeds.
764 	 */
765 	if (p->p_flag & P_TRACED)
766 		tdsignal(td, SIGTRAP);
767 
768 	/* clear "fork but no exec" flag, as we _are_ execing */
769 	p->p_acflag &= ~AFORK;
770 
771 	/*
772 	 * Free any previous argument cache and replace it with
773 	 * the new argument cache, if any.
774 	 */
775 	oldargs = p->p_args;
776 	p->p_args = newargs;
777 	newargs = NULL;
778 
779 #ifdef	HWPMC_HOOKS
780 	/*
781 	 * Check if system-wide sampling is in effect or if the
782 	 * current process is using PMCs.  If so, do exec() time
783 	 * processing.  This processing needs to happen AFTER the
784 	 * P_INEXEC flag is cleared.
785 	 *
786 	 * The proc lock needs to be released before taking the PMC
787 	 * SX.
788 	 */
789 	if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
790 		PROC_UNLOCK(p);
791 		VOP_UNLOCK(imgp->vp, 0);
792 		pe.pm_credentialschanged = credential_changing;
793 		pe.pm_entryaddr = imgp->entry_addr;
794 
795 		PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
796 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
797 	} else
798 		PROC_UNLOCK(p);
799 #else  /* !HWPMC_HOOKS */
800 	PROC_UNLOCK(p);
801 #endif
802 
803 	/* Set values passed into the program in registers. */
804 	if (p->p_sysent->sv_setregs)
805 		(*p->p_sysent->sv_setregs)(td, imgp,
806 		    (u_long)(uintptr_t)stack_base);
807 	else
808 		exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
809 
810 	vfs_mark_atime(imgp->vp, td->td_ucred);
811 
812 	SDT_PROBE(proc, kernel, , exec_success, args->fname, 0, 0, 0, 0);
813 
814 done1:
815 	/*
816 	 * Free any resources malloc'd earlier that we didn't use.
817 	 */
818 	uifree(euip);
819 	if (newcred == NULL)
820 		crfree(oldcred);
821 	else
822 		crfree(newcred);
823 	VOP_UNLOCK(imgp->vp, 0);
824 
825 	/*
826 	 * Handle deferred decrement of ref counts.
827 	 */
828 	if (textvp != NULL) {
829 		int tvfslocked;
830 
831 		tvfslocked = VFS_LOCK_GIANT(textvp->v_mount);
832 		vrele(textvp);
833 		VFS_UNLOCK_GIANT(tvfslocked);
834 	}
835 	if (binvp && error != 0)
836 		vrele(binvp);
837 #ifdef KTRACE
838 	if (tracevp != NULL) {
839 		int tvfslocked;
840 
841 		tvfslocked = VFS_LOCK_GIANT(tracevp->v_mount);
842 		vrele(tracevp);
843 		VFS_UNLOCK_GIANT(tvfslocked);
844 	}
845 	if (tracecred != NULL)
846 		crfree(tracecred);
847 #endif
848 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
849 	pargs_drop(oldargs);
850 	pargs_drop(newargs);
851 	if (oldsigacts != NULL)
852 		sigacts_free(oldsigacts);
853 
854 exec_fail_dealloc:
855 
856 	/*
857 	 * free various allocated resources
858 	 */
859 	if (imgp->firstpage != NULL)
860 		exec_unmap_first_page(imgp);
861 
862 	if (imgp->vp != NULL) {
863 		if (args->fname)
864 			NDFREE(&nd, NDF_ONLY_PNBUF);
865 		if (imgp->opened)
866 			VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
867 		vput(imgp->vp);
868 	}
869 
870 	if (imgp->object != NULL)
871 		vm_object_deallocate(imgp->object);
872 
873 	free(imgp->freepath, M_TEMP);
874 
875 	if (error == 0) {
876 		PROC_LOCK(p);
877 		td->td_dbgflags |= TDB_EXEC;
878 		PROC_UNLOCK(p);
879 
880 		/*
881 		 * Stop the process here if its stop event mask has
882 		 * the S_EXEC bit set.
883 		 */
884 		STOPEVENT(p, S_EXEC, 0);
885 		goto done2;
886 	}
887 
888 exec_fail:
889 	/* we're done here, clear P_INEXEC */
890 	PROC_LOCK(p);
891 	p->p_flag &= ~P_INEXEC;
892 	PROC_UNLOCK(p);
893 
894 	SDT_PROBE(proc, kernel, , exec_failure, error, 0, 0, 0, 0);
895 
896 done2:
897 #ifdef MAC
898 	mac_execve_exit(imgp);
899 	mac_execve_interpreter_exit(interpvplabel);
900 #endif
901 	VFS_UNLOCK_GIANT(vfslocked);
902 	exec_free_args(args);
903 
904 	if (error && imgp->vmspace_destroyed) {
905 		/* sorry, no more process anymore. exit gracefully */
906 		exit1(td, W_EXITCODE(0, SIGABRT));
907 		/* NOT REACHED */
908 	}
909 	return (error);
910 }
911 
912 int
913 exec_map_first_page(imgp)
914 	struct image_params *imgp;
915 {
916 	int rv, i;
917 	int initial_pagein;
918 	vm_page_t ma[VM_INITIAL_PAGEIN];
919 	vm_object_t object;
920 
921 	if (imgp->firstpage != NULL)
922 		exec_unmap_first_page(imgp);
923 
924 	object = imgp->vp->v_object;
925 	if (object == NULL)
926 		return (EACCES);
927 	VM_OBJECT_LOCK(object);
928 #if VM_NRESERVLEVEL > 0
929 	if ((object->flags & OBJ_COLORED) == 0) {
930 		object->flags |= OBJ_COLORED;
931 		object->pg_color = 0;
932 	}
933 #endif
934 	ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
935 	if (ma[0]->valid != VM_PAGE_BITS_ALL) {
936 		initial_pagein = VM_INITIAL_PAGEIN;
937 		if (initial_pagein > object->size)
938 			initial_pagein = object->size;
939 		for (i = 1; i < initial_pagein; i++) {
940 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
941 				if (ma[i]->valid)
942 					break;
943 				if ((ma[i]->oflags & VPO_BUSY) || ma[i]->busy)
944 					break;
945 				vm_page_busy(ma[i]);
946 			} else {
947 				ma[i] = vm_page_alloc(object, i,
948 				    VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
949 				if (ma[i] == NULL)
950 					break;
951 			}
952 		}
953 		initial_pagein = i;
954 		rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
955 		ma[0] = vm_page_lookup(object, 0);
956 		if ((rv != VM_PAGER_OK) || (ma[0] == NULL)) {
957 			if (ma[0] != NULL) {
958 				vm_page_lock(ma[0]);
959 				vm_page_free(ma[0]);
960 				vm_page_unlock(ma[0]);
961 			}
962 			VM_OBJECT_UNLOCK(object);
963 			return (EIO);
964 		}
965 	}
966 	vm_page_lock(ma[0]);
967 	vm_page_hold(ma[0]);
968 	vm_page_unlock(ma[0]);
969 	vm_page_wakeup(ma[0]);
970 	VM_OBJECT_UNLOCK(object);
971 
972 	imgp->firstpage = sf_buf_alloc(ma[0], 0);
973 	imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
974 
975 	return (0);
976 }
977 
978 void
979 exec_unmap_first_page(imgp)
980 	struct image_params *imgp;
981 {
982 	vm_page_t m;
983 
984 	if (imgp->firstpage != NULL) {
985 		m = sf_buf_page(imgp->firstpage);
986 		sf_buf_free(imgp->firstpage);
987 		imgp->firstpage = NULL;
988 		vm_page_lock(m);
989 		vm_page_unhold(m);
990 		vm_page_unlock(m);
991 	}
992 }
993 
994 /*
995  * Destroy old address space, and allocate a new stack
996  *	The new stack is only SGROWSIZ large because it is grown
997  *	automatically in trap.c.
998  */
999 int
1000 exec_new_vmspace(imgp, sv)
1001 	struct image_params *imgp;
1002 	struct sysentvec *sv;
1003 {
1004 	int error;
1005 	struct proc *p = imgp->proc;
1006 	struct vmspace *vmspace = p->p_vmspace;
1007 	vm_offset_t sv_minuser, stack_addr;
1008 	vm_map_t map;
1009 	u_long ssiz;
1010 
1011 	imgp->vmspace_destroyed = 1;
1012 	imgp->sysent = sv;
1013 
1014 	/* May be called with Giant held */
1015 	EVENTHANDLER_INVOKE(process_exec, p, imgp);
1016 
1017 	/*
1018 	 * Blow away entire process VM, if address space not shared,
1019 	 * otherwise, create a new VM space so that other threads are
1020 	 * not disrupted
1021 	 */
1022 	map = &vmspace->vm_map;
1023 	if (map_at_zero)
1024 		sv_minuser = sv->sv_minuser;
1025 	else
1026 		sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1027 	if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1028 	    vm_map_max(map) == sv->sv_maxuser) {
1029 		shmexit(vmspace);
1030 		pmap_remove_pages(vmspace_pmap(vmspace));
1031 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1032 	} else {
1033 		error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1034 		if (error)
1035 			return (error);
1036 		vmspace = p->p_vmspace;
1037 		map = &vmspace->vm_map;
1038 	}
1039 
1040 	/* Allocate a new stack */
1041 	if (sv->sv_maxssiz != NULL)
1042 		ssiz = *sv->sv_maxssiz;
1043 	else
1044 		ssiz = maxssiz;
1045 	stack_addr = sv->sv_usrstack - ssiz;
1046 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1047 	    sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1048 	if (error)
1049 		return (error);
1050 
1051 #ifdef __ia64__
1052 	/* Allocate a new register stack */
1053 	stack_addr = IA64_BACKINGSTORE;
1054 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1055 	    sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_UP);
1056 	if (error)
1057 		return (error);
1058 #endif
1059 
1060 	/* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
1061 	 * VM_STACK case, but they are still used to monitor the size of the
1062 	 * process stack so we can check the stack rlimit.
1063 	 */
1064 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1065 	vmspace->vm_maxsaddr = (char *)sv->sv_usrstack - ssiz;
1066 
1067 	return (0);
1068 }
1069 
1070 /*
1071  * Copy out argument and environment strings from the old process address
1072  * space into the temporary string buffer.
1073  */
1074 int
1075 exec_copyin_args(struct image_args *args, char *fname,
1076     enum uio_seg segflg, char **argv, char **envv)
1077 {
1078 	char *argp, *envp;
1079 	int error;
1080 	size_t length;
1081 
1082 	bzero(args, sizeof(*args));
1083 	if (argv == NULL)
1084 		return (EFAULT);
1085 
1086 	/*
1087 	 * Allocate demand-paged memory for the file name, argument, and
1088 	 * environment strings.
1089 	 */
1090 	error = exec_alloc_args(args);
1091 	if (error != 0)
1092 		return (error);
1093 
1094 	/*
1095 	 * Copy the file name.
1096 	 */
1097 	if (fname != NULL) {
1098 		args->fname = args->buf;
1099 		error = (segflg == UIO_SYSSPACE) ?
1100 		    copystr(fname, args->fname, PATH_MAX, &length) :
1101 		    copyinstr(fname, args->fname, PATH_MAX, &length);
1102 		if (error != 0)
1103 			goto err_exit;
1104 	} else
1105 		length = 0;
1106 
1107 	args->begin_argv = args->buf + length;
1108 	args->endp = args->begin_argv;
1109 	args->stringspace = ARG_MAX;
1110 
1111 	/*
1112 	 * extract arguments first
1113 	 */
1114 	while ((argp = (caddr_t) (intptr_t) fuword(argv++))) {
1115 		if (argp == (caddr_t) -1) {
1116 			error = EFAULT;
1117 			goto err_exit;
1118 		}
1119 		if ((error = copyinstr(argp, args->endp,
1120 		    args->stringspace, &length))) {
1121 			if (error == ENAMETOOLONG)
1122 				error = E2BIG;
1123 			goto err_exit;
1124 		}
1125 		args->stringspace -= length;
1126 		args->endp += length;
1127 		args->argc++;
1128 	}
1129 
1130 	args->begin_envv = args->endp;
1131 
1132 	/*
1133 	 * extract environment strings
1134 	 */
1135 	if (envv) {
1136 		while ((envp = (caddr_t)(intptr_t)fuword(envv++))) {
1137 			if (envp == (caddr_t)-1) {
1138 				error = EFAULT;
1139 				goto err_exit;
1140 			}
1141 			if ((error = copyinstr(envp, args->endp,
1142 			    args->stringspace, &length))) {
1143 				if (error == ENAMETOOLONG)
1144 					error = E2BIG;
1145 				goto err_exit;
1146 			}
1147 			args->stringspace -= length;
1148 			args->endp += length;
1149 			args->envc++;
1150 		}
1151 	}
1152 
1153 	return (0);
1154 
1155 err_exit:
1156 	exec_free_args(args);
1157 	return (error);
1158 }
1159 
1160 /*
1161  * Allocate temporary demand-paged, zero-filled memory for the file name,
1162  * argument, and environment strings.  Returns zero if the allocation succeeds
1163  * and ENOMEM otherwise.
1164  */
1165 int
1166 exec_alloc_args(struct image_args *args)
1167 {
1168 
1169 	args->buf = (char *)kmem_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1170 	return (args->buf != NULL ? 0 : ENOMEM);
1171 }
1172 
1173 void
1174 exec_free_args(struct image_args *args)
1175 {
1176 
1177 	if (args->buf != NULL) {
1178 		kmem_free_wakeup(exec_map, (vm_offset_t)args->buf,
1179 		    PATH_MAX + ARG_MAX);
1180 		args->buf = NULL;
1181 	}
1182 	if (args->fname_buf != NULL) {
1183 		free(args->fname_buf, M_TEMP);
1184 		args->fname_buf = NULL;
1185 	}
1186 }
1187 
1188 /*
1189  * Copy strings out to the new process address space, constructing new arg
1190  * and env vector tables. Return a pointer to the base so that it can be used
1191  * as the initial stack pointer.
1192  */
1193 register_t *
1194 exec_copyout_strings(imgp)
1195 	struct image_params *imgp;
1196 {
1197 	int argc, envc;
1198 	char **vectp;
1199 	char *stringp, *destp;
1200 	register_t *stack_base;
1201 	struct ps_strings *arginfo;
1202 	struct proc *p;
1203 	size_t execpath_len;
1204 	int szsigcode, szps;
1205 	char canary[sizeof(long) * 8];
1206 
1207 	szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1208 	/*
1209 	 * Calculate string base and vector table pointers.
1210 	 * Also deal with signal trampoline code for this exec type.
1211 	 */
1212 	if (imgp->execpath != NULL && imgp->auxargs != NULL)
1213 		execpath_len = strlen(imgp->execpath) + 1;
1214 	else
1215 		execpath_len = 0;
1216 	p = imgp->proc;
1217 	szsigcode = 0;
1218 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1219 	if (p->p_sysent->sv_szsigcode != NULL)
1220 		szsigcode = *(p->p_sysent->sv_szsigcode);
1221 	destp =	(caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
1222 	    roundup(execpath_len, sizeof(char *)) -
1223 	    roundup(sizeof(canary), sizeof(char *)) -
1224 	    roundup(szps, sizeof(char *)) -
1225 	    roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *));
1226 
1227 	/*
1228 	 * install sigcode
1229 	 */
1230 	if (szsigcode)
1231 		copyout(p->p_sysent->sv_sigcode, ((caddr_t)arginfo -
1232 		    szsigcode), szsigcode);
1233 
1234 	/*
1235 	 * Copy the image path for the rtld.
1236 	 */
1237 	if (execpath_len != 0) {
1238 		imgp->execpathp = (uintptr_t)arginfo - szsigcode - execpath_len;
1239 		copyout(imgp->execpath, (void *)imgp->execpathp,
1240 		    execpath_len);
1241 	}
1242 
1243 	/*
1244 	 * Prepare the canary for SSP.
1245 	 */
1246 	arc4rand(canary, sizeof(canary), 0);
1247 	imgp->canary = (uintptr_t)arginfo - szsigcode - execpath_len -
1248 	    sizeof(canary);
1249 	copyout(canary, (void *)imgp->canary, sizeof(canary));
1250 	imgp->canarylen = sizeof(canary);
1251 
1252 	/*
1253 	 * Prepare the pagesizes array.
1254 	 */
1255 	imgp->pagesizes = (uintptr_t)arginfo - szsigcode - execpath_len -
1256 	    roundup(sizeof(canary), sizeof(char *)) - szps;
1257 	copyout(pagesizes, (void *)imgp->pagesizes, szps);
1258 	imgp->pagesizeslen = szps;
1259 
1260 	/*
1261 	 * If we have a valid auxargs ptr, prepare some room
1262 	 * on the stack.
1263 	 */
1264 	if (imgp->auxargs) {
1265 		/*
1266 		 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1267 		 * lower compatibility.
1268 		 */
1269 		imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1270 		    (AT_COUNT * 2);
1271 		/*
1272 		 * The '+ 2' is for the null pointers at the end of each of
1273 		 * the arg and env vector sets,and imgp->auxarg_size is room
1274 		 * for argument of Runtime loader.
1275 		 */
1276 		vectp = (char **)(destp - (imgp->args->argc +
1277 		    imgp->args->envc + 2 + imgp->auxarg_size)
1278 		    * sizeof(char *));
1279 	} else {
1280 		/*
1281 		 * The '+ 2' is for the null pointers at the end of each of
1282 		 * the arg and env vector sets
1283 		 */
1284 		vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2) *
1285 		    sizeof(char *));
1286 	}
1287 
1288 	/*
1289 	 * vectp also becomes our initial stack base
1290 	 */
1291 	stack_base = (register_t *)vectp;
1292 
1293 	stringp = imgp->args->begin_argv;
1294 	argc = imgp->args->argc;
1295 	envc = imgp->args->envc;
1296 
1297 	/*
1298 	 * Copy out strings - arguments and environment.
1299 	 */
1300 	copyout(stringp, destp, ARG_MAX - imgp->args->stringspace);
1301 
1302 	/*
1303 	 * Fill in "ps_strings" struct for ps, w, etc.
1304 	 */
1305 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1306 	suword32(&arginfo->ps_nargvstr, argc);
1307 
1308 	/*
1309 	 * Fill in argument portion of vector table.
1310 	 */
1311 	for (; argc > 0; --argc) {
1312 		suword(vectp++, (long)(intptr_t)destp);
1313 		while (*stringp++ != 0)
1314 			destp++;
1315 		destp++;
1316 	}
1317 
1318 	/* a null vector table pointer separates the argp's from the envp's */
1319 	suword(vectp++, 0);
1320 
1321 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1322 	suword32(&arginfo->ps_nenvstr, envc);
1323 
1324 	/*
1325 	 * Fill in environment portion of vector table.
1326 	 */
1327 	for (; envc > 0; --envc) {
1328 		suword(vectp++, (long)(intptr_t)destp);
1329 		while (*stringp++ != 0)
1330 			destp++;
1331 		destp++;
1332 	}
1333 
1334 	/* end of vector table is a null pointer */
1335 	suword(vectp, 0);
1336 
1337 	return (stack_base);
1338 }
1339 
1340 /*
1341  * Check permissions of file to execute.
1342  *	Called with imgp->vp locked.
1343  *	Return 0 for success or error code on failure.
1344  */
1345 int
1346 exec_check_permissions(imgp)
1347 	struct image_params *imgp;
1348 {
1349 	struct vnode *vp = imgp->vp;
1350 	struct vattr *attr = imgp->attr;
1351 	struct thread *td;
1352 	int error;
1353 
1354 	td = curthread;
1355 
1356 	/* Get file attributes */
1357 	error = VOP_GETATTR(vp, attr, td->td_ucred);
1358 	if (error)
1359 		return (error);
1360 
1361 #ifdef MAC
1362 	error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1363 	if (error)
1364 		return (error);
1365 #endif
1366 
1367 	/*
1368 	 * 1) Check if file execution is disabled for the filesystem that this
1369 	 *	file resides on.
1370 	 * 2) Insure that at least one execute bit is on - otherwise root
1371 	 *	will always succeed, and we don't want to happen unless the
1372 	 *	file really is executable.
1373 	 * 3) Insure that the file is a regular file.
1374 	 */
1375 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1376 	    ((attr->va_mode & 0111) == 0) ||
1377 	    (attr->va_type != VREG))
1378 		return (EACCES);
1379 
1380 	/*
1381 	 * Zero length files can't be exec'd
1382 	 */
1383 	if (attr->va_size == 0)
1384 		return (ENOEXEC);
1385 
1386 	/*
1387 	 *  Check for execute permission to file based on current credentials.
1388 	 */
1389 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1390 	if (error)
1391 		return (error);
1392 
1393 	/*
1394 	 * Check number of open-for-writes on the file and deny execution
1395 	 * if there are any.
1396 	 */
1397 	if (vp->v_writecount)
1398 		return (ETXTBSY);
1399 
1400 	/*
1401 	 * Call filesystem specific open routine (which does nothing in the
1402 	 * general case).
1403 	 */
1404 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1405 	if (error == 0)
1406 		imgp->opened = 1;
1407 	return (error);
1408 }
1409 
1410 /*
1411  * Exec handler registration
1412  */
1413 int
1414 exec_register(execsw_arg)
1415 	const struct execsw *execsw_arg;
1416 {
1417 	const struct execsw **es, **xs, **newexecsw;
1418 	int count = 2;	/* New slot and trailing NULL */
1419 
1420 	if (execsw)
1421 		for (es = execsw; *es; es++)
1422 			count++;
1423 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1424 	if (newexecsw == NULL)
1425 		return (ENOMEM);
1426 	xs = newexecsw;
1427 	if (execsw)
1428 		for (es = execsw; *es; es++)
1429 			*xs++ = *es;
1430 	*xs++ = execsw_arg;
1431 	*xs = NULL;
1432 	if (execsw)
1433 		free(execsw, M_TEMP);
1434 	execsw = newexecsw;
1435 	return (0);
1436 }
1437 
1438 int
1439 exec_unregister(execsw_arg)
1440 	const struct execsw *execsw_arg;
1441 {
1442 	const struct execsw **es, **xs, **newexecsw;
1443 	int count = 1;
1444 
1445 	if (execsw == NULL)
1446 		panic("unregister with no handlers left?\n");
1447 
1448 	for (es = execsw; *es; es++) {
1449 		if (*es == execsw_arg)
1450 			break;
1451 	}
1452 	if (*es == NULL)
1453 		return (ENOENT);
1454 	for (es = execsw; *es; es++)
1455 		if (*es != execsw_arg)
1456 			count++;
1457 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1458 	if (newexecsw == NULL)
1459 		return (ENOMEM);
1460 	xs = newexecsw;
1461 	for (es = execsw; *es; es++)
1462 		if (*es != execsw_arg)
1463 			*xs++ = *es;
1464 	*xs = NULL;
1465 	if (execsw)
1466 		free(execsw, M_TEMP);
1467 	execsw = newexecsw;
1468 	return (0);
1469 }
1470