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