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 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
813 p->p_flag2 &= ~P2_NOTRACE;
814 if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
815 p->p_flag2 &= ~P2_STKGAP_DISABLE;
816 p->p_flag2 &= ~(P2_MEMBAR_PRIVE | P2_MEMBAR_PRIVE_SYNCORE |
817 P2_MEMBAR_GLOBE);
818 if (p->p_flag & P_PPWAIT) {
819 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
820 cv_broadcast(&p->p_pwait);
821 /* STOPs are no longer ignored, arrange for AST */
822 signotify(td);
823 }
824
825 if ((imgp->sysent->sv_setid_allowed != NULL &&
826 !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
827 (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
828 execve_nosetid(imgp);
829
830 /*
831 * Implement image setuid/setgid installation.
832 */
833 if (imgp->credential_setid) {
834 /*
835 * Turn off syscall tracing for set-id programs, except for
836 * root. Record any set-id flags first to make sure that
837 * we do not regain any tracing during a possible block.
838 */
839 setsugid(p);
840 #ifdef KTRACE
841 kiop = ktrprocexec(p);
842 #endif
843 /*
844 * Close any file descriptors 0..2 that reference procfs,
845 * then make sure file descriptors 0..2 are in use.
846 *
847 * Both fdsetugidsafety() and fdcheckstd() may call functions
848 * taking sleepable locks, so temporarily drop our locks.
849 */
850 PROC_UNLOCK(p);
851 VOP_UNLOCK(imgp->vp);
852 fdsetugidsafety(td);
853 error = fdcheckstd(td);
854 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
855 if (error != 0)
856 goto exec_fail_dealloc;
857 PROC_LOCK(p);
858 #ifdef MAC
859 if (will_transition) {
860 mac_vnode_execve_transition(oldcred, imgp->newcred,
861 imgp->vp, interpvplabel, imgp);
862 }
863 #endif
864 } else {
865 if (oldcred->cr_uid == oldcred->cr_ruid &&
866 oldcred->cr_gid == oldcred->cr_rgid)
867 p->p_flag &= ~P_SUGID;
868 }
869 /*
870 * Set the new credentials.
871 */
872 if (imgp->newcred != NULL) {
873 proc_set_cred(p, imgp->newcred);
874 crfree(oldcred);
875 oldcred = NULL;
876 }
877
878 /*
879 * Store the vp for use in kern.proc.pathname. This vnode was
880 * referenced by namei() or by fexecve variant of fname handling.
881 */
882 oldtextvp = p->p_textvp;
883 p->p_textvp = newtextvp;
884 oldtextdvp = p->p_textdvp;
885 p->p_textdvp = newtextdvp;
886 newtextdvp = NULL;
887 oldbinname = p->p_binname;
888 p->p_binname = newbinname;
889 newbinname = NULL;
890
891 #ifdef KDTRACE_HOOKS
892 /*
893 * Tell the DTrace fasttrap provider about the exec if it
894 * has declared an interest.
895 */
896 if (dtrace_fasttrap_exec)
897 dtrace_fasttrap_exec(p);
898 #endif
899
900 /*
901 * Notify others that we exec'd, and clear the P_INEXEC flag
902 * as we're now a bona fide freshly-execed process.
903 */
904 KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
905 p->p_flag &= ~P_INEXEC;
906
907 /* clear "fork but no exec" flag, as we _are_ execing */
908 p->p_acflag &= ~AFORK;
909
910 /*
911 * Free any previous argument cache and replace it with
912 * the new argument cache, if any.
913 */
914 oldargs = p->p_args;
915 p->p_args = newargs;
916 newargs = NULL;
917
918 PROC_UNLOCK(p);
919
920 #ifdef HWPMC_HOOKS
921 /*
922 * Check if system-wide sampling is in effect or if the
923 * current process is using PMCs. If so, do exec() time
924 * processing. This processing needs to happen AFTER the
925 * P_INEXEC flag is cleared.
926 */
927 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
928 VOP_UNLOCK(imgp->vp);
929 pe.pm_credentialschanged = credential_changing;
930 pe.pm_baseaddr = imgp->reloc_base;
931 pe.pm_dynaddr = imgp->et_dyn_addr;
932
933 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
934 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
935 }
936 #endif
937
938 /* Set values passed into the program in registers. */
939 (*p->p_sysent->sv_setregs)(td, imgp, stack_base);
940
941 VOP_MMAPPED(imgp->vp);
942
943 SDT_PROBE1(proc, , , exec__success, args->fname);
944
945 exec_fail_dealloc:
946 if (error != 0) {
947 p->p_osrel = orig_osrel;
948 p->p_fctl0 = orig_fctl0;
949 p->p_elf_brandinfo = orig_brandinfo;
950 }
951
952 if (imgp->firstpage != NULL)
953 exec_unmap_first_page(imgp);
954
955 if (imgp->vp != NULL) {
956 if (imgp->opened)
957 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
958 if (imgp->textset)
959 VOP_UNSET_TEXT_CHECKED(imgp->vp);
960 if (error != 0)
961 vput(imgp->vp);
962 else
963 VOP_UNLOCK(imgp->vp);
964 if (args->fname != NULL)
965 NDFREE_PNBUF(&nd);
966 if (newtextdvp != NULL)
967 vrele(newtextdvp);
968 free(newbinname, M_PARGS);
969 }
970
971 if (imgp->object != NULL)
972 vm_object_deallocate(imgp->object);
973
974 free(imgp->freepath, M_TEMP);
975
976 if (error == 0) {
977 if (p->p_ptevents & PTRACE_EXEC) {
978 PROC_LOCK(p);
979 if (p->p_ptevents & PTRACE_EXEC)
980 td->td_dbgflags |= TDB_EXEC;
981 PROC_UNLOCK(p);
982 }
983 } else {
984 exec_fail:
985 /* we're done here, clear P_INEXEC */
986 PROC_LOCK(p);
987 p->p_flag &= ~P_INEXEC;
988 PROC_UNLOCK(p);
989
990 SDT_PROBE1(proc, , , exec__failure, error);
991 }
992
993 if (imgp->newcred != NULL && oldcred != NULL)
994 crfree(imgp->newcred);
995
996 #ifdef MAC
997 mac_execve_exit(imgp);
998 mac_execve_interpreter_exit(interpvplabel);
999 #endif
1000 exec_free_args(args);
1001
1002 /*
1003 * Handle deferred decrement of ref counts.
1004 */
1005 if (oldtextvp != NULL)
1006 vrele(oldtextvp);
1007 if (oldtextdvp != NULL)
1008 vrele(oldtextdvp);
1009 free(oldbinname, M_PARGS);
1010 #ifdef KTRACE
1011 ktr_io_params_free(kiop);
1012 #endif
1013 pargs_drop(oldargs);
1014 pargs_drop(newargs);
1015 if (oldsigacts != NULL)
1016 sigacts_free(oldsigacts);
1017 if (euip != NULL)
1018 uifree(euip);
1019
1020 if (error && imgp->vmspace_destroyed) {
1021 /* sorry, no more process anymore. exit gracefully */
1022 exec_cleanup(td, oldvmspace);
1023 exit1(td, 0, SIGABRT);
1024 /* NOT REACHED */
1025 }
1026
1027 #ifdef KTRACE
1028 if (error == 0)
1029 ktrprocctor(p);
1030 #endif
1031
1032 /*
1033 * We don't want cpu_set_syscall_retval() to overwrite any of
1034 * the register values put in place by exec_setregs().
1035 * Implementations of cpu_set_syscall_retval() will leave
1036 * registers unmodified when returning EJUSTRETURN.
1037 */
1038 return (error == 0 ? EJUSTRETURN : error);
1039 }
1040
1041 void
exec_cleanup(struct thread * td,struct vmspace * oldvmspace)1042 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1043 {
1044 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1045 KASSERT(td->td_proc->p_vmspace != oldvmspace,
1046 ("oldvmspace still used"));
1047 vmspace_free(oldvmspace);
1048 td->td_pflags &= ~TDP_EXECVMSPC;
1049 }
1050 }
1051
1052 int
exec_map_first_page(struct image_params * imgp)1053 exec_map_first_page(struct image_params *imgp)
1054 {
1055 vm_object_t object;
1056 vm_page_t m;
1057 int error;
1058
1059 if (imgp->firstpage != NULL)
1060 exec_unmap_first_page(imgp);
1061
1062 object = imgp->vp->v_object;
1063 if (object == NULL)
1064 return (EACCES);
1065 #if VM_NRESERVLEVEL > 0
1066 if ((object->flags & OBJ_COLORED) == 0) {
1067 VM_OBJECT_WLOCK(object);
1068 vm_object_color(object, 0);
1069 VM_OBJECT_WUNLOCK(object);
1070 }
1071 #endif
1072 error = vm_page_grab_valid_unlocked(&m, object, 0,
1073 VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1074 VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1075
1076 if (error != VM_PAGER_OK)
1077 return (EIO);
1078 imgp->firstpage = sf_buf_alloc(m, 0);
1079 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1080
1081 return (0);
1082 }
1083
1084 void
exec_unmap_first_page(struct image_params * imgp)1085 exec_unmap_first_page(struct image_params *imgp)
1086 {
1087 vm_page_t m;
1088
1089 if (imgp->firstpage != NULL) {
1090 m = sf_buf_page(imgp->firstpage);
1091 sf_buf_free(imgp->firstpage);
1092 imgp->firstpage = NULL;
1093 vm_page_unwire(m, PQ_ACTIVE);
1094 }
1095 }
1096
1097 void
exec_onexec_old(struct thread * td)1098 exec_onexec_old(struct thread *td)
1099 {
1100 sigfastblock_clear(td);
1101 umtx_exec(td->td_proc);
1102 }
1103
1104 /*
1105 * This is an optimization which removes the unmanaged shared page
1106 * mapping. In combination with pmap_remove_pages(), which cleans all
1107 * managed mappings in the process' vmspace pmap, no work will be left
1108 * for pmap_remove(min, max).
1109 */
1110 void
exec_free_abi_mappings(struct proc * p)1111 exec_free_abi_mappings(struct proc *p)
1112 {
1113 struct vmspace *vmspace;
1114
1115 vmspace = p->p_vmspace;
1116 if (refcount_load(&vmspace->vm_refcnt) != 1)
1117 return;
1118
1119 if (!PROC_HAS_SHP(p))
1120 return;
1121
1122 pmap_remove(vmspace_pmap(vmspace), vmspace->vm_shp_base,
1123 vmspace->vm_shp_base + p->p_sysent->sv_shared_page_len);
1124 }
1125
1126 /*
1127 * Run down the current address space and install a new one.
1128 */
1129 int
exec_new_vmspace(struct image_params * imgp,struct sysentvec * sv)1130 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1131 {
1132 int error;
1133 struct proc *p = imgp->proc;
1134 struct vmspace *vmspace = p->p_vmspace;
1135 struct thread *td = curthread;
1136 vm_offset_t sv_minuser;
1137 vm_map_t map;
1138
1139 imgp->vmspace_destroyed = true;
1140 imgp->sysent = sv;
1141
1142 if (p->p_sysent->sv_onexec_old != NULL)
1143 p->p_sysent->sv_onexec_old(td);
1144 itimers_exec(p);
1145
1146 EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1147
1148 /*
1149 * Blow away entire process VM, if address space not shared,
1150 * otherwise, create a new VM space so that other threads are
1151 * not disrupted
1152 */
1153 map = &vmspace->vm_map;
1154 if (map_at_zero)
1155 sv_minuser = sv->sv_minuser;
1156 else
1157 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1158 if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1159 vm_map_min(map) == sv_minuser &&
1160 vm_map_max(map) == sv->sv_maxuser &&
1161 cpu_exec_vmspace_reuse(p, map)) {
1162 exec_free_abi_mappings(p);
1163 shmexit(vmspace);
1164 pmap_remove_pages(vmspace_pmap(vmspace));
1165 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1166 /*
1167 * An exec terminates mlockall(MCL_FUTURE).
1168 * ASLR and W^X states must be re-evaluated.
1169 */
1170 vm_map_lock(map);
1171 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1172 MAP_ASLR_IGNSTART | MAP_ASLR_STACK | MAP_WXORX);
1173 vm_map_unlock(map);
1174 } else {
1175 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1176 if (error)
1177 return (error);
1178 vmspace = p->p_vmspace;
1179 map = &vmspace->vm_map;
1180 }
1181 map->flags |= imgp->map_flags;
1182
1183 return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1184 }
1185
1186 /*
1187 * Compute the stack size limit and map the main process stack.
1188 * Map the shared page.
1189 */
1190 int
exec_map_stack(struct image_params * imgp)1191 exec_map_stack(struct image_params *imgp)
1192 {
1193 struct rlimit rlim_stack;
1194 struct sysentvec *sv;
1195 struct proc *p;
1196 vm_map_t map;
1197 struct vmspace *vmspace;
1198 vm_offset_t stack_addr, stack_top;
1199 vm_offset_t sharedpage_addr;
1200 u_long ssiz;
1201 int error, find_space, stack_off;
1202 vm_prot_t stack_prot;
1203 vm_object_t obj;
1204
1205 p = imgp->proc;
1206 sv = p->p_sysent;
1207
1208 if (imgp->stack_sz != 0) {
1209 ssiz = trunc_page(imgp->stack_sz);
1210 PROC_LOCK(p);
1211 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1212 PROC_UNLOCK(p);
1213 if (ssiz > rlim_stack.rlim_max)
1214 ssiz = rlim_stack.rlim_max;
1215 if (ssiz > rlim_stack.rlim_cur) {
1216 rlim_stack.rlim_cur = ssiz;
1217 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1218 }
1219 } else if (sv->sv_maxssiz != NULL) {
1220 ssiz = *sv->sv_maxssiz;
1221 } else {
1222 ssiz = maxssiz;
1223 }
1224
1225 vmspace = p->p_vmspace;
1226 map = &vmspace->vm_map;
1227
1228 stack_prot = sv->sv_shared_page_obj != NULL && imgp->stack_prot != 0 ?
1229 imgp->stack_prot : sv->sv_stackprot;
1230 if ((map->flags & MAP_ASLR_STACK) != 0) {
1231 stack_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
1232 lim_max(curthread, RLIMIT_DATA));
1233 find_space = VMFS_ANY_SPACE;
1234 } else {
1235 stack_addr = sv->sv_usrstack - ssiz;
1236 find_space = VMFS_NO_SPACE;
1237 }
1238 error = vm_map_find(map, NULL, 0, &stack_addr, (vm_size_t)ssiz,
1239 sv->sv_usrstack, find_space, stack_prot, VM_PROT_ALL,
1240 MAP_STACK_AREA);
1241 if (error != KERN_SUCCESS) {
1242 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1243 "failed, mach error %d errno %d\n", (uintmax_t)ssiz,
1244 stack_prot, error, vm_mmap_to_errno(error));
1245 return (vm_mmap_to_errno(error));
1246 }
1247
1248 stack_top = stack_addr + ssiz;
1249 if ((map->flags & MAP_ASLR_STACK) != 0) {
1250 /* Randomize within the first page of the stack. */
1251 arc4rand(&stack_off, sizeof(stack_off), 0);
1252 stack_top -= rounddown2(stack_off & PAGE_MASK, sizeof(void *));
1253 }
1254
1255 /* Map a shared page */
1256 obj = sv->sv_shared_page_obj;
1257 if (obj == NULL) {
1258 sharedpage_addr = 0;
1259 goto out;
1260 }
1261
1262 /*
1263 * If randomization is disabled then the shared page will
1264 * be mapped at address specified in sysentvec.
1265 * Otherwise any address above .data section can be selected.
1266 * Same logic is used for stack address randomization.
1267 * If the address randomization is applied map a guard page
1268 * at the top of UVA.
1269 */
1270 vm_object_reference(obj);
1271 if ((imgp->imgp_flags & IMGP_ASLR_SHARED_PAGE) != 0) {
1272 sharedpage_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
1273 lim_max(curthread, RLIMIT_DATA));
1274
1275 error = vm_map_fixed(map, NULL, 0,
1276 sv->sv_maxuser - PAGE_SIZE, PAGE_SIZE,
1277 VM_PROT_NONE, VM_PROT_NONE, MAP_CREATE_GUARD);
1278 if (error != KERN_SUCCESS) {
1279 /*
1280 * This is not fatal, so let's just print a warning
1281 * and continue.
1282 */
1283 uprintf("%s: Mapping guard page at the top of UVA failed"
1284 " mach error %d errno %d",
1285 __func__, error, vm_mmap_to_errno(error));
1286 }
1287
1288 error = vm_map_find(map, obj, 0,
1289 &sharedpage_addr, sv->sv_shared_page_len,
1290 sv->sv_maxuser, VMFS_ANY_SPACE,
1291 VM_PROT_READ | VM_PROT_EXECUTE,
1292 VM_PROT_READ | VM_PROT_EXECUTE,
1293 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1294 } else {
1295 sharedpage_addr = sv->sv_shared_page_base;
1296 vm_map_fixed(map, obj, 0,
1297 sharedpage_addr, sv->sv_shared_page_len,
1298 VM_PROT_READ | VM_PROT_EXECUTE,
1299 VM_PROT_READ | VM_PROT_EXECUTE,
1300 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1301 }
1302 if (error != KERN_SUCCESS) {
1303 uprintf("%s: mapping shared page at addr: %p"
1304 "failed, mach error %d errno %d\n", __func__,
1305 (void *)sharedpage_addr, error, vm_mmap_to_errno(error));
1306 vm_object_deallocate(obj);
1307 return (vm_mmap_to_errno(error));
1308 }
1309 out:
1310 /*
1311 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1312 * are still used to enforce the stack rlimit on the process stack.
1313 */
1314 vmspace->vm_maxsaddr = (char *)stack_addr;
1315 vmspace->vm_stacktop = stack_top;
1316 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1317 vmspace->vm_shp_base = sharedpage_addr;
1318
1319 return (0);
1320 }
1321
1322 /*
1323 * Copy out argument and environment strings from the old process address
1324 * space into the temporary string buffer.
1325 */
1326 int
exec_copyin_args(struct image_args * args,const char * fname,char ** argv,char ** envv)1327 exec_copyin_args(struct image_args *args, const char *fname,
1328 char **argv, char **envv)
1329 {
1330 u_long arg, env;
1331 int error;
1332
1333 bzero(args, sizeof(*args));
1334 if (argv == NULL)
1335 return (EFAULT);
1336
1337 /*
1338 * Allocate demand-paged memory for the file name, argument, and
1339 * environment strings.
1340 */
1341 error = exec_alloc_args(args);
1342 if (error != 0)
1343 return (error);
1344
1345 /*
1346 * Copy the file name.
1347 */
1348 error = exec_args_add_fname(args, fname, UIO_USERSPACE);
1349 if (error != 0)
1350 goto err_exit;
1351
1352 /*
1353 * extract arguments first
1354 */
1355 for (;;) {
1356 error = fueword(argv++, &arg);
1357 if (error == -1) {
1358 error = EFAULT;
1359 goto err_exit;
1360 }
1361 if (arg == 0)
1362 break;
1363 error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1364 UIO_USERSPACE);
1365 if (error != 0)
1366 goto err_exit;
1367 }
1368
1369 /*
1370 * extract environment strings
1371 */
1372 if (envv) {
1373 for (;;) {
1374 error = fueword(envv++, &env);
1375 if (error == -1) {
1376 error = EFAULT;
1377 goto err_exit;
1378 }
1379 if (env == 0)
1380 break;
1381 error = exec_args_add_env(args,
1382 (char *)(uintptr_t)env, UIO_USERSPACE);
1383 if (error != 0)
1384 goto err_exit;
1385 }
1386 }
1387
1388 return (0);
1389
1390 err_exit:
1391 exec_free_args(args);
1392 return (error);
1393 }
1394
1395 struct exec_args_kva {
1396 vm_offset_t addr;
1397 u_int gen;
1398 SLIST_ENTRY(exec_args_kva) next;
1399 };
1400
1401 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1402
1403 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1404 static struct mtx exec_args_kva_mtx;
1405 static u_int exec_args_gen;
1406
1407 static void
exec_prealloc_args_kva(void * arg __unused)1408 exec_prealloc_args_kva(void *arg __unused)
1409 {
1410 struct exec_args_kva *argkva;
1411 u_int i;
1412
1413 SLIST_INIT(&exec_args_kva_freelist);
1414 mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1415 for (i = 0; i < exec_map_entries; i++) {
1416 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1417 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size);
1418 argkva->gen = exec_args_gen;
1419 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1420 }
1421 }
1422 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1423
1424 static vm_offset_t
exec_alloc_args_kva(void ** cookie)1425 exec_alloc_args_kva(void **cookie)
1426 {
1427 struct exec_args_kva *argkva;
1428
1429 argkva = (void *)atomic_readandclear_ptr(
1430 (uintptr_t *)DPCPU_PTR(exec_args_kva));
1431 if (argkva == NULL) {
1432 mtx_lock(&exec_args_kva_mtx);
1433 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1434 (void)mtx_sleep(&exec_args_kva_freelist,
1435 &exec_args_kva_mtx, 0, "execkva", 0);
1436 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1437 mtx_unlock(&exec_args_kva_mtx);
1438 }
1439 kasan_mark((void *)argkva->addr, exec_map_entry_size,
1440 exec_map_entry_size, 0);
1441 *(struct exec_args_kva **)cookie = argkva;
1442 return (argkva->addr);
1443 }
1444
1445 static void
exec_release_args_kva(struct exec_args_kva * argkva,u_int gen)1446 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1447 {
1448 vm_offset_t base;
1449
1450 base = argkva->addr;
1451 kasan_mark((void *)argkva->addr, 0, exec_map_entry_size,
1452 KASAN_EXEC_ARGS_FREED);
1453 if (argkva->gen != gen) {
1454 (void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1455 MADV_FREE);
1456 argkva->gen = gen;
1457 }
1458 if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1459 (uintptr_t)NULL, (uintptr_t)argkva)) {
1460 mtx_lock(&exec_args_kva_mtx);
1461 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1462 wakeup_one(&exec_args_kva_freelist);
1463 mtx_unlock(&exec_args_kva_mtx);
1464 }
1465 }
1466
1467 static void
exec_free_args_kva(void * cookie)1468 exec_free_args_kva(void *cookie)
1469 {
1470
1471 exec_release_args_kva(cookie, exec_args_gen);
1472 }
1473
1474 static void
exec_args_kva_lowmem(void * arg __unused,int flags __unused)1475 exec_args_kva_lowmem(void *arg __unused, int flags __unused)
1476 {
1477 SLIST_HEAD(, exec_args_kva) head;
1478 struct exec_args_kva *argkva;
1479 u_int gen;
1480 int i;
1481
1482 gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1483
1484 /*
1485 * Force an madvise of each KVA range. Any currently allocated ranges
1486 * will have MADV_FREE applied once they are freed.
1487 */
1488 SLIST_INIT(&head);
1489 mtx_lock(&exec_args_kva_mtx);
1490 SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1491 mtx_unlock(&exec_args_kva_mtx);
1492 while ((argkva = SLIST_FIRST(&head)) != NULL) {
1493 SLIST_REMOVE_HEAD(&head, next);
1494 exec_release_args_kva(argkva, gen);
1495 }
1496
1497 CPU_FOREACH(i) {
1498 argkva = (void *)atomic_readandclear_ptr(
1499 (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1500 if (argkva != NULL)
1501 exec_release_args_kva(argkva, gen);
1502 }
1503 }
1504 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1505 EVENTHANDLER_PRI_ANY);
1506
1507 /*
1508 * Allocate temporary demand-paged, zero-filled memory for the file name,
1509 * argument, and environment strings.
1510 */
1511 int
exec_alloc_args(struct image_args * args)1512 exec_alloc_args(struct image_args *args)
1513 {
1514
1515 args->buf = (char *)exec_alloc_args_kva(&args->bufkva);
1516 return (0);
1517 }
1518
1519 void
exec_free_args(struct image_args * args)1520 exec_free_args(struct image_args *args)
1521 {
1522
1523 if (args->buf != NULL) {
1524 exec_free_args_kva(args->bufkva);
1525 args->buf = NULL;
1526 }
1527 if (args->fname_buf != NULL) {
1528 free(args->fname_buf, M_TEMP);
1529 args->fname_buf = NULL;
1530 }
1531 }
1532
1533 /*
1534 * A set to functions to fill struct image args.
1535 *
1536 * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1537 * fname) before the other functions. All exec_args_add_arg() calls must
1538 * be made before any exec_args_add_env() calls. exec_args_adjust_args()
1539 * may be called any time after exec_args_add_fname().
1540 *
1541 * exec_args_add_fname() - install path to be executed
1542 * exec_args_add_arg() - append an argument string
1543 * exec_args_add_env() - append an env string
1544 * exec_args_adjust_args() - adjust location of the argument list to
1545 * allow new arguments to be prepended
1546 */
1547 int
exec_args_add_fname(struct image_args * args,const char * fname,enum uio_seg segflg)1548 exec_args_add_fname(struct image_args *args, const char *fname,
1549 enum uio_seg segflg)
1550 {
1551 int error;
1552 size_t length;
1553
1554 KASSERT(args->fname == NULL, ("fname already appended"));
1555 KASSERT(args->endp == NULL, ("already appending to args"));
1556
1557 if (fname != NULL) {
1558 args->fname = args->buf;
1559 error = segflg == UIO_SYSSPACE ?
1560 copystr(fname, args->fname, PATH_MAX, &length) :
1561 copyinstr(fname, args->fname, PATH_MAX, &length);
1562 if (error != 0)
1563 return (error == ENAMETOOLONG ? E2BIG : error);
1564 } else
1565 length = 0;
1566
1567 /* Set up for _arg_*()/_env_*() */
1568 args->endp = args->buf + length;
1569 /* begin_argv must be set and kept updated */
1570 args->begin_argv = args->endp;
1571 KASSERT(exec_map_entry_size - length >= ARG_MAX,
1572 ("too little space remaining for arguments %zu < %zu",
1573 exec_map_entry_size - length, (size_t)ARG_MAX));
1574 args->stringspace = ARG_MAX;
1575
1576 return (0);
1577 }
1578
1579 static int
exec_args_add_str(struct image_args * args,const char * str,enum uio_seg segflg,int * countp)1580 exec_args_add_str(struct image_args *args, const char *str,
1581 enum uio_seg segflg, int *countp)
1582 {
1583 int error;
1584 size_t length;
1585
1586 KASSERT(args->endp != NULL, ("endp not initialized"));
1587 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1588
1589 error = (segflg == UIO_SYSSPACE) ?
1590 copystr(str, args->endp, args->stringspace, &length) :
1591 copyinstr(str, args->endp, args->stringspace, &length);
1592 if (error != 0)
1593 return (error == ENAMETOOLONG ? E2BIG : error);
1594 args->stringspace -= length;
1595 args->endp += length;
1596 (*countp)++;
1597
1598 return (0);
1599 }
1600
1601 int
exec_args_add_arg(struct image_args * args,const char * argp,enum uio_seg segflg)1602 exec_args_add_arg(struct image_args *args, const char *argp,
1603 enum uio_seg segflg)
1604 {
1605
1606 KASSERT(args->envc == 0, ("appending args after env"));
1607
1608 return (exec_args_add_str(args, argp, segflg, &args->argc));
1609 }
1610
1611 int
exec_args_add_env(struct image_args * args,const char * envp,enum uio_seg segflg)1612 exec_args_add_env(struct image_args *args, const char *envp,
1613 enum uio_seg segflg)
1614 {
1615
1616 if (args->envc == 0)
1617 args->begin_envv = args->endp;
1618
1619 return (exec_args_add_str(args, envp, segflg, &args->envc));
1620 }
1621
1622 int
exec_args_adjust_args(struct image_args * args,size_t consume,ssize_t extend)1623 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1624 {
1625 ssize_t offset;
1626
1627 KASSERT(args->endp != NULL, ("endp not initialized"));
1628 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1629
1630 offset = extend - consume;
1631 if (args->stringspace < offset)
1632 return (E2BIG);
1633 memmove(args->begin_argv + extend, args->begin_argv + consume,
1634 args->endp - args->begin_argv + consume);
1635 if (args->envc > 0)
1636 args->begin_envv += offset;
1637 args->endp += offset;
1638 args->stringspace -= offset;
1639 return (0);
1640 }
1641
1642 char *
exec_args_get_begin_envv(struct image_args * args)1643 exec_args_get_begin_envv(struct image_args *args)
1644 {
1645
1646 KASSERT(args->endp != NULL, ("endp not initialized"));
1647
1648 if (args->envc > 0)
1649 return (args->begin_envv);
1650 return (args->endp);
1651 }
1652
1653 /*
1654 * Copy strings out to the new process address space, constructing new arg
1655 * and env vector tables. Return a pointer to the base so that it can be used
1656 * as the initial stack pointer.
1657 */
1658 int
exec_copyout_strings(struct image_params * imgp,uintptr_t * stack_base)1659 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1660 {
1661 int argc, envc;
1662 char **vectp;
1663 char *stringp;
1664 uintptr_t destp, ustringp;
1665 struct ps_strings *arginfo;
1666 struct proc *p;
1667 struct sysentvec *sysent;
1668 size_t execpath_len;
1669 int error, szsigcode;
1670 char canary[sizeof(long) * 8];
1671
1672 p = imgp->proc;
1673 sysent = p->p_sysent;
1674
1675 destp = PROC_PS_STRINGS(p);
1676 arginfo = imgp->ps_strings = (void *)destp;
1677
1678 /*
1679 * Install sigcode.
1680 */
1681 if (sysent->sv_shared_page_base == 0 && sysent->sv_szsigcode != NULL) {
1682 szsigcode = *(sysent->sv_szsigcode);
1683 destp -= szsigcode;
1684 destp = rounddown2(destp, sizeof(void *));
1685 error = copyout(sysent->sv_sigcode, (void *)destp, szsigcode);
1686 if (error != 0)
1687 return (error);
1688 }
1689
1690 /*
1691 * Copy the image path for the rtld.
1692 */
1693 if (imgp->execpath != NULL && imgp->auxargs != NULL) {
1694 execpath_len = strlen(imgp->execpath) + 1;
1695 destp -= execpath_len;
1696 destp = rounddown2(destp, sizeof(void *));
1697 imgp->execpathp = (void *)destp;
1698 error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1699 if (error != 0)
1700 return (error);
1701 }
1702
1703 /*
1704 * Prepare the canary for SSP.
1705 */
1706 arc4rand(canary, sizeof(canary), 0);
1707 destp -= sizeof(canary);
1708 imgp->canary = (void *)destp;
1709 error = copyout(canary, imgp->canary, sizeof(canary));
1710 if (error != 0)
1711 return (error);
1712 imgp->canarylen = sizeof(canary);
1713
1714 /*
1715 * Prepare the pagesizes array.
1716 */
1717 imgp->pagesizeslen = sizeof(pagesizes[0]) * MAXPAGESIZES;
1718 destp -= imgp->pagesizeslen;
1719 destp = rounddown2(destp, sizeof(void *));
1720 imgp->pagesizes = (void *)destp;
1721 error = copyout(pagesizes, imgp->pagesizes, imgp->pagesizeslen);
1722 if (error != 0)
1723 return (error);
1724
1725 /*
1726 * Allocate room for the argument and environment strings.
1727 */
1728 destp -= ARG_MAX - imgp->args->stringspace;
1729 destp = rounddown2(destp, sizeof(void *));
1730 ustringp = destp;
1731
1732 if (imgp->auxargs) {
1733 /*
1734 * Allocate room on the stack for the ELF auxargs
1735 * array. It has up to AT_COUNT entries.
1736 */
1737 destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1738 destp = rounddown2(destp, sizeof(void *));
1739 }
1740
1741 vectp = (char **)destp;
1742
1743 /*
1744 * Allocate room for the argv[] and env vectors including the
1745 * terminating NULL pointers.
1746 */
1747 vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1748
1749 /*
1750 * vectp also becomes our initial stack base
1751 */
1752 *stack_base = (uintptr_t)vectp;
1753
1754 stringp = imgp->args->begin_argv;
1755 argc = imgp->args->argc;
1756 envc = imgp->args->envc;
1757
1758 /*
1759 * Copy out strings - arguments and environment.
1760 */
1761 error = copyout(stringp, (void *)ustringp,
1762 ARG_MAX - imgp->args->stringspace);
1763 if (error != 0)
1764 return (error);
1765
1766 /*
1767 * Fill in "ps_strings" struct for ps, w, etc.
1768 */
1769 imgp->argv = vectp;
1770 if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1771 suword32(&arginfo->ps_nargvstr, argc) != 0)
1772 return (EFAULT);
1773
1774 /*
1775 * Fill in argument portion of vector table.
1776 */
1777 for (; argc > 0; --argc) {
1778 if (suword(vectp++, ustringp) != 0)
1779 return (EFAULT);
1780 while (*stringp++ != 0)
1781 ustringp++;
1782 ustringp++;
1783 }
1784
1785 /* a null vector table pointer separates the argp's from the envp's */
1786 if (suword(vectp++, 0) != 0)
1787 return (EFAULT);
1788
1789 imgp->envv = vectp;
1790 if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1791 suword32(&arginfo->ps_nenvstr, envc) != 0)
1792 return (EFAULT);
1793
1794 /*
1795 * Fill in environment portion of vector table.
1796 */
1797 for (; envc > 0; --envc) {
1798 if (suword(vectp++, ustringp) != 0)
1799 return (EFAULT);
1800 while (*stringp++ != 0)
1801 ustringp++;
1802 ustringp++;
1803 }
1804
1805 /* end of vector table is a null pointer */
1806 if (suword(vectp, 0) != 0)
1807 return (EFAULT);
1808
1809 if (imgp->auxargs) {
1810 vectp++;
1811 error = imgp->sysent->sv_copyout_auxargs(imgp,
1812 (uintptr_t)vectp);
1813 if (error != 0)
1814 return (error);
1815 }
1816
1817 return (0);
1818 }
1819
1820 /*
1821 * Check permissions of file to execute.
1822 * Called with imgp->vp locked.
1823 * Return 0 for success or error code on failure.
1824 */
1825 int
exec_check_permissions(struct image_params * imgp)1826 exec_check_permissions(struct image_params *imgp)
1827 {
1828 struct vnode *vp = imgp->vp;
1829 struct vattr *attr = imgp->attr;
1830 struct thread *td;
1831 int error;
1832
1833 td = curthread;
1834
1835 /* Get file attributes */
1836 error = VOP_GETATTR(vp, attr, td->td_ucred);
1837 if (error)
1838 return (error);
1839
1840 #ifdef MAC
1841 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1842 if (error)
1843 return (error);
1844 #endif
1845
1846 /*
1847 * 1) Check if file execution is disabled for the filesystem that
1848 * this file resides on.
1849 * 2) Ensure that at least one execute bit is on. Otherwise, a
1850 * privileged user will always succeed, and we don't want this
1851 * to happen unless the file really is executable.
1852 * 3) Ensure that the file is a regular file.
1853 */
1854 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1855 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1856 (attr->va_type != VREG))
1857 return (EACCES);
1858
1859 /*
1860 * Zero length files can't be exec'd
1861 */
1862 if (attr->va_size == 0)
1863 return (ENOEXEC);
1864
1865 /*
1866 * Check for execute permission to file based on current credentials.
1867 */
1868 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1869 if (error)
1870 return (error);
1871
1872 /*
1873 * Check number of open-for-writes on the file and deny execution
1874 * if there are any.
1875 *
1876 * Add a text reference now so no one can write to the
1877 * executable while we're activating it.
1878 *
1879 * Remember if this was set before and unset it in case this is not
1880 * actually an executable image.
1881 */
1882 error = VOP_SET_TEXT(vp);
1883 if (error != 0)
1884 return (error);
1885 imgp->textset = true;
1886
1887 /*
1888 * Call filesystem specific open routine (which does nothing in the
1889 * general case).
1890 */
1891 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1892 if (error == 0)
1893 imgp->opened = true;
1894 return (error);
1895 }
1896
1897 /*
1898 * Exec handler registration
1899 */
1900 int
exec_register(const struct execsw * execsw_arg)1901 exec_register(const struct execsw *execsw_arg)
1902 {
1903 const struct execsw **es, **xs, **newexecsw;
1904 u_int count = 2; /* New slot and trailing NULL */
1905
1906 if (execsw)
1907 for (es = execsw; *es; es++)
1908 count++;
1909 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1910 xs = newexecsw;
1911 if (execsw)
1912 for (es = execsw; *es; es++)
1913 *xs++ = *es;
1914 *xs++ = execsw_arg;
1915 *xs = NULL;
1916 if (execsw)
1917 free(execsw, M_TEMP);
1918 execsw = newexecsw;
1919 return (0);
1920 }
1921
1922 int
exec_unregister(const struct execsw * execsw_arg)1923 exec_unregister(const struct execsw *execsw_arg)
1924 {
1925 const struct execsw **es, **xs, **newexecsw;
1926 int count = 1;
1927
1928 if (execsw == NULL)
1929 panic("unregister with no handlers left?\n");
1930
1931 for (es = execsw; *es; es++) {
1932 if (*es == execsw_arg)
1933 break;
1934 }
1935 if (*es == NULL)
1936 return (ENOENT);
1937 for (es = execsw; *es; es++)
1938 if (*es != execsw_arg)
1939 count++;
1940 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1941 xs = newexecsw;
1942 for (es = execsw; *es; es++)
1943 if (*es != execsw_arg)
1944 *xs++ = *es;
1945 *xs = NULL;
1946 if (execsw)
1947 free(execsw, M_TEMP);
1948 execsw = newexecsw;
1949 return (0);
1950 }
1951
1952 /*
1953 * Write out a core segment to the compression stream.
1954 */
1955 static int
compress_chunk(struct coredump_params * cp,char * base,char * buf,size_t len)1956 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
1957 {
1958 size_t chunk_len;
1959 int error;
1960
1961 error = 0;
1962 while (len > 0) {
1963 chunk_len = MIN(len, CORE_BUF_SIZE);
1964
1965 /*
1966 * We can get EFAULT error here.
1967 * In that case zero out the current chunk of the segment.
1968 */
1969 error = copyin(base, buf, chunk_len);
1970 if (error != 0)
1971 bzero(buf, chunk_len);
1972 error = compressor_write(cp->comp, buf, chunk_len);
1973 if (error != 0)
1974 break;
1975 base += chunk_len;
1976 len -= chunk_len;
1977 }
1978 return (error);
1979 }
1980
1981 int
core_write(struct coredump_params * cp,const void * base,size_t len,off_t offset,enum uio_seg seg,size_t * resid)1982 core_write(struct coredump_params *cp, const void *base, size_t len,
1983 off_t offset, enum uio_seg seg, size_t *resid)
1984 {
1985
1986 return (vn_rdwr_inchunks(UIO_WRITE, cp->vp, __DECONST(void *, base),
1987 len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1988 cp->active_cred, cp->file_cred, resid, cp->td));
1989 }
1990
1991 int
core_output(char * base,size_t len,off_t offset,struct coredump_params * cp,void * tmpbuf)1992 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
1993 void *tmpbuf)
1994 {
1995 vm_map_t map;
1996 struct mount *mp;
1997 size_t resid, runlen;
1998 int error;
1999 bool success;
2000
2001 KASSERT((uintptr_t)base % PAGE_SIZE == 0,
2002 ("%s: user address %p is not page-aligned", __func__, base));
2003
2004 if (cp->comp != NULL)
2005 return (compress_chunk(cp, base, tmpbuf, len));
2006
2007 error = 0;
2008 map = &cp->td->td_proc->p_vmspace->vm_map;
2009 for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
2010 /*
2011 * Attempt to page in all virtual pages in the range. If a
2012 * virtual page is not backed by the pager, it is represented as
2013 * a hole in the file. This can occur with zero-filled
2014 * anonymous memory or truncated files, for example.
2015 */
2016 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
2017 if (core_dump_can_intr && curproc_sigkilled())
2018 return (EINTR);
2019 error = vm_fault(map, (uintptr_t)base + runlen,
2020 VM_PROT_READ, VM_FAULT_NOFILL, NULL);
2021 if (runlen == 0)
2022 success = error == KERN_SUCCESS;
2023 else if ((error == KERN_SUCCESS) != success)
2024 break;
2025 }
2026
2027 if (success) {
2028 error = core_write(cp, base, runlen, offset,
2029 UIO_USERSPACE, &resid);
2030 if (error != 0) {
2031 if (error != EFAULT)
2032 break;
2033
2034 /*
2035 * EFAULT may be returned if the user mapping
2036 * could not be accessed, e.g., because a mapped
2037 * file has been truncated. Skip the page if no
2038 * progress was made, to protect against a
2039 * hypothetical scenario where vm_fault() was
2040 * successful but core_write() returns EFAULT
2041 * anyway.
2042 */
2043 runlen -= resid;
2044 if (runlen == 0) {
2045 success = false;
2046 runlen = PAGE_SIZE;
2047 }
2048 }
2049 }
2050 if (!success) {
2051 error = vn_start_write(cp->vp, &mp, V_WAIT);
2052 if (error != 0)
2053 break;
2054 vn_lock(cp->vp, LK_EXCLUSIVE | LK_RETRY);
2055 error = vn_truncate_locked(cp->vp, offset + runlen,
2056 false, cp->td->td_ucred);
2057 VOP_UNLOCK(cp->vp);
2058 vn_finished_write(mp);
2059 if (error != 0)
2060 break;
2061 }
2062 }
2063 return (error);
2064 }
2065
2066 /*
2067 * Drain into a core file.
2068 */
2069 int
sbuf_drain_core_output(void * arg,const char * data,int len)2070 sbuf_drain_core_output(void *arg, const char *data, int len)
2071 {
2072 struct coredump_params *cp;
2073 struct proc *p;
2074 int error, locked;
2075
2076 cp = arg;
2077 p = cp->td->td_proc;
2078
2079 /*
2080 * Some kern_proc out routines that print to this sbuf may
2081 * call us with the process lock held. Draining with the
2082 * non-sleepable lock held is unsafe. The lock is needed for
2083 * those routines when dumping a live process. In our case we
2084 * can safely release the lock before draining and acquire
2085 * again after.
2086 */
2087 locked = PROC_LOCKED(p);
2088 if (locked)
2089 PROC_UNLOCK(p);
2090 if (cp->comp != NULL)
2091 error = compressor_write(cp->comp, __DECONST(char *, data),
2092 len);
2093 else
2094 error = core_write(cp, __DECONST(void *, data), len, cp->offset,
2095 UIO_SYSSPACE, NULL);
2096 if (locked)
2097 PROC_LOCK(p);
2098 if (error != 0)
2099 return (-error);
2100 cp->offset += len;
2101 return (len);
2102 }
2103