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/ucoredump.h> 74 #include <sys/umtxvar.h> 75 #include <sys/vnode.h> 76 #include <sys/wait.h> 77 #ifdef KTRACE 78 #include <sys/ktrace.h> 79 #endif 80 81 #include <vm/vm.h> 82 #include <vm/vm_param.h> 83 #include <vm/pmap.h> 84 #include <vm/vm_page.h> 85 #include <vm/vm_map.h> 86 #include <vm/vm_kern.h> 87 #include <vm/vm_extern.h> 88 #include <vm/vm_object.h> 89 #include <vm/vm_pager.h> 90 91 #ifdef HWPMC_HOOKS 92 #include <sys/pmckern.h> 93 #endif 94 95 #ifdef HWT_HOOKS 96 #include <dev/hwt/hwt_hook.h> 97 #endif 98 99 #include <security/audit/audit.h> 100 #include <security/mac/mac_framework.h> 101 102 #ifdef KDTRACE_HOOKS 103 #include <sys/dtrace_bsd.h> 104 dtrace_execexit_func_t dtrace_fasttrap_exec; 105 #endif 106 107 SDT_PROVIDER_DECLARE(proc); 108 SDT_PROBE_DEFINE1(proc, , , exec, "char *"); 109 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int"); 110 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *"); 111 112 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments"); 113 114 int coredump_pack_fileinfo = 1; 115 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN, 116 &coredump_pack_fileinfo, 0, 117 "Enable file path packing in 'procstat -f' coredump notes"); 118 119 int coredump_pack_vmmapinfo = 1; 120 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN, 121 &coredump_pack_vmmapinfo, 0, 122 "Enable file path packing in 'procstat -v' coredump notes"); 123 124 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS); 125 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS); 126 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS); 127 static int do_execve(struct thread *td, struct image_args *args, 128 struct mac *mac_p, struct vmspace *oldvmspace); 129 130 /* XXX This should be vm_size_t. */ 131 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD| 132 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_ps_strings, "LU", 133 "Location of process' ps_strings structure"); 134 135 /* XXX This should be vm_size_t. */ 136 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD| 137 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_usrstack, "LU", 138 "Top of process stack"); 139 140 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_MPSAFE, 141 NULL, 0, sysctl_kern_stackprot, "I", 142 "Stack memory permissions"); 143 144 u_long ps_arg_cache_limit = PAGE_SIZE / 16; 145 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 146 &ps_arg_cache_limit, 0, 147 "Process' command line characters cache limit"); 148 149 static int disallow_high_osrel; 150 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW, 151 &disallow_high_osrel, 0, 152 "Disallow execution of binaries built for higher version of the world"); 153 154 static int map_at_zero = 0; 155 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0, 156 "Permit processes to map an object at virtual address 0."); 157 158 static int core_dump_can_intr = 1; 159 SYSCTL_INT(_kern, OID_AUTO, core_dump_can_intr, CTLFLAG_RWTUN, 160 &core_dump_can_intr, 0, 161 "Core dumping interruptible with SIGKILL"); 162 163 static int 164 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS) 165 { 166 struct proc *p; 167 vm_offset_t ps_strings; 168 169 p = curproc; 170 #ifdef SCTL_MASK32 171 if (req->flags & SCTL_MASK32) { 172 unsigned int val; 173 val = (unsigned int)PROC_PS_STRINGS(p); 174 return (SYSCTL_OUT(req, &val, sizeof(val))); 175 } 176 #endif 177 ps_strings = PROC_PS_STRINGS(p); 178 return (SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings))); 179 } 180 181 static int 182 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS) 183 { 184 struct proc *p; 185 vm_offset_t val; 186 187 p = curproc; 188 #ifdef SCTL_MASK32 189 if (req->flags & SCTL_MASK32) { 190 unsigned int val32; 191 192 val32 = round_page((unsigned int)p->p_vmspace->vm_stacktop); 193 return (SYSCTL_OUT(req, &val32, sizeof(val32))); 194 } 195 #endif 196 val = round_page(p->p_vmspace->vm_stacktop); 197 return (SYSCTL_OUT(req, &val, sizeof(val))); 198 } 199 200 static int 201 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS) 202 { 203 struct proc *p; 204 205 p = curproc; 206 return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot, 207 sizeof(p->p_sysent->sv_stackprot))); 208 } 209 210 /* 211 * Each of the items is a pointer to a `const struct execsw', hence the 212 * double pointer here. 213 */ 214 static const struct execsw **execsw; 215 216 #ifndef _SYS_SYSPROTO_H_ 217 struct execve_args { 218 char *fname; 219 char **argv; 220 char **envv; 221 }; 222 #endif 223 224 int 225 sys_execve(struct thread *td, struct execve_args *uap) 226 { 227 struct image_args args; 228 struct vmspace *oldvmspace; 229 int error; 230 231 error = pre_execve(td, &oldvmspace); 232 if (error != 0) 233 return (error); 234 error = exec_copyin_args(&args, uap->fname, uap->argv, uap->envv); 235 if (error == 0) 236 error = kern_execve(td, &args, NULL, oldvmspace); 237 post_execve(td, error, oldvmspace); 238 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td); 239 return (error); 240 } 241 242 #ifndef _SYS_SYSPROTO_H_ 243 struct fexecve_args { 244 int fd; 245 char **argv; 246 char **envv; 247 }; 248 #endif 249 int 250 sys_fexecve(struct thread *td, struct fexecve_args *uap) 251 { 252 struct image_args args; 253 struct vmspace *oldvmspace; 254 int error; 255 256 error = pre_execve(td, &oldvmspace); 257 if (error != 0) 258 return (error); 259 error = exec_copyin_args(&args, NULL, uap->argv, uap->envv); 260 if (error == 0) { 261 args.fd = uap->fd; 262 error = kern_execve(td, &args, NULL, oldvmspace); 263 } 264 post_execve(td, error, oldvmspace); 265 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td); 266 return (error); 267 } 268 269 #ifndef _SYS_SYSPROTO_H_ 270 struct __mac_execve_args { 271 char *fname; 272 char **argv; 273 char **envv; 274 struct mac *mac_p; 275 }; 276 #endif 277 278 int 279 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap) 280 { 281 #ifdef MAC 282 struct image_args args; 283 struct vmspace *oldvmspace; 284 int error; 285 286 error = pre_execve(td, &oldvmspace); 287 if (error != 0) 288 return (error); 289 error = exec_copyin_args(&args, uap->fname, uap->argv, uap->envv); 290 if (error == 0) 291 error = kern_execve(td, &args, uap->mac_p, oldvmspace); 292 post_execve(td, error, oldvmspace); 293 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td); 294 return (error); 295 #else 296 return (ENOSYS); 297 #endif 298 } 299 300 int 301 pre_execve(struct thread *td, struct vmspace **oldvmspace) 302 { 303 struct proc *p; 304 int error; 305 306 KASSERT(td == curthread, ("non-current thread %p", td)); 307 error = 0; 308 p = td->td_proc; 309 if ((p->p_flag & P_HADTHREADS) != 0) { 310 PROC_LOCK(p); 311 if (thread_single(p, SINGLE_BOUNDARY) != 0) 312 error = ERESTART; 313 PROC_UNLOCK(p); 314 } 315 KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0, 316 ("nested execve")); 317 *oldvmspace = p->p_vmspace; 318 return (error); 319 } 320 321 void 322 post_execve(struct thread *td, int error, struct vmspace *oldvmspace) 323 { 324 struct proc *p; 325 326 KASSERT(td == curthread, ("non-current thread %p", td)); 327 p = td->td_proc; 328 if ((p->p_flag & P_HADTHREADS) != 0) { 329 PROC_LOCK(p); 330 /* 331 * If success, we upgrade to SINGLE_EXIT state to 332 * force other threads to suicide. 333 */ 334 if (error == EJUSTRETURN) 335 thread_single(p, SINGLE_EXIT); 336 else 337 thread_single_end(p, SINGLE_BOUNDARY); 338 PROC_UNLOCK(p); 339 } 340 exec_cleanup(td, oldvmspace); 341 } 342 343 /* 344 * kern_execve() has the astonishing property of not always returning 345 * to the caller. If sufficiently bad things happen during the call 346 * to do_execve(), it can end up calling exit2(). Callers must avoid 347 * doing anything which they might need to undo (e.g., allocating 348 * memory), unless called from the ptrace(PT_SC_REMOTERQ) handler. 349 */ 350 int 351 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p, 352 struct vmspace *oldvmspace) 353 { 354 355 TSEXEC(td->td_proc->p_pid, args->begin_argv); 356 AUDIT_ARG_ARGV(args->begin_argv, args->argc, 357 exec_args_get_begin_envv(args) - args->begin_argv); 358 AUDIT_ARG_ENVV(exec_args_get_begin_envv(args), args->envc, 359 args->endp - exec_args_get_begin_envv(args)); 360 #ifdef KTRACE 361 if (KTRPOINT(td, KTR_ARGS)) { 362 ktrdata(KTR_ARGS, args->begin_argv, 363 exec_args_get_begin_envv(args) - args->begin_argv); 364 } 365 if (KTRPOINT(td, KTR_ENVS)) { 366 ktrdata(KTR_ENVS, exec_args_get_begin_envv(args), 367 args->endp - exec_args_get_begin_envv(args)); 368 } 369 #endif 370 /* Must have at least one argument. */ 371 if (args->argc == 0) { 372 exec_free_args(args); 373 return (EINVAL); 374 } 375 return (do_execve(td, args, mac_p, oldvmspace)); 376 } 377 378 static void 379 execve_nosetid(struct image_params *imgp) 380 { 381 imgp->credential_setid = false; 382 if (imgp->newcred != NULL) { 383 crfree(imgp->newcred); 384 imgp->newcred = NULL; 385 } 386 } 387 388 /* 389 * In-kernel implementation of execve(). All arguments are assumed to be 390 * userspace pointers from the passed thread. 391 */ 392 static int 393 do_execve(struct thread *td, struct image_args *args, struct mac *mac_p, 394 struct vmspace *oldvmspace) 395 { 396 struct proc *p = td->td_proc; 397 struct nameidata nd; 398 struct ucred *oldcred; 399 struct uidinfo *euip = NULL; 400 uintptr_t stack_base; 401 struct image_params image_params, *imgp; 402 struct vattr attr; 403 struct pargs *oldargs = NULL, *newargs = NULL; 404 struct sigacts *oldsigacts = NULL, *newsigacts = NULL; 405 #ifdef KTRACE 406 struct ktr_io_params *kiop; 407 #endif 408 struct vnode *oldtextvp, *newtextvp; 409 struct vnode *oldtextdvp, *newtextdvp; 410 char *oldbinname, *newbinname; 411 bool credential_changing; 412 #ifdef MAC 413 struct label *interpvplabel = NULL; 414 bool will_transition; 415 #endif 416 #ifdef HWPMC_HOOKS 417 struct pmckern_procexec pe; 418 #endif 419 int error, i, orig_osrel; 420 uint32_t orig_fctl0; 421 const Elf_Brandinfo *orig_brandinfo; 422 size_t freepath_size; 423 static const char fexecv_proc_title[] = "(fexecv)"; 424 425 imgp = &image_params; 426 oldtextvp = oldtextdvp = NULL; 427 newtextvp = newtextdvp = NULL; 428 newbinname = oldbinname = NULL; 429 #ifdef KTRACE 430 kiop = NULL; 431 #endif 432 433 /* 434 * Lock the process and set the P_INEXEC flag to indicate that 435 * it should be left alone until we're done here. This is 436 * necessary to avoid race conditions - e.g. in ptrace() - 437 * that might allow a local user to illicitly obtain elevated 438 * privileges. 439 */ 440 PROC_LOCK(p); 441 KASSERT((p->p_flag & P_INEXEC) == 0, 442 ("%s(): process already has P_INEXEC flag", __func__)); 443 p->p_flag |= P_INEXEC; 444 PROC_UNLOCK(p); 445 446 /* 447 * Initialize part of the common data 448 */ 449 bzero(imgp, sizeof(*imgp)); 450 imgp->proc = p; 451 imgp->td = td; 452 imgp->attr = &attr; 453 imgp->args = args; 454 oldcred = p->p_ucred; 455 orig_osrel = p->p_osrel; 456 orig_fctl0 = p->p_fctl0; 457 orig_brandinfo = p->p_elf_brandinfo; 458 459 #ifdef MAC 460 error = mac_execve_enter(imgp, mac_p); 461 if (error) 462 goto exec_fail; 463 #endif 464 465 SDT_PROBE1(proc, , , exec, args->fname); 466 467 interpret: 468 if (args->fname != NULL) { 469 #ifdef CAPABILITY_MODE 470 if (CAP_TRACING(td)) 471 ktrcapfail(CAPFAIL_NAMEI, args->fname); 472 /* 473 * While capability mode can't reach this point via direct 474 * path arguments to execve(), we also don't allow 475 * interpreters to be used in capability mode (for now). 476 * Catch indirect lookups and return a permissions error. 477 */ 478 if (IN_CAPABILITY_MODE(td)) { 479 error = ECAPMODE; 480 goto exec_fail; 481 } 482 #endif 483 484 /* 485 * Translate the file name. namei() returns a vnode 486 * pointer in ni_vp among other things. 487 */ 488 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW | 489 AUDITVNODE1 | WANTPARENT, UIO_SYSSPACE, 490 args->fname); 491 492 error = namei(&nd); 493 if (error) 494 goto exec_fail; 495 496 newtextvp = nd.ni_vp; 497 newtextdvp = nd.ni_dvp; 498 nd.ni_dvp = NULL; 499 newbinname = malloc(nd.ni_cnd.cn_namelen + 1, M_PARGS, 500 M_WAITOK); 501 memcpy(newbinname, nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen); 502 newbinname[nd.ni_cnd.cn_namelen] = '\0'; 503 imgp->vp = newtextvp; 504 505 /* 506 * Do the best to calculate the full path to the image file. 507 */ 508 if (args->fname[0] == '/') { 509 imgp->execpath = args->fname; 510 } else { 511 VOP_UNLOCK(imgp->vp); 512 freepath_size = MAXPATHLEN; 513 if (vn_fullpath_hardlink(newtextvp, newtextdvp, 514 newbinname, nd.ni_cnd.cn_namelen, &imgp->execpath, 515 &imgp->freepath, &freepath_size) != 0) 516 imgp->execpath = args->fname; 517 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 518 } 519 } else if (imgp->interpreter_vp) { 520 /* 521 * An image activator has already provided an open vnode 522 */ 523 newtextvp = imgp->interpreter_vp; 524 imgp->interpreter_vp = NULL; 525 if (vn_fullpath(newtextvp, &imgp->execpath, 526 &imgp->freepath) != 0) 527 imgp->execpath = args->fname; 528 vn_lock(newtextvp, LK_SHARED | LK_RETRY); 529 AUDIT_ARG_VNODE1(newtextvp); 530 imgp->vp = newtextvp; 531 } else { 532 AUDIT_ARG_FD(args->fd); 533 534 /* 535 * If the descriptors was not opened with O_PATH, then 536 * we require that it was opened with O_EXEC or 537 * O_RDONLY. In either case, exec_check_permissions() 538 * below checks _current_ file access mode regardless 539 * of the permissions additionally checked at the 540 * open(2). 541 */ 542 error = fgetvp_exec(td, args->fd, &cap_fexecve_rights, 543 &newtextvp); 544 if (error != 0) 545 goto exec_fail; 546 547 if (vn_fullpath(newtextvp, &imgp->execpath, 548 &imgp->freepath) != 0) 549 imgp->execpath = args->fname; 550 vn_lock(newtextvp, LK_SHARED | LK_RETRY); 551 AUDIT_ARG_VNODE1(newtextvp); 552 imgp->vp = newtextvp; 553 } 554 555 /* 556 * Check file permissions. Also 'opens' file and sets its vnode to 557 * text mode. 558 */ 559 error = exec_check_permissions(imgp); 560 if (error) 561 goto exec_fail_dealloc; 562 563 imgp->object = imgp->vp->v_object; 564 if (imgp->object != NULL) 565 vm_object_reference(imgp->object); 566 567 error = exec_map_first_page(imgp); 568 if (error) 569 goto exec_fail_dealloc; 570 571 imgp->proc->p_osrel = 0; 572 imgp->proc->p_fctl0 = 0; 573 imgp->proc->p_elf_brandinfo = NULL; 574 575 /* 576 * Implement image setuid/setgid. 577 * 578 * Determine new credentials before attempting image activators 579 * so that it can be used by process_exec handlers to determine 580 * credential/setid changes. 581 * 582 * Don't honor setuid/setgid if the filesystem prohibits it or if 583 * the process is being traced. 584 * 585 * We disable setuid/setgid/etc in capability mode on the basis 586 * that most setugid applications are not written with that 587 * environment in mind, and will therefore almost certainly operate 588 * incorrectly. In principle there's no reason that setugid 589 * applications might not be useful in capability mode, so we may want 590 * to reconsider this conservative design choice in the future. 591 * 592 * XXXMAC: For the time being, use NOSUID to also prohibit 593 * transitions on the file system. 594 */ 595 credential_changing = false; 596 credential_changing |= (attr.va_mode & S_ISUID) && 597 oldcred->cr_uid != attr.va_uid; 598 credential_changing |= (attr.va_mode & S_ISGID) && 599 oldcred->cr_gid != attr.va_gid; 600 #ifdef MAC 601 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp, 602 interpvplabel, imgp) != 0; 603 credential_changing |= will_transition; 604 #endif 605 606 /* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */ 607 if (credential_changing) 608 imgp->proc->p_pdeathsig = 0; 609 610 if (credential_changing && 611 #ifdef CAPABILITY_MODE 612 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) && 613 #endif 614 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 && 615 (p->p_flag & P_TRACED) == 0) { 616 imgp->credential_setid = true; 617 VOP_UNLOCK(imgp->vp); 618 imgp->newcred = crdup(oldcred); 619 if (attr.va_mode & S_ISUID) { 620 euip = uifind(attr.va_uid); 621 change_euid(imgp->newcred, euip); 622 } 623 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 624 if (attr.va_mode & S_ISGID) 625 change_egid(imgp->newcred, attr.va_gid); 626 /* 627 * Implement correct POSIX saved-id behavior. 628 * 629 * XXXMAC: Note that the current logic will save the 630 * uid and gid if a MAC domain transition occurs, even 631 * though maybe it shouldn't. 632 */ 633 change_svuid(imgp->newcred, imgp->newcred->cr_uid); 634 change_svgid(imgp->newcred, imgp->newcred->cr_gid); 635 } else { 636 /* 637 * Implement correct POSIX saved-id behavior. 638 * 639 * XXX: It's not clear that the existing behavior is 640 * POSIX-compliant. A number of sources indicate that the 641 * saved uid/gid should only be updated if the new ruid is 642 * not equal to the old ruid, or the new euid is not equal 643 * to the old euid and the new euid is not equal to the old 644 * ruid. The FreeBSD code always updates the saved uid/gid. 645 * Also, this code uses the new (replaced) euid and egid as 646 * the source, which may or may not be the right ones to use. 647 */ 648 if (oldcred->cr_svuid != oldcred->cr_uid || 649 oldcred->cr_svgid != oldcred->cr_gid) { 650 VOP_UNLOCK(imgp->vp); 651 imgp->newcred = crdup(oldcred); 652 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 653 change_svuid(imgp->newcred, imgp->newcred->cr_uid); 654 change_svgid(imgp->newcred, imgp->newcred->cr_gid); 655 } 656 } 657 /* The new credentials are installed into the process later. */ 658 659 /* 660 * Loop through the list of image activators, calling each one. 661 * An activator returns -1 if there is no match, 0 on success, 662 * and an error otherwise. 663 */ 664 error = -1; 665 for (i = 0; error == -1 && execsw[i]; ++i) { 666 if (execsw[i]->ex_imgact == NULL) 667 continue; 668 error = (*execsw[i]->ex_imgact)(imgp); 669 } 670 671 if (error) { 672 if (error == -1) 673 error = ENOEXEC; 674 goto exec_fail_dealloc; 675 } 676 677 /* 678 * Special interpreter operation, cleanup and loop up to try to 679 * activate the interpreter. 680 */ 681 if (imgp->interpreted) { 682 exec_unmap_first_page(imgp); 683 /* 684 * The text reference needs to be removed for scripts. 685 * There is a short period before we determine that 686 * something is a script where text reference is active. 687 * The vnode lock is held over this entire period 688 * so nothing should illegitimately be blocked. 689 */ 690 MPASS(imgp->textset); 691 VOP_UNSET_TEXT_CHECKED(newtextvp); 692 imgp->textset = false; 693 /* free name buffer and old vnode */ 694 #ifdef MAC 695 mac_execve_interpreter_enter(newtextvp, &interpvplabel); 696 #endif 697 if (imgp->opened) { 698 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td); 699 imgp->opened = false; 700 } 701 vput(newtextvp); 702 imgp->vp = newtextvp = NULL; 703 if (args->fname != NULL) { 704 if (newtextdvp != NULL) { 705 vrele(newtextdvp); 706 newtextdvp = NULL; 707 } 708 NDFREE_PNBUF(&nd); 709 free(newbinname, M_PARGS); 710 newbinname = NULL; 711 } 712 vm_object_deallocate(imgp->object); 713 imgp->object = NULL; 714 execve_nosetid(imgp); 715 imgp->execpath = NULL; 716 free(imgp->freepath, M_TEMP); 717 imgp->freepath = NULL; 718 /* set new name to that of the interpreter */ 719 if (imgp->interpreter_vp) { 720 args->fname = NULL; 721 } else { 722 args->fname = imgp->interpreter_name; 723 } 724 goto interpret; 725 } 726 727 /* 728 * NB: We unlock the vnode here because it is believed that none 729 * of the sv_copyout_strings/sv_fixup operations require the vnode. 730 */ 731 VOP_UNLOCK(imgp->vp); 732 733 if (disallow_high_osrel && 734 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) { 735 error = ENOEXEC; 736 uprintf("Osrel %d for image %s too high\n", p->p_osrel, 737 imgp->execpath != NULL ? imgp->execpath : "<unresolved>"); 738 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 739 goto exec_fail_dealloc; 740 } 741 742 /* 743 * Copy out strings (args and env) and initialize stack base. 744 */ 745 error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base); 746 if (error != 0) { 747 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 748 goto exec_fail_dealloc; 749 } 750 751 /* 752 * Stack setup. 753 */ 754 error = (*p->p_sysent->sv_fixup)(&stack_base, imgp); 755 if (error != 0) { 756 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 757 goto exec_fail_dealloc; 758 } 759 760 /* 761 * For security and other reasons, the file descriptor table cannot be 762 * shared after an exec. 763 */ 764 fdunshare(td); 765 pdunshare(td); 766 /* close files on exec */ 767 fdcloseexec(td); 768 769 /* 770 * Malloc things before we need locks. 771 */ 772 i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv; 773 /* Cache arguments if they fit inside our allowance */ 774 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) { 775 newargs = pargs_alloc(i); 776 bcopy(imgp->args->begin_argv, newargs->ar_args, i); 777 } 778 779 /* 780 * For security and other reasons, signal handlers cannot 781 * be shared after an exec. The new process gets a copy of the old 782 * handlers. In execsigs(), the new process will have its signals 783 * reset. 784 */ 785 if (sigacts_shared(p->p_sigacts)) { 786 oldsigacts = p->p_sigacts; 787 newsigacts = sigacts_alloc(); 788 sigacts_copy(newsigacts, oldsigacts); 789 } 790 791 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 792 793 PROC_LOCK(p); 794 if (oldsigacts) 795 p->p_sigacts = newsigacts; 796 /* Stop profiling */ 797 stopprofclock(p); 798 799 /* reset caught signals */ 800 execsigs(p); 801 802 /* name this process - nameiexec(p, ndp) */ 803 bzero(p->p_comm, sizeof(p->p_comm)); 804 if (args->fname) 805 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm, 806 min(nd.ni_cnd.cn_namelen, MAXCOMLEN)); 807 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0) 808 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title)); 809 bcopy(p->p_comm, td->td_name, sizeof(td->td_name)); 810 #ifdef KTR 811 sched_clear_tdname(td); 812 #endif 813 814 /* 815 * mark as execed, wakeup the process that vforked (if any) and tell 816 * it that it now has its own resources back 817 */ 818 p->p_flag |= P_EXEC; 819 td->td_pflags2 &= ~TDP2_UEXTERR; 820 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0) 821 p->p_flag2 &= ~P2_NOTRACE; 822 if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0) 823 p->p_flag2 &= ~P2_STKGAP_DISABLE; 824 p->p_flag2 &= ~(P2_MEMBAR_PRIVE | P2_MEMBAR_PRIVE_SYNCORE | 825 P2_MEMBAR_GLOBE); 826 if (p->p_flag & P_PPWAIT) { 827 p->p_flag &= ~(P_PPWAIT | P_PPTRACE); 828 cv_broadcast(&p->p_pwait); 829 /* STOPs are no longer ignored, arrange for AST */ 830 signotify(td); 831 } 832 833 if ((imgp->sysent->sv_setid_allowed != NULL && 834 !(*imgp->sysent->sv_setid_allowed)(td, imgp)) || 835 (p->p_flag2 & P2_NO_NEW_PRIVS) != 0) 836 execve_nosetid(imgp); 837 838 /* 839 * Implement image setuid/setgid installation. 840 */ 841 if (imgp->credential_setid) { 842 /* 843 * Turn off syscall tracing for set-id programs, except for 844 * root. Record any set-id flags first to make sure that 845 * we do not regain any tracing during a possible block. 846 */ 847 setsugid(p); 848 #ifdef KTRACE 849 kiop = ktrprocexec(p); 850 #endif 851 /* 852 * Close any file descriptors 0..2 that reference procfs, 853 * then make sure file descriptors 0..2 are in use. 854 * 855 * Both fdsetugidsafety() and fdcheckstd() may call functions 856 * taking sleepable locks, so temporarily drop our locks. 857 */ 858 PROC_UNLOCK(p); 859 VOP_UNLOCK(imgp->vp); 860 fdsetugidsafety(td); 861 error = fdcheckstd(td); 862 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 863 if (error != 0) 864 goto exec_fail_dealloc; 865 PROC_LOCK(p); 866 #ifdef MAC 867 if (will_transition) { 868 mac_vnode_execve_transition(oldcred, imgp->newcred, 869 imgp->vp, interpvplabel, imgp); 870 } 871 #endif 872 } else { 873 if (oldcred->cr_uid == oldcred->cr_ruid && 874 oldcred->cr_gid == oldcred->cr_rgid) 875 p->p_flag &= ~P_SUGID; 876 } 877 /* 878 * Set the new credentials. 879 */ 880 if (imgp->newcred != NULL) { 881 proc_set_cred(p, imgp->newcred); 882 crfree(oldcred); 883 oldcred = NULL; 884 } 885 886 /* 887 * Store the vp for use in kern.proc.pathname. This vnode was 888 * referenced by namei() or by fexecve variant of fname handling. 889 */ 890 oldtextvp = p->p_textvp; 891 p->p_textvp = newtextvp; 892 oldtextdvp = p->p_textdvp; 893 p->p_textdvp = newtextdvp; 894 newtextdvp = NULL; 895 oldbinname = p->p_binname; 896 p->p_binname = newbinname; 897 newbinname = NULL; 898 899 #ifdef KDTRACE_HOOKS 900 /* 901 * Tell the DTrace fasttrap provider about the exec if it 902 * has declared an interest. 903 */ 904 if (dtrace_fasttrap_exec) 905 dtrace_fasttrap_exec(p); 906 #endif 907 908 /* 909 * Notify others that we exec'd, and clear the P_INEXEC flag 910 * as we're now a bona fide freshly-execed process. 911 */ 912 KNOTE_LOCKED(p->p_klist, NOTE_EXEC); 913 p->p_flag &= ~P_INEXEC; 914 915 /* clear "fork but no exec" flag, as we _are_ execing */ 916 p->p_acflag &= ~AFORK; 917 918 /* 919 * Free any previous argument cache and replace it with 920 * the new argument cache, if any. 921 */ 922 oldargs = p->p_args; 923 p->p_args = newargs; 924 newargs = NULL; 925 926 PROC_UNLOCK(p); 927 928 #ifdef HWPMC_HOOKS 929 /* 930 * Check if system-wide sampling is in effect or if the 931 * current process is using PMCs. If so, do exec() time 932 * processing. This processing needs to happen AFTER the 933 * P_INEXEC flag is cleared. 934 */ 935 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) { 936 VOP_UNLOCK(imgp->vp); 937 pe.pm_credentialschanged = credential_changing; 938 pe.pm_baseaddr = imgp->reloc_base; 939 pe.pm_dynaddr = imgp->et_dyn_addr; 940 941 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe); 942 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 943 } 944 #endif 945 946 #ifdef HWT_HOOKS 947 if ((td->td_proc->p_flag2 & P2_HWT) != 0) { 948 struct hwt_record_entry ent; 949 950 VOP_UNLOCK(imgp->vp); 951 ent.fullpath = imgp->execpath; 952 ent.addr = imgp->et_dyn_addr; 953 ent.baseaddr = imgp->reloc_base; 954 ent.record_type = HWT_RECORD_EXECUTABLE; 955 HWT_CALL_HOOK(td, HWT_EXEC, &ent); 956 vn_lock(imgp->vp, LK_SHARED | LK_RETRY); 957 } 958 #endif 959 960 /* Set values passed into the program in registers. */ 961 (*p->p_sysent->sv_setregs)(td, imgp, stack_base); 962 963 VOP_MMAPPED(imgp->vp); 964 965 SDT_PROBE1(proc, , , exec__success, args->fname); 966 967 exec_fail_dealloc: 968 if (error != 0) { 969 p->p_osrel = orig_osrel; 970 p->p_fctl0 = orig_fctl0; 971 p->p_elf_brandinfo = orig_brandinfo; 972 } 973 974 if (imgp->firstpage != NULL) 975 exec_unmap_first_page(imgp); 976 977 if (imgp->vp != NULL) { 978 if (imgp->opened) 979 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td); 980 if (imgp->textset) 981 VOP_UNSET_TEXT_CHECKED(imgp->vp); 982 if (error != 0) 983 vput(imgp->vp); 984 else 985 VOP_UNLOCK(imgp->vp); 986 if (args->fname != NULL) 987 NDFREE_PNBUF(&nd); 988 if (newtextdvp != NULL) 989 vrele(newtextdvp); 990 free(newbinname, M_PARGS); 991 } 992 993 if (imgp->object != NULL) 994 vm_object_deallocate(imgp->object); 995 996 free(imgp->freepath, M_TEMP); 997 998 if (error == 0) { 999 if (p->p_ptevents & PTRACE_EXEC) { 1000 PROC_LOCK(p); 1001 if (p->p_ptevents & PTRACE_EXEC) 1002 td->td_dbgflags |= TDB_EXEC; 1003 PROC_UNLOCK(p); 1004 } 1005 } else { 1006 exec_fail: 1007 /* we're done here, clear P_INEXEC */ 1008 PROC_LOCK(p); 1009 p->p_flag &= ~P_INEXEC; 1010 PROC_UNLOCK(p); 1011 1012 SDT_PROBE1(proc, , , exec__failure, error); 1013 } 1014 1015 if (imgp->newcred != NULL && oldcred != NULL) 1016 crfree(imgp->newcred); 1017 1018 #ifdef MAC 1019 mac_execve_exit(imgp); 1020 mac_execve_interpreter_exit(interpvplabel); 1021 #endif 1022 exec_free_args(args); 1023 1024 /* 1025 * Handle deferred decrement of ref counts. 1026 */ 1027 if (oldtextvp != NULL) 1028 vrele(oldtextvp); 1029 if (oldtextdvp != NULL) 1030 vrele(oldtextdvp); 1031 free(oldbinname, M_PARGS); 1032 #ifdef KTRACE 1033 ktr_io_params_free(kiop); 1034 #endif 1035 pargs_drop(oldargs); 1036 pargs_drop(newargs); 1037 if (oldsigacts != NULL) 1038 sigacts_free(oldsigacts); 1039 if (euip != NULL) 1040 uifree(euip); 1041 1042 if (error && imgp->vmspace_destroyed) { 1043 /* sorry, no more process anymore. exit gracefully */ 1044 exec_cleanup(td, oldvmspace); 1045 kern_exit(td, 0, SIGABRT); 1046 } 1047 1048 #ifdef KTRACE 1049 if (error == 0) 1050 ktrprocctor(p); 1051 #endif 1052 1053 /* 1054 * We don't want cpu_set_syscall_retval() to overwrite any of 1055 * the register values put in place by exec_setregs(). 1056 * Implementations of cpu_set_syscall_retval() will leave 1057 * registers unmodified when returning EJUSTRETURN. 1058 */ 1059 return (error == 0 ? EJUSTRETURN : error); 1060 } 1061 1062 void 1063 exec_cleanup(struct thread *td, struct vmspace *oldvmspace) 1064 { 1065 if ((td->td_pflags & TDP_EXECVMSPC) != 0) { 1066 KASSERT(td->td_proc->p_vmspace != oldvmspace, 1067 ("oldvmspace still used")); 1068 vmspace_free(oldvmspace); 1069 td->td_pflags &= ~TDP_EXECVMSPC; 1070 } 1071 } 1072 1073 int 1074 exec_map_first_page(struct image_params *imgp) 1075 { 1076 vm_object_t object; 1077 vm_page_t m; 1078 int error; 1079 1080 if (imgp->firstpage != NULL) 1081 exec_unmap_first_page(imgp); 1082 1083 object = imgp->vp->v_object; 1084 if (object == NULL) 1085 return (EACCES); 1086 #if VM_NRESERVLEVEL > 0 1087 if ((object->flags & OBJ_COLORED) == 0) { 1088 VM_OBJECT_WLOCK(object); 1089 vm_object_color(object, 0); 1090 VM_OBJECT_WUNLOCK(object); 1091 } 1092 #endif 1093 error = vm_page_grab_valid_unlocked(&m, object, 0, 1094 VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) | 1095 VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED); 1096 1097 if (error != VM_PAGER_OK) 1098 return (EIO); 1099 imgp->firstpage = sf_buf_alloc(m, 0); 1100 imgp->image_header = sf_buf_kva(imgp->firstpage); 1101 1102 return (0); 1103 } 1104 1105 void 1106 exec_unmap_first_page(struct image_params *imgp) 1107 { 1108 vm_page_t m; 1109 1110 if (imgp->firstpage != NULL) { 1111 m = sf_buf_page(imgp->firstpage); 1112 sf_buf_free(imgp->firstpage); 1113 imgp->firstpage = NULL; 1114 vm_page_unwire(m, PQ_ACTIVE); 1115 } 1116 } 1117 1118 void 1119 exec_onexec_old(struct thread *td) 1120 { 1121 sigfastblock_clear(td); 1122 umtx_exec(td->td_proc); 1123 } 1124 1125 /* 1126 * This is an optimization which removes the unmanaged shared page 1127 * mapping. In combination with pmap_remove_pages(), which cleans all 1128 * managed mappings in the process' vmspace pmap, no work will be left 1129 * for pmap_remove(min, max). 1130 */ 1131 void 1132 exec_free_abi_mappings(struct proc *p) 1133 { 1134 struct vmspace *vmspace; 1135 1136 vmspace = p->p_vmspace; 1137 if (refcount_load(&vmspace->vm_refcnt) != 1) 1138 return; 1139 1140 if (!PROC_HAS_SHP(p)) 1141 return; 1142 1143 pmap_remove(vmspace_pmap(vmspace), vmspace->vm_shp_base, 1144 vmspace->vm_shp_base + p->p_sysent->sv_shared_page_len); 1145 } 1146 1147 /* 1148 * Run down the current address space and install a new one. 1149 */ 1150 int 1151 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv) 1152 { 1153 int error; 1154 struct proc *p = imgp->proc; 1155 struct vmspace *vmspace = p->p_vmspace; 1156 struct thread *td = curthread; 1157 vm_offset_t sv_minuser; 1158 vm_map_t map; 1159 1160 imgp->vmspace_destroyed = true; 1161 imgp->sysent = sv; 1162 1163 if (p->p_sysent->sv_onexec_old != NULL) 1164 p->p_sysent->sv_onexec_old(td); 1165 itimers_exec(p); 1166 1167 EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp); 1168 1169 /* 1170 * Blow away entire process VM, if address space not shared, 1171 * otherwise, create a new VM space so that other threads are 1172 * not disrupted 1173 */ 1174 map = &vmspace->vm_map; 1175 if (map_at_zero) 1176 sv_minuser = sv->sv_minuser; 1177 else 1178 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE); 1179 if (refcount_load(&vmspace->vm_refcnt) == 1 && 1180 vm_map_min(map) == sv_minuser && 1181 vm_map_max(map) == sv->sv_maxuser && 1182 cpu_exec_vmspace_reuse(p, map)) { 1183 exec_free_abi_mappings(p); 1184 shmexit(vmspace); 1185 pmap_remove_pages(vmspace_pmap(vmspace)); 1186 vm_map_remove(map, vm_map_min(map), vm_map_max(map)); 1187 /* 1188 * An exec terminates mlockall(MCL_FUTURE). 1189 * ASLR and W^X states must be re-evaluated. 1190 */ 1191 vm_map_lock(map); 1192 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR | 1193 MAP_ASLR_IGNSTART | MAP_ASLR_STACK | MAP_WXORX); 1194 vm_map_unlock(map); 1195 } else { 1196 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser); 1197 if (error) 1198 return (error); 1199 vmspace = p->p_vmspace; 1200 map = &vmspace->vm_map; 1201 } 1202 map->flags |= imgp->map_flags; 1203 1204 return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0); 1205 } 1206 1207 /* 1208 * Compute the stack size limit and map the main process stack. 1209 * Map the shared page. 1210 */ 1211 int 1212 exec_map_stack(struct image_params *imgp) 1213 { 1214 struct rlimit rlim_stack; 1215 struct sysentvec *sv; 1216 struct proc *p; 1217 vm_map_t map; 1218 struct vmspace *vmspace; 1219 vm_offset_t stack_addr, stack_top; 1220 vm_offset_t sharedpage_addr; 1221 u_long ssiz; 1222 int error, find_space, stack_off; 1223 vm_prot_t stack_prot; 1224 vm_object_t obj; 1225 1226 p = imgp->proc; 1227 sv = p->p_sysent; 1228 1229 if (imgp->stack_sz != 0) { 1230 ssiz = trunc_page(imgp->stack_sz); 1231 PROC_LOCK(p); 1232 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack); 1233 PROC_UNLOCK(p); 1234 if (ssiz > rlim_stack.rlim_max) 1235 ssiz = rlim_stack.rlim_max; 1236 if (ssiz > rlim_stack.rlim_cur) { 1237 rlim_stack.rlim_cur = ssiz; 1238 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack); 1239 } 1240 } else if (sv->sv_maxssiz != NULL) { 1241 ssiz = *sv->sv_maxssiz; 1242 } else { 1243 ssiz = maxssiz; 1244 } 1245 1246 vmspace = p->p_vmspace; 1247 map = &vmspace->vm_map; 1248 1249 stack_prot = sv->sv_shared_page_obj != NULL && imgp->stack_prot != 0 ? 1250 imgp->stack_prot : sv->sv_stackprot; 1251 if ((map->flags & MAP_ASLR_STACK) != 0) { 1252 stack_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr + 1253 lim_max(curthread, RLIMIT_DATA)); 1254 find_space = VMFS_ANY_SPACE; 1255 } else { 1256 stack_addr = sv->sv_usrstack - ssiz; 1257 find_space = VMFS_NO_SPACE; 1258 } 1259 error = vm_map_find(map, NULL, 0, &stack_addr, (vm_size_t)ssiz, 1260 sv->sv_usrstack, find_space, stack_prot, VM_PROT_ALL, 1261 MAP_STACK_AREA); 1262 if (error != KERN_SUCCESS) { 1263 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x " 1264 "failed, mach error %d errno %d\n", (uintmax_t)ssiz, 1265 stack_prot, error, vm_mmap_to_errno(error)); 1266 return (vm_mmap_to_errno(error)); 1267 } 1268 1269 stack_top = stack_addr + ssiz; 1270 if ((map->flags & MAP_ASLR_STACK) != 0) { 1271 /* Randomize within the first page of the stack. */ 1272 arc4rand(&stack_off, sizeof(stack_off), 0); 1273 stack_top -= rounddown2(stack_off & PAGE_MASK, sizeof(void *)); 1274 } 1275 1276 /* Map a shared page */ 1277 obj = sv->sv_shared_page_obj; 1278 if (obj == NULL) { 1279 sharedpage_addr = 0; 1280 goto out; 1281 } 1282 1283 /* 1284 * If randomization is disabled then the shared page will 1285 * be mapped at address specified in sysentvec. 1286 * Otherwise any address above .data section can be selected. 1287 * Same logic is used for stack address randomization. 1288 * If the address randomization is applied map a guard page 1289 * at the top of UVA. 1290 */ 1291 vm_object_reference(obj); 1292 if ((imgp->imgp_flags & IMGP_ASLR_SHARED_PAGE) != 0) { 1293 sharedpage_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr + 1294 lim_max(curthread, RLIMIT_DATA)); 1295 1296 error = vm_map_fixed(map, NULL, 0, 1297 sv->sv_maxuser - PAGE_SIZE, PAGE_SIZE, 1298 VM_PROT_NONE, VM_PROT_NONE, MAP_CREATE_GUARD); 1299 if (error != KERN_SUCCESS) { 1300 /* 1301 * This is not fatal, so let's just print a warning 1302 * and continue. 1303 */ 1304 uprintf("%s: Mapping guard page at the top of UVA failed" 1305 " mach error %d errno %d", 1306 __func__, error, vm_mmap_to_errno(error)); 1307 } 1308 1309 error = vm_map_find(map, obj, 0, 1310 &sharedpage_addr, sv->sv_shared_page_len, 1311 sv->sv_maxuser, VMFS_ANY_SPACE, 1312 VM_PROT_READ | VM_PROT_EXECUTE, 1313 VM_PROT_READ | VM_PROT_EXECUTE, 1314 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE); 1315 } else { 1316 sharedpage_addr = sv->sv_shared_page_base; 1317 error = vm_map_fixed(map, obj, 0, 1318 sharedpage_addr, sv->sv_shared_page_len, 1319 VM_PROT_READ | VM_PROT_EXECUTE, 1320 VM_PROT_READ | VM_PROT_EXECUTE, 1321 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE); 1322 } 1323 if (error != KERN_SUCCESS) { 1324 uprintf("%s: mapping shared page at addr: %p" 1325 "failed, mach error %d errno %d\n", __func__, 1326 (void *)sharedpage_addr, error, vm_mmap_to_errno(error)); 1327 vm_object_deallocate(obj); 1328 return (vm_mmap_to_errno(error)); 1329 } 1330 out: 1331 /* 1332 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they 1333 * are still used to enforce the stack rlimit on the process stack. 1334 */ 1335 vmspace->vm_maxsaddr = (char *)stack_addr; 1336 vmspace->vm_stacktop = stack_top; 1337 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT; 1338 vmspace->vm_shp_base = sharedpage_addr; 1339 1340 return (0); 1341 } 1342 1343 /* 1344 * Copy out argument and environment strings from the old process address 1345 * space into the temporary string buffer. 1346 */ 1347 int 1348 exec_copyin_args(struct image_args *args, const char *fname, 1349 char **argv, char **envv) 1350 { 1351 u_long arg, env; 1352 int error; 1353 1354 bzero(args, sizeof(*args)); 1355 if (argv == NULL) 1356 return (EFAULT); 1357 1358 /* 1359 * Allocate demand-paged memory for the file name, argument, and 1360 * environment strings. 1361 */ 1362 error = exec_alloc_args(args); 1363 if (error != 0) 1364 return (error); 1365 1366 /* 1367 * Copy the file name. 1368 */ 1369 error = exec_args_add_fname(args, fname, UIO_USERSPACE); 1370 if (error != 0) 1371 goto err_exit; 1372 1373 /* 1374 * extract arguments first 1375 */ 1376 for (;;) { 1377 error = fueword(argv++, &arg); 1378 if (error == -1) { 1379 error = EFAULT; 1380 goto err_exit; 1381 } 1382 if (arg == 0) 1383 break; 1384 error = exec_args_add_arg(args, (char *)(uintptr_t)arg, 1385 UIO_USERSPACE); 1386 if (error != 0) 1387 goto err_exit; 1388 } 1389 1390 /* 1391 * extract environment strings 1392 */ 1393 if (envv) { 1394 for (;;) { 1395 error = fueword(envv++, &env); 1396 if (error == -1) { 1397 error = EFAULT; 1398 goto err_exit; 1399 } 1400 if (env == 0) 1401 break; 1402 error = exec_args_add_env(args, 1403 (char *)(uintptr_t)env, UIO_USERSPACE); 1404 if (error != 0) 1405 goto err_exit; 1406 } 1407 } 1408 1409 return (0); 1410 1411 err_exit: 1412 exec_free_args(args); 1413 return (error); 1414 } 1415 1416 struct exec_args_kva { 1417 void *addr; 1418 u_int gen; 1419 SLIST_ENTRY(exec_args_kva) next; 1420 }; 1421 1422 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva); 1423 1424 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist; 1425 static struct mtx exec_args_kva_mtx; 1426 static u_int exec_args_gen; 1427 1428 static void 1429 exec_prealloc_args_kva(void *arg __unused) 1430 { 1431 struct exec_args_kva *argkva; 1432 u_int i; 1433 1434 SLIST_INIT(&exec_args_kva_freelist); 1435 mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF); 1436 for (i = 0; i < exec_map_entries; i++) { 1437 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK); 1438 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size, 1439 ptoa(exec_map_guard_pages)); 1440 argkva->gen = exec_args_gen; 1441 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next); 1442 } 1443 } 1444 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL); 1445 1446 static void * 1447 exec_alloc_args_kva(void **cookie) 1448 { 1449 struct exec_args_kva *argkva; 1450 1451 argkva = (void *)atomic_readandclear_ptr( 1452 (uintptr_t *)DPCPU_PTR(exec_args_kva)); 1453 if (argkva == NULL) { 1454 mtx_lock(&exec_args_kva_mtx); 1455 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL) 1456 (void)mtx_sleep(&exec_args_kva_freelist, 1457 &exec_args_kva_mtx, 0, "execkva", 0); 1458 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next); 1459 mtx_unlock(&exec_args_kva_mtx); 1460 } 1461 kasan_mark(argkva->addr, exec_map_entry_size, exec_map_entry_size, 0); 1462 *(struct exec_args_kva **)cookie = argkva; 1463 return (argkva->addr); 1464 } 1465 1466 static void 1467 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen) 1468 { 1469 vm_offset_t base; 1470 1471 base = (vm_offset_t)argkva->addr; 1472 kasan_mark(argkva->addr, 0, exec_map_entry_size, 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 = 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 return ((*cp->cdw->write_fn)(cp->cdw, base, len, offset, seg, 2006 cp->active_cred, resid, cp->td)); 2007 } 2008 2009 static int 2010 core_extend(struct coredump_params *cp, off_t newsz) 2011 { 2012 return ((*cp->cdw->extend_fn)(cp->cdw, newsz, cp->active_cred)); 2013 } 2014 2015 int 2016 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp, 2017 void *tmpbuf) 2018 { 2019 vm_map_t map; 2020 size_t resid, runlen; 2021 int error; 2022 bool success; 2023 2024 KASSERT((uintptr_t)base % PAGE_SIZE == 0, 2025 ("%s: user address %p is not page-aligned", __func__, base)); 2026 2027 if (cp->comp != NULL) 2028 return (compress_chunk(cp, base, tmpbuf, len)); 2029 2030 error = 0; 2031 map = &cp->td->td_proc->p_vmspace->vm_map; 2032 for (; len > 0; base += runlen, offset += runlen, len -= runlen) { 2033 /* 2034 * Attempt to page in all virtual pages in the range. If a 2035 * virtual page is not backed by the pager, it is represented as 2036 * a hole in the file. This can occur with zero-filled 2037 * anonymous memory or truncated files, for example. 2038 */ 2039 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) { 2040 if (core_dump_can_intr && curproc_sigkilled()) 2041 return (EINTR); 2042 error = vm_fault(map, (uintptr_t)base + runlen, 2043 VM_PROT_READ, VM_FAULT_NOFILL, NULL); 2044 if (runlen == 0) 2045 success = error == KERN_SUCCESS; 2046 else if ((error == KERN_SUCCESS) != success) 2047 break; 2048 } 2049 2050 if (success) { 2051 error = core_write(cp, base, runlen, offset, 2052 UIO_USERSPACE, &resid); 2053 if (error != 0) { 2054 if (error != EFAULT) 2055 break; 2056 2057 /* 2058 * EFAULT may be returned if the user mapping 2059 * could not be accessed, e.g., because a mapped 2060 * file has been truncated. Skip the page if no 2061 * progress was made, to protect against a 2062 * hypothetical scenario where vm_fault() was 2063 * successful but core_write() returns EFAULT 2064 * anyway. 2065 */ 2066 runlen -= resid; 2067 if (runlen == 0) { 2068 success = false; 2069 runlen = PAGE_SIZE; 2070 } 2071 } 2072 } 2073 if (!success) { 2074 error = core_extend(cp, offset + runlen); 2075 if (error != 0) 2076 break; 2077 } 2078 } 2079 return (error); 2080 } 2081 2082 /* 2083 * Drain into a core file. 2084 */ 2085 int 2086 sbuf_drain_core_output(void *arg, const char *data, int len) 2087 { 2088 struct coredump_params *cp; 2089 struct proc *p; 2090 int error, locked; 2091 2092 cp = arg; 2093 p = cp->td->td_proc; 2094 2095 /* 2096 * Some kern_proc out routines that print to this sbuf may 2097 * call us with the process lock held. Draining with the 2098 * non-sleepable lock held is unsafe. The lock is needed for 2099 * those routines when dumping a live process. In our case we 2100 * can safely release the lock before draining and acquire 2101 * again after. 2102 */ 2103 locked = PROC_LOCKED(p); 2104 if (locked) 2105 PROC_UNLOCK(p); 2106 if (cp->comp != NULL) 2107 error = compressor_write(cp->comp, __DECONST(char *, data), 2108 len); 2109 else 2110 error = core_write(cp, __DECONST(void *, data), len, cp->offset, 2111 UIO_SYSSPACE, NULL); 2112 if (locked) 2113 PROC_LOCK(p); 2114 if (error != 0) 2115 return (-error); 2116 cp->offset += len; 2117 return (len); 2118 } 2119