1 /* $NetBSD: kern_exec.c,v 1.533 2026/06/18 20:02:20 christos Exp $ */ 2 3 /*- 4 * Copyright (c) 2008, 2019, 2020 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Andrew Doran. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /*- 33 * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou 34 * Copyright (C) 1992 Wolfgang Solfrank. 35 * Copyright (C) 1992 TooLs GmbH. 36 * All rights reserved. 37 * 38 * Redistribution and use in source and binary forms, with or without 39 * modification, are permitted provided that the following conditions 40 * are met: 41 * 1. Redistributions of source code must retain the above copyright 42 * notice, this list of conditions and the following disclaimer. 43 * 2. Redistributions in binary form must reproduce the above copyright 44 * notice, this list of conditions and the following disclaimer in the 45 * documentation and/or other materials provided with the distribution. 46 * 3. All advertising materials mentioning features or use of this software 47 * must display the following acknowledgement: 48 * This product includes software developed by TooLs GmbH. 49 * 4. The name of TooLs GmbH may not be used to endorse or promote products 50 * derived from this software without specific prior written permission. 51 * 52 * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR 53 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 54 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 55 * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 56 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 57 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 58 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 59 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 60 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 61 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 62 */ 63 64 #include <sys/cdefs.h> 65 __KERNEL_RCSID(0, "$NetBSD: kern_exec.c,v 1.533 2026/06/18 20:02:20 christos Exp $"); 66 67 #include "opt_exec.h" 68 #include "opt_execfmt.h" 69 #include "opt_ktrace.h" 70 #include "opt_modular.h" 71 #include "opt_pax.h" 72 #include "opt_syscall_debug.h" 73 #include "veriexec.h" 74 75 #include <sys/param.h> 76 #include <sys/types.h> 77 78 #include <sys/acct.h> 79 #include <sys/atomic.h> 80 #include <sys/cprng.h> 81 #include <sys/cpu.h> 82 #include <sys/exec.h> 83 #include <sys/file.h> 84 #include <sys/filedesc.h> 85 #include <sys/futex.h> 86 #include <sys/kauth.h> 87 #include <sys/kernel.h> 88 #include <sys/kmem.h> 89 #include <sys/ktrace.h> 90 #include <sys/lwpctl.h> 91 #include <sys/mman.h> 92 #include <sys/module.h> 93 #include <sys/mount.h> 94 #include <sys/namei.h> 95 #include <sys/pax.h> 96 #include <sys/proc.h> 97 #include <sys/prot.h> 98 #include <sys/ptrace.h> 99 #include <sys/ras.h> 100 #include <sys/sdt.h> 101 #include <sys/signalvar.h> 102 #include <sys/spawn.h> 103 #include <sys/stat.h> 104 #include <sys/syscall.h> 105 #include <sys/syscallargs.h> 106 #include <sys/syscallvar.h> 107 #include <sys/systm.h> 108 #include <sys/uidinfo.h> 109 #if NVERIEXEC > 0 110 #include <sys/verified_exec.h> 111 #endif /* NVERIEXEC > 0 */ 112 #include <sys/vfs_syscalls.h> 113 #include <sys/vnode.h> 114 #include <sys/wait.h> 115 116 #include <uvm/uvm_extern.h> 117 118 #include <machine/reg.h> 119 120 #include <compat/common/compat_util.h> 121 122 #ifndef MD_TOPDOWN_INIT 123 #ifdef __USE_TOPDOWN_VM 124 #define MD_TOPDOWN_INIT(epp) (epp)->ep_flags |= EXEC_TOPDOWN_VM 125 #else 126 #define MD_TOPDOWN_INIT(epp) 127 #endif 128 #endif 129 130 struct execve_data; 131 132 extern int user_va0_disable; 133 134 static size_t calcargs(struct execve_data * restrict, const size_t); 135 static size_t calcstack(struct execve_data * restrict, const size_t); 136 static int copyoutargs(struct execve_data * restrict, struct lwp *, 137 char * const); 138 static int copyoutpsstrs(struct execve_data * restrict, struct proc *); 139 static int copyinargs(struct execve_data * restrict, char * const *, 140 char * const *, execve_fetch_element_t, char **); 141 static int copyinargstrs(struct execve_data * restrict, char * const *, 142 execve_fetch_element_t, char **, size_t *, void (*)(const void *, size_t)); 143 static int exec_sigcode_map(struct proc *, const struct emul *); 144 145 #if defined(DEBUG) && !defined(DEBUG_EXEC) 146 #define DEBUG_EXEC 147 #endif 148 #ifdef DEBUG_EXEC 149 #define DPRINTF(a) printf a 150 #define COPYPRINTF(s, a, b) printf("%s, %d: copyout%s @%p %zu\n", __func__, \ 151 __LINE__, (s), (a), (b)) 152 static void dump_vmcmds(const struct exec_package * const, size_t, int); 153 #define DUMPVMCMDS(p, x, e) do { dump_vmcmds((p), (x), (e)); } while (0) 154 #else 155 #define DPRINTF(a) 156 #define COPYPRINTF(s, a, b) 157 #define DUMPVMCMDS(p, x, e) do {} while (0) 158 #endif /* DEBUG_EXEC */ 159 160 /* 161 * DTrace SDT provider definitions 162 */ 163 SDT_PROVIDER_DECLARE(proc); 164 SDT_PROBE_DEFINE1(proc, kernel, , exec, "char *"); 165 SDT_PROBE_DEFINE1(proc, kernel, , exec__success, "char *"); 166 SDT_PROBE_DEFINE1(proc, kernel, , exec__failure, "int"); 167 168 /* 169 * Exec function switch: 170 * 171 * Note that each makecmds function is responsible for loading the 172 * exec package with the necessary functions for any exec-type-specific 173 * handling. 174 * 175 * Functions for specific exec types should be defined in their own 176 * header file. 177 */ 178 static const struct execsw **execsw = NULL; 179 static int nexecs; 180 181 u_int exec_maxhdrsz; /* must not be static - used by netbsd32 */ 182 183 /* list of dynamically loaded execsw entries */ 184 static LIST_HEAD(execlist_head, exec_entry) ex_head = 185 LIST_HEAD_INITIALIZER(ex_head); 186 struct exec_entry { 187 LIST_ENTRY(exec_entry) ex_list; 188 SLIST_ENTRY(exec_entry) ex_slist; 189 const struct execsw *ex_sw; 190 }; 191 192 #ifndef __HAVE_SYSCALL_INTERN 193 void syscall(void); 194 #endif 195 196 /* NetBSD autoloadable syscalls */ 197 #ifdef MODULAR 198 #include <kern/syscalls_autoload.c> 199 #endif 200 201 /* NetBSD emul struct */ 202 struct emul emul_netbsd = { 203 .e_name = "netbsd", 204 #ifdef EMUL_NATIVEROOT 205 .e_path = EMUL_NATIVEROOT, 206 #else 207 .e_path = NULL, 208 #endif 209 #ifndef __HAVE_MINIMAL_EMUL 210 .e_flags = EMUL_HAS_SYS___syscall, 211 .e_errno = NULL, 212 .e_nosys = SYS_syscall, 213 .e_nsysent = SYS_NSYSENT, 214 #endif 215 #ifdef MODULAR 216 .e_sc_autoload = netbsd_syscalls_autoload, 217 #endif 218 .e_sysent = sysent, 219 .e_nomodbits = sysent_nomodbits, 220 #ifdef SYSCALL_DEBUG 221 .e_syscallnames = syscallnames, 222 #else 223 .e_syscallnames = NULL, 224 #endif 225 .e_sendsig = sendsig, 226 .e_trapsignal = trapsignal, 227 .e_sigcode = NULL, 228 .e_esigcode = NULL, 229 .e_sigobject = NULL, 230 .e_setregs = setregs, 231 .e_proc_exec = NULL, 232 .e_proc_fork = NULL, 233 .e_proc_exit = NULL, 234 .e_lwp_fork = NULL, 235 .e_lwp_exit = NULL, 236 #ifdef __HAVE_SYSCALL_INTERN 237 .e_syscall_intern = syscall_intern, 238 #else 239 .e_syscall = syscall, 240 #endif 241 .e_sysctlovly = NULL, 242 .e_vm_default_addr = uvm_default_mapaddr, 243 .e_usertrap = NULL, 244 .e_ucsize = sizeof(ucontext_t), 245 .e_startlwp = startlwp 246 }; 247 248 /* 249 * Exec lock. Used to control access to execsw[] structures. 250 * This must not be static so that netbsd32 can access it, too. 251 */ 252 krwlock_t exec_lock __cacheline_aligned; 253 254 /* 255 * Data used between a loadvm and execve part of an "exec" operation 256 */ 257 struct execve_data { 258 struct exec_package ed_pack; 259 struct pathbuf *ed_pathbuf; 260 struct vattr ed_attr; 261 struct ps_strings ed_arginfo; 262 char *ed_argp; 263 const char *ed_pathstring; 264 char *ed_resolvedname; 265 size_t ed_ps_strings_sz; 266 int ed_szsigcode; 267 size_t ed_argslen; 268 long ed_argc; 269 long ed_envc; 270 }; 271 272 /* 273 * data passed from parent lwp to child during a posix_spawn() 274 */ 275 struct spawn_exec_data { 276 struct execve_data sed_exec; 277 struct posix_spawn_file_actions 278 *sed_actions; 279 struct posix_spawnattr *sed_attrs; 280 struct proc *sed_parent; 281 kcondvar_t sed_cv_child_ready; 282 kmutex_t sed_mtx_child; 283 int sed_error; 284 bool sed_child_ready; 285 volatile uint32_t sed_refcnt; 286 }; 287 288 static struct vm_map *exec_map; 289 static struct pool exec_pool; 290 291 static void * 292 exec_pool_alloc(struct pool *pp, int flags) 293 { 294 295 return (void *)uvm_km_alloc(exec_map, NCARGS, 0, 296 UVM_KMF_PAGEABLE | UVM_KMF_WAITVA); 297 } 298 299 static void 300 exec_pool_free(struct pool *pp, void *addr) 301 { 302 303 uvm_km_free(exec_map, (vaddr_t)addr, NCARGS, UVM_KMF_PAGEABLE); 304 } 305 306 static struct pool_allocator exec_palloc = { 307 .pa_alloc = exec_pool_alloc, 308 .pa_free = exec_pool_free, 309 .pa_pagesz = NCARGS 310 }; 311 312 static void 313 exec_path_free(struct execve_data *data) 314 { 315 pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring); 316 pathbuf_destroy(data->ed_pathbuf); 317 if (data->ed_resolvedname) 318 PNBUF_PUT(data->ed_resolvedname); 319 } 320 321 static int 322 exec_resolvename(struct lwp *l, struct exec_package *epp, struct vnode *vp, 323 char **rpath) 324 { 325 int error; 326 char *p; 327 328 KASSERT(rpath != NULL); 329 330 *rpath = PNBUF_GET(); 331 error = vnode_to_path(*rpath, MAXPATHLEN, vp, l, l->l_proc); 332 if (error) { 333 DPRINTF(("%s: can't resolve name for %s, error %d\n", 334 __func__, epp->ep_kname, error)); 335 PNBUF_PUT(*rpath); 336 *rpath = NULL; 337 return error; 338 } 339 epp->ep_resolvedname = *rpath; 340 if ((p = strrchr(*rpath, '/')) != NULL) 341 epp->ep_kname = p + 1; 342 return 0; 343 } 344 345 346 /* 347 * check exec: 348 * given an "executable" described in the exec package's namei info, 349 * see what we can do with it. 350 * 351 * ON ENTRY: 352 * exec package with appropriate namei info 353 * lwp pointer of exec'ing lwp 354 * NO SELF-LOCKED VNODES 355 * 356 * ON EXIT: 357 * error: nothing held, etc. exec header still allocated. 358 * ok: filled exec package, executable's vnode (unlocked). 359 * 360 * EXEC SWITCH ENTRY: 361 * Locked vnode to check, exec package, proc. 362 * 363 * EXEC SWITCH EXIT: 364 * ok: return 0, filled exec package, executable's vnode (unlocked). 365 * error: destructive: 366 * everything deallocated execept exec header. 367 * non-destructive: 368 * error code, executable's vnode (unlocked), 369 * exec header unmodified. 370 */ 371 int 372 /*ARGSUSED*/ 373 check_exec(struct lwp *l, struct exec_package *epp, struct pathbuf *pb, 374 char **rpath) 375 { 376 int error, i; 377 struct vnode *vp; 378 size_t resid; 379 380 if (epp->ep_resolvedname) { 381 struct nameidata nd; 382 383 // grab the absolute pathbuf here before namei() trashes it. 384 pathbuf_copystring(pb, epp->ep_resolvedname, PATH_MAX); 385 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb); 386 387 /* first get the vnode */ 388 if ((error = namei(&nd)) != 0) 389 return error; 390 391 epp->ep_vp = vp = nd.ni_vp; 392 #ifdef DIAGNOSTIC 393 /* paranoia (take this out once namei stuff stabilizes) */ 394 memset(nd.ni_pnbuf, '~', PATH_MAX); 395 #endif 396 } else { 397 struct file *fp; 398 399 if ((error = fd_getvnode(epp->ep_xfd, &fp)) != 0) 400 return error; 401 epp->ep_vp = vp = fp->f_vnode; 402 vref(vp); 403 fd_putfile(epp->ep_xfd); 404 if ((error = exec_resolvename(l, epp, vp, rpath)) != 0) 405 return error; 406 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 407 } 408 409 /* check access and type */ 410 if (vp->v_type != VREG) { 411 error = SET_ERROR(EACCES); 412 goto bad1; 413 } 414 if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0) 415 goto bad1; 416 417 /* get attributes */ 418 /* XXX VOP_GETATTR is the only thing that needs LK_EXCLUSIVE here */ 419 if ((error = VOP_GETATTR(vp, epp->ep_vap, l->l_cred)) != 0) 420 goto bad1; 421 422 /* Check mount point */ 423 if (vp->v_mount->mnt_flag & MNT_NOEXEC) { 424 error = SET_ERROR(EACCES); 425 goto bad1; 426 } 427 if (vp->v_mount->mnt_flag & MNT_NOSUID) 428 epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID); 429 430 /* try to open it */ 431 if ((error = VOP_OPEN(vp, FREAD, l->l_cred)) != 0) 432 goto bad1; 433 434 /* now we have the file, get the exec header */ 435 error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0, 436 UIO_SYSSPACE, IO_NODELOCKED, l->l_cred, &resid, NULL); 437 if (error) 438 goto bad1; 439 440 /* unlock vp, since we need it unlocked from here on out. */ 441 VOP_UNLOCK(vp); 442 443 #if NVERIEXEC > 0 444 error = veriexec_verify(l, vp, 445 epp->ep_resolvedname ? epp->ep_resolvedname : epp->ep_kname, 446 epp->ep_flags & EXEC_INDIR ? VERIEXEC_INDIRECT : VERIEXEC_DIRECT, 447 NULL); 448 if (error) 449 goto bad2; 450 #endif /* NVERIEXEC > 0 */ 451 452 #ifdef PAX_SEGVGUARD 453 error = pax_segvguard(l, vp, epp->ep_resolvedname, false); 454 if (error) 455 goto bad2; 456 #endif /* PAX_SEGVGUARD */ 457 458 epp->ep_hdrvalid = epp->ep_hdrlen - resid; 459 460 /* 461 * Set up default address space limits. Can be overridden 462 * by individual exec packages. 463 */ 464 epp->ep_vm_minaddr = exec_vm_minaddr(VM_MIN_ADDRESS); 465 epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS; 466 467 /* 468 * set up the vmcmds for creation of the process 469 * address space 470 */ 471 error = nexecs == 0 ? SET_ERROR(ENOEXEC) : ENOEXEC; 472 for (i = 0; i < nexecs; i++) { 473 int newerror; 474 475 epp->ep_esch = execsw[i]; 476 newerror = (*execsw[i]->es_makecmds)(l, epp); 477 478 if (!newerror) { 479 /* Seems ok: check that entry point is not too high */ 480 if (epp->ep_entry >= epp->ep_vm_maxaddr) { 481 #ifdef DIAGNOSTIC 482 printf("%s: rejecting %p due to " 483 "too high entry address (>= %p)\n", 484 __func__, (void *)epp->ep_entry, 485 (void *)epp->ep_vm_maxaddr); 486 #endif 487 error = SET_ERROR(ENOEXEC); 488 break; 489 } 490 /* Seems ok: check that entry point is not too low */ 491 if (epp->ep_entry < epp->ep_vm_minaddr) { 492 #ifdef DIAGNOSTIC 493 printf("%s: rejecting %p due to " 494 "too low entry address (< %p)\n", 495 __func__, (void *)epp->ep_entry, 496 (void *)epp->ep_vm_minaddr); 497 #endif 498 error = SET_ERROR(ENOEXEC); 499 break; 500 } 501 502 /* check limits */ 503 #ifdef DIAGNOSTIC 504 #define LMSG "%s: rejecting due to %s limit (%ju > %ju)\n" 505 #endif 506 #ifdef MAXTSIZ 507 if (epp->ep_tsize > MAXTSIZ) { 508 #ifdef DIAGNOSTIC 509 printf(LMSG, __func__, "text", 510 (uintmax_t)epp->ep_tsize, 511 (uintmax_t)MAXTSIZ); 512 #endif 513 error = SET_ERROR(ENOMEM); 514 break; 515 } 516 #endif 517 vsize_t dlimit = 518 (vsize_t)l->l_proc->p_rlimit[RLIMIT_DATA].rlim_cur; 519 if (epp->ep_dsize > dlimit) { 520 #ifdef DIAGNOSTIC 521 printf(LMSG, __func__, "data", 522 (uintmax_t)epp->ep_dsize, 523 (uintmax_t)dlimit); 524 #endif 525 error = SET_ERROR(ENOMEM); 526 break; 527 } 528 return 0; 529 } 530 531 /* 532 * Reset all the fields that may have been modified by the 533 * loader. 534 */ 535 KASSERT(epp->ep_emul_arg == NULL); 536 if (epp->ep_emul_root != NULL) { 537 vrele(epp->ep_emul_root); 538 epp->ep_emul_root = NULL; 539 } 540 if (epp->ep_interp != NULL) { 541 vrele(epp->ep_interp); 542 epp->ep_interp = NULL; 543 } 544 epp->ep_pax_flags = 0; 545 546 /* make sure the first "interesting" error code is saved. */ 547 if (error == ENOEXEC) 548 error = newerror; 549 550 if (epp->ep_flags & EXEC_DESTR) 551 /* Error from "#!" code, tidied up by recursive call */ 552 return error; 553 } 554 555 /* not found, error */ 556 557 /* 558 * free any vmspace-creation commands, 559 * and release their references 560 */ 561 kill_vmcmds(&epp->ep_vmcmds); 562 563 #if NVERIEXEC > 0 || defined(PAX_SEGVGUARD) 564 bad2: 565 #endif 566 /* 567 * close and release the vnode, restore the old one, free the 568 * pathname buf, and punt. 569 */ 570 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 571 VOP_CLOSE(vp, FREAD, l->l_cred); 572 vput(vp); 573 return error; 574 575 bad1: 576 /* 577 * free the namei pathname buffer, and put the vnode 578 * (which we don't yet have open). 579 */ 580 vput(vp); /* was still locked */ 581 return error; 582 } 583 584 #ifdef __MACHINE_STACK_GROWS_UP 585 #define STACK_PTHREADSPACE PAGE_SIZE 586 #else 587 #define STACK_PTHREADSPACE 0 588 #endif 589 590 static int 591 execve_fetch_element(char * const *array, size_t index, char **value) 592 { 593 return copyin(array + index, value, sizeof(*value)); 594 } 595 596 /* 597 * exec system call 598 */ 599 int 600 sys_execve(struct lwp *l, const struct sys_execve_args *uap, register_t *retval) 601 { 602 /* { 603 syscallarg(const char *) path; 604 syscallarg(char * const *) argp; 605 syscallarg(char * const *) envp; 606 } */ 607 608 return execve1(l, true, SCARG(uap, path), -1, SCARG(uap, argp), 609 SCARG(uap, envp), execve_fetch_element); 610 } 611 612 int 613 sys_fexecve(struct lwp *l, const struct sys_fexecve_args *uap, 614 register_t *retval) 615 { 616 /* { 617 syscallarg(int) fd; 618 syscallarg(char * const *) argp; 619 syscallarg(char * const *) envp; 620 } */ 621 622 return execve1(l, false, NULL, SCARG(uap, fd), SCARG(uap, argp), 623 SCARG(uap, envp), execve_fetch_element); 624 } 625 626 /* 627 * Load modules to try and execute an image that we do not understand. 628 * If no execsw entries are present, we load those likely to be needed 629 * in order to run native images only. Otherwise, we autoload all 630 * possible modules that could let us run the binary. XXX lame 631 */ 632 static void 633 exec_autoload(void) 634 { 635 #ifdef MODULAR 636 static const char * const native[] = { 637 "exec_elf32", 638 "exec_elf64", 639 "exec_script", 640 NULL 641 }; 642 static const char * const compat[] = { 643 "exec_elf32", 644 "exec_elf64", 645 "exec_script", 646 "exec_aout", 647 "exec_coff", 648 "exec_ecoff", 649 "compat_aoutm68k", 650 "compat_netbsd32", 651 #if 0 652 "compat_linux", 653 "compat_linux32", 654 #endif 655 "compat_sunos", 656 "compat_sunos32", 657 "compat_ultrix", 658 NULL 659 }; 660 char const * const *list; 661 int i; 662 663 list = nexecs == 0 ? native : compat; 664 for (i = 0; list[i] != NULL; i++) { 665 if (module_autoload(list[i], MODULE_CLASS_EXEC) != 0) { 666 continue; 667 } 668 yield(); 669 } 670 #endif 671 } 672 673 /* 674 * Copy the user or kernel supplied upath to the allocated pathbuffer pbp 675 * making it absolute in the process, by prepending the current working 676 * directory if it is not. If offs is supplied it will contain the offset 677 * where the original supplied copy of upath starts. 678 */ 679 int 680 exec_makepathbuf(struct lwp *l, const char *upath, enum uio_seg seg, 681 struct pathbuf **pbp, size_t *offs) 682 { 683 char *path, *bp; 684 size_t len, tlen; 685 int error; 686 struct cwdinfo *cwdi; 687 688 path = PNBUF_GET(); 689 if (seg == UIO_SYSSPACE) { 690 error = copystr(upath, path, MAXPATHLEN, &len); 691 } else { 692 error = copyinstr(upath, path, MAXPATHLEN, &len); 693 } 694 if (error) 695 goto err; 696 697 if (path[0] == '/') { 698 if (offs) 699 *offs = 0; 700 goto out; 701 } 702 703 len++; 704 if (len + 1 >= MAXPATHLEN) { 705 error = SET_ERROR(ENAMETOOLONG); 706 goto err; 707 } 708 bp = path + MAXPATHLEN - len; 709 memmove(bp, path, len); 710 *(--bp) = '/'; 711 712 cwdi = l->l_proc->p_cwdi; 713 rw_enter(&cwdi->cwdi_lock, RW_READER); 714 error = getcwd_common(cwdi->cwdi_cdir, NULL, &bp, path, MAXPATHLEN / 2, 715 GETCWD_CHECK_ACCESS, l); 716 rw_exit(&cwdi->cwdi_lock); 717 718 if (error) 719 goto err; 720 tlen = path + MAXPATHLEN - bp; 721 722 memmove(path, bp, tlen); 723 path[tlen - 1] = '\0'; 724 if (offs) 725 *offs = tlen - len; 726 out: 727 *pbp = pathbuf_assimilate(path); 728 return 0; 729 err: 730 PNBUF_PUT(path); 731 return error; 732 } 733 734 vaddr_t 735 exec_vm_minaddr(vaddr_t va_min) 736 { 737 /* 738 * Increase va_min if we don't want NULL to be mappable by the 739 * process. 740 */ 741 #define VM_MIN_GUARD PAGE_SIZE 742 if (user_va0_disable && (va_min < VM_MIN_GUARD)) 743 return VM_MIN_GUARD; 744 return va_min; 745 } 746 747 static int 748 execve_loadvm(struct lwp *l, bool has_path, const char *path, int fd, 749 char * const *args, char * const *envs, 750 execve_fetch_element_t fetch_element, 751 struct execve_data * restrict data) 752 { 753 struct exec_package * const epp = &data->ed_pack; 754 int error; 755 struct proc *p; 756 char *dp; 757 u_int modgen; 758 759 KASSERT(data != NULL); 760 761 p = l->l_proc; 762 modgen = 0; 763 764 SDT_PROBE(proc, kernel, , exec, path, 0, 0, 0, 0); 765 766 /* 767 * Check if we have exceeded our number of processes limit. 768 * This is so that we handle the case where a root daemon 769 * forked, ran setuid to become the desired user and is trying 770 * to exec. The obvious place to do the reference counting check 771 * is setuid(), but we don't do the reference counting check there 772 * like other OS's do because then all the programs that use setuid() 773 * must be modified to check the return code of setuid() and exit(). 774 * It is dangerous to make setuid() fail, because it fails open and 775 * the program will continue to run as root. If we make it succeed 776 * and return an error code, again we are not enforcing the limit. 777 * The best place to enforce the limit is here, when the process tries 778 * to execute a new image, because eventually the process will need 779 * to call exec in order to do something useful. 780 */ 781 retry: 782 if (p->p_flag & PK_SUGID) { 783 if (kauth_authorize_process(l->l_cred, KAUTH_PROCESS_RLIMIT, 784 p, KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS), 785 &p->p_rlimit[RLIMIT_NPROC], 786 KAUTH_ARG(RLIMIT_NPROC)) != 0 && 787 chgproccnt(kauth_cred_getuid(l->l_cred), 0) > 788 p->p_rlimit[RLIMIT_NPROC].rlim_cur) 789 return SET_ERROR(EAGAIN); 790 } 791 792 /* 793 * Drain existing references and forbid new ones. The process 794 * should be left alone until we're done here. This is necessary 795 * to avoid race conditions - e.g. in ptrace() - that might allow 796 * a local user to illicitly obtain elevated privileges. 797 */ 798 rw_enter(&p->p_reflock, RW_WRITER); 799 800 if (has_path) { 801 size_t offs; 802 /* 803 * Init the namei data to point the file user's program name. 804 * This is done here rather than in check_exec(), so that it's 805 * possible to override this settings if any of makecmd/probe 806 * functions call check_exec() recursively - for example, 807 * see exec_script_makecmds(). 808 */ 809 if ((error = exec_makepathbuf(l, path, UIO_USERSPACE, 810 &data->ed_pathbuf, &offs)) != 0) 811 goto clrflg; 812 data->ed_pathstring = pathbuf_stringcopy_get(data->ed_pathbuf); 813 epp->ep_kname = data->ed_pathstring + offs; 814 data->ed_resolvedname = PNBUF_GET(); 815 epp->ep_resolvedname = data->ed_resolvedname; 816 epp->ep_xfd = -1; 817 } else { 818 data->ed_pathbuf = pathbuf_assimilate(strcpy(PNBUF_GET(), "/")); 819 data->ed_pathstring = pathbuf_stringcopy_get(data->ed_pathbuf); 820 epp->ep_kname = "*fexecve*"; 821 data->ed_resolvedname = NULL; 822 epp->ep_resolvedname = NULL; 823 epp->ep_xfd = fd; 824 } 825 826 827 /* 828 * initialize the fields of the exec package. 829 */ 830 epp->ep_hdr = kmem_alloc(exec_maxhdrsz, KM_SLEEP); 831 epp->ep_hdrlen = exec_maxhdrsz; 832 epp->ep_hdrvalid = 0; 833 epp->ep_emul_arg = NULL; 834 epp->ep_emul_arg_free = NULL; 835 memset(&epp->ep_vmcmds, 0, sizeof(epp->ep_vmcmds)); 836 epp->ep_vap = &data->ed_attr; 837 epp->ep_flags = (p->p_flag & PK_32) ? EXEC_FROM32 : 0; 838 MD_TOPDOWN_INIT(epp); 839 epp->ep_emul_root = NULL; 840 epp->ep_interp = NULL; 841 epp->ep_esch = NULL; 842 epp->ep_pax_flags = 0; 843 memset(epp->ep_machine_arch, 0, sizeof(epp->ep_machine_arch)); 844 845 rw_enter(&exec_lock, RW_READER); 846 847 /* see if we can run it. */ 848 if ((error = check_exec(l, epp, data->ed_pathbuf, 849 &data->ed_resolvedname)) != 0) { 850 if (error != ENOENT && error != EACCES && error != ENOEXEC) { 851 DPRINTF(("%s: check exec failed for %s, error %d\n", 852 __func__, epp->ep_kname, error)); 853 } 854 goto freehdr; 855 } 856 857 /* allocate an argument buffer */ 858 data->ed_argp = pool_get(&exec_pool, PR_WAITOK); 859 KASSERT(data->ed_argp != NULL); 860 dp = data->ed_argp; 861 862 if ((error = copyinargs(data, args, envs, fetch_element, &dp)) != 0) { 863 goto bad; 864 } 865 866 /* 867 * Calculate the new stack size. 868 */ 869 870 #ifdef __MACHINE_STACK_GROWS_UP 871 /* 872 * copyargs() fills argc/argv/envp from the lower address even on 873 * __MACHINE_STACK_GROWS_UP machines. Reserve a few words just below the SP 874 * so that _rtld() use it. 875 */ 876 #define RTLD_GAP 32 877 #else 878 #define RTLD_GAP 0 879 #endif 880 881 const size_t argenvstrlen = (char *)ALIGN(dp) - data->ed_argp; 882 883 data->ed_argslen = calcargs(data, argenvstrlen); 884 885 const size_t len = calcstack(data, pax_aslr_stack_gap(epp) + RTLD_GAP); 886 887 if (len > epp->ep_ssize) { 888 /* in effect, compare to initial limit */ 889 DPRINTF(("%s: stack limit exceeded %zu\n", __func__, len)); 890 error = SET_ERROR(ENOMEM); 891 goto bad; 892 } 893 /* adjust "active stack depth" for process VSZ */ 894 epp->ep_ssize = len; 895 896 return 0; 897 898 bad: 899 /* free the vmspace-creation commands, and release their references */ 900 kill_vmcmds(&epp->ep_vmcmds); 901 /* kill any opened file descriptor, if necessary */ 902 if (epp->ep_flags & EXEC_HASFD) { 903 epp->ep_flags &= ~EXEC_HASFD; 904 fd_close(epp->ep_fd); 905 } 906 /* close and put the exec'd file */ 907 vn_lock(epp->ep_vp, LK_EXCLUSIVE | LK_RETRY); 908 VOP_CLOSE(epp->ep_vp, FREAD, l->l_cred); 909 vput(epp->ep_vp); 910 pool_put(&exec_pool, data->ed_argp); 911 912 freehdr: 913 kmem_free(epp->ep_hdr, epp->ep_hdrlen); 914 if (epp->ep_emul_root != NULL) 915 vrele(epp->ep_emul_root); 916 if (epp->ep_interp != NULL) 917 vrele(epp->ep_interp); 918 919 rw_exit(&exec_lock); 920 921 exec_path_free(data); 922 923 clrflg: 924 rw_exit(&p->p_reflock); 925 926 if (modgen != module_gen && error == ENOEXEC) { 927 modgen = module_gen; 928 exec_autoload(); 929 goto retry; 930 } 931 932 SDT_PROBE(proc, kernel, , exec__failure, error, 0, 0, 0, 0); 933 return error; 934 } 935 936 static int 937 execve_dovmcmds(struct lwp *l, struct execve_data * restrict data) 938 { 939 struct exec_package * const epp = &data->ed_pack; 940 struct proc *p = l->l_proc; 941 struct exec_vmcmd *base_vcp; 942 int error = 0; 943 size_t i; 944 945 /* record proc's vnode, for use by procfs and others */ 946 if (p->p_textvp) 947 vrele(p->p_textvp); 948 vref(epp->ep_vp); 949 p->p_textvp = epp->ep_vp; 950 951 /* create the new process's VM space by running the vmcmds */ 952 KASSERTMSG(epp->ep_vmcmds.evs_used != 0, "%s: no vmcmds", __func__); 953 954 #ifdef TRACE_EXEC 955 DUMPVMCMDS(epp, 0, 0); 956 #endif 957 958 base_vcp = NULL; 959 960 for (i = 0; i < epp->ep_vmcmds.evs_used; i++) { 961 struct exec_vmcmd *vcp; 962 963 vcp = &epp->ep_vmcmds.evs_cmds[i]; 964 if (vcp->ev_flags & VMCMD_BASE) 965 base_vcp = vcp; 966 967 if (vcp->ev_flags & VMCMD_RELATIVE) { 968 if (base_vcp == NULL) { 969 DPRINTF(("%s: relative vmcmd %zu with no base", 970 __func__, i)); 971 error = EINVAL; 972 break; 973 } 974 if ((vcp->ev_flags & VMCMD_BASE) != 0) { 975 DPRINTF(("%s: illegal base|relative vmcmd %zu", 976 __func__, i)); 977 error = EINVAL; 978 break; 979 } 980 vcp->ev_addr += base_vcp->ev_addr; 981 } 982 error = (*vcp->ev_proc)(l, vcp); 983 if (error) { 984 DUMPVMCMDS(epp, i, error); 985 DPRINTF(("%s: vmcmd %zu failed: %d\n", __func__, i, 986 error)); 987 break; 988 } 989 } 990 991 /* free the vmspace-creation commands, and release their references */ 992 kill_vmcmds(&epp->ep_vmcmds); 993 994 vn_lock(epp->ep_vp, LK_EXCLUSIVE | LK_RETRY); 995 VOP_CLOSE(epp->ep_vp, FREAD, l->l_cred); 996 vput(epp->ep_vp); 997 998 return error; 999 } 1000 1001 static void 1002 execve_free_data(struct execve_data *data) 1003 { 1004 struct exec_package * const epp = &data->ed_pack; 1005 1006 /* free the vmspace-creation commands, and release their references */ 1007 kill_vmcmds(&epp->ep_vmcmds); 1008 /* kill any opened file descriptor, if necessary */ 1009 if (epp->ep_flags & EXEC_HASFD) { 1010 epp->ep_flags &= ~EXEC_HASFD; 1011 fd_close(epp->ep_fd); 1012 } 1013 1014 /* close and put the exec'd file */ 1015 vn_lock(epp->ep_vp, LK_EXCLUSIVE | LK_RETRY); 1016 VOP_CLOSE(epp->ep_vp, FREAD, curlwp->l_cred); 1017 vput(epp->ep_vp); 1018 pool_put(&exec_pool, data->ed_argp); 1019 1020 kmem_free(epp->ep_hdr, epp->ep_hdrlen); 1021 if (epp->ep_emul_root != NULL) 1022 vrele(epp->ep_emul_root); 1023 if (epp->ep_interp != NULL) 1024 vrele(epp->ep_interp); 1025 1026 exec_path_free(data); 1027 } 1028 1029 static void 1030 pathexec(struct proc *p, const char *resolvedname) 1031 { 1032 /* set command name & other accounting info */ 1033 const char *cmdname; 1034 1035 if (resolvedname == NULL) { 1036 cmdname = "*fexecve*"; 1037 resolvedname = "/"; 1038 } else { 1039 cmdname = strrchr(resolvedname, '/') + 1; 1040 } 1041 KASSERTMSG(resolvedname[0] == '/', "bad resolvedname `%s'", 1042 resolvedname); 1043 1044 strlcpy(p->p_comm, cmdname, sizeof(p->p_comm)); 1045 1046 kmem_strfree(p->p_path); 1047 p->p_path = kmem_strdupsize(resolvedname, NULL, KM_SLEEP); 1048 } 1049 1050 /* XXX elsewhere */ 1051 static int 1052 credexec(struct lwp *l, struct execve_data *data) 1053 { 1054 struct proc *p = l->l_proc; 1055 struct vattr *attr = &data->ed_attr; 1056 int error; 1057 1058 /* 1059 * Deal with set[ug]id. MNT_NOSUID has already been used to disable 1060 * s[ug]id. It's OK to check for PSL_TRACED here as we have blocked 1061 * out additional references on the process for the moment. 1062 */ 1063 if ((p->p_slflag & PSL_TRACED) == 0 && 1064 1065 (((attr->va_mode & S_ISUID) != 0 && 1066 kauth_cred_geteuid(l->l_cred) != attr->va_uid) || 1067 1068 ((attr->va_mode & S_ISGID) != 0 && 1069 kauth_cred_getegid(l->l_cred) != attr->va_gid))) { 1070 /* 1071 * Mark the process as SUGID before we do 1072 * anything that might block. 1073 */ 1074 proc_crmod_enter(); 1075 proc_crmod_leave(NULL, NULL, true); 1076 if (data->ed_argc == 0) { 1077 DPRINTF(( 1078 "%s: not executing set[ug]id binary with no args\n", 1079 __func__)); 1080 return SET_ERROR(EINVAL); 1081 } 1082 1083 /* Make sure file descriptors 0..2 are in use. */ 1084 if ((error = fd_checkstd()) != 0) { 1085 DPRINTF(("%s: fdcheckstd failed %d\n", 1086 __func__, error)); 1087 return error; 1088 } 1089 1090 /* 1091 * Copy the credential so other references don't see our 1092 * changes. 1093 */ 1094 l->l_cred = kauth_cred_copy(l->l_cred); 1095 #ifdef KTRACE 1096 /* 1097 * If the persistent trace flag isn't set, turn off. 1098 */ 1099 if (p->p_tracep) { 1100 mutex_enter(&ktrace_lock); 1101 if (!(p->p_traceflag & KTRFAC_PERSISTENT)) 1102 ktrderef(p); 1103 mutex_exit(&ktrace_lock); 1104 } 1105 #endif 1106 if (attr->va_mode & S_ISUID) 1107 kauth_cred_seteuid(l->l_cred, attr->va_uid); 1108 if (attr->va_mode & S_ISGID) 1109 kauth_cred_setegid(l->l_cred, attr->va_gid); 1110 } else { 1111 if (kauth_cred_geteuid(l->l_cred) == 1112 kauth_cred_getuid(l->l_cred) && 1113 kauth_cred_getegid(l->l_cred) == 1114 kauth_cred_getgid(l->l_cred)) 1115 p->p_flag &= ~PK_SUGID; 1116 } 1117 1118 /* 1119 * Copy the credential so other references don't see our changes. 1120 * Test to see if this is necessary first, since in the common case 1121 * we won't need a private reference. 1122 */ 1123 if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) || 1124 kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) { 1125 l->l_cred = kauth_cred_copy(l->l_cred); 1126 kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred)); 1127 kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred)); 1128 } 1129 1130 /* Update the master credentials. */ 1131 if (l->l_cred != p->p_cred) { 1132 kauth_cred_t ocred; 1133 mutex_enter(p->p_lock); 1134 ocred = p->p_cred; 1135 p->p_cred = kauth_cred_hold(l->l_cred); 1136 mutex_exit(p->p_lock); 1137 kauth_cred_free(ocred); 1138 } 1139 1140 return 0; 1141 } 1142 1143 static void 1144 emulexec(struct lwp *l, struct exec_package *epp) 1145 { 1146 struct proc *p = l->l_proc; 1147 1148 /* The emulation root will usually have been found when we looked 1149 * for the elf interpreter (or similar), if not look now. */ 1150 if (epp->ep_esch->es_emul->e_path != NULL && 1151 epp->ep_emul_root == NULL) 1152 emul_find_root(l, epp); 1153 1154 /* Any old emulation root got removed by fdcloseexec */ 1155 rw_enter(&p->p_cwdi->cwdi_lock, RW_WRITER); 1156 p->p_cwdi->cwdi_edir = epp->ep_emul_root; 1157 rw_exit(&p->p_cwdi->cwdi_lock); 1158 epp->ep_emul_root = NULL; 1159 if (epp->ep_interp != NULL) 1160 vrele(epp->ep_interp); 1161 1162 /* 1163 * Call emulation specific exec hook. This can setup per-process 1164 * p->p_emuldata or do any other per-process stuff an emulation needs. 1165 * 1166 * If we are executing process of different emulation than the 1167 * original forked process, call e_proc_exit() of the old emulation 1168 * first, then e_proc_exec() of new emulation. If the emulation is 1169 * same, the exec hook code should deallocate any old emulation 1170 * resources held previously by this process. 1171 */ 1172 if (p->p_emul && p->p_emul->e_proc_exit 1173 && p->p_emul != epp->ep_esch->es_emul) 1174 (*p->p_emul->e_proc_exit)(p); 1175 1176 /* 1177 * Call exec hook. Emulation code may NOT store reference to anything 1178 * from &pack. 1179 */ 1180 if (epp->ep_esch->es_emul->e_proc_exec) 1181 (*epp->ep_esch->es_emul->e_proc_exec)(p, epp); 1182 1183 /* update p_emul, the old value is no longer needed */ 1184 p->p_emul = epp->ep_esch->es_emul; 1185 1186 /* ...and the same for p_execsw */ 1187 p->p_execsw = epp->ep_esch; 1188 1189 #ifdef __HAVE_SYSCALL_INTERN 1190 (*p->p_emul->e_syscall_intern)(p); 1191 #endif 1192 ktremul(); 1193 } 1194 1195 static int 1196 execve_runproc(struct lwp *l, struct execve_data * restrict data, 1197 bool no_local_exec_lock, bool is_spawn) 1198 { 1199 struct exec_package * const epp = &data->ed_pack; 1200 int error = 0; 1201 struct proc *p; 1202 struct vmspace *vm; 1203 1204 /* 1205 * In case of a posix_spawn operation, the child doing the exec 1206 * might not hold the reader lock on exec_lock, but the parent 1207 * will do this instead. 1208 */ 1209 KASSERT(no_local_exec_lock || rw_lock_held(&exec_lock)); 1210 KASSERT(!no_local_exec_lock || is_spawn); 1211 KASSERT(data != NULL); 1212 1213 p = l->l_proc; 1214 1215 /* Get rid of other LWPs. */ 1216 if (p->p_nlwps > 1) { 1217 mutex_enter(p->p_lock); 1218 exit_lwps(l); 1219 mutex_exit(p->p_lock); 1220 } 1221 KDASSERT(p->p_nlwps == 1); 1222 1223 /* 1224 * All of the other LWPs got rid of their robust futexes 1225 * when they exited above, but we might still have some 1226 * to dispose of. Do that now. 1227 */ 1228 if (__predict_false(l->l_robust_head != 0)) { 1229 futex_release_all_lwp(l); 1230 /* 1231 * Since this LWP will live on with a different 1232 * program image, we need to clear the robust 1233 * futex list pointer here. 1234 */ 1235 l->l_robust_head = 0; 1236 } 1237 1238 /* Destroy any lwpctl info. */ 1239 if (p->p_lwpctl != NULL) 1240 lwp_ctl_exit(); 1241 1242 /* Remove POSIX timers */ 1243 ptimers_free(p, TIMERS_POSIX); 1244 1245 /* Set the PaX flags. */ 1246 pax_set_flags(epp, p); 1247 1248 /* 1249 * Do whatever is necessary to prepare the address space 1250 * for remapping. Note that this might replace the current 1251 * vmspace with another! 1252 * 1253 * vfork(): do not touch any user space data in the new child 1254 * until we have awoken the parent below, or it will defeat 1255 * lazy pmap switching (on x86). 1256 */ 1257 uvmspace_exec(l, epp->ep_vm_minaddr, epp->ep_vm_maxaddr, 1258 epp->ep_flags & EXEC_TOPDOWN_VM); 1259 vm = p->p_vmspace; 1260 1261 vm->vm_taddr = (void *)epp->ep_taddr; 1262 vm->vm_tsize = btoc(epp->ep_tsize); 1263 vm->vm_daddr = (void*)epp->ep_daddr; 1264 vm->vm_dsize = btoc(epp->ep_dsize); 1265 vm->vm_ssize = btoc(epp->ep_ssize); 1266 vm->vm_issize = 0; 1267 vm->vm_maxsaddr = (void *)epp->ep_maxsaddr; 1268 vm->vm_minsaddr = (void *)epp->ep_minsaddr; 1269 1270 pax_aslr_init_vm(l, vm, epp); 1271 1272 cwdexec(p); 1273 fd_closeexec(); /* handle close on exec & close on fork */ 1274 1275 if (__predict_false(ktrace_on)) 1276 fd_ktrexecfd(); 1277 1278 execsigs(p); /* reset caught signals */ 1279 1280 mutex_enter(p->p_lock); 1281 l->l_ctxlink = NULL; /* reset ucontext link */ 1282 p->p_acflag &= ~AFORK; 1283 p->p_flag |= PK_EXEC; 1284 mutex_exit(p->p_lock); 1285 1286 error = credexec(l, data); 1287 if (error) 1288 goto exec_abort; 1289 1290 #if defined(__HAVE_RAS) 1291 /* 1292 * Remove all RASs from the address space. 1293 */ 1294 ras_purgeall(); 1295 #endif 1296 1297 /* 1298 * Stop profiling. 1299 */ 1300 if ((p->p_stflag & PST_PROFIL) != 0) { 1301 mutex_spin_enter(&p->p_stmutex); 1302 stopprofclock(p); 1303 mutex_spin_exit(&p->p_stmutex); 1304 } 1305 1306 /* 1307 * It's OK to test PL_PPWAIT unlocked here, as other LWPs have 1308 * exited and exec()/exit() are the only places it will be cleared. 1309 * 1310 * Once the parent has been awoken, curlwp may teleport to a new CPU 1311 * in sched_vforkexec(), and it's then OK to start messing with user 1312 * data. See comment above. 1313 */ 1314 if ((p->p_lflag & PL_PPWAIT) != 0) { 1315 bool samecpu; 1316 lwp_t *lp; 1317 1318 mutex_enter(&proc_lock); 1319 lp = p->p_vforklwp; 1320 p->p_vforklwp = NULL; 1321 l->l_lwpctl = NULL; /* was on loan from blocked parent */ 1322 1323 /* Clear flags after cv_broadcast() (scheduler needs them). */ 1324 p->p_lflag &= ~PL_PPWAIT; 1325 lp->l_vforkwaiting = false; 1326 1327 /* If parent is still on same CPU, teleport curlwp elsewhere. */ 1328 samecpu = (lp->l_cpu == curlwp->l_cpu); 1329 cv_broadcast(&lp->l_waitcv); 1330 mutex_exit(&proc_lock); 1331 1332 /* Give the parent its CPU back - find a new home. */ 1333 KASSERT(!is_spawn); 1334 sched_vforkexec(l, samecpu); 1335 } 1336 1337 /* Now map address space. */ 1338 error = execve_dovmcmds(l, data); 1339 if (error != 0) 1340 goto exec_abort; 1341 1342 pathexec(p, epp->ep_resolvedname); 1343 1344 char * const newstack = STACK_GROW(vm->vm_minsaddr, epp->ep_ssize); 1345 1346 error = copyoutargs(data, l, newstack); 1347 if (error != 0) 1348 goto exec_abort; 1349 1350 doexechooks(p); 1351 1352 /* 1353 * Set initial SP at the top of the stack. 1354 * 1355 * Note that on machines where stack grows up (e.g. hppa), SP points to 1356 * the end of arg/env strings. Userland guesses the address of argc 1357 * via ps_strings::ps_argvstr. 1358 */ 1359 1360 /* Setup new registers and do misc. setup. */ 1361 (*epp->ep_esch->es_emul->e_setregs)(l, epp, (vaddr_t)newstack); 1362 if (epp->ep_esch->es_setregs) 1363 (*epp->ep_esch->es_setregs)(l, epp, (vaddr_t)newstack); 1364 1365 /* Provide a consistent LWP private setting */ 1366 (void)lwp_setprivate(l, NULL); 1367 1368 /* Discard all PCU state; need to start fresh */ 1369 pcu_discard_all(l); 1370 1371 /* map the process's signal trampoline code */ 1372 if ((error = exec_sigcode_map(p, epp->ep_esch->es_emul)) != 0) { 1373 DPRINTF(("%s: map sigcode failed %d\n", __func__, error)); 1374 goto exec_abort; 1375 } 1376 1377 pool_put(&exec_pool, data->ed_argp); 1378 1379 /* 1380 * Notify anyone who might care that we've exec'd. 1381 * 1382 * This is slightly racy; someone could sneak in and 1383 * attach a knote after we've decided not to notify, 1384 * or vice-versa, but that's not particularly bothersome. 1385 * knote_proc_exec() will acquire p->p_lock as needed. 1386 */ 1387 if (!SLIST_EMPTY(&p->p_klist)) { 1388 knote_proc_exec(p); 1389 } 1390 1391 kmem_free(epp->ep_hdr, epp->ep_hdrlen); 1392 1393 SDT_PROBE(proc, kernel, , exec__success, epp->ep_kname, 0, 0, 0, 0); 1394 1395 emulexec(l, epp); 1396 1397 /* Allow new references from the debugger/procfs. */ 1398 rw_exit(&p->p_reflock); 1399 if (!no_local_exec_lock) 1400 rw_exit(&exec_lock); 1401 1402 mutex_enter(&proc_lock); 1403 1404 /* posix_spawn(3) reports a single event with implied exec(3) */ 1405 if ((p->p_slflag & PSL_TRACED) && !is_spawn) { 1406 mutex_enter(p->p_lock); 1407 eventswitch(TRAP_EXEC, 0, 0); 1408 mutex_enter(&proc_lock); 1409 } 1410 1411 if (p->p_sflag & PS_STOPEXEC) { 1412 ksiginfoq_t kq; 1413 1414 KASSERT(l->l_blcnt == 0); 1415 p->p_pptr->p_nstopchild++; 1416 p->p_waited = 0; 1417 mutex_enter(p->p_lock); 1418 ksiginfo_queue_init(&kq); 1419 sigclearall(p, &contsigmask, &kq); 1420 lwp_lock(l); 1421 l->l_stat = LSSTOP; 1422 p->p_stat = SSTOP; 1423 p->p_nrlwps--; 1424 lwp_unlock(l); 1425 mutex_exit(p->p_lock); 1426 mutex_exit(&proc_lock); 1427 lwp_lock(l); 1428 spc_lock(l->l_cpu); 1429 mi_switch(l); 1430 ksiginfo_queue_drain(&kq); 1431 } else { 1432 mutex_exit(&proc_lock); 1433 } 1434 1435 exec_path_free(data); 1436 #ifdef TRACE_EXEC 1437 DPRINTF(("%s finished\n", __func__)); 1438 #endif 1439 return EJUSTRETURN; 1440 1441 exec_abort: 1442 SDT_PROBE(proc, kernel, , exec__failure, error, 0, 0, 0, 0); 1443 rw_exit(&p->p_reflock); 1444 if (!no_local_exec_lock) 1445 rw_exit(&exec_lock); 1446 1447 exec_path_free(data); 1448 1449 /* 1450 * the old process doesn't exist anymore. exit gracefully. 1451 * get rid of the (new) address space we have created, if any, get rid 1452 * of our namei data and vnode, and exit noting failure 1453 */ 1454 if (vm != NULL) { 1455 uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS, 1456 VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS); 1457 } 1458 1459 exec_free_emul_arg(epp); 1460 pool_put(&exec_pool, data->ed_argp); 1461 kmem_free(epp->ep_hdr, epp->ep_hdrlen); 1462 if (epp->ep_emul_root != NULL) 1463 vrele(epp->ep_emul_root); 1464 if (epp->ep_interp != NULL) 1465 vrele(epp->ep_interp); 1466 1467 /* Acquire the sched-state mutex (exit1() will release it). */ 1468 if (!is_spawn) { 1469 mutex_enter(p->p_lock); 1470 exit1(l, error, SIGABRT); 1471 } 1472 1473 return error; 1474 } 1475 1476 int 1477 execve1(struct lwp *l, bool has_path, const char *path, int fd, 1478 char * const *args, char * const *envs, 1479 execve_fetch_element_t fetch_element) 1480 { 1481 struct execve_data data; 1482 int error; 1483 1484 error = execve_loadvm(l, has_path, path, fd, args, envs, fetch_element, 1485 &data); 1486 if (error) 1487 return error; 1488 error = execve_runproc(l, &data, false, false); 1489 return error; 1490 } 1491 1492 static size_t 1493 fromptrsz(const struct exec_package *epp) 1494 { 1495 return (epp->ep_flags & EXEC_FROM32) ? sizeof(int) : sizeof(char *); 1496 } 1497 1498 static size_t 1499 ptrsz(const struct exec_package *epp) 1500 { 1501 return (epp->ep_flags & EXEC_32) ? sizeof(int) : sizeof(char *); 1502 } 1503 1504 static size_t 1505 calcargs(struct execve_data * restrict data, const size_t argenvstrlen) 1506 { 1507 struct exec_package * const epp = &data->ed_pack; 1508 1509 const size_t nargenvptrs = 1510 1 + /* long argc */ 1511 data->ed_argc + /* char *argv[] */ 1512 1 + /* \0 */ 1513 data->ed_envc + /* char *env[] */ 1514 1; /* \0 */ 1515 1516 return (nargenvptrs * ptrsz(epp)) /* pointers */ 1517 + argenvstrlen /* strings */ 1518 + epp->ep_esch->es_arglen; /* auxinfo */ 1519 } 1520 1521 static size_t 1522 calcstack(struct execve_data * restrict data, const size_t gaplen) 1523 { 1524 struct exec_package * const epp = &data->ed_pack; 1525 1526 data->ed_szsigcode = epp->ep_esch->es_emul->e_esigcode - 1527 epp->ep_esch->es_emul->e_sigcode; 1528 1529 data->ed_ps_strings_sz = (epp->ep_flags & EXEC_32) ? 1530 sizeof(struct ps_strings32) : sizeof(struct ps_strings); 1531 1532 const size_t sigcode_psstr_sz = 1533 data->ed_szsigcode + /* sigcode */ 1534 data->ed_ps_strings_sz + /* ps_strings */ 1535 STACK_PTHREADSPACE; /* pthread space */ 1536 1537 const size_t stacklen = 1538 data->ed_argslen + 1539 gaplen + 1540 sigcode_psstr_sz; 1541 1542 /* make the stack "safely" aligned */ 1543 return STACK_LEN_ALIGN(stacklen, STACK_ALIGNBYTES); 1544 } 1545 1546 static int 1547 copyoutargs(struct execve_data * restrict data, struct lwp *l, 1548 char * const newstack) 1549 { 1550 struct exec_package * const epp = &data->ed_pack; 1551 struct proc *p = l->l_proc; 1552 int error; 1553 1554 memset(&data->ed_arginfo, 0, sizeof(data->ed_arginfo)); 1555 1556 /* remember information about the process */ 1557 data->ed_arginfo.ps_nargvstr = data->ed_argc; 1558 data->ed_arginfo.ps_nenvstr = data->ed_envc; 1559 1560 /* 1561 * Allocate the stack address passed to the newly execve()'ed process. 1562 * 1563 * The new stack address will be set to the SP (stack pointer) register 1564 * in setregs(). 1565 */ 1566 1567 char *newargs = STACK_ALLOC( 1568 STACK_SHRINK(newstack, data->ed_argslen), data->ed_argslen); 1569 1570 error = (*epp->ep_esch->es_copyargs)(l, epp, 1571 &data->ed_arginfo, &newargs, data->ed_argp); 1572 1573 if (error) { 1574 DPRINTF(("%s: copyargs failed %d\n", __func__, error)); 1575 return error; 1576 } 1577 1578 error = copyoutpsstrs(data, p); 1579 if (error != 0) 1580 return error; 1581 1582 return 0; 1583 } 1584 1585 static int 1586 copyoutpsstrs(struct execve_data * restrict data, struct proc *p) 1587 { 1588 struct exec_package * const epp = &data->ed_pack; 1589 struct ps_strings32 arginfo32; 1590 void *aip; 1591 int error; 1592 1593 /* fill process ps_strings info */ 1594 p->p_psstrp = (vaddr_t)STACK_ALLOC(STACK_GROW(epp->ep_minsaddr, 1595 STACK_PTHREADSPACE), data->ed_ps_strings_sz); 1596 1597 if (epp->ep_flags & EXEC_32) { 1598 aip = &arginfo32; 1599 arginfo32.ps_argvstr = (vaddr_t)data->ed_arginfo.ps_argvstr; 1600 arginfo32.ps_nargvstr = data->ed_arginfo.ps_nargvstr; 1601 arginfo32.ps_envstr = (vaddr_t)data->ed_arginfo.ps_envstr; 1602 arginfo32.ps_nenvstr = data->ed_arginfo.ps_nenvstr; 1603 } else 1604 aip = &data->ed_arginfo; 1605 1606 /* copy out the process's ps_strings structure */ 1607 if ((error = copyout(aip, (void *)p->p_psstrp, data->ed_ps_strings_sz)) 1608 != 0) { 1609 DPRINTF(("%s: ps_strings copyout %p->%p size %zu failed\n", 1610 __func__, aip, (void *)p->p_psstrp, data->ed_ps_strings_sz)); 1611 return error; 1612 } 1613 1614 return 0; 1615 } 1616 1617 static int 1618 copyinargs(struct execve_data * restrict data, char * const *args, 1619 char * const *envs, execve_fetch_element_t fetch_element, char **dpp) 1620 { 1621 struct exec_package * const epp = &data->ed_pack; 1622 char *dp; 1623 size_t i; 1624 int error; 1625 1626 dp = *dpp; 1627 1628 data->ed_argc = 0; 1629 1630 /* copy the fake args list, if there's one, freeing it as we go */ 1631 if (epp->ep_flags & EXEC_HASARGL) { 1632 struct exec_fakearg *fa = epp->ep_fa; 1633 1634 while (fa->fa_arg != NULL) { 1635 const size_t maxlen = ARG_MAX - (dp - data->ed_argp); 1636 size_t len; 1637 1638 len = strlcpy(dp, fa->fa_arg, maxlen); 1639 /* Count NUL into len. */ 1640 if (len < maxlen) 1641 len++; 1642 else { 1643 while (fa->fa_arg != NULL) { 1644 kmem_free(fa->fa_arg, fa->fa_len); 1645 fa++; 1646 } 1647 kmem_free(epp->ep_fa, epp->ep_fa_len); 1648 epp->ep_flags &= ~EXEC_HASARGL; 1649 return SET_ERROR(E2BIG); 1650 } 1651 ktrexecarg(fa->fa_arg, len - 1); 1652 dp += len; 1653 1654 kmem_free(fa->fa_arg, fa->fa_len); 1655 fa++; 1656 data->ed_argc++; 1657 } 1658 kmem_free(epp->ep_fa, epp->ep_fa_len); 1659 epp->ep_flags &= ~EXEC_HASARGL; 1660 } 1661 1662 /* 1663 * Read and count argument strings from user. 1664 */ 1665 1666 if (args == NULL) { 1667 DPRINTF(("%s: null args\n", __func__)); 1668 return SET_ERROR(EINVAL); 1669 } 1670 if (epp->ep_flags & EXEC_SKIPARG) 1671 args = (const void *)((const char *)args + fromptrsz(epp)); 1672 i = 0; 1673 error = copyinargstrs(data, args, fetch_element, &dp, &i, ktr_execarg); 1674 if (error != 0) { 1675 DPRINTF(("%s: copyin arg %d\n", __func__, error)); 1676 return error; 1677 } 1678 data->ed_argc += i; 1679 1680 /* 1681 * Read and count environment strings from user. 1682 */ 1683 1684 data->ed_envc = 0; 1685 /* environment need not be there */ 1686 if (envs == NULL) 1687 goto done; 1688 i = 0; 1689 error = copyinargstrs(data, envs, fetch_element, &dp, &i, ktr_execenv); 1690 if (error != 0) { 1691 DPRINTF(("%s: copyin env %d\n", __func__, error)); 1692 return error; 1693 } 1694 data->ed_envc += i; 1695 1696 done: 1697 *dpp = dp; 1698 1699 return 0; 1700 } 1701 1702 static int 1703 copyinargstrs(struct execve_data * restrict data, char * const *strs, 1704 execve_fetch_element_t fetch_element, char **dpp, size_t *ip, 1705 void (*ktr)(const void *, size_t)) 1706 { 1707 char *dp, *sp; 1708 size_t i; 1709 int error; 1710 1711 dp = *dpp; 1712 1713 i = 0; 1714 while (1) { 1715 const size_t maxlen = ARG_MAX - (dp - data->ed_argp); 1716 size_t len; 1717 1718 if ((error = (*fetch_element)(strs, i, &sp)) != 0) { 1719 return error; 1720 } 1721 if (!sp) 1722 break; 1723 if ((error = copyinstr(sp, dp, maxlen, &len)) != 0) { 1724 if (error == ENAMETOOLONG) 1725 error = SET_ERROR(E2BIG); 1726 return error; 1727 } 1728 if (__predict_false(ktrace_on)) 1729 (*ktr)(dp, len - 1); 1730 dp += len; 1731 i++; 1732 } 1733 1734 *dpp = dp; 1735 *ip = i; 1736 1737 return 0; 1738 } 1739 1740 /* 1741 * Copy argv and env strings from kernel buffer (argp) to the new stack. 1742 * Those strings are located just after auxinfo. 1743 */ 1744 int 1745 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo, 1746 char **stackp, void *argp) 1747 { 1748 char **cpp, *dp, *sp; 1749 size_t len; 1750 void *nullp; 1751 long argc, envc; 1752 int error; 1753 1754 cpp = (char **)*stackp; 1755 nullp = NULL; 1756 argc = arginfo->ps_nargvstr; 1757 envc = arginfo->ps_nenvstr; 1758 1759 /* argc on stack is long */ 1760 CTASSERT(sizeof(*cpp) == sizeof(argc)); 1761 1762 dp = (char *)(cpp + 1763 1 + /* long argc */ 1764 argc + /* char *argv[] */ 1765 1 + /* \0 */ 1766 envc + /* char *env[] */ 1767 1) + /* \0 */ 1768 pack->ep_esch->es_arglen; /* auxinfo */ 1769 sp = argp; 1770 1771 if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0) { 1772 COPYPRINTF("", cpp - 1, sizeof(argc)); 1773 return error; 1774 } 1775 1776 /* XXX don't copy them out, remap them! */ 1777 arginfo->ps_argvstr = cpp; /* remember location of argv for later */ 1778 1779 for (; --argc >= 0; sp += len, dp += len) { 1780 if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) { 1781 COPYPRINTF("", cpp - 1, sizeof(dp)); 1782 return error; 1783 } 1784 if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) { 1785 COPYPRINTF("str", dp, (size_t)ARG_MAX); 1786 return error; 1787 } 1788 } 1789 1790 if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) { 1791 COPYPRINTF("", cpp - 1, sizeof(nullp)); 1792 return error; 1793 } 1794 1795 arginfo->ps_envstr = cpp; /* remember location of envp for later */ 1796 1797 for (; --envc >= 0; sp += len, dp += len) { 1798 if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) { 1799 COPYPRINTF("", cpp - 1, sizeof(dp)); 1800 return error; 1801 } 1802 if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) { 1803 COPYPRINTF("str", dp, (size_t)ARG_MAX); 1804 return error; 1805 } 1806 1807 } 1808 1809 if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) { 1810 COPYPRINTF("", cpp - 1, sizeof(nullp)); 1811 return error; 1812 } 1813 1814 *stackp = (char *)cpp; 1815 return 0; 1816 } 1817 1818 1819 /* 1820 * Add execsw[] entries. 1821 */ 1822 int 1823 exec_add(struct execsw *esp, int count) 1824 { 1825 struct exec_entry *it; 1826 int i, error = 0; 1827 1828 if (count == 0) { 1829 return 0; 1830 } 1831 1832 /* Check for duplicates. */ 1833 rw_enter(&exec_lock, RW_WRITER); 1834 for (i = 0; i < count; i++) { 1835 LIST_FOREACH(it, &ex_head, ex_list) { 1836 /* assume unique (makecmds, probe_func, emulation) */ 1837 if (it->ex_sw->es_makecmds == esp[i].es_makecmds && 1838 it->ex_sw->u.elf_probe_func == 1839 esp[i].u.elf_probe_func && 1840 it->ex_sw->es_emul == esp[i].es_emul) { 1841 rw_exit(&exec_lock); 1842 return SET_ERROR(EEXIST); 1843 } 1844 } 1845 } 1846 1847 /* Allocate new entries. */ 1848 for (i = 0; i < count; i++) { 1849 it = kmem_alloc(sizeof(*it), KM_SLEEP); 1850 it->ex_sw = &esp[i]; 1851 error = exec_sigcode_alloc(it->ex_sw->es_emul); 1852 if (error != 0) { 1853 kmem_free(it, sizeof(*it)); 1854 break; 1855 } 1856 LIST_INSERT_HEAD(&ex_head, it, ex_list); 1857 } 1858 /* If even one fails, remove them all back. */ 1859 if (error != 0) { 1860 for (i--; i >= 0; i--) { 1861 it = LIST_FIRST(&ex_head); 1862 LIST_REMOVE(it, ex_list); 1863 exec_sigcode_free(it->ex_sw->es_emul); 1864 kmem_free(it, sizeof(*it)); 1865 } 1866 rw_exit(&exec_lock); 1867 return error; 1868 } 1869 1870 /* update execsw[] */ 1871 exec_init(0); 1872 rw_exit(&exec_lock); 1873 return 0; 1874 } 1875 1876 /* 1877 * Remove execsw[] entry. 1878 */ 1879 int 1880 exec_remove(struct execsw *esp, int count) 1881 { 1882 struct exec_entry *it, *next; 1883 int i; 1884 const struct proclist_desc *pd; 1885 proc_t *p; 1886 1887 if (count == 0) { 1888 return 0; 1889 } 1890 1891 /* Abort if any are busy. */ 1892 rw_enter(&exec_lock, RW_WRITER); 1893 for (i = 0; i < count; i++) { 1894 mutex_enter(&proc_lock); 1895 for (pd = proclists; pd->pd_list != NULL; pd++) { 1896 PROCLIST_FOREACH(p, pd->pd_list) { 1897 if (p->p_execsw == &esp[i]) { 1898 mutex_exit(&proc_lock); 1899 rw_exit(&exec_lock); 1900 return SET_ERROR(EBUSY); 1901 } 1902 } 1903 } 1904 mutex_exit(&proc_lock); 1905 } 1906 1907 /* None are busy, so remove them all. */ 1908 for (i = 0; i < count; i++) { 1909 for (it = LIST_FIRST(&ex_head); it != NULL; it = next) { 1910 next = LIST_NEXT(it, ex_list); 1911 if (it->ex_sw == &esp[i]) { 1912 LIST_REMOVE(it, ex_list); 1913 exec_sigcode_free(it->ex_sw->es_emul); 1914 kmem_free(it, sizeof(*it)); 1915 break; 1916 } 1917 } 1918 } 1919 1920 /* update execsw[] */ 1921 exec_init(0); 1922 rw_exit(&exec_lock); 1923 return 0; 1924 } 1925 1926 /* 1927 * Initialize exec structures. If init_boot is true, also does necessary 1928 * one-time initialization (it's called from main() that way). 1929 * Once system is multiuser, this should be called with exec_lock held, 1930 * i.e. via exec_{add|remove}(). 1931 */ 1932 int 1933 exec_init(int init_boot) 1934 { 1935 const struct execsw **sw; 1936 struct exec_entry *ex; 1937 SLIST_HEAD(,exec_entry) first; 1938 SLIST_HEAD(,exec_entry) any; 1939 SLIST_HEAD(,exec_entry) last; 1940 int i, sz; 1941 1942 if (init_boot) { 1943 /* do one-time initializations */ 1944 vaddr_t vmin = 0, vmax; 1945 1946 rw_init(&exec_lock); 1947 exec_map = uvm_km_suballoc(kernel_map, &vmin, &vmax, 1948 maxexec*NCARGS, VM_MAP_PAGEABLE, false, NULL); 1949 pool_init(&exec_pool, NCARGS, 0, 0, PR_NOALIGN|PR_NOTOUCH, 1950 "execargs", &exec_palloc, IPL_NONE); 1951 pool_sethardlimit(&exec_pool, maxexec, "should not happen", 0); 1952 } else { 1953 KASSERT(rw_write_held(&exec_lock)); 1954 } 1955 1956 /* Sort each entry onto the appropriate queue. */ 1957 SLIST_INIT(&first); 1958 SLIST_INIT(&any); 1959 SLIST_INIT(&last); 1960 sz = 0; 1961 LIST_FOREACH(ex, &ex_head, ex_list) { 1962 switch(ex->ex_sw->es_prio) { 1963 case EXECSW_PRIO_FIRST: 1964 SLIST_INSERT_HEAD(&first, ex, ex_slist); 1965 break; 1966 case EXECSW_PRIO_ANY: 1967 SLIST_INSERT_HEAD(&any, ex, ex_slist); 1968 break; 1969 case EXECSW_PRIO_LAST: 1970 SLIST_INSERT_HEAD(&last, ex, ex_slist); 1971 break; 1972 default: 1973 panic("%s", __func__); 1974 break; 1975 } 1976 sz++; 1977 } 1978 1979 /* 1980 * Create new execsw[]. Ensure we do not try a zero-sized 1981 * allocation. 1982 */ 1983 sw = kmem_alloc(sz * sizeof(struct execsw *) + 1, KM_SLEEP); 1984 i = 0; 1985 SLIST_FOREACH(ex, &first, ex_slist) { 1986 sw[i++] = ex->ex_sw; 1987 } 1988 SLIST_FOREACH(ex, &any, ex_slist) { 1989 sw[i++] = ex->ex_sw; 1990 } 1991 SLIST_FOREACH(ex, &last, ex_slist) { 1992 sw[i++] = ex->ex_sw; 1993 } 1994 1995 /* Replace old execsw[] and free used memory. */ 1996 if (execsw != NULL) { 1997 kmem_free(__UNCONST(execsw), 1998 nexecs * sizeof(struct execsw *) + 1); 1999 } 2000 execsw = sw; 2001 nexecs = sz; 2002 2003 /* Figure out the maximum size of an exec header. */ 2004 exec_maxhdrsz = sizeof(int); 2005 for (i = 0; i < nexecs; i++) { 2006 if (execsw[i]->es_hdrsz > exec_maxhdrsz) 2007 exec_maxhdrsz = execsw[i]->es_hdrsz; 2008 } 2009 2010 return 0; 2011 } 2012 2013 int 2014 exec_sigcode_alloc(const struct emul *e) 2015 { 2016 vaddr_t va; 2017 vsize_t sz; 2018 int error; 2019 struct uvm_object *uobj; 2020 2021 KASSERT(rw_lock_held(&exec_lock)); 2022 2023 if (e == NULL || e->e_sigobject == NULL) 2024 return 0; 2025 2026 sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode; 2027 if (sz == 0) 2028 return 0; 2029 2030 /* 2031 * Create a sigobject for this emulation. 2032 * 2033 * sigobject is an anonymous memory object (just like SYSV shared 2034 * memory) that we keep a permanent reference to and that we map 2035 * in all processes that need this sigcode. The creation is simple, 2036 * we create an object, add a permanent reference to it, map it in 2037 * kernel space, copy out the sigcode to it and unmap it. 2038 * We map it with PROT_READ|PROT_EXEC into the process just 2039 * the way sys_mmap() would map it. 2040 */ 2041 if (*e->e_sigobject == NULL) { 2042 uobj = uao_create(sz, 0); 2043 (*uobj->pgops->pgo_reference)(uobj); 2044 va = vm_map_min(kernel_map); 2045 if ((error = uvm_map(kernel_map, &va, round_page(sz), 2046 uobj, 0, 0, 2047 UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW, 2048 UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) { 2049 printf("sigcode kernel mapping failed %d\n", error); 2050 (*uobj->pgops->pgo_detach)(uobj); 2051 return error; 2052 } 2053 memcpy((void *)va, e->e_sigcode, sz); 2054 #ifdef PMAP_NEED_PROCWR 2055 pmap_procwr(&proc0, va, sz); 2056 #endif 2057 uvm_unmap(kernel_map, va, va + round_page(sz)); 2058 *e->e_sigobject = uobj; 2059 KASSERT(uobj->uo_refs == 1); 2060 } else { 2061 /* if already created, reference++ */ 2062 uobj = *e->e_sigobject; 2063 (*uobj->pgops->pgo_reference)(uobj); 2064 } 2065 2066 return 0; 2067 } 2068 2069 void 2070 exec_sigcode_free(const struct emul *e) 2071 { 2072 struct uvm_object *uobj; 2073 2074 KASSERT(rw_lock_held(&exec_lock)); 2075 2076 if (e == NULL || e->e_sigobject == NULL) 2077 return; 2078 2079 uobj = *e->e_sigobject; 2080 if (uobj == NULL) 2081 return; 2082 2083 if (uobj->uo_refs == 1) 2084 *e->e_sigobject = NULL; /* I'm the last person to reference. */ 2085 (*uobj->pgops->pgo_detach)(uobj); 2086 } 2087 2088 static int 2089 exec_sigcode_map(struct proc *p, const struct emul *e) 2090 { 2091 vaddr_t va; 2092 vsize_t sz; 2093 int error; 2094 struct uvm_object *uobj; 2095 2096 sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode; 2097 if (e->e_sigobject == NULL || sz == 0) 2098 return 0; 2099 2100 uobj = *e->e_sigobject; 2101 if (uobj == NULL) 2102 return 0; 2103 2104 /* Just a hint to uvm_map where to put it. */ 2105 va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr, 2106 round_page(sz), p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN); 2107 2108 #ifdef __alpha__ 2109 /* 2110 * Tru64 puts /sbin/loader at the end of user virtual memory, 2111 * which causes the above calculation to put the sigcode at 2112 * an invalid address. Put it just below the text instead. 2113 */ 2114 if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) { 2115 va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz); 2116 } 2117 #endif 2118 2119 (*uobj->pgops->pgo_reference)(uobj); 2120 error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz), 2121 uobj, 0, 0, 2122 UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE, 2123 UVM_ADV_RANDOM, 0)); 2124 if (error) { 2125 DPRINTF(("%s, %d: map %p " 2126 "uvm_map %#"PRIxVSIZE"@%#"PRIxVADDR" failed %d\n", 2127 __func__, __LINE__, &p->p_vmspace->vm_map, round_page(sz), 2128 va, error)); 2129 (*uobj->pgops->pgo_detach)(uobj); 2130 return error; 2131 } 2132 p->p_sigctx.ps_sigcode = (void *)va; 2133 return 0; 2134 } 2135 2136 /* 2137 * Release a refcount on spawn_exec_data and destroy memory, if this 2138 * was the last one. 2139 */ 2140 static void 2141 spawn_exec_data_release(struct spawn_exec_data *data) 2142 { 2143 2144 membar_release(); 2145 if (atomic_dec_32_nv(&data->sed_refcnt) != 0) 2146 return; 2147 membar_acquire(); 2148 2149 cv_destroy(&data->sed_cv_child_ready); 2150 mutex_destroy(&data->sed_mtx_child); 2151 2152 if (data->sed_actions) 2153 posix_spawn_fa_free(data->sed_actions, 2154 data->sed_actions->len); 2155 if (data->sed_attrs) 2156 kmem_free(data->sed_attrs, 2157 sizeof(*data->sed_attrs)); 2158 kmem_free(data, sizeof(*data)); 2159 } 2160 2161 static int 2162 handle_posix_spawn_file_actions(struct posix_spawn_file_actions *actions) 2163 { 2164 struct lwp *l = curlwp; 2165 register_t retval; 2166 int error = 0, newfd; 2167 2168 if (actions == NULL) 2169 return 0; 2170 2171 for (size_t i = 0; i < actions->len; i++) { 2172 const struct posix_spawn_file_actions_entry *fae = 2173 &actions->fae[i]; 2174 switch (fae->fae_action) { 2175 case FAE_OPEN: 2176 if (fd_getfile(fae->fae_fildes) != NULL) { 2177 error = fd_close(fae->fae_fildes); 2178 if (error) 2179 return error; 2180 } 2181 error = fd_open(fae->fae_path, fae->fae_oflag, 2182 fae->fae_mode, &newfd); 2183 if (error) 2184 return error; 2185 if (newfd != fae->fae_fildes) { 2186 error = dodup(l, newfd, 2187 fae->fae_fildes, 0, &retval); 2188 if (fd_getfile(newfd) != NULL) 2189 fd_close(newfd); 2190 } 2191 break; 2192 case FAE_DUP2: 2193 error = dodup(l, fae->fae_fildes, 2194 fae->fae_newfildes, 0, &retval); 2195 break; 2196 case FAE_CLOSE: 2197 /* 2198 * posix specifies failures from close() due to 2199 * already closed file descriptors should be ignored. 2200 * out of range filedescriptors would have been 2201 * caught earlier already. 2202 */ 2203 if (fd_getfile(fae->fae_fildes) != NULL) 2204 fd_close(fae->fae_fildes); 2205 break; 2206 case FAE_CHDIR: 2207 error = do_sys_chdir(l, fae->fae_chdir_path, 2208 UIO_SYSSPACE, &retval); 2209 break; 2210 case FAE_FCHDIR: 2211 error = do_sys_fchdir(l, fae->fae_fildes, &retval); 2212 break; 2213 } 2214 if (error) 2215 return error; 2216 } 2217 return 0; 2218 } 2219 2220 static int 2221 handle_posix_spawn_attrs(struct posix_spawnattr *attrs, struct proc *parent) 2222 { 2223 struct sigaction sigact; 2224 int error = 0; 2225 struct proc *p = curproc; 2226 struct lwp *l = curlwp; 2227 2228 if (attrs == NULL) 2229 return 0; 2230 2231 memset(&sigact, 0, sizeof(sigact)); 2232 sigact._sa_u._sa_handler = SIG_DFL; 2233 sigact.sa_flags = 0; 2234 2235 /* 2236 * set state to SSTOP so that this proc can be found by pid. 2237 * see proc_enterprp, do_sched_setparam below 2238 */ 2239 mutex_enter(&proc_lock); 2240 /* 2241 * p_stat should be SACTIVE, so we need to adjust the 2242 * parent's p_nstopchild here. For safety, just make 2243 * we're on the good side of SDEAD before we adjust. 2244 */ 2245 int ostat = p->p_stat; 2246 KASSERT(ostat < SSTOP); 2247 p->p_stat = SSTOP; 2248 p->p_waited = 0; 2249 p->p_pptr->p_nstopchild++; 2250 mutex_exit(&proc_lock); 2251 2252 /* Set process group */ 2253 if (attrs->sa_flags & POSIX_SPAWN_SETPGROUP) { 2254 pid_t mypid = p->p_pid; 2255 pid_t pgrp = attrs->sa_pgroup; 2256 2257 if (pgrp == 0) 2258 pgrp = mypid; 2259 2260 error = proc_enterpgrp(parent, mypid, pgrp, false); 2261 if (error) 2262 goto out; 2263 } 2264 2265 /* Set scheduler policy */ 2266 if (attrs->sa_flags & POSIX_SPAWN_SETSCHEDULER) 2267 error = do_sched_setparam(p->p_pid, 0, attrs->sa_schedpolicy, 2268 &attrs->sa_schedparam); 2269 else if (attrs->sa_flags & POSIX_SPAWN_SETSCHEDPARAM) { 2270 error = do_sched_setparam(parent->p_pid, 0, 2271 SCHED_NONE, &attrs->sa_schedparam); 2272 } 2273 if (error) 2274 goto out; 2275 2276 /* Reset user ID's */ 2277 if (attrs->sa_flags & POSIX_SPAWN_RESETIDS) { 2278 error = do_setresgid(l, -1, kauth_cred_getgid(l->l_cred), -1, 2279 ID_E_EQ_R | ID_E_EQ_S); 2280 if (error) 2281 return error; 2282 error = do_setresuid(l, -1, kauth_cred_getuid(l->l_cred), -1, 2283 ID_E_EQ_R | ID_E_EQ_S); 2284 if (error) 2285 goto out; 2286 } 2287 2288 /* Set signal masks/defaults */ 2289 if (attrs->sa_flags & POSIX_SPAWN_SETSIGMASK) { 2290 mutex_enter(p->p_lock); 2291 error = sigprocmask1(l, SIG_SETMASK, &attrs->sa_sigmask, NULL); 2292 mutex_exit(p->p_lock); 2293 if (error) 2294 goto out; 2295 } 2296 2297 if (attrs->sa_flags & POSIX_SPAWN_SETSIGDEF) { 2298 /* 2299 * The following sigaction call is using a sigaction 2300 * version 0 trampoline which is in the compatibility 2301 * code only. This is not a problem because for SIG_DFL 2302 * and SIG_IGN, the trampolines are now ignored. If they 2303 * were not, this would be a problem because we are 2304 * holding the exec_lock, and the compat code needs 2305 * to do the same in order to replace the trampoline 2306 * code of the process. 2307 */ 2308 for (int i = 1; i <= NSIG; i++) { 2309 if (sigismember(&attrs->sa_sigdefault, i)) 2310 sigaction1(l, i, &sigact, NULL, NULL, 0); 2311 } 2312 } 2313 out: 2314 mutex_enter(&proc_lock); 2315 p->p_stat = ostat; 2316 p->p_pptr->p_nstopchild--; 2317 mutex_exit(&proc_lock); 2318 return error; 2319 } 2320 2321 /* 2322 * A child lwp of a posix_spawn operation starts here and ends up in 2323 * cpu_spawn_return, dealing with all filedescriptor and scheduler 2324 * manipulations in between. 2325 * The parent waits for the child, as it is not clear whether the child 2326 * will be able to acquire its own exec_lock. If it can, the parent can 2327 * be released early and continue running in parallel. If not (or if the 2328 * magic debug flag is passed in the scheduler attribute struct), the 2329 * child rides on the parent's exec lock until it is ready to return to 2330 * to userland - and only then releases the parent. This method loses 2331 * concurrency, but improves error reporting. 2332 */ 2333 static void 2334 spawn_return(void *arg) 2335 { 2336 struct spawn_exec_data *spawn_data = arg; 2337 struct lwp *l = curlwp; 2338 struct proc *p = l->l_proc; 2339 int error; 2340 bool have_reflock; 2341 bool parent_is_waiting = true; 2342 2343 /* 2344 * Check if we can release parent early. 2345 * We either need to have no sed_attrs, or sed_attrs does not 2346 * have POSIX_SPAWN_RETURNERROR or one of the flags, that require 2347 * safe access to the parent proc (passed in sed_parent). 2348 * We then try to get the exec_lock, and only if that works, we can 2349 * release the parent here already. 2350 */ 2351 struct posix_spawnattr *attrs = spawn_data->sed_attrs; 2352 if ((!attrs || (attrs->sa_flags 2353 & (POSIX_SPAWN_RETURNERROR|POSIX_SPAWN_SETPGROUP)) == 0) 2354 && rw_tryenter(&exec_lock, RW_READER)) { 2355 parent_is_waiting = false; 2356 mutex_enter(&spawn_data->sed_mtx_child); 2357 KASSERT(!spawn_data->sed_child_ready); 2358 spawn_data->sed_error = 0; 2359 spawn_data->sed_child_ready = true; 2360 cv_signal(&spawn_data->sed_cv_child_ready); 2361 mutex_exit(&spawn_data->sed_mtx_child); 2362 } 2363 2364 /* don't allow debugger access yet */ 2365 rw_enter(&p->p_reflock, RW_WRITER); 2366 have_reflock = true; 2367 2368 /* handle posix_spawnattr */ 2369 error = handle_posix_spawn_attrs(attrs, spawn_data->sed_parent); 2370 if (error) 2371 goto report_error; 2372 2373 /* handle posix_spawn_file_actions */ 2374 error = handle_posix_spawn_file_actions(spawn_data->sed_actions); 2375 if (error) 2376 goto report_error; 2377 2378 /* now do the real exec */ 2379 error = execve_runproc(l, &spawn_data->sed_exec, parent_is_waiting, 2380 true); 2381 have_reflock = false; 2382 if (error == EJUSTRETURN) 2383 error = 0; 2384 else if (error) 2385 goto report_error; 2386 2387 if (parent_is_waiting) { 2388 mutex_enter(&spawn_data->sed_mtx_child); 2389 KASSERT(!spawn_data->sed_child_ready); 2390 spawn_data->sed_error = 0; 2391 spawn_data->sed_child_ready = true; 2392 cv_signal(&spawn_data->sed_cv_child_ready); 2393 mutex_exit(&spawn_data->sed_mtx_child); 2394 } 2395 2396 /* release our refcount on the data */ 2397 spawn_exec_data_release(spawn_data); 2398 2399 if ((p->p_slflag & (PSL_TRACED|PSL_TRACEDCHILD)) == 2400 (PSL_TRACED|PSL_TRACEDCHILD)) { 2401 eventswitchchild(p, TRAP_CHLD, PTRACE_POSIX_SPAWN); 2402 } 2403 2404 /* and finally: leave to userland for the first time */ 2405 cpu_spawn_return(l); 2406 2407 /* NOTREACHED */ 2408 return; 2409 2410 report_error: 2411 if (have_reflock) { 2412 /* 2413 * We have not passed through execve_runproc(), 2414 * which would have released the p_reflock and also 2415 * taken ownership of the sed_exec part of spawn_data, 2416 * so release/free both here. 2417 */ 2418 rw_exit(&p->p_reflock); 2419 execve_free_data(&spawn_data->sed_exec); 2420 } 2421 2422 if (parent_is_waiting) { 2423 /* pass error to parent */ 2424 mutex_enter(&spawn_data->sed_mtx_child); 2425 KASSERT(!spawn_data->sed_child_ready); 2426 spawn_data->sed_error = error; 2427 spawn_data->sed_child_ready = true; 2428 cv_signal(&spawn_data->sed_cv_child_ready); 2429 mutex_exit(&spawn_data->sed_mtx_child); 2430 } else { 2431 rw_exit(&exec_lock); 2432 } 2433 2434 /* release our refcount on the data */ 2435 spawn_exec_data_release(spawn_data); 2436 2437 /* done, exit */ 2438 mutex_enter(p->p_lock); 2439 /* 2440 * Posix explicitly asks for an exit code of 127 if we report 2441 * errors from the child process - so, unfortunately, there 2442 * is no way to report a more exact error code. 2443 * A NetBSD specific workaround is POSIX_SPAWN_RETURNERROR as 2444 * flag bit in the attrp argument to posix_spawn(2), see above. 2445 */ 2446 exit1(l, 127, 0); 2447 } 2448 2449 static __inline char ** 2450 posix_spawn_fae_path(struct posix_spawn_file_actions_entry *fae) 2451 { 2452 switch (fae->fae_action) { 2453 case FAE_OPEN: 2454 return &fae->fae_path; 2455 case FAE_CHDIR: 2456 return &fae->fae_chdir_path; 2457 default: 2458 return NULL; 2459 } 2460 } 2461 2462 void 2463 posix_spawn_fa_free(struct posix_spawn_file_actions *fa, size_t len) 2464 { 2465 2466 for (size_t i = 0; i < len; i++) { 2467 char **pathp = posix_spawn_fae_path(&fa->fae[i]); 2468 if (pathp) 2469 kmem_strfree(*pathp); 2470 } 2471 if (fa->len > 0) 2472 kmem_free(fa->fae, sizeof(*fa->fae) * fa->len); 2473 kmem_free(fa, sizeof(*fa)); 2474 } 2475 2476 static int 2477 posix_spawn_fa_alloc(struct posix_spawn_file_actions **fap, 2478 const struct posix_spawn_file_actions *ufa, rlim_t lim) 2479 { 2480 struct posix_spawn_file_actions *fa; 2481 struct posix_spawn_file_actions_entry *fae; 2482 char *pbuf = NULL; 2483 int error; 2484 size_t i = 0; 2485 2486 fa = kmem_alloc(sizeof(*fa), KM_SLEEP); 2487 error = copyin(ufa, fa, sizeof(*fa)); 2488 if (error || fa->len == 0) { 2489 kmem_free(fa, sizeof(*fa)); 2490 return error; /* 0 if not an error, and len == 0 */ 2491 } 2492 2493 if (fa->len > lim) { 2494 kmem_free(fa, sizeof(*fa)); 2495 return SET_ERROR(EINVAL); 2496 } 2497 2498 fa->size = fa->len; 2499 size_t fal = fa->len * sizeof(*fae); 2500 fae = fa->fae; 2501 fa->fae = kmem_alloc(fal, KM_SLEEP); 2502 error = copyin(fae, fa->fae, fal); 2503 if (error) 2504 goto out; 2505 2506 pbuf = PNBUF_GET(); 2507 for (; i < fa->len; i++) { 2508 char **pathp = posix_spawn_fae_path(&fa->fae[i]); 2509 if (pathp == NULL) 2510 continue; 2511 error = copyinstr(*pathp, pbuf, MAXPATHLEN, &fal); 2512 if (error) 2513 goto out; 2514 *pathp = kmem_alloc(fal, KM_SLEEP); 2515 memcpy(*pathp, pbuf, fal); 2516 } 2517 PNBUF_PUT(pbuf); 2518 2519 *fap = fa; 2520 return 0; 2521 out: 2522 if (pbuf) 2523 PNBUF_PUT(pbuf); 2524 posix_spawn_fa_free(fa, i); 2525 return error; 2526 } 2527 2528 /* 2529 * N.B. increments nprocs upon success. Callers need to drop nprocs if 2530 * they fail for some other reason. 2531 */ 2532 int 2533 check_posix_spawn(struct lwp *l1) 2534 { 2535 int error, tnprocs, count; 2536 uid_t uid; 2537 struct proc *p1; 2538 2539 p1 = l1->l_proc; 2540 uid = kauth_cred_getuid(l1->l_cred); 2541 tnprocs = atomic_inc_uint_nv(&nprocs); 2542 2543 /* 2544 * Although process entries are dynamically created, we still keep 2545 * a global limit on the maximum number we will create. 2546 */ 2547 if (__predict_false(tnprocs >= maxproc)) 2548 error = -1; 2549 else 2550 error = kauth_authorize_process(l1->l_cred, 2551 KAUTH_PROCESS_FORK, p1, KAUTH_ARG(tnprocs), NULL, NULL); 2552 2553 if (error) { 2554 atomic_dec_uint(&nprocs); 2555 return SET_ERROR(EAGAIN); 2556 } 2557 2558 /* 2559 * Enforce limits. 2560 */ 2561 count = chgproccnt(uid, 1); 2562 if (kauth_authorize_process(l1->l_cred, KAUTH_PROCESS_RLIMIT, 2563 p1, KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS), 2564 &p1->p_rlimit[RLIMIT_NPROC], KAUTH_ARG(RLIMIT_NPROC)) != 0 && 2565 __predict_false(count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) { 2566 (void)chgproccnt(uid, -1); 2567 atomic_dec_uint(&nprocs); 2568 return SET_ERROR(EAGAIN); 2569 } 2570 2571 return 0; 2572 } 2573 2574 int 2575 do_posix_spawn(struct lwp *l1, pid_t *pid_res, bool *child_ok, const char *path, 2576 struct posix_spawn_file_actions *fa, 2577 struct posix_spawnattr *sa, 2578 char *const *argv, char *const *envp, 2579 execve_fetch_element_t fetch) 2580 { 2581 2582 struct proc *p1, *p2; 2583 struct lwp *l2; 2584 int error; 2585 struct spawn_exec_data *spawn_data; 2586 vaddr_t uaddr = 0; 2587 pid_t pid; 2588 bool have_exec_lock = false; 2589 2590 p1 = l1->l_proc; 2591 2592 /* Allocate and init spawn_data */ 2593 spawn_data = kmem_zalloc(sizeof(*spawn_data), KM_SLEEP); 2594 spawn_data->sed_refcnt = 1; /* only parent so far */ 2595 cv_init(&spawn_data->sed_cv_child_ready, "pspawn"); 2596 mutex_init(&spawn_data->sed_mtx_child, MUTEX_DEFAULT, IPL_NONE); 2597 mutex_enter(&spawn_data->sed_mtx_child); 2598 2599 /* 2600 * Do the first part of the exec now, collect state 2601 * in spawn_data. 2602 */ 2603 error = execve_loadvm(l1, true, path, -1, argv, 2604 envp, fetch, &spawn_data->sed_exec); 2605 if (error == EJUSTRETURN) 2606 error = 0; 2607 else if (error) 2608 goto error_exit; 2609 2610 have_exec_lock = true; 2611 2612 /* 2613 * Allocate virtual address space for the U-area now, while it 2614 * is still easy to abort the fork operation if we're out of 2615 * kernel virtual address space. 2616 */ 2617 uaddr = uvm_uarea_alloc(); 2618 if (__predict_false(uaddr == 0)) { 2619 error = SET_ERROR(ENOMEM); 2620 goto error_exit; 2621 } 2622 2623 /* 2624 * Allocate new proc. Borrow proc0 vmspace for it, we will 2625 * replace it with its own before returning to userland 2626 * in the child. 2627 */ 2628 p2 = proc_alloc(); 2629 if (p2 == NULL) { 2630 /* We were unable to allocate a process ID. */ 2631 error = SET_ERROR(EAGAIN); 2632 goto error_exit; 2633 } 2634 2635 /* 2636 * This is a point of no return, we will have to go through 2637 * the child proc to properly clean it up past this point. 2638 */ 2639 pid = p2->p_pid; 2640 2641 /* 2642 * Make a proc table entry for the new process. 2643 * Start by zeroing the section of proc that is zero-initialized, 2644 * then copy the section that is copied directly from the parent. 2645 */ 2646 memset(&p2->p_startzero, 0, 2647 (unsigned) ((char *)&p2->p_endzero - (char *)&p2->p_startzero)); 2648 memcpy(&p2->p_startcopy, &p1->p_startcopy, 2649 (unsigned) ((char *)&p2->p_endcopy - (char *)&p2->p_startcopy)); 2650 2651 /* 2652 * Allocate an empty user vmspace for the new process now. 2653 * The min/max and topdown parameters given here are just placeholders, 2654 * the right values will be assigned in uvmspace_exec(). 2655 */ 2656 p2->p_vmspace = uvmspace_alloc(exec_vm_minaddr(VM_MIN_ADDRESS), 2657 VM_MAXUSER_ADDRESS, true); 2658 2659 TAILQ_INIT(&p2->p_sigpend.sp_info); 2660 2661 LIST_INIT(&p2->p_lwps); 2662 LIST_INIT(&p2->p_sigwaiters); 2663 2664 /* 2665 * Duplicate sub-structures as needed. 2666 * Increase reference counts on shared objects. 2667 * Inherit flags we want to keep. The flags related to SIGCHLD 2668 * handling are important in order to keep a consistent behaviour 2669 * for the child after the fork. If we are a 32-bit process, the 2670 * child will be too. 2671 */ 2672 p2->p_flag = 2673 p1->p_flag & (PK_SUGID | PK_NOCLDWAIT | PK_CLDSIGIGN | PK_32); 2674 p2->p_emul = p1->p_emul; 2675 p2->p_execsw = p1->p_execsw; 2676 2677 mutex_init(&p2->p_stmutex, MUTEX_DEFAULT, IPL_HIGH); 2678 mutex_init(&p2->p_auxlock, MUTEX_DEFAULT, IPL_NONE); 2679 rw_init(&p2->p_reflock); 2680 cv_init(&p2->p_waitcv, "wait"); 2681 cv_init(&p2->p_lwpcv, "lwpwait"); 2682 2683 p2->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE); 2684 2685 kauth_proc_fork(p1, p2); 2686 2687 p2->p_raslist = NULL; 2688 p2->p_fd = fd_copy(); 2689 2690 /* XXX racy */ 2691 p2->p_mqueue_cnt = p1->p_mqueue_cnt; 2692 2693 p2->p_cwdi = cwdinit(); 2694 2695 /* 2696 * Note: p_limit (rlimit stuff) is copy-on-write, so normally 2697 * we just need increase pl_refcnt. 2698 */ 2699 if (!p1->p_limit->pl_writeable) { 2700 lim_addref(p1->p_limit); 2701 p2->p_limit = p1->p_limit; 2702 } else { 2703 p2->p_limit = lim_copy(p1->p_limit); 2704 } 2705 2706 p2->p_lflag = 0; 2707 l1->l_vforkwaiting = false; 2708 p2->p_sflag = 0; 2709 p2->p_slflag = 0; 2710 p2->p_pptr = p1; 2711 p2->p_ppid = p1->p_pid; 2712 LIST_INIT(&p2->p_children); 2713 2714 p2->p_aio = NULL; 2715 2716 #ifdef KTRACE 2717 /* 2718 * Copy traceflag and tracefile if enabled. 2719 * If not inherited, these were zeroed above. 2720 */ 2721 if (p1->p_traceflag & KTRFAC_INHERIT) { 2722 mutex_enter(&ktrace_lock); 2723 p2->p_traceflag = p1->p_traceflag; 2724 if ((p2->p_tracep = p1->p_tracep) != NULL) 2725 ktradref(p2); 2726 mutex_exit(&ktrace_lock); 2727 } 2728 #endif 2729 2730 /* 2731 * Create signal actions for the child process. 2732 */ 2733 p2->p_sigacts = sigactsinit(p1, 0); 2734 mutex_enter(p1->p_lock); 2735 p2->p_sflag |= 2736 (p1->p_sflag & (PS_STOPFORK | PS_STOPEXEC | PS_NOCLDSTOP)); 2737 sched_proc_fork(p1, p2); 2738 mutex_exit(p1->p_lock); 2739 2740 p2->p_stflag = p1->p_stflag; 2741 2742 /* 2743 * p_stats. 2744 * Copy parts of p_stats, and zero out the rest. 2745 */ 2746 p2->p_stats = pstatscopy(p1->p_stats); 2747 2748 /* copy over machdep flags to the new proc */ 2749 cpu_proc_fork(p1, p2); 2750 2751 /* 2752 * Prepare remaining parts of spawn data 2753 */ 2754 spawn_data->sed_actions = fa; 2755 spawn_data->sed_attrs = sa; 2756 2757 spawn_data->sed_parent = p1; 2758 2759 /* create LWP */ 2760 lwp_create(l1, p2, uaddr, 0, NULL, 0, spawn_return, spawn_data, 2761 &l2, l1->l_class, &l1->l_sigmask, &l1->l_sigstk); 2762 l2->l_ctxlink = NULL; /* reset ucontext link */ 2763 2764 /* 2765 * Copy the credential so other references don't see our changes. 2766 * Test to see if this is necessary first, since in the common case 2767 * we won't need a private reference. 2768 */ 2769 if (kauth_cred_geteuid(l2->l_cred) != kauth_cred_getsvuid(l2->l_cred) || 2770 kauth_cred_getegid(l2->l_cred) != kauth_cred_getsvgid(l2->l_cred)) { 2771 l2->l_cred = kauth_cred_copy(l2->l_cred); 2772 kauth_cred_setsvuid(l2->l_cred, kauth_cred_geteuid(l2->l_cred)); 2773 kauth_cred_setsvgid(l2->l_cred, kauth_cred_getegid(l2->l_cred)); 2774 } 2775 2776 /* Update the master credentials. */ 2777 if (l2->l_cred != p2->p_cred) { 2778 kauth_cred_t ocred; 2779 mutex_enter(p2->p_lock); 2780 ocred = p2->p_cred; 2781 p2->p_cred = kauth_cred_hold(l2->l_cred); 2782 mutex_exit(p2->p_lock); 2783 kauth_cred_free(ocred); 2784 } 2785 2786 *child_ok = true; 2787 spawn_data->sed_refcnt = 2; /* child gets it as well */ 2788 #if 0 2789 l2->l_nopreempt = 1; /* start it non-preemptable */ 2790 #endif 2791 2792 /* 2793 * It's now safe for the scheduler and other processes to see the 2794 * child process. 2795 */ 2796 mutex_enter(&proc_lock); 2797 2798 if (p1->p_session->s_ttyvp != NULL && p1->p_lflag & PL_CONTROLT) 2799 p2->p_lflag |= PL_CONTROLT; 2800 2801 LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling); 2802 p2->p_exitsig = SIGCHLD; /* signal for parent on exit */ 2803 2804 if ((p1->p_slflag & (PSL_TRACEPOSIX_SPAWN|PSL_TRACED)) == 2805 (PSL_TRACEPOSIX_SPAWN|PSL_TRACED)) { 2806 proc_changeparent(p2, p1->p_pptr); 2807 SET(p2->p_slflag, PSL_TRACEDCHILD); 2808 } 2809 2810 p2->p_oppid = p1->p_pid; /* Remember the original parent id. */ 2811 2812 LIST_INSERT_AFTER(p1, p2, p_pglist); 2813 LIST_INSERT_HEAD(&allproc, p2, p_list); 2814 2815 p2->p_trace_enabled = trace_is_enabled(p2); 2816 #ifdef __HAVE_SYSCALL_INTERN 2817 (*p2->p_emul->e_syscall_intern)(p2); 2818 #endif 2819 2820 /* 2821 * Make child runnable, set start time, and add to run queue except 2822 * if the parent requested the child to start in SSTOP state. 2823 */ 2824 mutex_enter(p2->p_lock); 2825 2826 getmicrotime(&p2->p_stats->p_start); 2827 2828 lwp_lock(l2); 2829 KASSERT(p2->p_nrlwps == 1); 2830 KASSERT(l2->l_stat == LSIDL); 2831 p2->p_nrlwps = 1; 2832 p2->p_stat = SACTIVE; 2833 setrunnable(l2); 2834 /* LWP now unlocked */ 2835 2836 mutex_exit(p2->p_lock); 2837 mutex_exit(&proc_lock); 2838 2839 while (!spawn_data->sed_child_ready) { 2840 cv_wait(&spawn_data->sed_cv_child_ready, 2841 &spawn_data->sed_mtx_child); 2842 } 2843 error = spawn_data->sed_error; 2844 mutex_exit(&spawn_data->sed_mtx_child); 2845 spawn_exec_data_release(spawn_data); 2846 2847 rw_exit(&p1->p_reflock); 2848 rw_exit(&exec_lock); 2849 have_exec_lock = false; 2850 2851 *pid_res = pid; 2852 2853 if (error) 2854 return error; 2855 2856 if (p1->p_slflag & PSL_TRACED) { 2857 /* Paranoid check */ 2858 mutex_enter(&proc_lock); 2859 if ((p1->p_slflag & (PSL_TRACEPOSIX_SPAWN|PSL_TRACED)) != 2860 (PSL_TRACEPOSIX_SPAWN|PSL_TRACED)) { 2861 mutex_exit(&proc_lock); 2862 return 0; 2863 } 2864 2865 mutex_enter(p1->p_lock); 2866 eventswitch(TRAP_CHLD, PTRACE_POSIX_SPAWN, pid); 2867 } 2868 return 0; 2869 2870 error_exit: 2871 if (have_exec_lock) { 2872 execve_free_data(&spawn_data->sed_exec); 2873 rw_exit(&p1->p_reflock); 2874 rw_exit(&exec_lock); 2875 } 2876 mutex_exit(&spawn_data->sed_mtx_child); 2877 spawn_exec_data_release(spawn_data); 2878 if (uaddr != 0) 2879 uvm_uarea_free(uaddr); 2880 2881 return error; 2882 } 2883 2884 int 2885 sys_posix_spawn(struct lwp *l1, const struct sys_posix_spawn_args *uap, 2886 register_t *retval) 2887 { 2888 /* { 2889 syscallarg(pid_t *) pid; 2890 syscallarg(const char *) path; 2891 syscallarg(const struct posix_spawn_file_actions *) file_actions; 2892 syscallarg(const struct posix_spawnattr *) attrp; 2893 syscallarg(char *const *) argv; 2894 syscallarg(char *const *) envp; 2895 } */ 2896 2897 int error; 2898 struct posix_spawn_file_actions *fa = NULL; 2899 struct posix_spawnattr *sa = NULL; 2900 pid_t pid; 2901 bool child_ok = false; 2902 rlim_t max_fileactions; 2903 proc_t *p = l1->l_proc; 2904 2905 /* check_posix_spawn() increments nprocs for us. */ 2906 error = check_posix_spawn(l1); 2907 if (error) { 2908 *retval = error; 2909 return 0; 2910 } 2911 2912 /* copy in file_actions struct */ 2913 if (SCARG(uap, file_actions) != NULL) { 2914 max_fileactions = 2 * uimin(p->p_rlimit[RLIMIT_NOFILE].rlim_cur, 2915 maxfiles); 2916 error = posix_spawn_fa_alloc(&fa, SCARG(uap, file_actions), 2917 max_fileactions); 2918 if (error) 2919 goto error_exit; 2920 } 2921 2922 /* copyin posix_spawnattr struct */ 2923 if (SCARG(uap, attrp) != NULL) { 2924 sa = kmem_alloc(sizeof(*sa), KM_SLEEP); 2925 error = copyin(SCARG(uap, attrp), sa, sizeof(*sa)); 2926 if (error) 2927 goto error_exit; 2928 } 2929 2930 /* 2931 * Do the spawn 2932 */ 2933 error = do_posix_spawn(l1, &pid, &child_ok, SCARG(uap, path), fa, sa, 2934 SCARG(uap, argv), SCARG(uap, envp), execve_fetch_element); 2935 if (error) 2936 goto error_exit; 2937 2938 if (error == 0 && SCARG(uap, pid) != NULL) 2939 error = copyout(&pid, SCARG(uap, pid), sizeof(pid)); 2940 2941 *retval = error; 2942 return 0; 2943 2944 error_exit: 2945 if (!child_ok) { 2946 (void)chgproccnt(kauth_cred_getuid(l1->l_cred), -1); 2947 atomic_dec_uint(&nprocs); 2948 2949 if (sa) 2950 kmem_free(sa, sizeof(*sa)); 2951 if (fa) 2952 posix_spawn_fa_free(fa, fa->len); 2953 } 2954 2955 *retval = error; 2956 return 0; 2957 } 2958 2959 void 2960 exec_free_emul_arg(struct exec_package *epp) 2961 { 2962 if (epp->ep_emul_arg_free != NULL) { 2963 KASSERT(epp->ep_emul_arg != NULL); 2964 (*epp->ep_emul_arg_free)(epp->ep_emul_arg); 2965 epp->ep_emul_arg_free = NULL; 2966 epp->ep_emul_arg = NULL; 2967 } else { 2968 KASSERT(epp->ep_emul_arg == NULL); 2969 } 2970 } 2971 2972 #ifdef DEBUG_EXEC 2973 static void 2974 dump_vmcmds(const struct exec_package * const epp, size_t x, int error) 2975 { 2976 struct exec_vmcmd *vp = &epp->ep_vmcmds.evs_cmds[0]; 2977 size_t j; 2978 2979 if (error == 0) 2980 DPRINTF(("vmcmds %u\n", epp->ep_vmcmds.evs_used)); 2981 else 2982 DPRINTF(("vmcmds %zu/%u, error %d\n", x, 2983 epp->ep_vmcmds.evs_used, error)); 2984 2985 for (j = 0; j < epp->ep_vmcmds.evs_used; j++) { 2986 DPRINTF(("vmcmd[%zu] = vmcmd_map_%s %#" 2987 PRIxVADDR"/%#"PRIxVSIZE" fd@%#" 2988 PRIxVSIZE" prot=0%o flags=%d\n", j, 2989 vp[j].ev_proc == vmcmd_map_pagedvn ? 2990 "pagedvn" : 2991 vp[j].ev_proc == vmcmd_map_readvn ? 2992 "readvn" : 2993 vp[j].ev_proc == vmcmd_map_zero ? 2994 "zero" : "*unknown*", 2995 vp[j].ev_addr, vp[j].ev_len, 2996 vp[j].ev_offset, vp[j].ev_prot, 2997 vp[j].ev_flags)); 2998 if (error != 0 && j == x) 2999 DPRINTF((" ^--- failed\n")); 3000 } 3001 } 3002 #endif 3003