xref: /freebsd/sys/kern/kern_exec.c (revision 128e3872b90b0da81dc8340f720c87d18955895e)
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, , , exec, "char *");
98 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
99 SDT_PROBE_DEFINE1(proc, , , 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 *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 	oldcred = p->p_ucred;
408 
409 #ifdef MAC
410 	error = mac_execve_enter(imgp, mac_p);
411 	if (error)
412 		goto exec_fail;
413 #endif
414 
415 	/*
416 	 * Translate the file name. namei() returns a vnode pointer
417 	 *	in ni_vp among other things.
418 	 *
419 	 * XXXAUDIT: It would be desirable to also audit the name of the
420 	 * interpreter if this is an interpreted binary.
421 	 */
422 	if (args->fname != NULL) {
423 		NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
424 		    | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
425 	}
426 
427 	SDT_PROBE1(proc, , , exec, args->fname);
428 
429 interpret:
430 	if (args->fname != NULL) {
431 #ifdef CAPABILITY_MODE
432 		/*
433 		 * While capability mode can't reach this point via direct
434 		 * path arguments to execve(), we also don't allow
435 		 * interpreters to be used in capability mode (for now).
436 		 * Catch indirect lookups and return a permissions error.
437 		 */
438 		if (IN_CAPABILITY_MODE(td)) {
439 			error = ECAPMODE;
440 			goto exec_fail;
441 		}
442 #endif
443 		error = namei(&nd);
444 		if (error)
445 			goto exec_fail;
446 
447 		newtextvp = nd.ni_vp;
448 		imgp->vp = newtextvp;
449 	} else {
450 		AUDIT_ARG_FD(args->fd);
451 		/*
452 		 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
453 		 */
454 		error = fgetvp_exec(td, args->fd,
455 		    cap_rights_init(&rights, CAP_FEXECVE), &newtextvp);
456 		if (error)
457 			goto exec_fail;
458 		vn_lock(newtextvp, LK_EXCLUSIVE | LK_RETRY);
459 		AUDIT_ARG_VNODE1(newtextvp);
460 		imgp->vp = newtextvp;
461 	}
462 
463 	/*
464 	 * Check file permissions (also 'opens' file)
465 	 */
466 	error = exec_check_permissions(imgp);
467 	if (error)
468 		goto exec_fail_dealloc;
469 
470 	imgp->object = imgp->vp->v_object;
471 	if (imgp->object != NULL)
472 		vm_object_reference(imgp->object);
473 
474 	/*
475 	 * Set VV_TEXT now so no one can write to the executable while we're
476 	 * activating it.
477 	 *
478 	 * Remember if this was set before and unset it in case this is not
479 	 * actually an executable image.
480 	 */
481 	textset = VOP_IS_TEXT(imgp->vp);
482 	VOP_SET_TEXT(imgp->vp);
483 
484 	error = exec_map_first_page(imgp);
485 	if (error)
486 		goto exec_fail_dealloc;
487 
488 	imgp->proc->p_osrel = 0;
489 
490 	/*
491 	 * Implement image setuid/setgid.
492 	 *
493 	 * Determine new credentials before attempting image activators
494 	 * so that it can be used by process_exec handlers to determine
495 	 * credential/setid changes.
496 	 *
497 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
498 	 * the process is being traced.
499 	 *
500 	 * We disable setuid/setgid/etc in capability mode on the basis
501 	 * that most setugid applications are not written with that
502 	 * environment in mind, and will therefore almost certainly operate
503 	 * incorrectly. In principle there's no reason that setugid
504 	 * applications might not be useful in capability mode, so we may want
505 	 * to reconsider this conservative design choice in the future.
506 	 *
507 	 * XXXMAC: For the time being, use NOSUID to also prohibit
508 	 * transitions on the file system.
509 	 */
510 	credential_changing = 0;
511 	credential_changing |= (attr.va_mode & S_ISUID) &&
512 	    oldcred->cr_uid != attr.va_uid;
513 	credential_changing |= (attr.va_mode & S_ISGID) &&
514 	    oldcred->cr_gid != attr.va_gid;
515 #ifdef MAC
516 	will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
517 	    interpvplabel, imgp);
518 	credential_changing |= will_transition;
519 #endif
520 
521 	if (credential_changing &&
522 #ifdef CAPABILITY_MODE
523 	    ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
524 #endif
525 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
526 	    (p->p_flag & P_TRACED) == 0) {
527 		imgp->credential_setid = true;
528 		VOP_UNLOCK(imgp->vp, 0);
529 		imgp->newcred = crdup(oldcred);
530 		if (attr.va_mode & S_ISUID) {
531 			euip = uifind(attr.va_uid);
532 			change_euid(imgp->newcred, euip);
533 		}
534 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
535 		if (attr.va_mode & S_ISGID)
536 			change_egid(imgp->newcred, attr.va_gid);
537 		/*
538 		 * Implement correct POSIX saved-id behavior.
539 		 *
540 		 * XXXMAC: Note that the current logic will save the
541 		 * uid and gid if a MAC domain transition occurs, even
542 		 * though maybe it shouldn't.
543 		 */
544 		change_svuid(imgp->newcred, imgp->newcred->cr_uid);
545 		change_svgid(imgp->newcred, imgp->newcred->cr_gid);
546 	} else {
547 		/*
548 		 * Implement correct POSIX saved-id behavior.
549 		 *
550 		 * XXX: It's not clear that the existing behavior is
551 		 * POSIX-compliant.  A number of sources indicate that the
552 		 * saved uid/gid should only be updated if the new ruid is
553 		 * not equal to the old ruid, or the new euid is not equal
554 		 * to the old euid and the new euid is not equal to the old
555 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
556 		 * Also, this code uses the new (replaced) euid and egid as
557 		 * the source, which may or may not be the right ones to use.
558 		 */
559 		if (oldcred->cr_svuid != oldcred->cr_uid ||
560 		    oldcred->cr_svgid != oldcred->cr_gid) {
561 			VOP_UNLOCK(imgp->vp, 0);
562 			imgp->newcred = crdup(oldcred);
563 			vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
564 			change_svuid(imgp->newcred, imgp->newcred->cr_uid);
565 			change_svgid(imgp->newcred, imgp->newcred->cr_gid);
566 		}
567 	}
568 	/* The new credentials are installed into the process later. */
569 
570 	/*
571 	 * Do the best to calculate the full path to the image file.
572 	 */
573 	if (args->fname != NULL && args->fname[0] == '/')
574 		imgp->execpath = args->fname;
575 	else {
576 		VOP_UNLOCK(imgp->vp, 0);
577 		if (vn_fullpath(td, imgp->vp, &imgp->execpath,
578 		    &imgp->freepath) != 0)
579 			imgp->execpath = args->fname;
580 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
581 	}
582 
583 	/*
584 	 *	If the current process has a special image activator it
585 	 *	wants to try first, call it.   For example, emulating shell
586 	 *	scripts differently.
587 	 */
588 	error = -1;
589 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
590 		error = img_first(imgp);
591 
592 	/*
593 	 *	Loop through the list of image activators, calling each one.
594 	 *	An activator returns -1 if there is no match, 0 on success,
595 	 *	and an error otherwise.
596 	 */
597 	for (i = 0; error == -1 && execsw[i]; ++i) {
598 		if (execsw[i]->ex_imgact == NULL ||
599 		    execsw[i]->ex_imgact == img_first) {
600 			continue;
601 		}
602 		error = (*execsw[i]->ex_imgact)(imgp);
603 	}
604 
605 	if (error) {
606 		if (error == -1) {
607 			if (textset == 0)
608 				VOP_UNSET_TEXT(imgp->vp);
609 			error = ENOEXEC;
610 		}
611 		goto exec_fail_dealloc;
612 	}
613 
614 	/*
615 	 * Special interpreter operation, cleanup and loop up to try to
616 	 * activate the interpreter.
617 	 */
618 	if (imgp->interpreted) {
619 		exec_unmap_first_page(imgp);
620 		/*
621 		 * VV_TEXT needs to be unset for scripts.  There is a short
622 		 * period before we determine that something is a script where
623 		 * VV_TEXT will be set. The vnode lock is held over this
624 		 * entire period so nothing should illegitimately be blocked.
625 		 */
626 		VOP_UNSET_TEXT(imgp->vp);
627 		/* free name buffer and old vnode */
628 		if (args->fname != NULL)
629 			NDFREE(&nd, NDF_ONLY_PNBUF);
630 #ifdef MAC
631 		mac_execve_interpreter_enter(newtextvp, &interpvplabel);
632 #endif
633 		if (imgp->opened) {
634 			VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
635 			imgp->opened = 0;
636 		}
637 		vput(newtextvp);
638 		vm_object_deallocate(imgp->object);
639 		imgp->object = NULL;
640 		imgp->credential_setid = false;
641 		if (imgp->newcred != NULL) {
642 			crfree(imgp->newcred);
643 			imgp->newcred = NULL;
644 		}
645 		imgp->execpath = NULL;
646 		free(imgp->freepath, M_TEMP);
647 		imgp->freepath = NULL;
648 		/* set new name to that of the interpreter */
649 		NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
650 		    UIO_SYSSPACE, imgp->interpreter_name, td);
651 		args->fname = imgp->interpreter_name;
652 		goto interpret;
653 	}
654 
655 	/*
656 	 * NB: We unlock the vnode here because it is believed that none
657 	 * of the sv_copyout_strings/sv_fixup operations require the vnode.
658 	 */
659 	VOP_UNLOCK(imgp->vp, 0);
660 
661 	if (disallow_high_osrel &&
662 	    P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
663 		error = ENOEXEC;
664 		uprintf("Osrel %d for image %s too high\n", p->p_osrel,
665 		    imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
666 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
667 		goto exec_fail_dealloc;
668 	}
669 
670 	/* ABI enforces the use of Capsicum. Switch into capabilities mode. */
671 	if (SV_PROC_FLAG(p, SV_CAPSICUM))
672 		sys_cap_enter(td, NULL);
673 
674 	/*
675 	 * Copy out strings (args and env) and initialize stack base
676 	 */
677 	if (p->p_sysent->sv_copyout_strings)
678 		stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
679 	else
680 		stack_base = exec_copyout_strings(imgp);
681 
682 	/*
683 	 * If custom stack fixup routine present for this process
684 	 * let it do the stack setup.
685 	 * Else stuff argument count as first item on stack
686 	 */
687 	if (p->p_sysent->sv_fixup != NULL)
688 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
689 	else
690 		suword(--stack_base, imgp->args->argc);
691 
692 	if (args->fdp != NULL) {
693 		/* Install a brand new file descriptor table. */
694 		fdinstall_remapped(td, args->fdp);
695 		args->fdp = NULL;
696 	} else {
697 		/*
698 		 * Keep on using the existing file descriptor table. For
699 		 * security and other reasons, the file descriptor table
700 		 * cannot be shared after an exec.
701 		 */
702 		fdunshare(td);
703 		/* close files on exec */
704 		fdcloseexec(td);
705 	}
706 
707 	/*
708 	 * Malloc things before we need locks.
709 	 */
710 	i = imgp->args->begin_envv - imgp->args->begin_argv;
711 	/* Cache arguments if they fit inside our allowance */
712 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
713 		newargs = pargs_alloc(i);
714 		bcopy(imgp->args->begin_argv, newargs->ar_args, i);
715 	}
716 
717 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
718 
719 	/*
720 	 * For security and other reasons, signal handlers cannot
721 	 * be shared after an exec. The new process gets a copy of the old
722 	 * handlers. In execsigs(), the new process will have its signals
723 	 * reset.
724 	 */
725 	if (sigacts_shared(p->p_sigacts)) {
726 		oldsigacts = p->p_sigacts;
727 		newsigacts = sigacts_alloc();
728 		sigacts_copy(newsigacts, oldsigacts);
729 	} else {
730 		oldsigacts = NULL;
731 		newsigacts = NULL; /* satisfy gcc */
732 	}
733 
734 	PROC_LOCK(p);
735 	if (oldsigacts)
736 		p->p_sigacts = newsigacts;
737 	/* Stop profiling */
738 	stopprofclock(p);
739 
740 	/* reset caught signals */
741 	execsigs(p);
742 
743 	/* name this process - nameiexec(p, ndp) */
744 	bzero(p->p_comm, sizeof(p->p_comm));
745 	if (args->fname)
746 		bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
747 		    min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
748 	else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
749 		bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
750 	bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
751 #ifdef KTR
752 	sched_clear_tdname(td);
753 #endif
754 
755 	/*
756 	 * mark as execed, wakeup the process that vforked (if any) and tell
757 	 * it that it now has its own resources back
758 	 */
759 	p->p_flag |= P_EXEC;
760 	if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
761 		p->p_flag2 &= ~P2_NOTRACE;
762 	if (p->p_flag & P_PPWAIT) {
763 		p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
764 		cv_broadcast(&p->p_pwait);
765 	}
766 
767 	/*
768 	 * Implement image setuid/setgid installation.
769 	 */
770 	if (imgp->credential_setid) {
771 		/*
772 		 * Turn off syscall tracing for set-id programs, except for
773 		 * root.  Record any set-id flags first to make sure that
774 		 * we do not regain any tracing during a possible block.
775 		 */
776 		setsugid(p);
777 
778 #ifdef KTRACE
779 		if (p->p_tracecred != NULL &&
780 		    priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
781 			ktrprocexec(p, &tracecred, &tracevp);
782 #endif
783 		/*
784 		 * Close any file descriptors 0..2 that reference procfs,
785 		 * then make sure file descriptors 0..2 are in use.
786 		 *
787 		 * Both fdsetugidsafety() and fdcheckstd() may call functions
788 		 * taking sleepable locks, so temporarily drop our locks.
789 		 */
790 		PROC_UNLOCK(p);
791 		VOP_UNLOCK(imgp->vp, 0);
792 		fdsetugidsafety(td);
793 		error = fdcheckstd(td);
794 		if (error != 0)
795 			goto done1;
796 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
797 		PROC_LOCK(p);
798 #ifdef MAC
799 		if (will_transition) {
800 			mac_vnode_execve_transition(oldcred, imgp->newcred,
801 			    imgp->vp, interpvplabel, imgp);
802 		}
803 #endif
804 	} else {
805 		if (oldcred->cr_uid == oldcred->cr_ruid &&
806 		    oldcred->cr_gid == oldcred->cr_rgid)
807 			p->p_flag &= ~P_SUGID;
808 	}
809 	/*
810 	 * Set the new credentials.
811 	 */
812 	if (imgp->newcred != NULL)
813 		proc_set_cred(p, imgp->newcred);
814 
815 	/*
816 	 * Store the vp for use in procfs.  This vnode was referenced by namei
817 	 * or fgetvp_exec.
818 	 */
819 	oldtextvp = p->p_textvp;
820 	p->p_textvp = newtextvp;
821 
822 #ifdef KDTRACE_HOOKS
823 	/*
824 	 * Tell the DTrace fasttrap provider about the exec if it
825 	 * has declared an interest.
826 	 */
827 	if (dtrace_fasttrap_exec)
828 		dtrace_fasttrap_exec(p);
829 #endif
830 
831 	/*
832 	 * Notify others that we exec'd, and clear the P_INEXEC flag
833 	 * as we're now a bona fide freshly-execed process.
834 	 */
835 	KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
836 	p->p_flag &= ~P_INEXEC;
837 
838 	/* clear "fork but no exec" flag, as we _are_ execing */
839 	p->p_acflag &= ~AFORK;
840 
841 	/*
842 	 * Free any previous argument cache and replace it with
843 	 * the new argument cache, if any.
844 	 */
845 	oldargs = p->p_args;
846 	p->p_args = newargs;
847 	newargs = NULL;
848 
849 #ifdef	HWPMC_HOOKS
850 	/*
851 	 * Check if system-wide sampling is in effect or if the
852 	 * current process is using PMCs.  If so, do exec() time
853 	 * processing.  This processing needs to happen AFTER the
854 	 * P_INEXEC flag is cleared.
855 	 *
856 	 * The proc lock needs to be released before taking the PMC
857 	 * SX.
858 	 */
859 	if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
860 		PROC_UNLOCK(p);
861 		VOP_UNLOCK(imgp->vp, 0);
862 		pe.pm_credentialschanged = credential_changing;
863 		pe.pm_entryaddr = imgp->entry_addr;
864 
865 		PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
866 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
867 	} else
868 		PROC_UNLOCK(p);
869 #else  /* !HWPMC_HOOKS */
870 	PROC_UNLOCK(p);
871 #endif
872 
873 	/* Set values passed into the program in registers. */
874 	if (p->p_sysent->sv_setregs)
875 		(*p->p_sysent->sv_setregs)(td, imgp,
876 		    (u_long)(uintptr_t)stack_base);
877 	else
878 		exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
879 
880 	vfs_mark_atime(imgp->vp, td->td_ucred);
881 
882 	SDT_PROBE1(proc, , , exec__success, args->fname);
883 
884 	VOP_UNLOCK(imgp->vp, 0);
885 done1:
886 	/*
887 	 * Handle deferred decrement of ref counts.
888 	 */
889 	if (oldtextvp != NULL)
890 		vrele(oldtextvp);
891 #ifdef KTRACE
892 	if (tracevp != NULL)
893 		vrele(tracevp);
894 	if (tracecred != NULL)
895 		crfree(tracecred);
896 #endif
897 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
898 	pargs_drop(oldargs);
899 	pargs_drop(newargs);
900 	if (oldsigacts != NULL)
901 		sigacts_free(oldsigacts);
902 
903 exec_fail_dealloc:
904 	/*
905 	 * free various allocated resources
906 	 */
907 	if (euip != NULL)
908 		uifree(euip);
909 
910 	if (imgp->firstpage != NULL)
911 		exec_unmap_first_page(imgp);
912 
913 	if (imgp->vp != NULL) {
914 		if (args->fname)
915 			NDFREE(&nd, NDF_ONLY_PNBUF);
916 		if (imgp->opened)
917 			VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
918 		if (error != 0)
919 			vput(imgp->vp);
920 		else
921 			VOP_UNLOCK(imgp->vp, 0);
922 	}
923 
924 	if (imgp->object != NULL)
925 		vm_object_deallocate(imgp->object);
926 
927 	free(imgp->freepath, M_TEMP);
928 
929 	if (error == 0) {
930 		PROC_LOCK(p);
931 		td->td_dbgflags |= TDB_EXEC;
932 		PROC_UNLOCK(p);
933 
934 		/*
935 		 * Stop the process here if its stop event mask has
936 		 * the S_EXEC bit set.
937 		 */
938 		STOPEVENT(p, S_EXEC, 0);
939 		goto done2;
940 	}
941 
942 exec_fail:
943 	/* we're done here, clear P_INEXEC */
944 	PROC_LOCK(p);
945 	p->p_flag &= ~P_INEXEC;
946 	PROC_UNLOCK(p);
947 
948 	SDT_PROBE1(proc, , , exec__failure, error);
949 
950 done2:
951 	if (imgp->newcred != NULL)
952 		crfree(oldcred);
953 #ifdef MAC
954 	mac_execve_exit(imgp);
955 	mac_execve_interpreter_exit(interpvplabel);
956 #endif
957 	exec_free_args(args);
958 
959 	if (error && imgp->vmspace_destroyed) {
960 		/* sorry, no more process anymore. exit gracefully */
961 		exit1(td, 0, SIGABRT);
962 		/* NOT REACHED */
963 	}
964 
965 #ifdef KTRACE
966 	if (error == 0)
967 		ktrprocctor(p);
968 #endif
969 
970 	return (error);
971 }
972 
973 int
974 exec_map_first_page(imgp)
975 	struct image_params *imgp;
976 {
977 	int rv, i, after, initial_pagein;
978 	vm_page_t ma[VM_INITIAL_PAGEIN];
979 	vm_object_t object;
980 
981 	if (imgp->firstpage != NULL)
982 		exec_unmap_first_page(imgp);
983 
984 	object = imgp->vp->v_object;
985 	if (object == NULL)
986 		return (EACCES);
987 	VM_OBJECT_WLOCK(object);
988 #if VM_NRESERVLEVEL > 0
989 	vm_object_color(object, 0);
990 #endif
991 	ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
992 	if (ma[0]->valid != VM_PAGE_BITS_ALL) {
993 		if (!vm_pager_has_page(object, 0, NULL, &after)) {
994 			vm_page_lock(ma[0]);
995 			vm_page_free(ma[0]);
996 			vm_page_unlock(ma[0]);
997 			vm_page_xunbusy(ma[0]);
998 			VM_OBJECT_WUNLOCK(object);
999 			return (EIO);
1000 		}
1001 		initial_pagein = min(after, VM_INITIAL_PAGEIN);
1002 		KASSERT(initial_pagein <= object->size,
1003 		    ("%s: initial_pagein %d object->size %ju",
1004 		    __func__, initial_pagein, (uintmax_t )object->size));
1005 		for (i = 1; i < initial_pagein; i++) {
1006 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
1007 				if (ma[i]->valid)
1008 					break;
1009 				if (vm_page_tryxbusy(ma[i]))
1010 					break;
1011 			} else {
1012 				ma[i] = vm_page_alloc(object, i,
1013 				    VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
1014 				if (ma[i] == NULL)
1015 					break;
1016 			}
1017 		}
1018 		initial_pagein = i;
1019 		rv = vm_pager_get_pages(object, ma, initial_pagein, NULL, NULL);
1020 		if (rv != VM_PAGER_OK) {
1021 			for (i = 0; i < initial_pagein; i++) {
1022 				vm_page_lock(ma[i]);
1023 				vm_page_free(ma[i]);
1024 				vm_page_unlock(ma[i]);
1025 				vm_page_xunbusy(ma[i]);
1026 			}
1027 			VM_OBJECT_WUNLOCK(object);
1028 			return (EIO);
1029 		}
1030 		for (i = 1; i < initial_pagein; i++)
1031 			vm_page_readahead_finish(ma[i]);
1032 	}
1033 	vm_page_xunbusy(ma[0]);
1034 	vm_page_lock(ma[0]);
1035 	vm_page_hold(ma[0]);
1036 	vm_page_activate(ma[0]);
1037 	vm_page_unlock(ma[0]);
1038 	VM_OBJECT_WUNLOCK(object);
1039 
1040 	imgp->firstpage = sf_buf_alloc(ma[0], 0);
1041 	imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1042 
1043 	return (0);
1044 }
1045 
1046 void
1047 exec_unmap_first_page(imgp)
1048 	struct image_params *imgp;
1049 {
1050 	vm_page_t m;
1051 
1052 	if (imgp->firstpage != NULL) {
1053 		m = sf_buf_page(imgp->firstpage);
1054 		sf_buf_free(imgp->firstpage);
1055 		imgp->firstpage = NULL;
1056 		vm_page_lock(m);
1057 		vm_page_unhold(m);
1058 		vm_page_unlock(m);
1059 	}
1060 }
1061 
1062 /*
1063  * Destroy old address space, and allocate a new stack
1064  *	The new stack is only SGROWSIZ large because it is grown
1065  *	automatically in trap.c.
1066  */
1067 int
1068 exec_new_vmspace(imgp, sv)
1069 	struct image_params *imgp;
1070 	struct sysentvec *sv;
1071 {
1072 	int error;
1073 	struct proc *p = imgp->proc;
1074 	struct vmspace *vmspace = p->p_vmspace;
1075 	vm_object_t obj;
1076 	struct rlimit rlim_stack;
1077 	vm_offset_t sv_minuser, stack_addr;
1078 	vm_map_t map;
1079 	u_long ssiz;
1080 
1081 	imgp->vmspace_destroyed = 1;
1082 	imgp->sysent = sv;
1083 
1084 	/* May be called with Giant held */
1085 	EVENTHANDLER_INVOKE(process_exec, p, imgp);
1086 
1087 	/*
1088 	 * Blow away entire process VM, if address space not shared,
1089 	 * otherwise, create a new VM space so that other threads are
1090 	 * not disrupted
1091 	 */
1092 	map = &vmspace->vm_map;
1093 	if (map_at_zero)
1094 		sv_minuser = sv->sv_minuser;
1095 	else
1096 		sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1097 	if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1098 	    vm_map_max(map) == sv->sv_maxuser) {
1099 		shmexit(vmspace);
1100 		pmap_remove_pages(vmspace_pmap(vmspace));
1101 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1102 	} else {
1103 		error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1104 		if (error)
1105 			return (error);
1106 		vmspace = p->p_vmspace;
1107 		map = &vmspace->vm_map;
1108 	}
1109 
1110 	/* Map a shared page */
1111 	obj = sv->sv_shared_page_obj;
1112 	if (obj != NULL) {
1113 		vm_object_reference(obj);
1114 		error = vm_map_fixed(map, obj, 0,
1115 		    sv->sv_shared_page_base, sv->sv_shared_page_len,
1116 		    VM_PROT_READ | VM_PROT_EXECUTE,
1117 		    VM_PROT_READ | VM_PROT_EXECUTE,
1118 		    MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1119 		if (error) {
1120 			vm_object_deallocate(obj);
1121 			return (error);
1122 		}
1123 	}
1124 
1125 	/* Allocate a new stack */
1126 	if (imgp->stack_sz != 0) {
1127 		ssiz = trunc_page(imgp->stack_sz);
1128 		PROC_LOCK(p);
1129 		lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1130 		PROC_UNLOCK(p);
1131 		if (ssiz > rlim_stack.rlim_max)
1132 			ssiz = rlim_stack.rlim_max;
1133 		if (ssiz > rlim_stack.rlim_cur) {
1134 			rlim_stack.rlim_cur = ssiz;
1135 			kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1136 		}
1137 	} else if (sv->sv_maxssiz != NULL) {
1138 		ssiz = *sv->sv_maxssiz;
1139 	} else {
1140 		ssiz = maxssiz;
1141 	}
1142 	stack_addr = sv->sv_usrstack - ssiz;
1143 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1144 	    obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1145 		sv->sv_stackprot,
1146 	    VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1147 	if (error)
1148 		return (error);
1149 
1150 	/*
1151 	 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1152 	 * are still used to enforce the stack rlimit on the process stack.
1153 	 */
1154 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1155 	vmspace->vm_maxsaddr = (char *)stack_addr;
1156 
1157 	return (0);
1158 }
1159 
1160 /*
1161  * Copy out argument and environment strings from the old process address
1162  * space into the temporary string buffer.
1163  */
1164 int
1165 exec_copyin_args(struct image_args *args, char *fname,
1166     enum uio_seg segflg, char **argv, char **envv)
1167 {
1168 	u_long argp, envp;
1169 	int error;
1170 	size_t length;
1171 
1172 	bzero(args, sizeof(*args));
1173 	if (argv == NULL)
1174 		return (EFAULT);
1175 
1176 	/*
1177 	 * Allocate demand-paged memory for the file name, argument, and
1178 	 * environment strings.
1179 	 */
1180 	error = exec_alloc_args(args);
1181 	if (error != 0)
1182 		return (error);
1183 
1184 	/*
1185 	 * Copy the file name.
1186 	 */
1187 	if (fname != NULL) {
1188 		args->fname = args->buf;
1189 		error = (segflg == UIO_SYSSPACE) ?
1190 		    copystr(fname, args->fname, PATH_MAX, &length) :
1191 		    copyinstr(fname, args->fname, PATH_MAX, &length);
1192 		if (error != 0)
1193 			goto err_exit;
1194 	} else
1195 		length = 0;
1196 
1197 	args->begin_argv = args->buf + length;
1198 	args->endp = args->begin_argv;
1199 	args->stringspace = ARG_MAX;
1200 
1201 	/*
1202 	 * extract arguments first
1203 	 */
1204 	for (;;) {
1205 		error = fueword(argv++, &argp);
1206 		if (error == -1) {
1207 			error = EFAULT;
1208 			goto err_exit;
1209 		}
1210 		if (argp == 0)
1211 			break;
1212 		error = copyinstr((void *)(uintptr_t)argp, args->endp,
1213 		    args->stringspace, &length);
1214 		if (error != 0) {
1215 			if (error == ENAMETOOLONG)
1216 				error = E2BIG;
1217 			goto err_exit;
1218 		}
1219 		args->stringspace -= length;
1220 		args->endp += length;
1221 		args->argc++;
1222 	}
1223 
1224 	args->begin_envv = args->endp;
1225 
1226 	/*
1227 	 * extract environment strings
1228 	 */
1229 	if (envv) {
1230 		for (;;) {
1231 			error = fueword(envv++, &envp);
1232 			if (error == -1) {
1233 				error = EFAULT;
1234 				goto err_exit;
1235 			}
1236 			if (envp == 0)
1237 				break;
1238 			error = copyinstr((void *)(uintptr_t)envp,
1239 			    args->endp, args->stringspace, &length);
1240 			if (error != 0) {
1241 				if (error == ENAMETOOLONG)
1242 					error = E2BIG;
1243 				goto err_exit;
1244 			}
1245 			args->stringspace -= length;
1246 			args->endp += length;
1247 			args->envc++;
1248 		}
1249 	}
1250 
1251 	return (0);
1252 
1253 err_exit:
1254 	exec_free_args(args);
1255 	return (error);
1256 }
1257 
1258 int
1259 exec_copyin_data_fds(struct thread *td, struct image_args *args,
1260     const void *data, size_t datalen, const int *fds, size_t fdslen)
1261 {
1262 	struct filedesc *ofdp;
1263 	const char *p;
1264 	int *kfds;
1265 	int error;
1266 
1267 	memset(args, '\0', sizeof(*args));
1268 	ofdp = td->td_proc->p_fd;
1269 	if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
1270 		return (E2BIG);
1271 	error = exec_alloc_args(args);
1272 	if (error != 0)
1273 		return (error);
1274 
1275 	args->begin_argv = args->buf;
1276 	args->stringspace = ARG_MAX;
1277 
1278 	if (datalen > 0) {
1279 		/*
1280 		 * Argument buffer has been provided. Copy it into the
1281 		 * kernel as a single string and add a terminating null
1282 		 * byte.
1283 		 */
1284 		error = copyin(data, args->begin_argv, datalen);
1285 		if (error != 0)
1286 			goto err_exit;
1287 		args->begin_argv[datalen] = '\0';
1288 		args->endp = args->begin_argv + datalen + 1;
1289 		args->stringspace -= datalen + 1;
1290 
1291 		/*
1292 		 * Traditional argument counting. Count the number of
1293 		 * null bytes.
1294 		 */
1295 		for (p = args->begin_argv; p < args->endp; ++p)
1296 			if (*p == '\0')
1297 				++args->argc;
1298 	} else {
1299 		/* No argument buffer provided. */
1300 		args->endp = args->begin_argv;
1301 	}
1302 	/* There are no environment variables. */
1303 	args->begin_envv = args->endp;
1304 
1305 	/* Create new file descriptor table. */
1306 	kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
1307 	error = copyin(fds, kfds, fdslen * sizeof(int));
1308 	if (error != 0) {
1309 		free(kfds, M_TEMP);
1310 		goto err_exit;
1311 	}
1312 	error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
1313 	free(kfds, M_TEMP);
1314 	if (error != 0)
1315 		goto err_exit;
1316 
1317 	return (0);
1318 err_exit:
1319 	exec_free_args(args);
1320 	return (error);
1321 }
1322 
1323 /*
1324  * Allocate temporary demand-paged, zero-filled memory for the file name,
1325  * argument, and environment strings.  Returns zero if the allocation succeeds
1326  * and ENOMEM otherwise.
1327  */
1328 int
1329 exec_alloc_args(struct image_args *args)
1330 {
1331 
1332 	args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1333 	return (args->buf != NULL ? 0 : ENOMEM);
1334 }
1335 
1336 void
1337 exec_free_args(struct image_args *args)
1338 {
1339 
1340 	if (args->buf != NULL) {
1341 		kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
1342 		    PATH_MAX + ARG_MAX);
1343 		args->buf = NULL;
1344 	}
1345 	if (args->fname_buf != NULL) {
1346 		free(args->fname_buf, M_TEMP);
1347 		args->fname_buf = NULL;
1348 	}
1349 	if (args->fdp != NULL)
1350 		fdescfree_remapped(args->fdp);
1351 }
1352 
1353 /*
1354  * Copy strings out to the new process address space, constructing new arg
1355  * and env vector tables. Return a pointer to the base so that it can be used
1356  * as the initial stack pointer.
1357  */
1358 register_t *
1359 exec_copyout_strings(imgp)
1360 	struct image_params *imgp;
1361 {
1362 	int argc, envc;
1363 	char **vectp;
1364 	char *stringp;
1365 	uintptr_t destp;
1366 	register_t *stack_base;
1367 	struct ps_strings *arginfo;
1368 	struct proc *p;
1369 	size_t execpath_len;
1370 	int szsigcode, szps;
1371 	char canary[sizeof(long) * 8];
1372 
1373 	szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1374 	/*
1375 	 * Calculate string base and vector table pointers.
1376 	 * Also deal with signal trampoline code for this exec type.
1377 	 */
1378 	if (imgp->execpath != NULL && imgp->auxargs != NULL)
1379 		execpath_len = strlen(imgp->execpath) + 1;
1380 	else
1381 		execpath_len = 0;
1382 	p = imgp->proc;
1383 	szsigcode = 0;
1384 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1385 	if (p->p_sysent->sv_sigcode_base == 0) {
1386 		if (p->p_sysent->sv_szsigcode != NULL)
1387 			szsigcode = *(p->p_sysent->sv_szsigcode);
1388 	}
1389 	destp =	(uintptr_t)arginfo;
1390 
1391 	/*
1392 	 * install sigcode
1393 	 */
1394 	if (szsigcode != 0) {
1395 		destp -= szsigcode;
1396 		destp = rounddown2(destp, sizeof(void *));
1397 		copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
1398 	}
1399 
1400 	/*
1401 	 * Copy the image path for the rtld.
1402 	 */
1403 	if (execpath_len != 0) {
1404 		destp -= execpath_len;
1405 		imgp->execpathp = destp;
1406 		copyout(imgp->execpath, (void *)destp, execpath_len);
1407 	}
1408 
1409 	/*
1410 	 * Prepare the canary for SSP.
1411 	 */
1412 	arc4rand(canary, sizeof(canary), 0);
1413 	destp -= sizeof(canary);
1414 	imgp->canary = destp;
1415 	copyout(canary, (void *)destp, sizeof(canary));
1416 	imgp->canarylen = sizeof(canary);
1417 
1418 	/*
1419 	 * Prepare the pagesizes array.
1420 	 */
1421 	destp -= szps;
1422 	destp = rounddown2(destp, sizeof(void *));
1423 	imgp->pagesizes = destp;
1424 	copyout(pagesizes, (void *)destp, szps);
1425 	imgp->pagesizeslen = szps;
1426 
1427 	destp -= ARG_MAX - imgp->args->stringspace;
1428 	destp = rounddown2(destp, sizeof(void *));
1429 
1430 	/*
1431 	 * If we have a valid auxargs ptr, prepare some room
1432 	 * on the stack.
1433 	 */
1434 	if (imgp->auxargs) {
1435 		/*
1436 		 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1437 		 * lower compatibility.
1438 		 */
1439 		imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1440 		    (AT_COUNT * 2);
1441 		/*
1442 		 * The '+ 2' is for the null pointers at the end of each of
1443 		 * the arg and env vector sets,and imgp->auxarg_size is room
1444 		 * for argument of Runtime loader.
1445 		 */
1446 		vectp = (char **)(destp - (imgp->args->argc +
1447 		    imgp->args->envc + 2 + imgp->auxarg_size)
1448 		    * sizeof(char *));
1449 	} else {
1450 		/*
1451 		 * The '+ 2' is for the null pointers at the end of each of
1452 		 * the arg and env vector sets
1453 		 */
1454 		vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
1455 		    + 2) * sizeof(char *));
1456 	}
1457 
1458 	/*
1459 	 * vectp also becomes our initial stack base
1460 	 */
1461 	stack_base = (register_t *)vectp;
1462 
1463 	stringp = imgp->args->begin_argv;
1464 	argc = imgp->args->argc;
1465 	envc = imgp->args->envc;
1466 
1467 	/*
1468 	 * Copy out strings - arguments and environment.
1469 	 */
1470 	copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
1471 
1472 	/*
1473 	 * Fill in "ps_strings" struct for ps, w, etc.
1474 	 */
1475 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1476 	suword32(&arginfo->ps_nargvstr, argc);
1477 
1478 	/*
1479 	 * Fill in argument portion of vector table.
1480 	 */
1481 	for (; argc > 0; --argc) {
1482 		suword(vectp++, (long)(intptr_t)destp);
1483 		while (*stringp++ != 0)
1484 			destp++;
1485 		destp++;
1486 	}
1487 
1488 	/* a null vector table pointer separates the argp's from the envp's */
1489 	suword(vectp++, 0);
1490 
1491 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1492 	suword32(&arginfo->ps_nenvstr, envc);
1493 
1494 	/*
1495 	 * Fill in environment portion of vector table.
1496 	 */
1497 	for (; envc > 0; --envc) {
1498 		suword(vectp++, (long)(intptr_t)destp);
1499 		while (*stringp++ != 0)
1500 			destp++;
1501 		destp++;
1502 	}
1503 
1504 	/* end of vector table is a null pointer */
1505 	suword(vectp, 0);
1506 
1507 	return (stack_base);
1508 }
1509 
1510 /*
1511  * Check permissions of file to execute.
1512  *	Called with imgp->vp locked.
1513  *	Return 0 for success or error code on failure.
1514  */
1515 int
1516 exec_check_permissions(imgp)
1517 	struct image_params *imgp;
1518 {
1519 	struct vnode *vp = imgp->vp;
1520 	struct vattr *attr = imgp->attr;
1521 	struct thread *td;
1522 	int error, writecount;
1523 
1524 	td = curthread;
1525 
1526 	/* Get file attributes */
1527 	error = VOP_GETATTR(vp, attr, td->td_ucred);
1528 	if (error)
1529 		return (error);
1530 
1531 #ifdef MAC
1532 	error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1533 	if (error)
1534 		return (error);
1535 #endif
1536 
1537 	/*
1538 	 * 1) Check if file execution is disabled for the filesystem that
1539 	 *    this file resides on.
1540 	 * 2) Ensure that at least one execute bit is on. Otherwise, a
1541 	 *    privileged user will always succeed, and we don't want this
1542 	 *    to happen unless the file really is executable.
1543 	 * 3) Ensure that the file is a regular file.
1544 	 */
1545 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1546 	    (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1547 	    (attr->va_type != VREG))
1548 		return (EACCES);
1549 
1550 	/*
1551 	 * Zero length files can't be exec'd
1552 	 */
1553 	if (attr->va_size == 0)
1554 		return (ENOEXEC);
1555 
1556 	/*
1557 	 *  Check for execute permission to file based on current credentials.
1558 	 */
1559 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1560 	if (error)
1561 		return (error);
1562 
1563 	/*
1564 	 * Check number of open-for-writes on the file and deny execution
1565 	 * if there are any.
1566 	 */
1567 	error = VOP_GET_WRITECOUNT(vp, &writecount);
1568 	if (error != 0)
1569 		return (error);
1570 	if (writecount != 0)
1571 		return (ETXTBSY);
1572 
1573 	/*
1574 	 * Call filesystem specific open routine (which does nothing in the
1575 	 * general case).
1576 	 */
1577 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1578 	if (error == 0)
1579 		imgp->opened = 1;
1580 	return (error);
1581 }
1582 
1583 /*
1584  * Exec handler registration
1585  */
1586 int
1587 exec_register(execsw_arg)
1588 	const struct execsw *execsw_arg;
1589 {
1590 	const struct execsw **es, **xs, **newexecsw;
1591 	int count = 2;	/* New slot and trailing NULL */
1592 
1593 	if (execsw)
1594 		for (es = execsw; *es; es++)
1595 			count++;
1596 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1597 	xs = newexecsw;
1598 	if (execsw)
1599 		for (es = execsw; *es; es++)
1600 			*xs++ = *es;
1601 	*xs++ = execsw_arg;
1602 	*xs = NULL;
1603 	if (execsw)
1604 		free(execsw, M_TEMP);
1605 	execsw = newexecsw;
1606 	return (0);
1607 }
1608 
1609 int
1610 exec_unregister(execsw_arg)
1611 	const struct execsw *execsw_arg;
1612 {
1613 	const struct execsw **es, **xs, **newexecsw;
1614 	int count = 1;
1615 
1616 	if (execsw == NULL)
1617 		panic("unregister with no handlers left?\n");
1618 
1619 	for (es = execsw; *es; es++) {
1620 		if (*es == execsw_arg)
1621 			break;
1622 	}
1623 	if (*es == NULL)
1624 		return (ENOENT);
1625 	for (es = execsw; *es; es++)
1626 		if (*es != execsw_arg)
1627 			count++;
1628 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1629 	xs = newexecsw;
1630 	for (es = execsw; *es; es++)
1631 		if (*es != execsw_arg)
1632 			*xs++ = *es;
1633 	*xs = NULL;
1634 	if (execsw)
1635 		free(execsw, M_TEMP);
1636 	execsw = newexecsw;
1637 	return (0);
1638 }
1639