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