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