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