1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1989, 1991, 1993 5 * The Regents of the University of California. All rights reserved. 6 * (c) UNIX System Laboratories, Inc. 7 * All or some portions of this file are derived from material licensed 8 * to the University of California by American Telephone and Telegraph 9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 10 * the permission of UNIX System Laboratories, Inc. 11 * 12 * Redistribution and use in source and binary forms, with or without 13 * modification, are permitted provided that the following conditions 14 * are met: 15 * 1. Redistributions of source code must retain the above copyright 16 * notice, this list of conditions and the following disclaimer. 17 * 2. Redistributions in binary form must reproduce the above copyright 18 * notice, this list of conditions and the following disclaimer in the 19 * documentation and/or other materials provided with the distribution. 20 * 3. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 */ 36 37 #include "opt_ktrace.h" 38 #include "opt_kstack_pages.h" 39 40 #define EXTERR_CATEGORY EXTERR_CAT_FORK 41 #include <sys/systm.h> 42 #include <sys/acct.h> 43 #include <sys/bitstring.h> 44 #include <sys/eventhandler.h> 45 #include <sys/exterrvar.h> 46 #include <sys/fcntl.h> 47 #include <sys/filedesc.h> 48 #include <sys/jail.h> 49 #include <sys/kernel.h> 50 #include <sys/kthread.h> 51 #include <sys/ktr.h> 52 #include <sys/ktrace.h> 53 #include <sys/sysctl.h> 54 #include <sys/lock.h> 55 #include <sys/malloc.h> 56 #include <sys/msan.h> 57 #include <sys/mutex.h> 58 #include <sys/priv.h> 59 #include <sys/proc.h> 60 #include <sys/procdesc.h> 61 #include <sys/ptrace.h> 62 #include <sys/racct.h> 63 #include <sys/resourcevar.h> 64 #include <sys/sched.h> 65 #include <sys/sdt.h> 66 #include <sys/signalvar.h> 67 #include <sys/sx.h> 68 #include <sys/syscall.h> 69 #include <sys/sysent.h> 70 #include <sys/sysproto.h> 71 #include <sys/vmmeter.h> 72 #include <sys/vnode.h> 73 #include <sys/unistd.h> 74 75 #include <security/audit/audit.h> 76 #include <security/mac/mac_framework.h> 77 78 #include <vm/vm.h> 79 #include <vm/pmap.h> 80 #include <vm/vm_map.h> 81 #include <vm/vm_extern.h> 82 #include <vm/uma.h> 83 84 #ifdef KDTRACE_HOOKS 85 #include <sys/dtrace_bsd.h> 86 dtrace_fork_func_t dtrace_fasttrap_fork; 87 #endif 88 89 SDT_PROVIDER_DECLARE(proc); 90 SDT_PROBE_DEFINE3(proc, , , create, "struct proc *", "struct proc *", "int"); 91 92 #ifndef _SYS_SYSPROTO_H_ 93 struct fork_args { 94 int dummy; 95 }; 96 #endif 97 98 /* ARGSUSED */ 99 int 100 sys_fork(struct thread *td, struct fork_args *uap) 101 { 102 struct fork_req fr; 103 int error, pid; 104 105 bzero(&fr, sizeof(fr)); 106 fr.fr_flags = RFFDG | RFPROC; 107 fr.fr_pidp = &pid; 108 error = fork1(td, &fr); 109 if (error == 0) { 110 td->td_retval[0] = pid; 111 td->td_retval[1] = 0; 112 } 113 return (error); 114 } 115 116 /* ARGUSED */ 117 int 118 sys_pdfork(struct thread *td, struct pdfork_args *uap) 119 { 120 struct fork_req fr; 121 int error, fd, pid; 122 123 bzero(&fr, sizeof(fr)); 124 fr.fr_flags = RFFDG | RFPROC | RFPROCDESC; 125 fr.fr_pidp = &pid; 126 fr.fr_pd_fd = &fd; 127 fr.fr_pd_flags = uap->flags; 128 AUDIT_ARG_FFLAGS(uap->flags); 129 /* 130 * It is necessary to return fd by reference because 0 is a valid file 131 * descriptor number, and the child needs to be able to distinguish 132 * itself from the parent using the return value. 133 */ 134 error = fork1(td, &fr); 135 if (error == 0) { 136 td->td_retval[0] = pid; 137 td->td_retval[1] = 0; 138 error = copyout(&fd, uap->fdp, sizeof(fd)); 139 } 140 return (error); 141 } 142 143 /* ARGSUSED */ 144 int 145 sys_vfork(struct thread *td, struct vfork_args *uap) 146 { 147 struct fork_req fr; 148 int error, pid; 149 150 bzero(&fr, sizeof(fr)); 151 fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM; 152 fr.fr_pidp = &pid; 153 error = fork1(td, &fr); 154 if (error == 0) { 155 td->td_retval[0] = pid; 156 td->td_retval[1] = 0; 157 } 158 return (error); 159 } 160 161 int 162 sys_rfork(struct thread *td, struct rfork_args *uap) 163 { 164 struct fork_req fr; 165 int error, pid; 166 167 /* Don't allow kernel-only flags. */ 168 if ((uap->flags & RFKERNELONLY) != 0) 169 return (EXTERROR(EINVAL, "Kernel-only flags %#jx", uap->flags)); 170 /* RFSPAWN must not appear with others */ 171 if ((uap->flags & RFSPAWN) != 0 && uap->flags != RFSPAWN) 172 return (EXTERROR(EINVAL, "RFSPAWN must be the only flag %#jx", 173 uap->flags)); 174 175 AUDIT_ARG_FFLAGS(uap->flags); 176 bzero(&fr, sizeof(fr)); 177 if ((uap->flags & RFSPAWN) != 0) { 178 fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM; 179 fr.fr_flags2 = FR2_DROPSIG_CAUGHT; 180 } else { 181 fr.fr_flags = uap->flags; 182 } 183 fr.fr_pidp = &pid; 184 error = fork1(td, &fr); 185 if (error == 0) { 186 td->td_retval[0] = pid; 187 td->td_retval[1] = 0; 188 } 189 return (error); 190 } 191 192 int 193 sys_pdrfork(struct thread *td, struct pdrfork_args *uap) 194 { 195 struct fork_req fr; 196 int error, fd, pid; 197 198 bzero(&fr, sizeof(fr)); 199 fd = -1; 200 201 AUDIT_ARG_FFLAGS(uap->pdflags); 202 AUDIT_ARG_CMD(uap->rfflags); 203 204 if ((uap->rfflags & (RFSTOPPED | RFHIGHPID)) != 0) 205 return (EXTERROR(EINVAL, 206 "Kernel-only flags %#jx", uap->rfflags)); 207 208 /* RFSPAWN must not appear with others */ 209 if ((uap->rfflags & RFSPAWN) != 0) { 210 if (uap->rfflags != RFSPAWN) 211 return (EXTERROR(EINVAL, 212 "RFSPAWN must be the only flag %#jx", 213 uap->rfflags)); 214 fr.fr_flags = RFFDG | RFPROC | RFPPWAIT | RFMEM | RFPROCDESC; 215 fr.fr_flags2 = FR2_DROPSIG_CAUGHT; 216 } else { 217 if ((uap->rfflags & (RFPROC | RFPROCDESC)) != 218 (RFPROC | RFPROCDESC)) { 219 return (EXTERROR(EINVAL, 220 "RFPROC|RFPROCDESC required %#jx", uap->rfflags)); 221 } 222 fr.fr_flags = uap->rfflags; 223 } 224 225 fr.fr_pidp = &pid; 226 fr.fr_pd_fd = &fd; 227 fr.fr_pd_flags = uap->pdflags; 228 error = fork1(td, &fr); 229 if (error == 0) { 230 td->td_retval[0] = pid; 231 td->td_retval[1] = 0; 232 if ((fr.fr_flags & (RFPROC | RFPROCDESC)) == 233 (RFPROC | RFPROCDESC) || uap->rfflags == RFSPAWN) 234 error = copyout(&fd, uap->fdp, sizeof(fd)); 235 } 236 return (error); 237 } 238 239 int __exclusive_cache_line nprocs = 1; /* process 0 */ 240 int lastpid = 0; 241 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0, 242 "Last used PID"); 243 244 /* 245 * Random component to lastpid generation. We mix in a random factor to make 246 * it a little harder to predict. We sanity check the modulus value to avoid 247 * doing it in critical paths. Don't let it be too small or we pointlessly 248 * waste randomness entropy, and don't let it be impossibly large. Using a 249 * modulus that is too big causes a LOT more process table scans and slows 250 * down fork processing as the pidchecked caching is defeated. 251 */ 252 static int randompid = 0; 253 254 static int 255 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS) 256 { 257 int error, pid; 258 259 error = sysctl_wire_old_buffer(req, sizeof(int)); 260 if (error != 0) 261 return(error); 262 sx_xlock(&allproc_lock); 263 pid = randompid; 264 error = sysctl_handle_int(oidp, &pid, 0, req); 265 if (error == 0 && req->newptr != NULL) { 266 if (pid == 0) 267 randompid = 0; 268 else if (pid == 1) 269 /* generate a random PID modulus between 100 and 1123 */ 270 randompid = 100 + arc4random() % 1024; 271 else if (pid < 0 || pid > pid_max - 100) 272 /* out of range */ 273 randompid = pid_max - 100; 274 else if (pid < 100) 275 /* Make it reasonable */ 276 randompid = 100; 277 else 278 randompid = pid; 279 } 280 sx_xunlock(&allproc_lock); 281 return (error); 282 } 283 284 SYSCTL_PROC(_kern, OID_AUTO, randompid, 285 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0, 286 sysctl_kern_randompid, "I", 287 "Random PID modulus. Special values: 0: disable, 1: choose random value"); 288 289 extern bitstr_t proc_id_pidmap; 290 extern bitstr_t proc_id_grpidmap; 291 extern bitstr_t proc_id_sessidmap; 292 extern bitstr_t proc_id_reapmap; 293 294 /* 295 * Find an unused process ID 296 * 297 * If RFHIGHPID is set (used during system boot), do not allocate 298 * low-numbered pids. 299 */ 300 static int 301 fork_findpid(int flags) 302 { 303 pid_t result; 304 int trypid, random; 305 306 /* 307 * Avoid calling arc4random with procid_lock held. 308 */ 309 random = 0; 310 if (__predict_false(randompid)) 311 random = arc4random() % randompid; 312 313 mtx_lock(&procid_lock); 314 315 trypid = lastpid + 1; 316 if (flags & RFHIGHPID) { 317 if (trypid < 10) 318 trypid = 10; 319 } else { 320 trypid += random; 321 } 322 retry: 323 if (trypid >= pid_max) 324 trypid = 2; 325 326 bit_ffc_at(&proc_id_pidmap, trypid, pid_max, &result); 327 if (result == -1) { 328 KASSERT(trypid != 2, ("unexpectedly ran out of IDs")); 329 trypid = 2; 330 goto retry; 331 } 332 if (bit_test(&proc_id_grpidmap, result) || 333 bit_test(&proc_id_sessidmap, result) || 334 bit_test(&proc_id_reapmap, result)) { 335 trypid = result + 1; 336 goto retry; 337 } 338 339 /* 340 * RFHIGHPID does not mess with the lastpid counter during boot. 341 */ 342 if ((flags & RFHIGHPID) == 0) 343 lastpid = result; 344 345 bit_set(&proc_id_pidmap, result); 346 mtx_unlock(&procid_lock); 347 348 return (result); 349 } 350 351 static int 352 fork_norfproc(struct thread *td, int flags) 353 { 354 struct proc *p1; 355 int error; 356 357 KASSERT((flags & RFPROC) == 0, 358 ("fork_norfproc called with RFPROC set")); 359 p1 = td->td_proc; 360 361 /* 362 * Quiesce other threads if necessary. If RFMEM is not specified we 363 * must ensure that other threads do not concurrently create a second 364 * process sharing the vmspace, see vmspace_unshare(). 365 */ 366 if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS && 367 ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) { 368 PROC_LOCK(p1); 369 if (thread_single(p1, SINGLE_BOUNDARY)) { 370 PROC_UNLOCK(p1); 371 return (ERESTART); 372 } 373 PROC_UNLOCK(p1); 374 } 375 376 error = vm_forkproc(td, NULL, NULL, NULL, flags); 377 if (error != 0) 378 goto fail; 379 380 /* 381 * Close all file descriptors. 382 */ 383 if ((flags & RFCFDG) != 0) { 384 struct filedesc *fdtmp; 385 struct pwddesc *pdtmp; 386 387 pdtmp = pdinit(td->td_proc->p_pd, false); 388 fdtmp = fdinit(); 389 pdescfree(td); 390 fdescfree(td); 391 p1->p_fd = fdtmp; 392 p1->p_pd = pdtmp; 393 } 394 395 /* 396 * Unshare file descriptors (from parent). 397 */ 398 if ((flags & RFFDG) != 0) { 399 fdunshare(td); 400 pdunshare(td); 401 } 402 403 fail: 404 if ((p1->p_flag & (P_HADTHREADS | P_SYSTEM)) == P_HADTHREADS && 405 ((flags & (RFCFDG | RFFDG)) != 0 || (flags & RFMEM) == 0)) { 406 PROC_LOCK(p1); 407 thread_single_end(p1, SINGLE_BOUNDARY); 408 PROC_UNLOCK(p1); 409 } 410 return (error); 411 } 412 413 static void 414 do_fork(struct thread *td, struct fork_req *fr, struct proc *p2, struct thread *td2, 415 struct vmspace *vm2, struct file *fp_procdesc) 416 { 417 struct proc *p1, *pptr; 418 struct filedesc *fd; 419 struct filedesc_to_leader *fdtol; 420 struct pwddesc *pd; 421 struct sigacts *newsigacts; 422 423 p1 = td->td_proc; 424 425 PROC_LOCK(p1); 426 bcopy(&p1->p_startcopy, &p2->p_startcopy, 427 __rangeof(struct proc, p_startcopy, p_endcopy)); 428 pargs_hold(p2->p_args); 429 PROC_UNLOCK(p1); 430 431 bzero(&p2->p_startzero, 432 __rangeof(struct proc, p_startzero, p_endzero)); 433 434 /* Tell the prison that we exist. */ 435 prison_proc_hold(p2->p_ucred->cr_prison); 436 437 p2->p_state = PRS_NEW; /* protect against others */ 438 p2->p_pid = fork_findpid(fr->fr_flags); 439 AUDIT_ARG_PID(p2->p_pid); 440 TSFORK(p2->p_pid, p1->p_pid); 441 442 sx_xlock(&allproc_lock); 443 LIST_INSERT_HEAD(&allproc, p2, p_list); 444 allproc_gen++; 445 prison_proc_link(p2->p_ucred->cr_prison, p2); 446 sx_xunlock(&allproc_lock); 447 448 sx_xlock(PIDHASHLOCK(p2->p_pid)); 449 LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash); 450 sx_xunlock(PIDHASHLOCK(p2->p_pid)); 451 452 tidhash_add(td2); 453 454 /* 455 * Malloc things while we don't hold any locks. 456 */ 457 if (fr->fr_flags & RFSIGSHARE) 458 newsigacts = NULL; 459 else 460 newsigacts = sigacts_alloc(); 461 462 /* 463 * Copy filedesc. 464 */ 465 if (fr->fr_flags & RFCFDG) { 466 pd = pdinit(p1->p_pd, false); 467 fd = fdinit(); 468 fdtol = NULL; 469 } else if (fr->fr_flags & RFFDG) { 470 if (fr->fr_flags2 & FR2_SHARE_PATHS) 471 pd = pdshare(p1->p_pd); 472 else 473 pd = pdcopy(p1->p_pd); 474 fd = fdcopy(p1->p_fd, p2); 475 fdtol = NULL; 476 } else { 477 if (fr->fr_flags2 & FR2_SHARE_PATHS) 478 pd = pdcopy(p1->p_pd); 479 else 480 pd = pdshare(p1->p_pd); 481 fd = fdshare(p1->p_fd); 482 if (p1->p_fdtol == NULL) 483 p1->p_fdtol = filedesc_to_leader_alloc(NULL, NULL, 484 p1->p_leader); 485 if ((fr->fr_flags & RFTHREAD) != 0) { 486 /* 487 * Shared file descriptor table, and shared 488 * process leaders. 489 */ 490 fdtol = filedesc_to_leader_share(p1->p_fdtol, p1->p_fd); 491 } else { 492 /* 493 * Shared file descriptor table, and different 494 * process leaders. 495 */ 496 fdtol = filedesc_to_leader_alloc(p1->p_fdtol, 497 p1->p_fd, p2); 498 } 499 } 500 /* 501 * Make a proc table entry for the new process. 502 * Start by zeroing the section of proc that is zero-initialized, 503 * then copy the section that is copied directly from the parent. 504 */ 505 506 PROC_LOCK(p2); 507 PROC_LOCK(p1); 508 509 bzero(&td2->td_startzero, 510 __rangeof(struct thread, td_startzero, td_endzero)); 511 512 bcopy(&td->td_startcopy, &td2->td_startcopy, 513 __rangeof(struct thread, td_startcopy, td_endcopy)); 514 515 bcopy(&p2->p_comm, &td2->td_name, sizeof(td2->td_name)); 516 td2->td_sigstk = td->td_sigstk; 517 td2->td_flags = TDF_INMEM; 518 td2->td_lend_user_pri = PRI_MAX; 519 520 #ifdef VIMAGE 521 td2->td_vnet = NULL; 522 td2->td_vnet_lpush = NULL; 523 #endif 524 525 /* 526 * Allow the scheduler to initialize the child. 527 */ 528 thread_lock(td); 529 sched_fork(td, td2); 530 /* 531 * Request AST to check for TDP_RFPPWAIT. Do it here 532 * to avoid calling thread_lock() again. 533 */ 534 if ((fr->fr_flags & RFPPWAIT) != 0) 535 ast_sched_locked(td, TDA_VFORK); 536 thread_unlock(td); 537 538 /* 539 * Duplicate sub-structures as needed. 540 * Increase reference counts on shared objects. 541 */ 542 p2->p_flag = P_INMEM; 543 p2->p_flag2 = p1->p_flag2 & (P2_ASLR_DISABLE | P2_ASLR_ENABLE | 544 P2_ASLR_IGNSTART | P2_NOTRACE | P2_NOTRACE_EXEC | 545 P2_PROTMAX_ENABLE | P2_PROTMAX_DISABLE | P2_TRAPCAP | 546 P2_STKGAP_DISABLE | P2_STKGAP_DISABLE_EXEC | P2_NO_NEW_PRIVS | 547 P2_WXORX_DISABLE | P2_WXORX_ENABLE_EXEC | P2_LOGSIGEXIT_CTL | 548 P2_LOGSIGEXIT_ENABLE); 549 p2->p_swtick = ticks; 550 if (p1->p_flag & P_PROFIL) 551 startprofclock(p2); 552 553 if (fr->fr_flags & RFSIGSHARE) { 554 p2->p_sigacts = sigacts_hold(p1->p_sigacts); 555 } else { 556 sigacts_copy(newsigacts, p1->p_sigacts); 557 p2->p_sigacts = newsigacts; 558 if ((fr->fr_flags2 & (FR2_DROPSIG_CAUGHT | FR2_KPROC)) != 0) { 559 mtx_lock(&p2->p_sigacts->ps_mtx); 560 if ((fr->fr_flags2 & FR2_DROPSIG_CAUGHT) != 0) 561 sig_drop_caught(p2); 562 if ((fr->fr_flags2 & FR2_KPROC) != 0) 563 p2->p_sigacts->ps_flag |= PS_NOCLDWAIT; 564 mtx_unlock(&p2->p_sigacts->ps_mtx); 565 } 566 } 567 568 if (fr->fr_flags & RFTSIGZMB) 569 p2->p_sigparent = RFTSIGNUM(fr->fr_flags); 570 else if (fr->fr_flags & RFLINUXTHPN) 571 p2->p_sigparent = SIGUSR1; 572 else 573 p2->p_sigparent = SIGCHLD; 574 575 if ((fr->fr_flags2 & FR2_KPROC) != 0) { 576 p2->p_flag |= P_SYSTEM | P_KPROC; 577 td2->td_pflags |= TDP_KTHREAD; 578 } 579 580 p2->p_textvp = p1->p_textvp; 581 p2->p_textdvp = p1->p_textdvp; 582 p2->p_fd = fd; 583 p2->p_fdtol = fdtol; 584 p2->p_pd = pd; 585 586 if (p1->p_flag2 & P2_INHERIT_PROTECTED) { 587 p2->p_flag |= P_PROTECTED; 588 p2->p_flag2 |= P2_INHERIT_PROTECTED; 589 } 590 591 /* 592 * p_limit is copy-on-write. Bump its refcount. 593 */ 594 lim_fork(p1, p2); 595 596 thread_cow_get_proc(td2, p2); 597 598 pstats_fork(p1->p_stats, p2->p_stats); 599 600 PROC_UNLOCK(p1); 601 PROC_UNLOCK(p2); 602 603 /* 604 * Bump references to the text vnode and directory, and copy 605 * the hardlink name. 606 */ 607 if (p2->p_textvp != NULL) 608 vrefact(p2->p_textvp); 609 if (p2->p_textdvp != NULL) 610 vrefact(p2->p_textdvp); 611 p2->p_binname = p1->p_binname == NULL ? NULL : 612 strdup(p1->p_binname, M_PARGS); 613 614 /* 615 * Set up linkage for kernel based threading. 616 */ 617 if ((fr->fr_flags & RFTHREAD) != 0) { 618 mtx_lock(&ppeers_lock); 619 p2->p_peers = p1->p_peers; 620 p1->p_peers = p2; 621 p2->p_leader = p1->p_leader; 622 mtx_unlock(&ppeers_lock); 623 PROC_LOCK(p1->p_leader); 624 if ((p1->p_leader->p_flag & P_WEXIT) != 0) { 625 PROC_UNLOCK(p1->p_leader); 626 /* 627 * The task leader is exiting, so process p1 is 628 * going to be killed shortly. Since p1 obviously 629 * isn't dead yet, we know that the leader is either 630 * sending SIGKILL's to all the processes in this 631 * task or is sleeping waiting for all the peers to 632 * exit. We let p1 complete the fork, but we need 633 * to go ahead and kill the new process p2 since 634 * the task leader may not get a chance to send 635 * SIGKILL to it. We leave it on the list so that 636 * the task leader will wait for this new process 637 * to commit suicide. 638 */ 639 PROC_LOCK(p2); 640 kern_psignal(p2, SIGKILL); 641 PROC_UNLOCK(p2); 642 } else 643 PROC_UNLOCK(p1->p_leader); 644 } else { 645 p2->p_peers = NULL; 646 p2->p_leader = p2; 647 } 648 649 sx_xlock(&proctree_lock); 650 PGRP_LOCK(p1->p_pgrp); 651 PROC_LOCK(p2); 652 PROC_LOCK(p1); 653 654 /* 655 * Preserve some more flags in subprocess. P_PROFIL has already 656 * been preserved. 657 */ 658 p2->p_flag |= p1->p_flag & P_SUGID; 659 td2->td_pflags |= td->td_pflags & (TDP_ALTSTACK | TDP_SIGFASTBLOCK); 660 td2->td_pflags2 |= td->td_pflags2 & TDP2_UEXTERR; 661 if (p1->p_flag & P_CONTROLT) { 662 SESS_LOCK(p1->p_session); 663 if (p1->p_session->s_ttyvp != NULL) 664 p2->p_flag |= P_CONTROLT; 665 SESS_UNLOCK(p1->p_session); 666 } 667 if (fr->fr_flags & RFPPWAIT) 668 p2->p_flag |= P_PPWAIT; 669 670 p2->p_pgrp = p1->p_pgrp; 671 LIST_INSERT_AFTER(p1, p2, p_pglist); 672 PGRP_UNLOCK(p1->p_pgrp); 673 LIST_INIT(&p2->p_children); 674 LIST_INIT(&p2->p_orphans); 675 676 callout_init_mtx(&p2->p_itcallout, &p2->p_mtx, 0); 677 678 /* 679 * This begins the section where we must prevent the parent 680 * from being swapped. 681 */ 682 _PHOLD(p1); 683 PROC_UNLOCK(p1); 684 685 /* 686 * Attach the new process to its parent. 687 * 688 * If RFNOWAIT is set, the newly created process becomes a child 689 * of init. This effectively disassociates the child from the 690 * parent. 691 */ 692 if ((fr->fr_flags & RFNOWAIT) != 0) { 693 pptr = p1->p_reaper; 694 p2->p_reaper = pptr; 695 } else { 696 p2->p_reaper = (p1->p_treeflag & P_TREE_REAPER) != 0 ? 697 p1 : p1->p_reaper; 698 pptr = p1; 699 } 700 p2->p_pptr = pptr; 701 p2->p_oppid = pptr->p_pid; 702 LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling); 703 LIST_INIT(&p2->p_reaplist); 704 LIST_INSERT_HEAD(&p2->p_reaper->p_reaplist, p2, p_reapsibling); 705 if (p2->p_reaper == p1 && p1 != initproc) { 706 p2->p_reapsubtree = p2->p_pid; 707 proc_id_set_cond(PROC_ID_REAP, p2->p_pid); 708 } 709 sx_xunlock(&proctree_lock); 710 711 /* Inform accounting that we have forked. */ 712 p2->p_acflag = AFORK; 713 PROC_UNLOCK(p2); 714 715 #ifdef KTRACE 716 ktrprocfork(p1, p2); 717 #endif 718 719 /* 720 * Finish creating the child process. It will return via a different 721 * execution path later. (ie: directly into user mode) 722 */ 723 vm_forkproc(td, p2, td2, vm2, fr->fr_flags); 724 725 if (fr->fr_flags == (RFFDG | RFPROC)) { 726 VM_CNT_INC(v_forks); 727 VM_CNT_ADD(v_forkpages, p2->p_vmspace->vm_dsize + 728 p2->p_vmspace->vm_ssize); 729 } else if (fr->fr_flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) { 730 VM_CNT_INC(v_vforks); 731 VM_CNT_ADD(v_vforkpages, p2->p_vmspace->vm_dsize + 732 p2->p_vmspace->vm_ssize); 733 } else if (p1 == &proc0) { 734 VM_CNT_INC(v_kthreads); 735 VM_CNT_ADD(v_kthreadpages, p2->p_vmspace->vm_dsize + 736 p2->p_vmspace->vm_ssize); 737 } else { 738 VM_CNT_INC(v_rforks); 739 VM_CNT_ADD(v_rforkpages, p2->p_vmspace->vm_dsize + 740 p2->p_vmspace->vm_ssize); 741 } 742 743 /* 744 * Associate the process descriptor with the process before anything 745 * can happen that might cause that process to need the descriptor. 746 * However, don't do this until after fork(2) can no longer fail. 747 */ 748 if (fr->fr_flags & RFPROCDESC) 749 procdesc_new(p2, fr->fr_pd_flags); 750 751 /* 752 * Both processes are set up, now check if any loadable modules want 753 * to adjust anything. 754 */ 755 EVENTHANDLER_DIRECT_INVOKE(process_fork, p1, p2, fr->fr_flags); 756 757 /* 758 * Set the child start time and mark the process as being complete. 759 */ 760 PROC_LOCK(p2); 761 PROC_LOCK(p1); 762 microuptime(&p2->p_stats->p_start); 763 PROC_SLOCK(p2); 764 p2->p_state = PRS_NORMAL; 765 PROC_SUNLOCK(p2); 766 767 #ifdef KDTRACE_HOOKS 768 /* 769 * Tell the DTrace fasttrap provider about the new process so that any 770 * tracepoints inherited from the parent can be removed. We have to do 771 * this only after p_state is PRS_NORMAL since the fasttrap module will 772 * use pfind() later on. 773 */ 774 if ((fr->fr_flags & RFMEM) == 0 && dtrace_fasttrap_fork) 775 dtrace_fasttrap_fork(p1, p2); 776 #endif 777 if (fr->fr_flags & RFPPWAIT) { 778 td->td_pflags |= TDP_RFPPWAIT; 779 td->td_rfppwait_p = p2; 780 td->td_dbgflags |= TDB_VFORK; 781 } 782 PROC_UNLOCK(p2); 783 784 /* 785 * Tell any interested parties about the new process. 786 */ 787 knote_fork(p1->p_klist, p2->p_pid); 788 789 /* 790 * Now can be swapped. 791 */ 792 _PRELE(p1); 793 PROC_UNLOCK(p1); 794 SDT_PROBE3(proc, , , create, p2, p1, fr->fr_flags); 795 796 if (fr->fr_flags & RFPROCDESC) { 797 procdesc_finit(p2->p_procdesc, fp_procdesc); 798 fdrop(fp_procdesc, td); 799 } 800 801 /* 802 * Speculative check for PTRACE_FORK. PTRACE_FORK is not 803 * synced with forks in progress so it is OK if we miss it 804 * if being set atm. 805 */ 806 if ((p1->p_ptevents & PTRACE_FORK) != 0) { 807 sx_xlock(&proctree_lock); 808 PROC_LOCK(p2); 809 810 /* 811 * p1->p_ptevents & p1->p_pptr are protected by both 812 * process and proctree locks for modifications, 813 * so owning proctree_lock allows the race-free read. 814 */ 815 if ((p1->p_ptevents & PTRACE_FORK) != 0) { 816 /* 817 * Arrange for debugger to receive the fork event. 818 * 819 * We can report PL_FLAG_FORKED regardless of 820 * P_FOLLOWFORK settings, but it does not make a sense 821 * for runaway child. 822 */ 823 td->td_dbgflags |= TDB_FORK; 824 td->td_dbg_forked = p2->p_pid; 825 td2->td_dbgflags |= TDB_STOPATFORK; 826 proc_set_traced(p2, true); 827 CTR2(KTR_PTRACE, 828 "do_fork: attaching to new child pid %d: oppid %d", 829 p2->p_pid, p2->p_oppid); 830 proc_reparent(p2, p1->p_pptr, false); 831 } 832 PROC_UNLOCK(p2); 833 sx_xunlock(&proctree_lock); 834 } 835 836 racct_proc_fork_done(p2); 837 838 if ((fr->fr_flags & RFSTOPPED) == 0) { 839 if (fr->fr_pidp != NULL) 840 *fr->fr_pidp = p2->p_pid; 841 /* 842 * If RFSTOPPED not requested, make child runnable and 843 * add to run queue. 844 */ 845 thread_lock(td2); 846 TD_SET_CAN_RUN(td2); 847 sched_add(td2, SRQ_BORING); 848 } else { 849 *fr->fr_procp = p2; 850 } 851 } 852 853 static void 854 ast_vfork(struct thread *td, int tda __unused) 855 { 856 struct proc *p, *p2; 857 858 MPASS(td->td_pflags & TDP_RFPPWAIT); 859 860 p = td->td_proc; 861 /* 862 * Preserve synchronization semantics of vfork. If 863 * waiting for child to exec or exit, fork set 864 * P_PPWAIT on child, and there we sleep on our proc 865 * (in case of exit). 866 * 867 * Do it after the ptracestop() above is finished, to 868 * not block our debugger until child execs or exits 869 * to finish vfork wait. 870 */ 871 td->td_pflags &= ~TDP_RFPPWAIT; 872 p2 = td->td_rfppwait_p; 873 again: 874 PROC_LOCK(p2); 875 while (p2->p_flag & P_PPWAIT) { 876 PROC_LOCK(p); 877 if (thread_suspend_check_needed()) { 878 PROC_UNLOCK(p2); 879 thread_suspend_check(0); 880 PROC_UNLOCK(p); 881 goto again; 882 } else { 883 PROC_UNLOCK(p); 884 } 885 cv_timedwait(&p2->p_pwait, &p2->p_mtx, hz); 886 } 887 PROC_UNLOCK(p2); 888 889 if (td->td_dbgflags & TDB_VFORK) { 890 PROC_LOCK(p); 891 if (p->p_ptevents & PTRACE_VFORK) 892 ptracestop(td, SIGTRAP, NULL); 893 td->td_dbgflags &= ~TDB_VFORK; 894 PROC_UNLOCK(p); 895 } 896 } 897 898 int 899 fork1(struct thread *td, struct fork_req *fr) 900 { 901 struct proc *p1, *newproc; 902 struct thread *td2; 903 struct vmspace *vm2; 904 struct ucred *cred; 905 struct file *fp_procdesc; 906 struct pgrp *pg; 907 vm_ooffset_t mem_charged; 908 int error, nprocs_new; 909 static int curfail; 910 static struct timeval lastfail; 911 int flags, pages; 912 bool killsx_locked, singlethreaded; 913 914 flags = fr->fr_flags; 915 pages = fr->fr_pages; 916 917 if ((flags & RFSTOPPED) != 0) 918 MPASS(fr->fr_procp != NULL && fr->fr_pidp == NULL); 919 else 920 MPASS(fr->fr_procp == NULL); 921 922 if ((flags & ~(RFFLAGS | RFTSIGFLAGS(RFTSIGMASK))) != 0) 923 return (EXTERROR(EINVAL, 924 "Undef or unimplemented flags %#jx", flags)); 925 926 if ((flags & RFTSIGFLAGS(RFTSIGMASK)) != 0 && (flags & RFTSIGZMB) == 0) 927 return (EXTERROR(EINVAL, 928 "Signal value requires RFTSIGZMB", flags)); 929 930 if ((flags & (RFFDG | RFCFDG)) == (RFFDG | RFCFDG)) 931 return (EXTERROR(EINVAL, "Can not copy and clear")); 932 933 if ((flags & RFTSIGZMB) != 0 && (u_int)RFTSIGNUM(flags) > _SIG_MAXSIG) 934 return (EXTERROR(EINVAL, "Invalid signal", RFTSIGNUM(flags))); 935 936 if ((flags & RFPROCDESC) != 0) { 937 if ((flags & RFPROC) == 0) 938 return (EXTERROR(EINVAL, 939 "Can not not create a process yet get a process descriptor")); 940 941 if (fr->fr_pd_fd == NULL) 942 return (EXTERROR(EINVAL, 943 "Must provide a place to put a procdesc if creating one")); 944 945 if ((fr->fr_pd_flags & ~PD_ALLOWED_AT_FORK) != 0) 946 return (EXTERROR(EINVAL, 947 "Invallid pdflags at fork %#jx", fr->fr_pd_flags)); 948 } 949 950 p1 = td->td_proc; 951 952 /* 953 * Here we don't create a new process, but we divorce 954 * certain parts of a process from itself. 955 */ 956 if ((flags & RFPROC) == 0) { 957 if (fr->fr_procp != NULL) 958 *fr->fr_procp = NULL; 959 else if (fr->fr_pidp != NULL) 960 *fr->fr_pidp = 0; 961 return (fork_norfproc(td, flags)); 962 } 963 964 fp_procdesc = NULL; 965 newproc = NULL; 966 vm2 = NULL; 967 killsx_locked = false; 968 singlethreaded = false; 969 970 /* 971 * Increment the nprocs resource before allocations occur. 972 * Although process entries are dynamically created, we still 973 * keep a global limit on the maximum number we will 974 * create. There are hard-limits as to the number of processes 975 * that can run, established by the KVA and memory usage for 976 * the process data. 977 * 978 * Don't allow a nonprivileged user to use the last ten 979 * processes; don't let root exceed the limit. 980 */ 981 nprocs_new = atomic_fetchadd_int(&nprocs, 1) + 1; 982 if (nprocs_new >= maxproc - 10) { 983 if (priv_check_cred(td->td_ucred, PRIV_MAXPROC) != 0 || 984 nprocs_new >= maxproc) { 985 error = EAGAIN; 986 sx_xlock(&allproc_lock); 987 if (ppsratecheck(&lastfail, &curfail, 1)) { 988 printf("maxproc limit exceeded by uid %u " 989 "(pid %d); see tuning(7) and " 990 "login.conf(5)\n", 991 td->td_ucred->cr_ruid, p1->p_pid); 992 } 993 sx_xunlock(&allproc_lock); 994 goto fail2; 995 } 996 } 997 998 /* 999 * If we are possibly multi-threaded, and there is a process 1000 * sending a signal to our group right now, ensure that our 1001 * other threads cannot be chosen for the signal queueing. 1002 * Otherwise, this might delay signal action, and make the new 1003 * child escape the signaling. 1004 */ 1005 pg = p1->p_pgrp; 1006 if (p1->p_numthreads > 1) { 1007 if (sx_try_slock(&pg->pg_killsx) != 0) { 1008 killsx_locked = true; 1009 } else { 1010 PROC_LOCK(p1); 1011 if (thread_single(p1, SINGLE_BOUNDARY)) { 1012 PROC_UNLOCK(p1); 1013 error = ERESTART; 1014 goto fail2; 1015 } 1016 PROC_UNLOCK(p1); 1017 singlethreaded = true; 1018 } 1019 } 1020 1021 /* 1022 * Atomically check for signals and block processes from sending 1023 * a signal to our process group until the child is visible. 1024 */ 1025 if (!killsx_locked && sx_slock_sig(&pg->pg_killsx) != 0) { 1026 error = ERESTART; 1027 goto fail2; 1028 } 1029 if (__predict_false(p1->p_pgrp != pg || sig_intr() != 0)) { 1030 /* 1031 * Either the process was moved to other process 1032 * group, or there is pending signal. sx_slock_sig() 1033 * does not check for signals if not sleeping for the 1034 * lock. 1035 */ 1036 sx_sunlock(&pg->pg_killsx); 1037 killsx_locked = false; 1038 error = ERESTART; 1039 goto fail2; 1040 } else { 1041 killsx_locked = true; 1042 } 1043 1044 /* 1045 * If required, create a process descriptor in the parent first; we 1046 * will abandon it if something goes wrong. We don't finit() until 1047 * later. 1048 */ 1049 if (flags & RFPROCDESC) { 1050 error = procdesc_falloc(td, &fp_procdesc, fr->fr_pd_fd, 1051 fr->fr_pd_flags, fr->fr_pd_fcaps); 1052 if (error != 0) 1053 goto fail2; 1054 AUDIT_ARG_FD(*fr->fr_pd_fd); 1055 } 1056 1057 mem_charged = 0; 1058 if (pages == 0) 1059 pages = kstack_pages; 1060 /* Allocate new proc. */ 1061 newproc = uma_zalloc(proc_zone, M_WAITOK); 1062 td2 = FIRST_THREAD_IN_PROC(newproc); 1063 if (td2 == NULL) { 1064 td2 = thread_alloc(pages); 1065 if (td2 == NULL) { 1066 error = ENOMEM; 1067 goto fail2; 1068 } 1069 proc_linkup(newproc, td2); 1070 } else { 1071 error = thread_recycle(td2, pages); 1072 if (error != 0) 1073 goto fail2; 1074 } 1075 1076 if ((flags & RFMEM) == 0) { 1077 vm2 = vmspace_fork(p1->p_vmspace, &mem_charged); 1078 if (vm2 == NULL) { 1079 error = ENOMEM; 1080 goto fail2; 1081 } 1082 if (!swap_reserve(mem_charged)) { 1083 /* 1084 * The swap reservation failed. The accounting 1085 * from the entries of the copied vm2 will be 1086 * subtracted in vmspace_free(), so force the 1087 * reservation there. 1088 */ 1089 swap_reserve_force(mem_charged); 1090 error = ENOMEM; 1091 goto fail2; 1092 } 1093 } else 1094 vm2 = NULL; 1095 1096 /* 1097 * XXX: This is ugly; when we copy resource usage, we need to bump 1098 * per-cred resource counters. 1099 */ 1100 newproc->p_ucred = crcowget(td->td_ucred); 1101 1102 /* 1103 * Initialize resource accounting for the child process. 1104 */ 1105 error = racct_proc_fork(p1, newproc); 1106 if (error != 0) { 1107 error = EAGAIN; 1108 goto fail1; 1109 } 1110 1111 #ifdef MAC 1112 mac_proc_init(newproc); 1113 #endif 1114 1115 /* 1116 * Increment the count of procs running with this uid. Don't allow 1117 * a nonprivileged user to exceed their current limit. 1118 */ 1119 cred = td->td_ucred; 1120 if (!chgproccnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPROC))) { 1121 if (priv_check_cred(cred, PRIV_PROC_LIMIT) != 0) 1122 goto fail0; 1123 chgproccnt(cred->cr_ruidinfo, 1, 0); 1124 } 1125 1126 newproc->p_klist = knlist_alloc(&newproc->p_mtx); 1127 1128 do_fork(td, fr, newproc, td2, vm2, fp_procdesc); 1129 error = 0; 1130 goto cleanup; 1131 fail0: 1132 error = EAGAIN; 1133 #ifdef MAC 1134 mac_proc_destroy(newproc); 1135 #endif 1136 racct_proc_exit(newproc); 1137 fail1: 1138 proc_unset_cred(newproc, false); 1139 fail2: 1140 if (vm2 != NULL) 1141 vmspace_free(vm2); 1142 uma_zfree(proc_zone, newproc); 1143 if ((flags & RFPROCDESC) != 0 && fp_procdesc != NULL) { 1144 fdclose(td, fp_procdesc, *fr->fr_pd_fd); 1145 fdrop(fp_procdesc, td); 1146 } 1147 atomic_add_int(&nprocs, -1); 1148 cleanup: 1149 if (killsx_locked) 1150 sx_sunlock(&pg->pg_killsx); 1151 if (singlethreaded) { 1152 PROC_LOCK(p1); 1153 thread_single_end(p1, SINGLE_BOUNDARY); 1154 PROC_UNLOCK(p1); 1155 } 1156 if (error != 0) 1157 pause("fork", hz / 2); 1158 return (error); 1159 } 1160 1161 /* 1162 * Handle the return of a child process from fork1(). This function 1163 * is called from the MD fork_trampoline() entry point. 1164 */ 1165 void 1166 fork_exit(void (*callout)(void *, struct trapframe *), void *arg, 1167 struct trapframe *frame) 1168 { 1169 struct proc *p; 1170 struct thread *td; 1171 struct thread *dtd; 1172 1173 kmsan_mark(frame, sizeof(*frame), KMSAN_STATE_INITED); 1174 1175 td = curthread; 1176 p = td->td_proc; 1177 KASSERT(p->p_state == PRS_NORMAL, ("executing process is still new")); 1178 1179 CTR4(KTR_PROC, "fork_exit: new thread %p (td_sched %p, pid %d, %s)", 1180 td, td_get_sched(td), p->p_pid, td->td_name); 1181 1182 sched_fork_exit(td); 1183 1184 /* 1185 * Processes normally resume in mi_switch() after being 1186 * cpu_switch()'ed to, but when children start up they arrive here 1187 * instead, so we must do much the same things as mi_switch() would. 1188 */ 1189 if ((dtd = PCPU_GET(deadthread))) { 1190 PCPU_SET(deadthread, NULL); 1191 thread_stash(dtd); 1192 } 1193 thread_unlock(td); 1194 1195 /* 1196 * cpu_fork_kthread_handler intercepts this function call to 1197 * have this call a non-return function to stay in kernel mode. 1198 * initproc has its own fork handler, but it does return. 1199 */ 1200 KASSERT(callout != NULL, ("NULL callout in fork_exit")); 1201 callout(arg, frame); 1202 1203 /* 1204 * Check if a kernel thread misbehaved and returned from its main 1205 * function. 1206 */ 1207 if (p->p_flag & P_KPROC) { 1208 printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n", 1209 td->td_name, p->p_pid); 1210 kthread_exit(); 1211 } 1212 mtx_assert(&Giant, MA_NOTOWNED); 1213 1214 /* 1215 * Now going to return to userland. 1216 */ 1217 1218 if (p->p_sysent->sv_schedtail != NULL) 1219 (p->p_sysent->sv_schedtail)(td); 1220 1221 userret(td, frame); 1222 } 1223 1224 /* 1225 * Simplified back end of syscall(), used when returning from fork() 1226 * directly into user mode. This function is passed in to fork_exit() 1227 * as the first parameter and is called when returning to a new 1228 * userland process. 1229 */ 1230 void 1231 fork_return(struct thread *td, struct trapframe *frame) 1232 { 1233 struct proc *p; 1234 1235 p = td->td_proc; 1236 if (td->td_dbgflags & TDB_STOPATFORK) { 1237 PROC_LOCK(p); 1238 if ((p->p_flag & P_TRACED) != 0) { 1239 /* 1240 * Inform the debugger if one is still present. 1241 */ 1242 td->td_dbgflags |= TDB_CHILD | TDB_SCX | TDB_FSTP; 1243 ptracestop(td, SIGSTOP, NULL); 1244 td->td_dbgflags &= ~(TDB_CHILD | TDB_SCX); 1245 } else { 1246 /* 1247 * ... otherwise clear the request. 1248 */ 1249 td->td_dbgflags &= ~TDB_STOPATFORK; 1250 } 1251 PROC_UNLOCK(p); 1252 } else if (p->p_flag & P_TRACED) { 1253 /* 1254 * This is the start of a new thread in a traced 1255 * process. Report a system call exit event. 1256 */ 1257 PROC_LOCK(p); 1258 td->td_dbgflags |= TDB_SCX; 1259 if ((p->p_ptevents & PTRACE_SCX) != 0 || 1260 (td->td_dbgflags & TDB_BORN) != 0) 1261 ptracestop(td, SIGTRAP, NULL); 1262 td->td_dbgflags &= ~(TDB_SCX | TDB_BORN); 1263 PROC_UNLOCK(p); 1264 } 1265 1266 /* 1267 * If the prison was killed mid-fork, die along with it. 1268 */ 1269 if (!prison_isalive(td->td_ucred->cr_prison)) 1270 exit1(td, 0, SIGKILL); 1271 1272 #ifdef KTRACE 1273 if (KTRPOINT(td, KTR_SYSRET)) 1274 ktrsysret(td->td_sa.code, 0, 0); 1275 #endif 1276 } 1277 1278 static void 1279 fork_init(void *arg __unused) 1280 { 1281 ast_register(TDA_VFORK, ASTR_ASTF_REQUIRED | ASTR_TDP, TDP_RFPPWAIT, 1282 ast_vfork); 1283 } 1284 SYSINIT(fork, SI_SUB_INTRINSIC, SI_ORDER_ANY, fork_init, NULL); 1285