1 /* $OpenBSD: kern_fork.c,v 1.221 2020/01/21 15:20:47 visa Exp $ */ 2 /* $NetBSD: kern_fork.c,v 1.29 1996/02/09 18:59:34 christos Exp $ */ 3 4 /* 5 * Copyright (c) 1982, 1986, 1989, 1991, 1993 6 * The Regents of the University of California. All rights reserved. 7 * (c) UNIX System Laboratories, Inc. 8 * All or some portions of this file are derived from material licensed 9 * to the University of California by American Telephone and Telegraph 10 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 11 * the permission of UNIX System Laboratories, Inc. 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 3. Neither the name of the University nor the names of its contributors 22 * may be used to endorse or promote products derived from this software 23 * without specific prior written permission. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 35 * SUCH DAMAGE. 36 * 37 * @(#)kern_fork.c 8.6 (Berkeley) 4/8/94 38 */ 39 40 #include <sys/param.h> 41 #include <sys/systm.h> 42 #include <sys/filedesc.h> 43 #include <sys/kernel.h> 44 #include <sys/malloc.h> 45 #include <sys/mount.h> 46 #include <sys/proc.h> 47 #include <sys/exec.h> 48 #include <sys/resourcevar.h> 49 #include <sys/signalvar.h> 50 #include <sys/vnode.h> 51 #include <sys/vmmeter.h> 52 #include <sys/acct.h> 53 #include <sys/ktrace.h> 54 #include <sys/sched.h> 55 #include <sys/sysctl.h> 56 #include <sys/pool.h> 57 #include <sys/mman.h> 58 #include <sys/ptrace.h> 59 #include <sys/atomic.h> 60 #include <sys/pledge.h> 61 #include <sys/unistd.h> 62 63 #include <sys/syscallargs.h> 64 65 #include <uvm/uvm.h> 66 #include <machine/tcb.h> 67 68 int nprocesses = 1; /* process 0 */ 69 int nthreads = 1; /* proc 0 */ 70 int randompid; /* when set to 1, pid's go random */ 71 struct forkstat forkstat; 72 73 void fork_return(void *); 74 pid_t alloctid(void); 75 pid_t allocpid(void); 76 int ispidtaken(pid_t); 77 78 void unveil_copy(struct process *parent, struct process *child); 79 80 struct proc *thread_new(struct proc *_parent, vaddr_t _uaddr); 81 struct process *process_new(struct proc *, struct process *, int); 82 int fork_check_maxthread(uid_t _uid); 83 84 void 85 fork_return(void *arg) 86 { 87 struct proc *p = (struct proc *)arg; 88 89 if (p->p_p->ps_flags & PS_TRACED) 90 psignal(p, SIGTRAP); 91 92 child_return(p); 93 } 94 95 int 96 sys_fork(struct proc *p, void *v, register_t *retval) 97 { 98 int flags; 99 100 flags = FORK_FORK; 101 if (p->p_p->ps_ptmask & PTRACE_FORK) 102 flags |= FORK_PTRACE; 103 return fork1(p, flags, fork_return, NULL, retval, NULL); 104 } 105 106 int 107 sys_vfork(struct proc *p, void *v, register_t *retval) 108 { 109 return fork1(p, FORK_VFORK|FORK_PPWAIT, child_return, NULL, 110 retval, NULL); 111 } 112 113 int 114 sys___tfork(struct proc *p, void *v, register_t *retval) 115 { 116 struct sys___tfork_args /* { 117 syscallarg(const struct __tfork) *param; 118 syscallarg(size_t) psize; 119 } */ *uap = v; 120 size_t psize = SCARG(uap, psize); 121 struct __tfork param = { 0 }; 122 int error; 123 124 if (psize == 0 || psize > sizeof(param)) 125 return EINVAL; 126 if ((error = copyin(SCARG(uap, param), ¶m, psize))) 127 return error; 128 #ifdef KTRACE 129 if (KTRPOINT(p, KTR_STRUCT)) 130 ktrstruct(p, "tfork", ¶m, sizeof(param)); 131 #endif 132 #ifdef TCB_INVALID 133 if (TCB_INVALID(param.tf_tcb)) 134 return EINVAL; 135 #endif /* TCB_INVALID */ 136 137 return thread_fork(p, param.tf_stack, param.tf_tcb, param.tf_tid, 138 retval); 139 } 140 141 /* 142 * Allocate and initialize a thread (proc) structure, given the parent thread. 143 */ 144 struct proc * 145 thread_new(struct proc *parent, vaddr_t uaddr) 146 { 147 struct proc *p; 148 149 p = pool_get(&proc_pool, PR_WAITOK); 150 p->p_stat = SIDL; /* protect against others */ 151 p->p_flag = 0; 152 153 /* 154 * Make a proc table entry for the new process. 155 * Start by zeroing the section of proc that is zero-initialized, 156 * then copy the section that is copied directly from the parent. 157 */ 158 memset(&p->p_startzero, 0, 159 (caddr_t)&p->p_endzero - (caddr_t)&p->p_startzero); 160 memcpy(&p->p_startcopy, &parent->p_startcopy, 161 (caddr_t)&p->p_endcopy - (caddr_t)&p->p_startcopy); 162 crhold(p->p_ucred); 163 p->p_addr = (struct user *)uaddr; 164 165 /* 166 * Initialize the timeouts. 167 */ 168 timeout_set(&p->p_sleep_to, endtsleep, p); 169 170 return p; 171 } 172 173 /* 174 * Initialize common bits of a process structure, given the initial thread. 175 */ 176 void 177 process_initialize(struct process *pr, struct proc *p) 178 { 179 /* initialize the thread links */ 180 pr->ps_mainproc = p; 181 TAILQ_INIT(&pr->ps_threads); 182 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 183 pr->ps_refcnt = 1; 184 p->p_p = pr; 185 186 /* give the process the same creds as the initial thread */ 187 pr->ps_ucred = p->p_ucred; 188 crhold(pr->ps_ucred); 189 KASSERT(p->p_ucred->cr_ref >= 2); /* new thread and new process */ 190 191 LIST_INIT(&pr->ps_children); 192 LIST_INIT(&pr->ps_ftlist); 193 LIST_INIT(&pr->ps_sigiolst); 194 TAILQ_INIT(&pr->ps_tslpqueue); 195 196 rw_init(&pr->ps_lock, "pslock"); 197 mtx_init(&pr->ps_mtx, IPL_MPFLOOR); 198 199 timeout_set(&pr->ps_realit_to, realitexpire, pr); 200 timeout_set(&pr->ps_rucheck_to, rucheck, pr); 201 } 202 203 204 /* 205 * Allocate and initialize a new process. 206 */ 207 struct process * 208 process_new(struct proc *p, struct process *parent, int flags) 209 { 210 struct process *pr; 211 212 pr = pool_get(&process_pool, PR_WAITOK); 213 214 /* 215 * Make a process structure for the new process. 216 * Start by zeroing the section of proc that is zero-initialized, 217 * then copy the section that is copied directly from the parent. 218 */ 219 memset(&pr->ps_startzero, 0, 220 (caddr_t)&pr->ps_endzero - (caddr_t)&pr->ps_startzero); 221 memcpy(&pr->ps_startcopy, &parent->ps_startcopy, 222 (caddr_t)&pr->ps_endcopy - (caddr_t)&pr->ps_startcopy); 223 224 process_initialize(pr, p); 225 pr->ps_pid = allocpid(); 226 lim_fork(parent, pr); 227 228 /* post-copy fixups */ 229 pr->ps_pptr = parent; 230 231 /* bump references to the text vnode (for sysctl) */ 232 pr->ps_textvp = parent->ps_textvp; 233 if (pr->ps_textvp) 234 vref(pr->ps_textvp); 235 236 /* copy unveil if unveil is active */ 237 unveil_copy(parent, pr); 238 239 pr->ps_flags = parent->ps_flags & 240 (PS_SUGID | PS_SUGIDEXEC | PS_PLEDGE | PS_EXECPLEDGE | PS_WXNEEDED); 241 if (parent->ps_session->s_ttyvp != NULL) 242 pr->ps_flags |= parent->ps_flags & PS_CONTROLT; 243 244 /* 245 * Duplicate sub-structures as needed. 246 * Increase reference counts on shared objects. 247 */ 248 if (flags & FORK_SHAREFILES) 249 pr->ps_fd = fdshare(parent); 250 else 251 pr->ps_fd = fdcopy(parent); 252 if (flags & FORK_SIGHAND) 253 pr->ps_sigacts = sigactsshare(parent); 254 else 255 pr->ps_sigacts = sigactsinit(parent); 256 if (flags & FORK_SHAREVM) 257 pr->ps_vmspace = uvmspace_share(parent); 258 else 259 pr->ps_vmspace = uvmspace_fork(parent); 260 261 if (parent->ps_flags & PS_PROFIL) 262 startprofclock(pr); 263 if (flags & FORK_PTRACE) 264 pr->ps_flags |= parent->ps_flags & PS_TRACED; 265 if (flags & FORK_NOZOMBIE) 266 pr->ps_flags |= PS_NOZOMBIE; 267 if (flags & FORK_SYSTEM) 268 pr->ps_flags |= PS_SYSTEM; 269 270 /* mark as embryo to protect against others */ 271 pr->ps_flags |= PS_EMBRYO; 272 273 /* Force visibility of all of the above changes */ 274 membar_producer(); 275 276 /* it's sufficiently inited to be globally visible */ 277 LIST_INSERT_HEAD(&allprocess, pr, ps_list); 278 279 return pr; 280 } 281 282 /* print the 'table full' message once per 10 seconds */ 283 struct timeval fork_tfmrate = { 10, 0 }; 284 285 int 286 fork_check_maxthread(uid_t uid) 287 { 288 /* 289 * Although process entries are dynamically created, we still keep 290 * a global limit on the maximum number we will create. We reserve 291 * the last 5 processes to root. The variable nprocesses is the 292 * current number of processes, maxprocess is the limit. Similar 293 * rules for threads (struct proc): we reserve the last 5 to root; 294 * the variable nthreads is the current number of procs, maxthread is 295 * the limit. 296 */ 297 if ((nthreads >= maxthread - 5 && uid != 0) || nthreads >= maxthread) { 298 static struct timeval lasttfm; 299 300 if (ratecheck(&lasttfm, &fork_tfmrate)) 301 tablefull("proc"); 302 return EAGAIN; 303 } 304 nthreads++; 305 306 return 0; 307 } 308 309 static inline void 310 fork_thread_start(struct proc *p, struct proc *parent, int flags) 311 { 312 struct cpu_info *ci; 313 int s; 314 315 SCHED_LOCK(s); 316 ci = sched_choosecpu_fork(parent, flags); 317 setrunqueue(ci, p, p->p_priority); 318 SCHED_UNLOCK(s); 319 } 320 321 int 322 fork1(struct proc *curp, int flags, void (*func)(void *), void *arg, 323 register_t *retval, struct proc **rnewprocp) 324 { 325 struct process *curpr = curp->p_p; 326 struct process *pr; 327 struct proc *p; 328 uid_t uid = curp->p_ucred->cr_ruid; 329 struct vmspace *vm; 330 int count; 331 vaddr_t uaddr; 332 int error; 333 struct ptrace_state *newptstat = NULL; 334 335 KASSERT((flags & ~(FORK_FORK | FORK_VFORK | FORK_PPWAIT | FORK_PTRACE 336 | FORK_IDLE | FORK_SHAREVM | FORK_SHAREFILES | FORK_NOZOMBIE 337 | FORK_SYSTEM | FORK_SIGHAND)) == 0); 338 KASSERT((flags & FORK_SIGHAND) == 0 || (flags & FORK_SHAREVM)); 339 KASSERT(func != NULL); 340 341 if ((error = fork_check_maxthread(uid))) 342 return error; 343 344 if ((nprocesses >= maxprocess - 5 && uid != 0) || 345 nprocesses >= maxprocess) { 346 static struct timeval lasttfm; 347 348 if (ratecheck(&lasttfm, &fork_tfmrate)) 349 tablefull("process"); 350 nthreads--; 351 return EAGAIN; 352 } 353 nprocesses++; 354 355 /* 356 * Increment the count of processes running with this uid. 357 * Don't allow a nonprivileged user to exceed their current limit. 358 */ 359 count = chgproccnt(uid, 1); 360 if (uid != 0 && count > lim_cur(RLIMIT_NPROC)) { 361 (void)chgproccnt(uid, -1); 362 nprocesses--; 363 nthreads--; 364 return EAGAIN; 365 } 366 367 uaddr = uvm_uarea_alloc(); 368 if (uaddr == 0) { 369 (void)chgproccnt(uid, -1); 370 nprocesses--; 371 nthreads--; 372 return (ENOMEM); 373 } 374 375 /* 376 * From now on, we're committed to the fork and cannot fail. 377 */ 378 p = thread_new(curp, uaddr); 379 pr = process_new(p, curpr, flags); 380 381 p->p_fd = pr->ps_fd; 382 p->p_vmspace = pr->ps_vmspace; 383 if (pr->ps_flags & PS_SYSTEM) 384 atomic_setbits_int(&p->p_flag, P_SYSTEM); 385 386 if (flags & FORK_PPWAIT) { 387 atomic_setbits_int(&pr->ps_flags, PS_PPWAIT); 388 atomic_setbits_int(&curpr->ps_flags, PS_ISPWAIT); 389 } 390 391 #ifdef KTRACE 392 /* 393 * Copy traceflag and tracefile if enabled. 394 * If not inherited, these were zeroed above. 395 */ 396 if (curpr->ps_traceflag & KTRFAC_INHERIT) 397 ktrsettrace(pr, curpr->ps_traceflag, curpr->ps_tracevp, 398 curpr->ps_tracecred); 399 #endif 400 401 /* 402 * Finish creating the child thread. cpu_fork() will copy 403 * and update the pcb and make the child ready to run. If 404 * this is a normal user fork, the child will exit directly 405 * to user mode via child_return() on its first time slice 406 * and will not return here. If this is a kernel thread, 407 * the specified entry point will be executed. 408 */ 409 cpu_fork(curp, p, NULL, NULL, func, arg ? arg : p); 410 411 vm = pr->ps_vmspace; 412 413 if (flags & FORK_FORK) { 414 forkstat.cntfork++; 415 forkstat.sizfork += vm->vm_dsize + vm->vm_ssize; 416 } else if (flags & FORK_VFORK) { 417 forkstat.cntvfork++; 418 forkstat.sizvfork += vm->vm_dsize + vm->vm_ssize; 419 } else { 420 forkstat.cntkthread++; 421 } 422 423 if (pr->ps_flags & PS_TRACED && flags & FORK_FORK) 424 newptstat = malloc(sizeof(*newptstat), M_SUBPROC, M_WAITOK); 425 426 p->p_tid = alloctid(); 427 428 LIST_INSERT_HEAD(&allproc, p, p_list); 429 LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash); 430 LIST_INSERT_HEAD(PIDHASH(pr->ps_pid), pr, ps_hash); 431 LIST_INSERT_AFTER(curpr, pr, ps_pglist); 432 LIST_INSERT_HEAD(&curpr->ps_children, pr, ps_sibling); 433 434 if (pr->ps_flags & PS_TRACED) { 435 pr->ps_oppid = curpr->ps_pid; 436 if (pr->ps_pptr != curpr->ps_pptr) 437 proc_reparent(pr, curpr->ps_pptr); 438 439 /* 440 * Set ptrace status. 441 */ 442 if (newptstat != NULL) { 443 pr->ps_ptstat = newptstat; 444 newptstat = NULL; 445 curpr->ps_ptstat->pe_report_event = PTRACE_FORK; 446 pr->ps_ptstat->pe_report_event = PTRACE_FORK; 447 curpr->ps_ptstat->pe_other_pid = pr->ps_pid; 448 pr->ps_ptstat->pe_other_pid = curpr->ps_pid; 449 } 450 } 451 452 /* 453 * For new processes, set accounting bits and mark as complete. 454 */ 455 nanouptime(&pr->ps_start); 456 pr->ps_acflag = AFORK; 457 atomic_clearbits_int(&pr->ps_flags, PS_EMBRYO); 458 459 if ((flags & FORK_IDLE) == 0) 460 fork_thread_start(p, curp, flags); 461 else 462 p->p_cpu = arg; 463 464 free(newptstat, M_SUBPROC, sizeof(*newptstat)); 465 466 /* 467 * Notify any interested parties about the new process. 468 */ 469 KNOTE(&curpr->ps_klist, NOTE_FORK | pr->ps_pid); 470 471 /* 472 * Update stats now that we know the fork was successful. 473 */ 474 uvmexp.forks++; 475 if (flags & FORK_PPWAIT) 476 uvmexp.forks_ppwait++; 477 if (flags & FORK_SHAREVM) 478 uvmexp.forks_sharevm++; 479 480 /* 481 * Pass a pointer to the new process to the caller. 482 */ 483 if (rnewprocp != NULL) 484 *rnewprocp = p; 485 486 /* 487 * Preserve synchronization semantics of vfork. If waiting for 488 * child to exec or exit, set PS_PPWAIT on child and PS_ISPWAIT 489 * on ourselves, and sleep on our process for the latter flag 490 * to go away. 491 * XXX Need to stop other rthreads in the parent 492 */ 493 if (flags & FORK_PPWAIT) 494 while (curpr->ps_flags & PS_ISPWAIT) 495 tsleep_nsec(curpr, PWAIT, "ppwait", INFSLP); 496 497 /* 498 * If we're tracing the child, alert the parent too. 499 */ 500 if ((flags & FORK_PTRACE) && (curpr->ps_flags & PS_TRACED)) 501 psignal(curp, SIGTRAP); 502 503 /* 504 * Return child pid to parent process 505 */ 506 if (retval != NULL) { 507 retval[0] = pr->ps_pid; 508 retval[1] = 0; 509 } 510 return (0); 511 } 512 513 int 514 thread_fork(struct proc *curp, void *stack, void *tcb, pid_t *tidptr, 515 register_t *retval) 516 { 517 struct process *pr = curp->p_p; 518 struct proc *p; 519 pid_t tid; 520 vaddr_t uaddr; 521 int error; 522 523 if (stack == NULL) 524 return EINVAL; 525 526 if ((error = fork_check_maxthread(curp->p_ucred->cr_ruid))) 527 return error; 528 529 uaddr = uvm_uarea_alloc(); 530 if (uaddr == 0) { 531 nthreads--; 532 return ENOMEM; 533 } 534 535 /* 536 * From now on, we're committed to the fork and cannot fail. 537 */ 538 p = thread_new(curp, uaddr); 539 atomic_setbits_int(&p->p_flag, P_THREAD); 540 sigstkinit(&p->p_sigstk); 541 542 /* other links */ 543 p->p_p = pr; 544 pr->ps_refcnt++; 545 546 /* local copies */ 547 p->p_fd = pr->ps_fd; 548 p->p_vmspace = pr->ps_vmspace; 549 550 /* 551 * Finish creating the child thread. cpu_fork() will copy 552 * and update the pcb and make the child ready to run. The 553 * child will exit directly to user mode via child_return() 554 * on its first time slice and will not return here. 555 */ 556 cpu_fork(curp, p, stack, tcb, child_return, p); 557 558 p->p_tid = alloctid(); 559 560 LIST_INSERT_HEAD(&allproc, p, p_list); 561 LIST_INSERT_HEAD(TIDHASH(p->p_tid), p, p_hash); 562 TAILQ_INSERT_TAIL(&pr->ps_threads, p, p_thr_link); 563 564 /* 565 * if somebody else wants to take us to single threaded mode, 566 * count ourselves in. 567 */ 568 if (pr->ps_single) { 569 pr->ps_singlecount++; 570 atomic_setbits_int(&p->p_flag, P_SUSPSINGLE); 571 } 572 573 /* 574 * Return tid to parent thread and copy it out to userspace 575 */ 576 retval[0] = tid = p->p_tid + THREAD_PID_OFFSET; 577 retval[1] = 0; 578 if (tidptr != NULL) { 579 if (copyout(&tid, tidptr, sizeof(tid))) 580 psignal(curp, SIGSEGV); 581 } 582 583 fork_thread_start(p, curp, 0); 584 585 /* 586 * Update stats now that we know the fork was successful. 587 */ 588 forkstat.cnttfork++; 589 uvmexp.forks++; 590 uvmexp.forks_sharevm++; 591 592 return 0; 593 } 594 595 596 /* Find an unused tid */ 597 pid_t 598 alloctid(void) 599 { 600 pid_t tid; 601 602 do { 603 /* (0 .. TID_MASK+1] */ 604 tid = 1 + (arc4random() & TID_MASK); 605 } while (tfind(tid) != NULL); 606 607 return (tid); 608 } 609 610 /* 611 * Checks for current use of a pid, either as a pid or pgid. 612 */ 613 pid_t oldpids[128]; 614 int 615 ispidtaken(pid_t pid) 616 { 617 uint32_t i; 618 619 for (i = 0; i < nitems(oldpids); i++) 620 if (pid == oldpids[i]) 621 return (1); 622 623 if (prfind(pid) != NULL) 624 return (1); 625 if (pgfind(pid) != NULL) 626 return (1); 627 if (zombiefind(pid) != NULL) 628 return (1); 629 return (0); 630 } 631 632 /* Find an unused pid */ 633 pid_t 634 allocpid(void) 635 { 636 static pid_t lastpid; 637 pid_t pid; 638 639 if (!randompid) { 640 /* only used early on for system processes */ 641 pid = ++lastpid; 642 } else { 643 /* Find an unused pid satisfying lastpid < pid <= PID_MAX */ 644 do { 645 pid = arc4random_uniform(PID_MAX - lastpid) + 1 + 646 lastpid; 647 } while (ispidtaken(pid)); 648 } 649 650 return pid; 651 } 652 653 void 654 freepid(pid_t pid) 655 { 656 static uint32_t idx; 657 658 oldpids[idx++ % nitems(oldpids)] = pid; 659 } 660 661 #if defined(MULTIPROCESSOR) 662 /* 663 * XXX This is a slight hack to get newly-formed processes to 664 * XXX acquire the kernel lock as soon as they run. 665 */ 666 void 667 proc_trampoline_mp(void) 668 { 669 SCHED_ASSERT_LOCKED(); 670 __mp_unlock(&sched_lock); 671 spl0(); 672 SCHED_ASSERT_UNLOCKED(); 673 KERNEL_ASSERT_UNLOCKED(); 674 675 KERNEL_LOCK(); 676 } 677 #endif 678