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