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