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