1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 1993, David Greenman
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include <sys/cdefs.h>
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/systm.h>
37 #include <sys/acct.h>
38 #include <sys/asan.h>
39 #include <sys/capsicum.h>
40 #include <sys/compressor.h>
41 #include <sys/eventhandler.h>
42 #include <sys/exec.h>
43 #include <sys/fcntl.h>
44 #include <sys/filedesc.h>
45 #include <sys/imgact.h>
46 #include <sys/imgact_elf.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mman.h>
51 #include <sys/mount.h>
52 #include <sys/mutex.h>
53 #include <sys/namei.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/ptrace.h>
57 #include <sys/reg.h>
58 #include <sys/resourcevar.h>
59 #include <sys/rwlock.h>
60 #include <sys/sched.h>
61 #include <sys/sdt.h>
62 #include <sys/sf_buf.h>
63 #include <sys/shm.h>
64 #include <sys/signalvar.h>
65 #include <sys/smp.h>
66 #include <sys/stat.h>
67 #include <sys/syscallsubr.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysent.h>
70 #include <sys/sysproto.h>
71 #include <sys/timers.h>
72 #include <sys/umtxvar.h>
73 #include <sys/vnode.h>
74 #include <sys/wait.h>
75 #ifdef KTRACE
76 #include <sys/ktrace.h>
77 #endif
78
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_kern.h>
85 #include <vm/vm_extern.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_pager.h>
88
89 #ifdef HWPMC_HOOKS
90 #include <sys/pmckern.h>
91 #endif
92
93 #include <security/audit/audit.h>
94 #include <security/mac/mac_framework.h>
95
96 #ifdef KDTRACE_HOOKS
97 #include <sys/dtrace_bsd.h>
98 dtrace_execexit_func_t dtrace_fasttrap_exec;
99 #endif
100
101 SDT_PROVIDER_DECLARE(proc);
102 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
103 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
104 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
105
106 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
107
108 int coredump_pack_fileinfo = 1;
109 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
110 &coredump_pack_fileinfo, 0,
111 "Enable file path packing in 'procstat -f' coredump notes");
112
113 int coredump_pack_vmmapinfo = 1;
114 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
115 &coredump_pack_vmmapinfo, 0,
116 "Enable file path packing in 'procstat -v' coredump notes");
117
118 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
119 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
120 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
121 static int do_execve(struct thread *td, struct image_args *args,
122 struct mac *mac_p, struct vmspace *oldvmspace);
123
124 /* XXX This should be vm_size_t. */
125 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD|
126 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_ps_strings, "LU",
127 "Location of process' ps_strings structure");
128
129 /* XXX This should be vm_size_t. */
130 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
131 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_usrstack, "LU",
132 "Top of process stack");
133
134 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_MPSAFE,
135 NULL, 0, sysctl_kern_stackprot, "I",
136 "Stack memory permissions");
137
138 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
139 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
140 &ps_arg_cache_limit, 0,
141 "Process' command line characters cache limit");
142
143 static int disallow_high_osrel;
144 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
145 &disallow_high_osrel, 0,
146 "Disallow execution of binaries built for higher version of the world");
147
148 static int map_at_zero = 0;
149 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
150 "Permit processes to map an object at virtual address 0.");
151
152 static int core_dump_can_intr = 1;
153 SYSCTL_INT(_kern, OID_AUTO, core_dump_can_intr, CTLFLAG_RWTUN,
154 &core_dump_can_intr, 0,
155 "Core dumping interruptible with SIGKILL");
156
157 static int
sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)158 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
159 {
160 struct proc *p;
161 vm_offset_t ps_strings;
162
163 p = curproc;
164 #ifdef SCTL_MASK32
165 if (req->flags & SCTL_MASK32) {
166 unsigned int val;
167 val = (unsigned int)PROC_PS_STRINGS(p);
168 return (SYSCTL_OUT(req, &val, sizeof(val)));
169 }
170 #endif
171 ps_strings = PROC_PS_STRINGS(p);
172 return (SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings)));
173 }
174
175 static int
sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)176 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
177 {
178 struct proc *p;
179 vm_offset_t val;
180
181 p = curproc;
182 #ifdef SCTL_MASK32
183 if (req->flags & SCTL_MASK32) {
184 unsigned int val32;
185
186 val32 = round_page((unsigned int)p->p_vmspace->vm_stacktop);
187 return (SYSCTL_OUT(req, &val32, sizeof(val32)));
188 }
189 #endif
190 val = round_page(p->p_vmspace->vm_stacktop);
191 return (SYSCTL_OUT(req, &val, sizeof(val)));
192 }
193
194 static int
sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)195 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
196 {
197 struct proc *p;
198
199 p = curproc;
200 return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
201 sizeof(p->p_sysent->sv_stackprot)));
202 }
203
204 /*
205 * Each of the items is a pointer to a `const struct execsw', hence the
206 * double pointer here.
207 */
208 static const struct execsw **execsw;
209
210 #ifndef _SYS_SYSPROTO_H_
211 struct execve_args {
212 char *fname;
213 char **argv;
214 char **envv;
215 };
216 #endif
217
218 int
sys_execve(struct thread * td,struct execve_args * uap)219 sys_execve(struct thread *td, struct execve_args *uap)
220 {
221 struct image_args args;
222 struct vmspace *oldvmspace;
223 int error;
224
225 error = pre_execve(td, &oldvmspace);
226 if (error != 0)
227 return (error);
228 error = exec_copyin_args(&args, uap->fname, uap->argv, uap->envv);
229 if (error == 0)
230 error = kern_execve(td, &args, NULL, oldvmspace);
231 post_execve(td, error, oldvmspace);
232 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
233 return (error);
234 }
235
236 #ifndef _SYS_SYSPROTO_H_
237 struct fexecve_args {
238 int fd;
239 char **argv;
240 char **envv;
241 };
242 #endif
243 int
sys_fexecve(struct thread * td,struct fexecve_args * uap)244 sys_fexecve(struct thread *td, struct fexecve_args *uap)
245 {
246 struct image_args args;
247 struct vmspace *oldvmspace;
248 int error;
249
250 error = pre_execve(td, &oldvmspace);
251 if (error != 0)
252 return (error);
253 error = exec_copyin_args(&args, NULL, uap->argv, uap->envv);
254 if (error == 0) {
255 args.fd = uap->fd;
256 error = kern_execve(td, &args, NULL, oldvmspace);
257 }
258 post_execve(td, error, oldvmspace);
259 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
260 return (error);
261 }
262
263 #ifndef _SYS_SYSPROTO_H_
264 struct __mac_execve_args {
265 char *fname;
266 char **argv;
267 char **envv;
268 struct mac *mac_p;
269 };
270 #endif
271
272 int
sys___mac_execve(struct thread * td,struct __mac_execve_args * uap)273 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
274 {
275 #ifdef MAC
276 struct image_args args;
277 struct vmspace *oldvmspace;
278 int error;
279
280 error = pre_execve(td, &oldvmspace);
281 if (error != 0)
282 return (error);
283 error = exec_copyin_args(&args, uap->fname, uap->argv, uap->envv);
284 if (error == 0)
285 error = kern_execve(td, &args, uap->mac_p, oldvmspace);
286 post_execve(td, error, oldvmspace);
287 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
288 return (error);
289 #else
290 return (ENOSYS);
291 #endif
292 }
293
294 int
pre_execve(struct thread * td,struct vmspace ** oldvmspace)295 pre_execve(struct thread *td, struct vmspace **oldvmspace)
296 {
297 struct proc *p;
298 int error;
299
300 KASSERT(td == curthread, ("non-current thread %p", td));
301 error = 0;
302 p = td->td_proc;
303 if ((p->p_flag & P_HADTHREADS) != 0) {
304 PROC_LOCK(p);
305 if (thread_single(p, SINGLE_BOUNDARY) != 0)
306 error = ERESTART;
307 PROC_UNLOCK(p);
308 }
309 KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
310 ("nested execve"));
311 *oldvmspace = p->p_vmspace;
312 return (error);
313 }
314
315 void
post_execve(struct thread * td,int error,struct vmspace * oldvmspace)316 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
317 {
318 struct proc *p;
319
320 KASSERT(td == curthread, ("non-current thread %p", td));
321 p = td->td_proc;
322 if ((p->p_flag & P_HADTHREADS) != 0) {
323 PROC_LOCK(p);
324 /*
325 * If success, we upgrade to SINGLE_EXIT state to
326 * force other threads to suicide.
327 */
328 if (error == EJUSTRETURN)
329 thread_single(p, SINGLE_EXIT);
330 else
331 thread_single_end(p, SINGLE_BOUNDARY);
332 PROC_UNLOCK(p);
333 }
334 exec_cleanup(td, oldvmspace);
335 }
336
337 /*
338 * kern_execve() has the astonishing property of not always returning to
339 * the caller. If sufficiently bad things happen during the call to
340 * do_execve(), it can end up calling exit1(); as a result, callers must
341 * avoid doing anything which they might need to undo (e.g., allocating
342 * memory).
343 */
344 int
kern_execve(struct thread * td,struct image_args * args,struct mac * mac_p,struct vmspace * oldvmspace)345 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
346 struct vmspace *oldvmspace)
347 {
348
349 TSEXEC(td->td_proc->p_pid, args->begin_argv);
350 AUDIT_ARG_ARGV(args->begin_argv, args->argc,
351 exec_args_get_begin_envv(args) - args->begin_argv);
352 AUDIT_ARG_ENVV(exec_args_get_begin_envv(args), args->envc,
353 args->endp - exec_args_get_begin_envv(args));
354 #ifdef KTRACE
355 if (KTRPOINT(td, KTR_ARGS)) {
356 ktrdata(KTR_ARGS, args->begin_argv,
357 exec_args_get_begin_envv(args) - args->begin_argv);
358 }
359 if (KTRPOINT(td, KTR_ENVS)) {
360 ktrdata(KTR_ENVS, exec_args_get_begin_envv(args),
361 args->endp - exec_args_get_begin_envv(args));
362 }
363 #endif
364 /* Must have at least one argument. */
365 if (args->argc == 0) {
366 exec_free_args(args);
367 return (EINVAL);
368 }
369 return (do_execve(td, args, mac_p, oldvmspace));
370 }
371
372 static void
execve_nosetid(struct image_params * imgp)373 execve_nosetid(struct image_params *imgp)
374 {
375 imgp->credential_setid = false;
376 if (imgp->newcred != NULL) {
377 crfree(imgp->newcred);
378 imgp->newcred = NULL;
379 }
380 }
381
382 /*
383 * In-kernel implementation of execve(). All arguments are assumed to be
384 * userspace pointers from the passed thread.
385 */
386 static int
do_execve(struct thread * td,struct image_args * args,struct mac * mac_p,struct vmspace * oldvmspace)387 do_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
388 struct vmspace *oldvmspace)
389 {
390 struct proc *p = td->td_proc;
391 struct nameidata nd;
392 struct ucred *oldcred;
393 struct uidinfo *euip = NULL;
394 uintptr_t stack_base;
395 struct image_params image_params, *imgp;
396 struct vattr attr;
397 struct pargs *oldargs = NULL, *newargs = NULL;
398 struct sigacts *oldsigacts = NULL, *newsigacts = NULL;
399 #ifdef KTRACE
400 struct ktr_io_params *kiop;
401 #endif
402 struct vnode *oldtextvp, *newtextvp;
403 struct vnode *oldtextdvp, *newtextdvp;
404 char *oldbinname, *newbinname;
405 bool credential_changing;
406 #ifdef MAC
407 struct label *interpvplabel = NULL;
408 bool will_transition;
409 #endif
410 #ifdef HWPMC_HOOKS
411 struct pmckern_procexec pe;
412 #endif
413 int error, i, orig_osrel;
414 uint32_t orig_fctl0;
415 Elf_Brandinfo *orig_brandinfo;
416 size_t freepath_size;
417 static const char fexecv_proc_title[] = "(fexecv)";
418
419 imgp = &image_params;
420 oldtextvp = oldtextdvp = NULL;
421 newtextvp = newtextdvp = NULL;
422 newbinname = oldbinname = NULL;
423 #ifdef KTRACE
424 kiop = NULL;
425 #endif
426
427 /*
428 * Lock the process and set the P_INEXEC flag to indicate that
429 * it should be left alone until we're done here. This is
430 * necessary to avoid race conditions - e.g. in ptrace() -
431 * that might allow a local user to illicitly obtain elevated
432 * privileges.
433 */
434 PROC_LOCK(p);
435 KASSERT((p->p_flag & P_INEXEC) == 0,
436 ("%s(): process already has P_INEXEC flag", __func__));
437 p->p_flag |= P_INEXEC;
438 PROC_UNLOCK(p);
439
440 /*
441 * Initialize part of the common data
442 */
443 bzero(imgp, sizeof(*imgp));
444 imgp->proc = p;
445 imgp->attr = &attr;
446 imgp->args = args;
447 oldcred = p->p_ucred;
448 orig_osrel = p->p_osrel;
449 orig_fctl0 = p->p_fctl0;
450 orig_brandinfo = p->p_elf_brandinfo;
451
452 #ifdef MAC
453 error = mac_execve_enter(imgp, mac_p);
454 if (error)
455 goto exec_fail;
456 #endif
457
458 SDT_PROBE1(proc, , , exec, args->fname);
459
460 interpret:
461 if (args->fname != NULL) {
462 #ifdef CAPABILITY_MODE
463 if (CAP_TRACING(td))
464 ktrcapfail(CAPFAIL_NAMEI, args->fname);
465 /*
466 * While capability mode can't reach this point via direct
467 * path arguments to execve(), we also don't allow
468 * interpreters to be used in capability mode (for now).
469 * Catch indirect lookups and return a permissions error.
470 */
471 if (IN_CAPABILITY_MODE(td)) {
472 error = ECAPMODE;
473 goto exec_fail;
474 }
475 #endif
476
477 /*
478 * Translate the file name. namei() returns a vnode
479 * pointer in ni_vp among other things.
480 */
481 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
482 AUDITVNODE1 | WANTPARENT, UIO_SYSSPACE,
483 args->fname);
484
485 error = namei(&nd);
486 if (error)
487 goto exec_fail;
488
489 newtextvp = nd.ni_vp;
490 newtextdvp = nd.ni_dvp;
491 nd.ni_dvp = NULL;
492 newbinname = malloc(nd.ni_cnd.cn_namelen + 1, M_PARGS,
493 M_WAITOK);
494 memcpy(newbinname, nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen);
495 newbinname[nd.ni_cnd.cn_namelen] = '\0';
496 imgp->vp = newtextvp;
497
498 /*
499 * Do the best to calculate the full path to the image file.
500 */
501 if (args->fname[0] == '/') {
502 imgp->execpath = args->fname;
503 } else {
504 VOP_UNLOCK(imgp->vp);
505 freepath_size = MAXPATHLEN;
506 if (vn_fullpath_hardlink(newtextvp, newtextdvp,
507 newbinname, nd.ni_cnd.cn_namelen, &imgp->execpath,
508 &imgp->freepath, &freepath_size) != 0)
509 imgp->execpath = args->fname;
510 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
511 }
512 } else if (imgp->interpreter_vp) {
513 /*
514 * An image activator has already provided an open vnode
515 */
516 newtextvp = imgp->interpreter_vp;
517 imgp->interpreter_vp = NULL;
518 if (vn_fullpath(newtextvp, &imgp->execpath,
519 &imgp->freepath) != 0)
520 imgp->execpath = args->fname;
521 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
522 AUDIT_ARG_VNODE1(newtextvp);
523 imgp->vp = newtextvp;
524 } else {
525 AUDIT_ARG_FD(args->fd);
526
527 /*
528 * If the descriptors was not opened with O_PATH, then
529 * we require that it was opened with O_EXEC or
530 * O_RDONLY. In either case, exec_check_permissions()
531 * below checks _current_ file access mode regardless
532 * of the permissions additionally checked at the
533 * open(2).
534 */
535 error = fgetvp_exec(td, args->fd, &cap_fexecve_rights,
536 &newtextvp);
537 if (error != 0)
538 goto exec_fail;
539
540 if (vn_fullpath(newtextvp, &imgp->execpath,
541 &imgp->freepath) != 0)
542 imgp->execpath = args->fname;
543 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
544 AUDIT_ARG_VNODE1(newtextvp);
545 imgp->vp = newtextvp;
546 }
547
548 /*
549 * Check file permissions. Also 'opens' file and sets its vnode to
550 * text mode.
551 */
552 error = exec_check_permissions(imgp);
553 if (error)
554 goto exec_fail_dealloc;
555
556 imgp->object = imgp->vp->v_object;
557 if (imgp->object != NULL)
558 vm_object_reference(imgp->object);
559
560 error = exec_map_first_page(imgp);
561 if (error)
562 goto exec_fail_dealloc;
563
564 imgp->proc->p_osrel = 0;
565 imgp->proc->p_fctl0 = 0;
566 imgp->proc->p_elf_brandinfo = NULL;
567
568 /*
569 * Implement image setuid/setgid.
570 *
571 * Determine new credentials before attempting image activators
572 * so that it can be used by process_exec handlers to determine
573 * credential/setid changes.
574 *
575 * Don't honor setuid/setgid if the filesystem prohibits it or if
576 * the process is being traced.
577 *
578 * We disable setuid/setgid/etc in capability mode on the basis
579 * that most setugid applications are not written with that
580 * environment in mind, and will therefore almost certainly operate
581 * incorrectly. In principle there's no reason that setugid
582 * applications might not be useful in capability mode, so we may want
583 * to reconsider this conservative design choice in the future.
584 *
585 * XXXMAC: For the time being, use NOSUID to also prohibit
586 * transitions on the file system.
587 */
588 credential_changing = false;
589 credential_changing |= (attr.va_mode & S_ISUID) &&
590 oldcred->cr_uid != attr.va_uid;
591 credential_changing |= (attr.va_mode & S_ISGID) &&
592 oldcred->cr_gid != attr.va_gid;
593 #ifdef MAC
594 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
595 interpvplabel, imgp) != 0;
596 credential_changing |= will_transition;
597 #endif
598
599 /* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */
600 if (credential_changing)
601 imgp->proc->p_pdeathsig = 0;
602
603 if (credential_changing &&
604 #ifdef CAPABILITY_MODE
605 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
606 #endif
607 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
608 (p->p_flag & P_TRACED) == 0) {
609 imgp->credential_setid = true;
610 VOP_UNLOCK(imgp->vp);
611 imgp->newcred = crdup(oldcred);
612 if (attr.va_mode & S_ISUID) {
613 euip = uifind(attr.va_uid);
614 change_euid(imgp->newcred, euip);
615 }
616 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
617 if (attr.va_mode & S_ISGID)
618 change_egid(imgp->newcred, attr.va_gid);
619 /*
620 * Implement correct POSIX saved-id behavior.
621 *
622 * XXXMAC: Note that the current logic will save the
623 * uid and gid if a MAC domain transition occurs, even
624 * though maybe it shouldn't.
625 */
626 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
627 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
628 } else {
629 /*
630 * Implement correct POSIX saved-id behavior.
631 *
632 * XXX: It's not clear that the existing behavior is
633 * POSIX-compliant. A number of sources indicate that the
634 * saved uid/gid should only be updated if the new ruid is
635 * not equal to the old ruid, or the new euid is not equal
636 * to the old euid and the new euid is not equal to the old
637 * ruid. The FreeBSD code always updates the saved uid/gid.
638 * Also, this code uses the new (replaced) euid and egid as
639 * the source, which may or may not be the right ones to use.
640 */
641 if (oldcred->cr_svuid != oldcred->cr_uid ||
642 oldcred->cr_svgid != oldcred->cr_gid) {
643 VOP_UNLOCK(imgp->vp);
644 imgp->newcred = crdup(oldcred);
645 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
646 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
647 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
648 }
649 }
650 /* The new credentials are installed into the process later. */
651
652 /*
653 * Loop through the list of image activators, calling each one.
654 * An activator returns -1 if there is no match, 0 on success,
655 * and an error otherwise.
656 */
657 error = -1;
658 for (i = 0; error == -1 && execsw[i]; ++i) {
659 if (execsw[i]->ex_imgact == NULL)
660 continue;
661 error = (*execsw[i]->ex_imgact)(imgp);
662 }
663
664 if (error) {
665 if (error == -1)
666 error = ENOEXEC;
667 goto exec_fail_dealloc;
668 }
669
670 /*
671 * Special interpreter operation, cleanup and loop up to try to
672 * activate the interpreter.
673 */
674 if (imgp->interpreted) {
675 exec_unmap_first_page(imgp);
676 /*
677 * The text reference needs to be removed for scripts.
678 * There is a short period before we determine that
679 * something is a script where text reference is active.
680 * The vnode lock is held over this entire period
681 * so nothing should illegitimately be blocked.
682 */
683 MPASS(imgp->textset);
684 VOP_UNSET_TEXT_CHECKED(newtextvp);
685 imgp->textset = false;
686 /* free name buffer and old vnode */
687 #ifdef MAC
688 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
689 #endif
690 if (imgp->opened) {
691 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
692 imgp->opened = false;
693 }
694 vput(newtextvp);
695 imgp->vp = newtextvp = NULL;
696 if (args->fname != NULL) {
697 if (newtextdvp != NULL) {
698 vrele(newtextdvp);
699 newtextdvp = NULL;
700 }
701 NDFREE_PNBUF(&nd);
702 free(newbinname, M_PARGS);
703 newbinname = NULL;
704 }
705 vm_object_deallocate(imgp->object);
706 imgp->object = NULL;
707 execve_nosetid(imgp);
708 imgp->execpath = NULL;
709 free(imgp->freepath, M_TEMP);
710 imgp->freepath = NULL;
711 /* set new name to that of the interpreter */
712 if (imgp->interpreter_vp) {
713 args->fname = NULL;
714 } else {
715 args->fname = imgp->interpreter_name;
716 }
717 goto interpret;
718 }
719
720 /*
721 * NB: We unlock the vnode here because it is believed that none
722 * of the sv_copyout_strings/sv_fixup operations require the vnode.
723 */
724 VOP_UNLOCK(imgp->vp);
725
726 if (disallow_high_osrel &&
727 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
728 error = ENOEXEC;
729 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
730 imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
731 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
732 goto exec_fail_dealloc;
733 }
734
735 /*
736 * Copy out strings (args and env) and initialize stack base.
737 */
738 error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base);
739 if (error != 0) {
740 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
741 goto exec_fail_dealloc;
742 }
743
744 /*
745 * Stack setup.
746 */
747 error = (*p->p_sysent->sv_fixup)(&stack_base, imgp);
748 if (error != 0) {
749 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
750 goto exec_fail_dealloc;
751 }
752
753 /*
754 * For security and other reasons, the file descriptor table cannot be
755 * shared after an exec.
756 */
757 fdunshare(td);
758 pdunshare(td);
759 /* close files on exec */
760 fdcloseexec(td);
761
762 /*
763 * Malloc things before we need locks.
764 */
765 i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv;
766 /* Cache arguments if they fit inside our allowance */
767 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
768 newargs = pargs_alloc(i);
769 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
770 }
771
772 /*
773 * For security and other reasons, signal handlers cannot
774 * be shared after an exec. The new process gets a copy of the old
775 * handlers. In execsigs(), the new process will have its signals
776 * reset.
777 */
778 if (sigacts_shared(p->p_sigacts)) {
779 oldsigacts = p->p_sigacts;
780 newsigacts = sigacts_alloc();
781 sigacts_copy(newsigacts, oldsigacts);
782 }
783
784 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
785
786 PROC_LOCK(p);
787 if (oldsigacts)
788 p->p_sigacts = newsigacts;
789 /* Stop profiling */
790 stopprofclock(p);
791
792 /* reset caught signals */
793 execsigs(p);
794
795 /* name this process - nameiexec(p, ndp) */
796 bzero(p->p_comm, sizeof(p->p_comm));
797 if (args->fname)
798 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
799 min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
800 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
801 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
802 bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
803 #ifdef KTR
804 sched_clear_tdname(td);
805 #endif
806
807 /*
808 * mark as execed, wakeup the process that vforked (if any) and tell
809 * it that it now has its own resources back
810 */
811 p->p_flag |= P_EXEC;
812 td->td_pflags2 &= ~TDP2_UEXTERR;
813 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
814 p->p_flag2 &= ~P2_NOTRACE;
815 if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
816 p->p_flag2 &= ~P2_STKGAP_DISABLE;
817 p->p_flag2 &= ~(P2_MEMBAR_PRIVE | P2_MEMBAR_PRIVE_SYNCORE |
818 P2_MEMBAR_GLOBE);
819 if (p->p_flag & P_PPWAIT) {
820 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
821 cv_broadcast(&p->p_pwait);
822 /* STOPs are no longer ignored, arrange for AST */
823 signotify(td);
824 }
825
826 if ((imgp->sysent->sv_setid_allowed != NULL &&
827 !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
828 (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
829 execve_nosetid(imgp);
830
831 /*
832 * Implement image setuid/setgid installation.
833 */
834 if (imgp->credential_setid) {
835 /*
836 * Turn off syscall tracing for set-id programs, except for
837 * root. Record any set-id flags first to make sure that
838 * we do not regain any tracing during a possible block.
839 */
840 setsugid(p);
841 #ifdef KTRACE
842 kiop = ktrprocexec(p);
843 #endif
844 /*
845 * Close any file descriptors 0..2 that reference procfs,
846 * then make sure file descriptors 0..2 are in use.
847 *
848 * Both fdsetugidsafety() and fdcheckstd() may call functions
849 * taking sleepable locks, so temporarily drop our locks.
850 */
851 PROC_UNLOCK(p);
852 VOP_UNLOCK(imgp->vp);
853 fdsetugidsafety(td);
854 error = fdcheckstd(td);
855 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
856 if (error != 0)
857 goto exec_fail_dealloc;
858 PROC_LOCK(p);
859 #ifdef MAC
860 if (will_transition) {
861 mac_vnode_execve_transition(oldcred, imgp->newcred,
862 imgp->vp, interpvplabel, imgp);
863 }
864 #endif
865 } else {
866 if (oldcred->cr_uid == oldcred->cr_ruid &&
867 oldcred->cr_gid == oldcred->cr_rgid)
868 p->p_flag &= ~P_SUGID;
869 }
870 /*
871 * Set the new credentials.
872 */
873 if (imgp->newcred != NULL) {
874 proc_set_cred(p, imgp->newcred);
875 crfree(oldcred);
876 oldcred = NULL;
877 }
878
879 /*
880 * Store the vp for use in kern.proc.pathname. This vnode was
881 * referenced by namei() or by fexecve variant of fname handling.
882 */
883 oldtextvp = p->p_textvp;
884 p->p_textvp = newtextvp;
885 oldtextdvp = p->p_textdvp;
886 p->p_textdvp = newtextdvp;
887 newtextdvp = NULL;
888 oldbinname = p->p_binname;
889 p->p_binname = newbinname;
890 newbinname = NULL;
891
892 #ifdef KDTRACE_HOOKS
893 /*
894 * Tell the DTrace fasttrap provider about the exec if it
895 * has declared an interest.
896 */
897 if (dtrace_fasttrap_exec)
898 dtrace_fasttrap_exec(p);
899 #endif
900
901 /*
902 * Notify others that we exec'd, and clear the P_INEXEC flag
903 * as we're now a bona fide freshly-execed process.
904 */
905 KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
906 p->p_flag &= ~P_INEXEC;
907
908 /* clear "fork but no exec" flag, as we _are_ execing */
909 p->p_acflag &= ~AFORK;
910
911 /*
912 * Free any previous argument cache and replace it with
913 * the new argument cache, if any.
914 */
915 oldargs = p->p_args;
916 p->p_args = newargs;
917 newargs = NULL;
918
919 PROC_UNLOCK(p);
920
921 #ifdef HWPMC_HOOKS
922 /*
923 * Check if system-wide sampling is in effect or if the
924 * current process is using PMCs. If so, do exec() time
925 * processing. This processing needs to happen AFTER the
926 * P_INEXEC flag is cleared.
927 */
928 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
929 VOP_UNLOCK(imgp->vp);
930 pe.pm_credentialschanged = credential_changing;
931 pe.pm_baseaddr = imgp->reloc_base;
932 pe.pm_dynaddr = imgp->et_dyn_addr;
933
934 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
935 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
936 }
937 #endif
938
939 /* Set values passed into the program in registers. */
940 (*p->p_sysent->sv_setregs)(td, imgp, stack_base);
941
942 VOP_MMAPPED(imgp->vp);
943
944 SDT_PROBE1(proc, , , exec__success, args->fname);
945
946 exec_fail_dealloc:
947 if (error != 0) {
948 p->p_osrel = orig_osrel;
949 p->p_fctl0 = orig_fctl0;
950 p->p_elf_brandinfo = orig_brandinfo;
951 }
952
953 if (imgp->firstpage != NULL)
954 exec_unmap_first_page(imgp);
955
956 if (imgp->vp != NULL) {
957 if (imgp->opened)
958 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
959 if (imgp->textset)
960 VOP_UNSET_TEXT_CHECKED(imgp->vp);
961 if (error != 0)
962 vput(imgp->vp);
963 else
964 VOP_UNLOCK(imgp->vp);
965 if (args->fname != NULL)
966 NDFREE_PNBUF(&nd);
967 if (newtextdvp != NULL)
968 vrele(newtextdvp);
969 free(newbinname, M_PARGS);
970 }
971
972 if (imgp->object != NULL)
973 vm_object_deallocate(imgp->object);
974
975 free(imgp->freepath, M_TEMP);
976
977 if (error == 0) {
978 if (p->p_ptevents & PTRACE_EXEC) {
979 PROC_LOCK(p);
980 if (p->p_ptevents & PTRACE_EXEC)
981 td->td_dbgflags |= TDB_EXEC;
982 PROC_UNLOCK(p);
983 }
984 } else {
985 exec_fail:
986 /* we're done here, clear P_INEXEC */
987 PROC_LOCK(p);
988 p->p_flag &= ~P_INEXEC;
989 PROC_UNLOCK(p);
990
991 SDT_PROBE1(proc, , , exec__failure, error);
992 }
993
994 if (imgp->newcred != NULL && oldcred != NULL)
995 crfree(imgp->newcred);
996
997 #ifdef MAC
998 mac_execve_exit(imgp);
999 mac_execve_interpreter_exit(interpvplabel);
1000 #endif
1001 exec_free_args(args);
1002
1003 /*
1004 * Handle deferred decrement of ref counts.
1005 */
1006 if (oldtextvp != NULL)
1007 vrele(oldtextvp);
1008 if (oldtextdvp != NULL)
1009 vrele(oldtextdvp);
1010 free(oldbinname, M_PARGS);
1011 #ifdef KTRACE
1012 ktr_io_params_free(kiop);
1013 #endif
1014 pargs_drop(oldargs);
1015 pargs_drop(newargs);
1016 if (oldsigacts != NULL)
1017 sigacts_free(oldsigacts);
1018 if (euip != NULL)
1019 uifree(euip);
1020
1021 if (error && imgp->vmspace_destroyed) {
1022 /* sorry, no more process anymore. exit gracefully */
1023 exec_cleanup(td, oldvmspace);
1024 exit1(td, 0, SIGABRT);
1025 /* NOT REACHED */
1026 }
1027
1028 #ifdef KTRACE
1029 if (error == 0)
1030 ktrprocctor(p);
1031 #endif
1032
1033 /*
1034 * We don't want cpu_set_syscall_retval() to overwrite any of
1035 * the register values put in place by exec_setregs().
1036 * Implementations of cpu_set_syscall_retval() will leave
1037 * registers unmodified when returning EJUSTRETURN.
1038 */
1039 return (error == 0 ? EJUSTRETURN : error);
1040 }
1041
1042 void
exec_cleanup(struct thread * td,struct vmspace * oldvmspace)1043 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1044 {
1045 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1046 KASSERT(td->td_proc->p_vmspace != oldvmspace,
1047 ("oldvmspace still used"));
1048 vmspace_free(oldvmspace);
1049 td->td_pflags &= ~TDP_EXECVMSPC;
1050 }
1051 }
1052
1053 int
exec_map_first_page(struct image_params * imgp)1054 exec_map_first_page(struct image_params *imgp)
1055 {
1056 vm_object_t object;
1057 vm_page_t m;
1058 int error;
1059
1060 if (imgp->firstpage != NULL)
1061 exec_unmap_first_page(imgp);
1062
1063 object = imgp->vp->v_object;
1064 if (object == NULL)
1065 return (EACCES);
1066 #if VM_NRESERVLEVEL > 0
1067 if ((object->flags & OBJ_COLORED) == 0) {
1068 VM_OBJECT_WLOCK(object);
1069 vm_object_color(object, 0);
1070 VM_OBJECT_WUNLOCK(object);
1071 }
1072 #endif
1073 error = vm_page_grab_valid_unlocked(&m, object, 0,
1074 VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1075 VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1076
1077 if (error != VM_PAGER_OK)
1078 return (EIO);
1079 imgp->firstpage = sf_buf_alloc(m, 0);
1080 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1081
1082 return (0);
1083 }
1084
1085 void
exec_unmap_first_page(struct image_params * imgp)1086 exec_unmap_first_page(struct image_params *imgp)
1087 {
1088 vm_page_t m;
1089
1090 if (imgp->firstpage != NULL) {
1091 m = sf_buf_page(imgp->firstpage);
1092 sf_buf_free(imgp->firstpage);
1093 imgp->firstpage = NULL;
1094 vm_page_unwire(m, PQ_ACTIVE);
1095 }
1096 }
1097
1098 void
exec_onexec_old(struct thread * td)1099 exec_onexec_old(struct thread *td)
1100 {
1101 sigfastblock_clear(td);
1102 umtx_exec(td->td_proc);
1103 }
1104
1105 /*
1106 * This is an optimization which removes the unmanaged shared page
1107 * mapping. In combination with pmap_remove_pages(), which cleans all
1108 * managed mappings in the process' vmspace pmap, no work will be left
1109 * for pmap_remove(min, max).
1110 */
1111 void
exec_free_abi_mappings(struct proc * p)1112 exec_free_abi_mappings(struct proc *p)
1113 {
1114 struct vmspace *vmspace;
1115
1116 vmspace = p->p_vmspace;
1117 if (refcount_load(&vmspace->vm_refcnt) != 1)
1118 return;
1119
1120 if (!PROC_HAS_SHP(p))
1121 return;
1122
1123 pmap_remove(vmspace_pmap(vmspace), vmspace->vm_shp_base,
1124 vmspace->vm_shp_base + p->p_sysent->sv_shared_page_len);
1125 }
1126
1127 /*
1128 * Run down the current address space and install a new one.
1129 */
1130 int
exec_new_vmspace(struct image_params * imgp,struct sysentvec * sv)1131 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1132 {
1133 int error;
1134 struct proc *p = imgp->proc;
1135 struct vmspace *vmspace = p->p_vmspace;
1136 struct thread *td = curthread;
1137 vm_offset_t sv_minuser;
1138 vm_map_t map;
1139
1140 imgp->vmspace_destroyed = true;
1141 imgp->sysent = sv;
1142
1143 if (p->p_sysent->sv_onexec_old != NULL)
1144 p->p_sysent->sv_onexec_old(td);
1145 itimers_exec(p);
1146
1147 EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1148
1149 /*
1150 * Blow away entire process VM, if address space not shared,
1151 * otherwise, create a new VM space so that other threads are
1152 * not disrupted
1153 */
1154 map = &vmspace->vm_map;
1155 if (map_at_zero)
1156 sv_minuser = sv->sv_minuser;
1157 else
1158 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1159 if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1160 vm_map_min(map) == sv_minuser &&
1161 vm_map_max(map) == sv->sv_maxuser &&
1162 cpu_exec_vmspace_reuse(p, map)) {
1163 exec_free_abi_mappings(p);
1164 shmexit(vmspace);
1165 pmap_remove_pages(vmspace_pmap(vmspace));
1166 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1167 /*
1168 * An exec terminates mlockall(MCL_FUTURE).
1169 * ASLR and W^X states must be re-evaluated.
1170 */
1171 vm_map_lock(map);
1172 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1173 MAP_ASLR_IGNSTART | MAP_ASLR_STACK | MAP_WXORX);
1174 vm_map_unlock(map);
1175 } else {
1176 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1177 if (error)
1178 return (error);
1179 vmspace = p->p_vmspace;
1180 map = &vmspace->vm_map;
1181 }
1182 map->flags |= imgp->map_flags;
1183
1184 return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1185 }
1186
1187 /*
1188 * Compute the stack size limit and map the main process stack.
1189 * Map the shared page.
1190 */
1191 int
exec_map_stack(struct image_params * imgp)1192 exec_map_stack(struct image_params *imgp)
1193 {
1194 struct rlimit rlim_stack;
1195 struct sysentvec *sv;
1196 struct proc *p;
1197 vm_map_t map;
1198 struct vmspace *vmspace;
1199 vm_offset_t stack_addr, stack_top;
1200 vm_offset_t sharedpage_addr;
1201 u_long ssiz;
1202 int error, find_space, stack_off;
1203 vm_prot_t stack_prot;
1204 vm_object_t obj;
1205
1206 p = imgp->proc;
1207 sv = p->p_sysent;
1208
1209 if (imgp->stack_sz != 0) {
1210 ssiz = trunc_page(imgp->stack_sz);
1211 PROC_LOCK(p);
1212 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1213 PROC_UNLOCK(p);
1214 if (ssiz > rlim_stack.rlim_max)
1215 ssiz = rlim_stack.rlim_max;
1216 if (ssiz > rlim_stack.rlim_cur) {
1217 rlim_stack.rlim_cur = ssiz;
1218 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1219 }
1220 } else if (sv->sv_maxssiz != NULL) {
1221 ssiz = *sv->sv_maxssiz;
1222 } else {
1223 ssiz = maxssiz;
1224 }
1225
1226 vmspace = p->p_vmspace;
1227 map = &vmspace->vm_map;
1228
1229 stack_prot = sv->sv_shared_page_obj != NULL && imgp->stack_prot != 0 ?
1230 imgp->stack_prot : sv->sv_stackprot;
1231 if ((map->flags & MAP_ASLR_STACK) != 0) {
1232 stack_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
1233 lim_max(curthread, RLIMIT_DATA));
1234 find_space = VMFS_ANY_SPACE;
1235 } else {
1236 stack_addr = sv->sv_usrstack - ssiz;
1237 find_space = VMFS_NO_SPACE;
1238 }
1239 error = vm_map_find(map, NULL, 0, &stack_addr, (vm_size_t)ssiz,
1240 sv->sv_usrstack, find_space, stack_prot, VM_PROT_ALL,
1241 MAP_STACK_AREA);
1242 if (error != KERN_SUCCESS) {
1243 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1244 "failed, mach error %d errno %d\n", (uintmax_t)ssiz,
1245 stack_prot, error, vm_mmap_to_errno(error));
1246 return (vm_mmap_to_errno(error));
1247 }
1248
1249 stack_top = stack_addr + ssiz;
1250 if ((map->flags & MAP_ASLR_STACK) != 0) {
1251 /* Randomize within the first page of the stack. */
1252 arc4rand(&stack_off, sizeof(stack_off), 0);
1253 stack_top -= rounddown2(stack_off & PAGE_MASK, sizeof(void *));
1254 }
1255
1256 /* Map a shared page */
1257 obj = sv->sv_shared_page_obj;
1258 if (obj == NULL) {
1259 sharedpage_addr = 0;
1260 goto out;
1261 }
1262
1263 /*
1264 * If randomization is disabled then the shared page will
1265 * be mapped at address specified in sysentvec.
1266 * Otherwise any address above .data section can be selected.
1267 * Same logic is used for stack address randomization.
1268 * If the address randomization is applied map a guard page
1269 * at the top of UVA.
1270 */
1271 vm_object_reference(obj);
1272 if ((imgp->imgp_flags & IMGP_ASLR_SHARED_PAGE) != 0) {
1273 sharedpage_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
1274 lim_max(curthread, RLIMIT_DATA));
1275
1276 error = vm_map_fixed(map, NULL, 0,
1277 sv->sv_maxuser - PAGE_SIZE, PAGE_SIZE,
1278 VM_PROT_NONE, VM_PROT_NONE, MAP_CREATE_GUARD);
1279 if (error != KERN_SUCCESS) {
1280 /*
1281 * This is not fatal, so let's just print a warning
1282 * and continue.
1283 */
1284 uprintf("%s: Mapping guard page at the top of UVA failed"
1285 " mach error %d errno %d",
1286 __func__, error, vm_mmap_to_errno(error));
1287 }
1288
1289 error = vm_map_find(map, obj, 0,
1290 &sharedpage_addr, sv->sv_shared_page_len,
1291 sv->sv_maxuser, VMFS_ANY_SPACE,
1292 VM_PROT_READ | VM_PROT_EXECUTE,
1293 VM_PROT_READ | VM_PROT_EXECUTE,
1294 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1295 } else {
1296 sharedpage_addr = sv->sv_shared_page_base;
1297 vm_map_fixed(map, obj, 0,
1298 sharedpage_addr, sv->sv_shared_page_len,
1299 VM_PROT_READ | VM_PROT_EXECUTE,
1300 VM_PROT_READ | VM_PROT_EXECUTE,
1301 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1302 }
1303 if (error != KERN_SUCCESS) {
1304 uprintf("%s: mapping shared page at addr: %p"
1305 "failed, mach error %d errno %d\n", __func__,
1306 (void *)sharedpage_addr, error, vm_mmap_to_errno(error));
1307 vm_object_deallocate(obj);
1308 return (vm_mmap_to_errno(error));
1309 }
1310 out:
1311 /*
1312 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1313 * are still used to enforce the stack rlimit on the process stack.
1314 */
1315 vmspace->vm_maxsaddr = (char *)stack_addr;
1316 vmspace->vm_stacktop = stack_top;
1317 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1318 vmspace->vm_shp_base = sharedpage_addr;
1319
1320 return (0);
1321 }
1322
1323 /*
1324 * Copy out argument and environment strings from the old process address
1325 * space into the temporary string buffer.
1326 */
1327 int
exec_copyin_args(struct image_args * args,const char * fname,char ** argv,char ** envv)1328 exec_copyin_args(struct image_args *args, const char *fname,
1329 char **argv, char **envv)
1330 {
1331 u_long arg, env;
1332 int error;
1333
1334 bzero(args, sizeof(*args));
1335 if (argv == NULL)
1336 return (EFAULT);
1337
1338 /*
1339 * Allocate demand-paged memory for the file name, argument, and
1340 * environment strings.
1341 */
1342 error = exec_alloc_args(args);
1343 if (error != 0)
1344 return (error);
1345
1346 /*
1347 * Copy the file name.
1348 */
1349 error = exec_args_add_fname(args, fname, UIO_USERSPACE);
1350 if (error != 0)
1351 goto err_exit;
1352
1353 /*
1354 * extract arguments first
1355 */
1356 for (;;) {
1357 error = fueword(argv++, &arg);
1358 if (error == -1) {
1359 error = EFAULT;
1360 goto err_exit;
1361 }
1362 if (arg == 0)
1363 break;
1364 error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1365 UIO_USERSPACE);
1366 if (error != 0)
1367 goto err_exit;
1368 }
1369
1370 /*
1371 * extract environment strings
1372 */
1373 if (envv) {
1374 for (;;) {
1375 error = fueword(envv++, &env);
1376 if (error == -1) {
1377 error = EFAULT;
1378 goto err_exit;
1379 }
1380 if (env == 0)
1381 break;
1382 error = exec_args_add_env(args,
1383 (char *)(uintptr_t)env, UIO_USERSPACE);
1384 if (error != 0)
1385 goto err_exit;
1386 }
1387 }
1388
1389 return (0);
1390
1391 err_exit:
1392 exec_free_args(args);
1393 return (error);
1394 }
1395
1396 struct exec_args_kva {
1397 vm_offset_t addr;
1398 u_int gen;
1399 SLIST_ENTRY(exec_args_kva) next;
1400 };
1401
1402 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1403
1404 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1405 static struct mtx exec_args_kva_mtx;
1406 static u_int exec_args_gen;
1407
1408 static void
exec_prealloc_args_kva(void * arg __unused)1409 exec_prealloc_args_kva(void *arg __unused)
1410 {
1411 struct exec_args_kva *argkva;
1412 u_int i;
1413
1414 SLIST_INIT(&exec_args_kva_freelist);
1415 mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1416 for (i = 0; i < exec_map_entries; i++) {
1417 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1418 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size);
1419 argkva->gen = exec_args_gen;
1420 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1421 }
1422 }
1423 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1424
1425 static vm_offset_t
exec_alloc_args_kva(void ** cookie)1426 exec_alloc_args_kva(void **cookie)
1427 {
1428 struct exec_args_kva *argkva;
1429
1430 argkva = (void *)atomic_readandclear_ptr(
1431 (uintptr_t *)DPCPU_PTR(exec_args_kva));
1432 if (argkva == NULL) {
1433 mtx_lock(&exec_args_kva_mtx);
1434 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1435 (void)mtx_sleep(&exec_args_kva_freelist,
1436 &exec_args_kva_mtx, 0, "execkva", 0);
1437 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1438 mtx_unlock(&exec_args_kva_mtx);
1439 }
1440 kasan_mark((void *)argkva->addr, exec_map_entry_size,
1441 exec_map_entry_size, 0);
1442 *(struct exec_args_kva **)cookie = argkva;
1443 return (argkva->addr);
1444 }
1445
1446 static void
exec_release_args_kva(struct exec_args_kva * argkva,u_int gen)1447 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1448 {
1449 vm_offset_t base;
1450
1451 base = argkva->addr;
1452 kasan_mark((void *)argkva->addr, 0, exec_map_entry_size,
1453 KASAN_EXEC_ARGS_FREED);
1454 if (argkva->gen != gen) {
1455 (void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1456 MADV_FREE);
1457 argkva->gen = gen;
1458 }
1459 if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1460 (uintptr_t)NULL, (uintptr_t)argkva)) {
1461 mtx_lock(&exec_args_kva_mtx);
1462 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1463 wakeup_one(&exec_args_kva_freelist);
1464 mtx_unlock(&exec_args_kva_mtx);
1465 }
1466 }
1467
1468 static void
exec_free_args_kva(void * cookie)1469 exec_free_args_kva(void *cookie)
1470 {
1471
1472 exec_release_args_kva(cookie, exec_args_gen);
1473 }
1474
1475 static void
exec_args_kva_lowmem(void * arg __unused,int flags __unused)1476 exec_args_kva_lowmem(void *arg __unused, int flags __unused)
1477 {
1478 SLIST_HEAD(, exec_args_kva) head;
1479 struct exec_args_kva *argkva;
1480 u_int gen;
1481 int i;
1482
1483 gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1484
1485 /*
1486 * Force an madvise of each KVA range. Any currently allocated ranges
1487 * will have MADV_FREE applied once they are freed.
1488 */
1489 SLIST_INIT(&head);
1490 mtx_lock(&exec_args_kva_mtx);
1491 SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1492 mtx_unlock(&exec_args_kva_mtx);
1493 while ((argkva = SLIST_FIRST(&head)) != NULL) {
1494 SLIST_REMOVE_HEAD(&head, next);
1495 exec_release_args_kva(argkva, gen);
1496 }
1497
1498 CPU_FOREACH(i) {
1499 argkva = (void *)atomic_readandclear_ptr(
1500 (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1501 if (argkva != NULL)
1502 exec_release_args_kva(argkva, gen);
1503 }
1504 }
1505 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1506 EVENTHANDLER_PRI_ANY);
1507
1508 /*
1509 * Allocate temporary demand-paged, zero-filled memory for the file name,
1510 * argument, and environment strings.
1511 */
1512 int
exec_alloc_args(struct image_args * args)1513 exec_alloc_args(struct image_args *args)
1514 {
1515
1516 args->buf = (char *)exec_alloc_args_kva(&args->bufkva);
1517 return (0);
1518 }
1519
1520 void
exec_free_args(struct image_args * args)1521 exec_free_args(struct image_args *args)
1522 {
1523
1524 if (args->buf != NULL) {
1525 exec_free_args_kva(args->bufkva);
1526 args->buf = NULL;
1527 }
1528 if (args->fname_buf != NULL) {
1529 free(args->fname_buf, M_TEMP);
1530 args->fname_buf = NULL;
1531 }
1532 }
1533
1534 /*
1535 * A set to functions to fill struct image args.
1536 *
1537 * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1538 * fname) before the other functions. All exec_args_add_arg() calls must
1539 * be made before any exec_args_add_env() calls. exec_args_adjust_args()
1540 * may be called any time after exec_args_add_fname().
1541 *
1542 * exec_args_add_fname() - install path to be executed
1543 * exec_args_add_arg() - append an argument string
1544 * exec_args_add_env() - append an env string
1545 * exec_args_adjust_args() - adjust location of the argument list to
1546 * allow new arguments to be prepended
1547 */
1548 int
exec_args_add_fname(struct image_args * args,const char * fname,enum uio_seg segflg)1549 exec_args_add_fname(struct image_args *args, const char *fname,
1550 enum uio_seg segflg)
1551 {
1552 int error;
1553 size_t length;
1554
1555 KASSERT(args->fname == NULL, ("fname already appended"));
1556 KASSERT(args->endp == NULL, ("already appending to args"));
1557
1558 if (fname != NULL) {
1559 args->fname = args->buf;
1560 error = segflg == UIO_SYSSPACE ?
1561 copystr(fname, args->fname, PATH_MAX, &length) :
1562 copyinstr(fname, args->fname, PATH_MAX, &length);
1563 if (error != 0)
1564 return (error == ENAMETOOLONG ? E2BIG : error);
1565 } else
1566 length = 0;
1567
1568 /* Set up for _arg_*()/_env_*() */
1569 args->endp = args->buf + length;
1570 /* begin_argv must be set and kept updated */
1571 args->begin_argv = args->endp;
1572 KASSERT(exec_map_entry_size - length >= ARG_MAX,
1573 ("too little space remaining for arguments %zu < %zu",
1574 exec_map_entry_size - length, (size_t)ARG_MAX));
1575 args->stringspace = ARG_MAX;
1576
1577 return (0);
1578 }
1579
1580 static int
exec_args_add_str(struct image_args * args,const char * str,enum uio_seg segflg,int * countp)1581 exec_args_add_str(struct image_args *args, const char *str,
1582 enum uio_seg segflg, int *countp)
1583 {
1584 int error;
1585 size_t length;
1586
1587 KASSERT(args->endp != NULL, ("endp not initialized"));
1588 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1589
1590 error = (segflg == UIO_SYSSPACE) ?
1591 copystr(str, args->endp, args->stringspace, &length) :
1592 copyinstr(str, args->endp, args->stringspace, &length);
1593 if (error != 0)
1594 return (error == ENAMETOOLONG ? E2BIG : error);
1595 args->stringspace -= length;
1596 args->endp += length;
1597 (*countp)++;
1598
1599 return (0);
1600 }
1601
1602 int
exec_args_add_arg(struct image_args * args,const char * argp,enum uio_seg segflg)1603 exec_args_add_arg(struct image_args *args, const char *argp,
1604 enum uio_seg segflg)
1605 {
1606
1607 KASSERT(args->envc == 0, ("appending args after env"));
1608
1609 return (exec_args_add_str(args, argp, segflg, &args->argc));
1610 }
1611
1612 int
exec_args_add_env(struct image_args * args,const char * envp,enum uio_seg segflg)1613 exec_args_add_env(struct image_args *args, const char *envp,
1614 enum uio_seg segflg)
1615 {
1616
1617 if (args->envc == 0)
1618 args->begin_envv = args->endp;
1619
1620 return (exec_args_add_str(args, envp, segflg, &args->envc));
1621 }
1622
1623 int
exec_args_adjust_args(struct image_args * args,size_t consume,ssize_t extend)1624 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1625 {
1626 ssize_t offset;
1627
1628 KASSERT(args->endp != NULL, ("endp not initialized"));
1629 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1630
1631 offset = extend - consume;
1632 if (args->stringspace < offset)
1633 return (E2BIG);
1634 memmove(args->begin_argv + extend, args->begin_argv + consume,
1635 args->endp - args->begin_argv + consume);
1636 if (args->envc > 0)
1637 args->begin_envv += offset;
1638 args->endp += offset;
1639 args->stringspace -= offset;
1640 return (0);
1641 }
1642
1643 char *
exec_args_get_begin_envv(struct image_args * args)1644 exec_args_get_begin_envv(struct image_args *args)
1645 {
1646
1647 KASSERT(args->endp != NULL, ("endp not initialized"));
1648
1649 if (args->envc > 0)
1650 return (args->begin_envv);
1651 return (args->endp);
1652 }
1653
1654 /*
1655 * Copy strings out to the new process address space, constructing new arg
1656 * and env vector tables. Return a pointer to the base so that it can be used
1657 * as the initial stack pointer.
1658 */
1659 int
exec_copyout_strings(struct image_params * imgp,uintptr_t * stack_base)1660 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1661 {
1662 int argc, envc;
1663 char **vectp;
1664 char *stringp;
1665 uintptr_t destp, ustringp;
1666 struct ps_strings *arginfo;
1667 struct proc *p;
1668 struct sysentvec *sysent;
1669 size_t execpath_len;
1670 int error, szsigcode;
1671 char canary[sizeof(long) * 8];
1672
1673 p = imgp->proc;
1674 sysent = p->p_sysent;
1675
1676 destp = PROC_PS_STRINGS(p);
1677 arginfo = imgp->ps_strings = (void *)destp;
1678
1679 /*
1680 * Install sigcode.
1681 */
1682 if (sysent->sv_shared_page_base == 0 && sysent->sv_szsigcode != NULL) {
1683 szsigcode = *(sysent->sv_szsigcode);
1684 destp -= szsigcode;
1685 destp = rounddown2(destp, sizeof(void *));
1686 error = copyout(sysent->sv_sigcode, (void *)destp, szsigcode);
1687 if (error != 0)
1688 return (error);
1689 }
1690
1691 /*
1692 * Copy the image path for the rtld.
1693 */
1694 if (imgp->execpath != NULL && imgp->auxargs != NULL) {
1695 execpath_len = strlen(imgp->execpath) + 1;
1696 destp -= execpath_len;
1697 destp = rounddown2(destp, sizeof(void *));
1698 imgp->execpathp = (void *)destp;
1699 error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1700 if (error != 0)
1701 return (error);
1702 }
1703
1704 /*
1705 * Prepare the canary for SSP.
1706 */
1707 arc4rand(canary, sizeof(canary), 0);
1708 destp -= sizeof(canary);
1709 imgp->canary = (void *)destp;
1710 error = copyout(canary, imgp->canary, sizeof(canary));
1711 if (error != 0)
1712 return (error);
1713 imgp->canarylen = sizeof(canary);
1714
1715 /*
1716 * Prepare the pagesizes array.
1717 */
1718 imgp->pagesizeslen = sizeof(pagesizes[0]) * MAXPAGESIZES;
1719 destp -= imgp->pagesizeslen;
1720 destp = rounddown2(destp, sizeof(void *));
1721 imgp->pagesizes = (void *)destp;
1722 error = copyout(pagesizes, imgp->pagesizes, imgp->pagesizeslen);
1723 if (error != 0)
1724 return (error);
1725
1726 /*
1727 * Allocate room for the argument and environment strings.
1728 */
1729 destp -= ARG_MAX - imgp->args->stringspace;
1730 destp = rounddown2(destp, sizeof(void *));
1731 ustringp = destp;
1732
1733 if (imgp->auxargs) {
1734 /*
1735 * Allocate room on the stack for the ELF auxargs
1736 * array. It has up to AT_COUNT entries.
1737 */
1738 destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1739 destp = rounddown2(destp, sizeof(void *));
1740 }
1741
1742 vectp = (char **)destp;
1743
1744 /*
1745 * Allocate room for the argv[] and env vectors including the
1746 * terminating NULL pointers.
1747 */
1748 vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1749
1750 /*
1751 * vectp also becomes our initial stack base
1752 */
1753 *stack_base = (uintptr_t)vectp;
1754
1755 stringp = imgp->args->begin_argv;
1756 argc = imgp->args->argc;
1757 envc = imgp->args->envc;
1758
1759 /*
1760 * Copy out strings - arguments and environment.
1761 */
1762 error = copyout(stringp, (void *)ustringp,
1763 ARG_MAX - imgp->args->stringspace);
1764 if (error != 0)
1765 return (error);
1766
1767 /*
1768 * Fill in "ps_strings" struct for ps, w, etc.
1769 */
1770 imgp->argv = vectp;
1771 if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1772 suword32(&arginfo->ps_nargvstr, argc) != 0)
1773 return (EFAULT);
1774
1775 /*
1776 * Fill in argument portion of vector table.
1777 */
1778 for (; argc > 0; --argc) {
1779 if (suword(vectp++, ustringp) != 0)
1780 return (EFAULT);
1781 while (*stringp++ != 0)
1782 ustringp++;
1783 ustringp++;
1784 }
1785
1786 /* a null vector table pointer separates the argp's from the envp's */
1787 if (suword(vectp++, 0) != 0)
1788 return (EFAULT);
1789
1790 imgp->envv = vectp;
1791 if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1792 suword32(&arginfo->ps_nenvstr, envc) != 0)
1793 return (EFAULT);
1794
1795 /*
1796 * Fill in environment portion of vector table.
1797 */
1798 for (; envc > 0; --envc) {
1799 if (suword(vectp++, ustringp) != 0)
1800 return (EFAULT);
1801 while (*stringp++ != 0)
1802 ustringp++;
1803 ustringp++;
1804 }
1805
1806 /* end of vector table is a null pointer */
1807 if (suword(vectp, 0) != 0)
1808 return (EFAULT);
1809
1810 if (imgp->auxargs) {
1811 vectp++;
1812 error = imgp->sysent->sv_copyout_auxargs(imgp,
1813 (uintptr_t)vectp);
1814 if (error != 0)
1815 return (error);
1816 }
1817
1818 return (0);
1819 }
1820
1821 /*
1822 * Check permissions of file to execute.
1823 * Called with imgp->vp locked.
1824 * Return 0 for success or error code on failure.
1825 */
1826 int
exec_check_permissions(struct image_params * imgp)1827 exec_check_permissions(struct image_params *imgp)
1828 {
1829 struct vnode *vp = imgp->vp;
1830 struct vattr *attr = imgp->attr;
1831 struct thread *td;
1832 int error;
1833
1834 td = curthread;
1835
1836 /* Get file attributes */
1837 error = VOP_GETATTR(vp, attr, td->td_ucred);
1838 if (error)
1839 return (error);
1840
1841 #ifdef MAC
1842 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1843 if (error)
1844 return (error);
1845 #endif
1846
1847 /*
1848 * 1) Check if file execution is disabled for the filesystem that
1849 * this file resides on.
1850 * 2) Ensure that at least one execute bit is on. Otherwise, a
1851 * privileged user will always succeed, and we don't want this
1852 * to happen unless the file really is executable.
1853 * 3) Ensure that the file is a regular file.
1854 */
1855 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1856 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1857 (attr->va_type != VREG))
1858 return (EACCES);
1859
1860 /*
1861 * Zero length files can't be exec'd
1862 */
1863 if (attr->va_size == 0)
1864 return (ENOEXEC);
1865
1866 /*
1867 * Check for execute permission to file based on current credentials.
1868 */
1869 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1870 if (error)
1871 return (error);
1872
1873 /*
1874 * Check number of open-for-writes on the file and deny execution
1875 * if there are any.
1876 *
1877 * Add a text reference now so no one can write to the
1878 * executable while we're activating it.
1879 *
1880 * Remember if this was set before and unset it in case this is not
1881 * actually an executable image.
1882 */
1883 error = VOP_SET_TEXT(vp);
1884 if (error != 0)
1885 return (error);
1886 imgp->textset = true;
1887
1888 /*
1889 * Call filesystem specific open routine (which does nothing in the
1890 * general case).
1891 */
1892 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1893 if (error == 0)
1894 imgp->opened = true;
1895 return (error);
1896 }
1897
1898 /*
1899 * Exec handler registration
1900 */
1901 int
exec_register(const struct execsw * execsw_arg)1902 exec_register(const struct execsw *execsw_arg)
1903 {
1904 const struct execsw **es, **xs, **newexecsw;
1905 u_int count = 2; /* New slot and trailing NULL */
1906
1907 if (execsw)
1908 for (es = execsw; *es; es++)
1909 count++;
1910 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1911 xs = newexecsw;
1912 if (execsw)
1913 for (es = execsw; *es; es++)
1914 *xs++ = *es;
1915 *xs++ = execsw_arg;
1916 *xs = NULL;
1917 if (execsw)
1918 free(execsw, M_TEMP);
1919 execsw = newexecsw;
1920 return (0);
1921 }
1922
1923 int
exec_unregister(const struct execsw * execsw_arg)1924 exec_unregister(const struct execsw *execsw_arg)
1925 {
1926 const struct execsw **es, **xs, **newexecsw;
1927 int count = 1;
1928
1929 if (execsw == NULL)
1930 panic("unregister with no handlers left?\n");
1931
1932 for (es = execsw; *es; es++) {
1933 if (*es == execsw_arg)
1934 break;
1935 }
1936 if (*es == NULL)
1937 return (ENOENT);
1938 for (es = execsw; *es; es++)
1939 if (*es != execsw_arg)
1940 count++;
1941 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1942 xs = newexecsw;
1943 for (es = execsw; *es; es++)
1944 if (*es != execsw_arg)
1945 *xs++ = *es;
1946 *xs = NULL;
1947 if (execsw)
1948 free(execsw, M_TEMP);
1949 execsw = newexecsw;
1950 return (0);
1951 }
1952
1953 /*
1954 * Write out a core segment to the compression stream.
1955 */
1956 static int
compress_chunk(struct coredump_params * cp,char * base,char * buf,size_t len)1957 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
1958 {
1959 size_t chunk_len;
1960 int error;
1961
1962 error = 0;
1963 while (len > 0) {
1964 chunk_len = MIN(len, CORE_BUF_SIZE);
1965
1966 /*
1967 * We can get EFAULT error here.
1968 * In that case zero out the current chunk of the segment.
1969 */
1970 error = copyin(base, buf, chunk_len);
1971 if (error != 0)
1972 bzero(buf, chunk_len);
1973 error = compressor_write(cp->comp, buf, chunk_len);
1974 if (error != 0)
1975 break;
1976 base += chunk_len;
1977 len -= chunk_len;
1978 }
1979 return (error);
1980 }
1981
1982 int
core_write(struct coredump_params * cp,const void * base,size_t len,off_t offset,enum uio_seg seg,size_t * resid)1983 core_write(struct coredump_params *cp, const void *base, size_t len,
1984 off_t offset, enum uio_seg seg, size_t *resid)
1985 {
1986
1987 return (vn_rdwr_inchunks(UIO_WRITE, cp->vp, __DECONST(void *, base),
1988 len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1989 cp->active_cred, cp->file_cred, resid, cp->td));
1990 }
1991
1992 int
core_output(char * base,size_t len,off_t offset,struct coredump_params * cp,void * tmpbuf)1993 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
1994 void *tmpbuf)
1995 {
1996 vm_map_t map;
1997 struct mount *mp;
1998 size_t resid, runlen;
1999 int error;
2000 bool success;
2001
2002 KASSERT((uintptr_t)base % PAGE_SIZE == 0,
2003 ("%s: user address %p is not page-aligned", __func__, base));
2004
2005 if (cp->comp != NULL)
2006 return (compress_chunk(cp, base, tmpbuf, len));
2007
2008 error = 0;
2009 map = &cp->td->td_proc->p_vmspace->vm_map;
2010 for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
2011 /*
2012 * Attempt to page in all virtual pages in the range. If a
2013 * virtual page is not backed by the pager, it is represented as
2014 * a hole in the file. This can occur with zero-filled
2015 * anonymous memory or truncated files, for example.
2016 */
2017 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
2018 if (core_dump_can_intr && curproc_sigkilled())
2019 return (EINTR);
2020 error = vm_fault(map, (uintptr_t)base + runlen,
2021 VM_PROT_READ, VM_FAULT_NOFILL, NULL);
2022 if (runlen == 0)
2023 success = error == KERN_SUCCESS;
2024 else if ((error == KERN_SUCCESS) != success)
2025 break;
2026 }
2027
2028 if (success) {
2029 error = core_write(cp, base, runlen, offset,
2030 UIO_USERSPACE, &resid);
2031 if (error != 0) {
2032 if (error != EFAULT)
2033 break;
2034
2035 /*
2036 * EFAULT may be returned if the user mapping
2037 * could not be accessed, e.g., because a mapped
2038 * file has been truncated. Skip the page if no
2039 * progress was made, to protect against a
2040 * hypothetical scenario where vm_fault() was
2041 * successful but core_write() returns EFAULT
2042 * anyway.
2043 */
2044 runlen -= resid;
2045 if (runlen == 0) {
2046 success = false;
2047 runlen = PAGE_SIZE;
2048 }
2049 }
2050 }
2051 if (!success) {
2052 error = vn_start_write(cp->vp, &mp, V_WAIT);
2053 if (error != 0)
2054 break;
2055 vn_lock(cp->vp, LK_EXCLUSIVE | LK_RETRY);
2056 error = vn_truncate_locked(cp->vp, offset + runlen,
2057 false, cp->td->td_ucred);
2058 VOP_UNLOCK(cp->vp);
2059 vn_finished_write(mp);
2060 if (error != 0)
2061 break;
2062 }
2063 }
2064 return (error);
2065 }
2066
2067 /*
2068 * Drain into a core file.
2069 */
2070 int
sbuf_drain_core_output(void * arg,const char * data,int len)2071 sbuf_drain_core_output(void *arg, const char *data, int len)
2072 {
2073 struct coredump_params *cp;
2074 struct proc *p;
2075 int error, locked;
2076
2077 cp = arg;
2078 p = cp->td->td_proc;
2079
2080 /*
2081 * Some kern_proc out routines that print to this sbuf may
2082 * call us with the process lock held. Draining with the
2083 * non-sleepable lock held is unsafe. The lock is needed for
2084 * those routines when dumping a live process. In our case we
2085 * can safely release the lock before draining and acquire
2086 * again after.
2087 */
2088 locked = PROC_LOCKED(p);
2089 if (locked)
2090 PROC_UNLOCK(p);
2091 if (cp->comp != NULL)
2092 error = compressor_write(cp->comp, __DECONST(char *, data),
2093 len);
2094 else
2095 error = core_write(cp, __DECONST(void *, data), len, cp->offset,
2096 UIO_SYSSPACE, NULL);
2097 if (locked)
2098 PROC_LOCK(p);
2099 if (error != 0)
2100 return (-error);
2101 cp->offset += len;
2102 return (len);
2103 }
2104