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