]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/kern_fork.c
xnu-2782.20.48.tar.gz
[apple/xnu.git] / bsd / kern / kern_fork.c
CommitLineData
1c79356b 1/*
2d21ac55 2 * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
29/*
30 * Copyright (c) 1982, 1986, 1989, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)kern_fork.c 8.8 (Berkeley) 2/14/95
67 */
2d21ac55
A
68/*
69 * NOTICE: This file was modified by McAfee Research in 2004 to introduce
70 * support for mandatory and extensible security protections. This notice
71 * is included in support of clause 2.2 (b) of the Apple Public License,
72 * Version 2.0.
73 */
74/*
75 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
76 * support for mandatory and extensible security protections. This notice
77 * is included in support of clause 2.2 (b) of the Apple Public License,
78 * Version 2.0.
79 */
1c79356b 80
55e303ae 81#include <kern/assert.h>
1c79356b
A
82#include <sys/param.h>
83#include <sys/systm.h>
84#include <sys/filedesc.h>
85#include <sys/kernel.h>
86#include <sys/malloc.h>
91447636
A
87#include <sys/proc_internal.h>
88#include <sys/kauth.h>
1c79356b
A
89#include <sys/user.h>
90#include <sys/resourcevar.h>
91447636
A
91#include <sys/vnode_internal.h>
92#include <sys/file_internal.h>
1c79356b 93#include <sys/acct.h>
2d21ac55
A
94#include <sys/codesign.h>
95#include <sys/sysproto.h>
96#if CONFIG_DTRACE
97/* Do not include dtrace.h, it redefines kmem_[alloc/free] */
98extern void dtrace_fasttrap_fork(proc_t, proc_t);
99extern void (*dtrace_helpers_fork)(proc_t, proc_t);
fe8ab488 100extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
2d21ac55
A
101extern void dtrace_lazy_dofs_duplicate(proc_t, proc_t);
102
fe8ab488
A
103/*
104 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
105 * we will store its value before actually calling it.
106 */
107static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
108
2d21ac55 109#include <sys/dtrace_ptss.h>
9bccf70c 110#endif
1c79356b 111
b0d623f7 112#include <security/audit/audit.h>
91447636 113
1c79356b 114#include <mach/mach_types.h>
fe8ab488 115#include <kern/coalition.h>
91447636
A
116#include <kern/kern_types.h>
117#include <kern/kalloc.h>
1c79356b 118#include <kern/mach_param.h>
91447636 119#include <kern/task.h>
4b17d6b6 120#include <kern/thread.h>
2d21ac55 121#include <kern/thread_call.h>
91447636 122#include <kern/zalloc.h>
1c79356b
A
123
124#include <machine/spl.h>
125
2d21ac55
A
126#if CONFIG_MACF
127#include <security/mac.h>
128#include <security/mac_mach_internal.h>
129#endif
130
131#include <vm/vm_map.h>
132#include <vm/vm_protos.h>
133#include <vm/vm_shared_region.h>
134
135#include <sys/shm_internal.h> /* for shmfork() */
136#include <mach/task.h> /* for thread_create() */
137#include <mach/thread_act.h> /* for thread_resume() */
91447636 138
2d21ac55
A
139#include <sys/sdt.h>
140
316670eb
A
141#if CONFIG_MEMORYSTATUS
142#include <sys/kern_memorystatus.h>
143#endif
144
2d21ac55
A
145/* XXX routines which should have Mach prototypes, but don't */
146void thread_set_parent(thread_t parent, int pid);
147extern void act_thread_catt(void *ctx);
148void thread_set_child(thread_t child, int pid);
149void *act_thread_csave(void);
150
151
fe8ab488 152thread_t cloneproc(task_t, coalition_t, proc_t, int, int);
b0d623f7
A
153proc_t forkproc(proc_t);
154void forkproc_free(proc_t);
fe8ab488 155thread_t fork_create_child(task_t parent_task, coalition_t parent_coalition, proc_t child, int inherit_memory, int is64bit);
b0d623f7
A
156void proc_vfork_begin(proc_t parent_proc);
157void proc_vfork_end(proc_t parent_proc);
1c79356b
A
158
159#define DOFORK 0x1 /* fork() system call */
160#define DOVFORK 0x2 /* vfork() system call */
1c79356b 161
b0d623f7
A
162/*
163 * proc_vfork_begin
164 *
165 * Description: start a vfork on a process
166 *
167 * Parameters: parent_proc process (re)entering vfork state
168 *
169 * Returns: (void)
170 *
171 * Notes: Although this function increments a count, a count in
172 * excess of 1 is not currently supported. According to the
173 * POSIX standard, calling anything other than execve() or
316670eb
A
174 * _exit() following a vfork(), including calling vfork()
175 * itself again, will result in undefined behaviour
b0d623f7
A
176 */
177void
178proc_vfork_begin(proc_t parent_proc)
179{
180 proc_lock(parent_proc);
181 parent_proc->p_lflag |= P_LVFORK;
182 parent_proc->p_vforkcnt++;
183 proc_unlock(parent_proc);
184}
185
186/*
187 * proc_vfork_end
188 *
189 * Description: stop a vfork on a process
190 *
191 * Parameters: parent_proc process leaving vfork state
192 *
193 * Returns: (void)
194 *
316670eb 195 * Notes: Decrements the count; currently, reentrancy of vfork()
b0d623f7
A
196 * is unsupported on the current process
197 */
198void
199proc_vfork_end(proc_t parent_proc)
200{
201 proc_lock(parent_proc);
202 parent_proc->p_vforkcnt--;
203 if (parent_proc->p_vforkcnt < 0)
204 panic("vfork cnt is -ve");
b0d623f7
A
205 if (parent_proc->p_vforkcnt == 0)
206 parent_proc->p_lflag &= ~P_LVFORK;
207 proc_unlock(parent_proc);
208}
209
1c79356b
A
210
211/*
2d21ac55
A
212 * vfork
213 *
214 * Description: vfork system call
215 *
216 * Parameters: void [no arguments]
217 *
218 * Retval: 0 (to child process)
219 * !0 pid of child (to parent process)
220 * -1 error (see "Returns:")
221 *
222 * Returns: EAGAIN Administrative limit reached
b0d623f7 223 * EINVAL vfork() called during vfork()
2d21ac55
A
224 * ENOMEM Failed to allocate new process
225 *
226 * Note: After a successful call to this function, the parent process
227 * has its task, thread, and uthread lent to the child process,
228 * and control is returned to the caller; if this function is
229 * invoked as a system call, the return is to user space, and
230 * is effectively running on the child process.
231 *
232 * Subsequent calls that operate on process state are permitted,
233 * though discouraged, and will operate on the child process; any
234 * operations on the task, thread, or uthread will result in
235 * changes in the parent state, and, if inheritable, the child
236 * state, when a task, thread, and uthread are realized for the
237 * child process at execve() time, will also be effected. Given
238 * this, it's recemmended that people use the posix_spawn() call
239 * instead.
b0d623f7
A
240 *
241 * BLOCK DIAGRAM OF VFORK
242 *
243 * Before:
244 *
245 * ,----------------. ,-------------.
246 * | | task | |
247 * | parent_thread | ------> | parent_task |
248 * | | <.list. | |
249 * `----------------' `-------------'
250 * uthread | ^ bsd_info | ^
251 * v | vc_thread v | task
252 * ,----------------. ,-------------.
253 * | | | |
254 * | parent_uthread | <.list. | parent_proc | <-- current_proc()
255 * | | | |
256 * `----------------' `-------------'
257 * uu_proc |
258 * v
259 * NULL
260 *
261 * After:
262 *
263 * ,----------------. ,-------------.
264 * | | task | |
265 * ,----> | parent_thread | ------> | parent_task |
266 * | | | <.list. | |
267 * | `----------------' `-------------'
268 * | uthread | ^ bsd_info | ^
269 * | v | vc_thread v | task
270 * | ,----------------. ,-------------.
271 * | | | | |
272 * | | parent_uthread | <.list. | parent_proc |
273 * | | | | |
274 * | `----------------' `-------------'
275 * | uu_proc | . list
276 * | v v
277 * | ,----------------.
278 * `----- | |
279 * p_vforkact | child_proc | <-- current_proc()
280 * | |
281 * `----------------'
282 */
283int
284vfork(proc_t parent_proc, __unused struct vfork_args *uap, int32_t *retval)
285{
286 thread_t child_thread;
287 int err;
288
fe8ab488 289 if ((err = fork1(parent_proc, &child_thread, PROC_CREATE_VFORK, COALITION_NULL)) != 0) {
b0d623f7
A
290 retval[1] = 0;
291 } else {
39236c6e
A
292 uthread_t ut = get_bsdthread_info(current_thread());
293 proc_t child_proc = ut->uu_proc;
b0d623f7
A
294
295 retval[0] = child_proc->p_pid;
296 retval[1] = 1; /* flag child return for user space */
297
298 /*
299 * Drop the signal lock on the child which was taken on our
300 * behalf by forkproc()/cloneproc() to prevent signals being
301 * received by the child in a partially constructed state.
302 */
303 proc_signalend(child_proc, 0);
304 proc_transend(child_proc, 0);
305
b0d623f7
A
306 proc_knote(parent_proc, NOTE_FORK | child_proc->p_pid);
307 DTRACE_PROC1(create, proc_t, child_proc);
39236c6e 308 ut->uu_flag &= ~UT_VFORKING;
b0d623f7
A
309 }
310
39236c6e 311 return (err);
b0d623f7
A
312}
313
314
315/*
316 * fork1
317 *
318 * Description: common code used by all new process creation other than the
319 * bootstrap of the initial process on the system
320 *
321 * Parameters: parent_proc parent process of the process being
322 * child_threadp pointer to location to receive the
323 * Mach thread_t of the child process
324 * breated
325 * kind kind of creation being requested
fe8ab488
A
326 * coalition if spawn, coalition the child process
327 * should join, or COALITION_NULL to
328 * inherit the parent's. On non-spawns,
329 * this param is ignored and the child
330 * always inherits the parent's coalition.
b0d623f7
A
331 *
332 * Notes: Permissable values for 'kind':
333 *
334 * PROC_CREATE_FORK Create a complete process which will
335 * return actively running in both the
336 * parent and the child; the child copies
337 * the parent address space.
338 * PROC_CREATE_SPAWN Create a complete process which will
339 * return actively running in the parent
340 * only after returning actively running
341 * in the child; the child address space
342 * is newly created by an image activator,
343 * after which the child is run.
344 * PROC_CREATE_VFORK Creates a partial process which will
345 * borrow the parent task, thread, and
346 * uthread to return running in the child;
347 * the child address space and other parts
348 * are lazily created at execve() time, or
349 * the child is terminated, and the parent
350 * does not actively run until that
351 * happens.
352 *
353 * At first it may seem strange that we return the child thread
354 * address rather than process structure, since the process is
355 * the only part guaranteed to be "new"; however, since we do
356 * not actualy adjust other references between Mach and BSD (see
357 * the block diagram above the implementation of vfork()), this
358 * is the only method which guarantees us the ability to get
359 * back to the other information.
1c79356b
A
360 */
361int
fe8ab488 362fork1(proc_t parent_proc, thread_t *child_threadp, int kind, coalition_t coalition)
1c79356b 363{
b0d623f7
A
364 thread_t parent_thread = (thread_t)current_thread();
365 uthread_t parent_uthread = (uthread_t)get_bsdthread_info(parent_thread);
366 proc_t child_proc = NULL; /* set in switch, but compiler... */
367 thread_t child_thread = NULL;
2d21ac55 368 uid_t uid;
0b4e3aa0 369 int count;
b0d623f7
A
370 int err = 0;
371 int spawn = 0;
91447636 372
0b4e3aa0
A
373 /*
374 * Although process entries are dynamically created, we still keep
375 * a global limit on the maximum number we will create. Don't allow
376 * a nonprivileged user to use the last process; don't let root
377 * exceed the limit. The variable nprocs is the current number of
378 * processes, maxproc is the limit.
379 */
6d2010ae 380 uid = kauth_getruid();
2d21ac55 381 proc_list_lock();
0b4e3aa0 382 if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
2d21ac55 383 proc_list_unlock();
0b4e3aa0 384 tablefull("proc");
0b4e3aa0
A
385 return (EAGAIN);
386 }
2d21ac55 387 proc_list_unlock();
0b4e3aa0
A
388
389 /*
390 * Increment the count of procs running with this uid. Don't allow
2d21ac55
A
391 * a nonprivileged user to exceed their current limit, which is
392 * always less than what an rlim_t can hold.
393 * (locking protection is provided by list lock held in chgproccnt)
0b4e3aa0
A
394 */
395 count = chgproccnt(uid, 1);
2d21ac55 396 if (uid != 0 &&
b0d623f7
A
397 (rlim_t)count > parent_proc->p_rlimit[RLIMIT_NPROC].rlim_cur) {
398 err = EAGAIN;
399 goto bad;
0b4e3aa0 400 }
2d21ac55
A
401
402#if CONFIG_MACF
403 /*
404 * Determine if MAC policies applied to the process will allow
b0d623f7 405 * it to fork. This is an advisory-only check.
2d21ac55 406 */
b0d623f7 407 err = mac_proc_check_fork(parent_proc);
2d21ac55 408 if (err != 0) {
b0d623f7 409 goto bad;
2d21ac55
A
410 }
411#endif
412
b0d623f7
A
413 switch(kind) {
414 case PROC_CREATE_VFORK:
415 /*
416 * Prevent a vfork while we are in vfork(); we should
417 * also likely preventing a fork here as well, and this
418 * check should then be outside the switch statement,
419 * since the proc struct contents will copy from the
420 * child and the tash/thread/uthread from the parent in
421 * that case. We do not support vfork() in vfork()
422 * because we don't have to; the same non-requirement
423 * is true of both fork() and posix_spawn() and any
424 * call other than execve() amd _exit(), but we've
425 * been historically lenient, so we continue to be so
426 * (for now).
427 *
428 * <rdar://6640521> Probably a source of random panics
429 */
430 if (parent_uthread->uu_flag & UT_VFORK) {
431 printf("fork1 called within vfork by %s\n", parent_proc->p_comm);
432 err = EINVAL;
433 goto bad;
434 }
0b4e3aa0 435
2d21ac55 436 /*
b0d623f7
A
437 * Flag us in progress; if we chose to support vfork() in
438 * vfork(), we would chain our parent at this point (in
439 * effect, a stack push). We don't, since we actually want
440 * to disallow everything not specified in the standard
2d21ac55 441 */
b0d623f7
A
442 proc_vfork_begin(parent_proc);
443
444 /* The newly created process comes with signal lock held */
445 if ((child_proc = forkproc(parent_proc)) == NULL) {
446 /* Failed to allocate new process */
447 proc_vfork_end(parent_proc);
448 err = ENOMEM;
449 goto bad;
450 }
2d21ac55 451
b0d623f7 452// XXX BEGIN: wants to move to be common code (and safe)
2d21ac55 453#if CONFIG_MACF
b0d623f7
A
454 /*
455 * allow policies to associate the credential/label that
456 * we referenced from the parent ... with the child
457 * JMM - this really isn't safe, as we can drop that
458 * association without informing the policy in other
459 * situations (keep long enough to get policies changed)
460 */
461 mac_cred_label_associate_fork(child_proc->p_ucred, child_proc);
2d21ac55
A
462#endif
463
b0d623f7
A
464 /*
465 * Propogate change of PID - may get new cred if auditing.
466 *
467 * NOTE: This has no effect in the vfork case, since
468 * child_proc->task != current_task(), but we duplicate it
469 * because this is probably, ultimately, wrong, since we
470 * will be running in the "child" which is the parent task
471 * with the wrong token until we get to the execve() or
472 * _exit() call; a lot of "undefined" can happen before
473 * that.
474 *
475 * <rdar://6640530> disallow everything but exeve()/_exit()?
476 */
477 set_security_token(child_proc);
2d21ac55 478
b0d623f7 479 AUDIT_ARG(pid, child_proc->p_pid);
2d21ac55 480
b0d623f7 481// XXX END: wants to move to be common code (and safe)
2d21ac55 482
b0d623f7
A
483 /*
484 * BORROW PARENT TASK, THREAD, UTHREAD FOR CHILD
485 *
486 * Note: this is where we would "push" state instead of setting
487 * it for nested vfork() support (see proc_vfork_end() for
488 * description if issues here).
489 */
490 child_proc->task = parent_proc->task;
0b4e3aa0 491
b0d623f7
A
492 child_proc->p_lflag |= P_LINVFORK;
493 child_proc->p_vforkact = parent_thread;
494 child_proc->p_stat = SRUN;
0b4e3aa0 495
39236c6e
A
496 /*
497 * Until UT_VFORKING is cleared at the end of the vfork
498 * syscall, the process identity of this thread is slightly
499 * murky.
500 *
501 * As long as UT_VFORK and it's associated field (uu_proc)
502 * is set, current_proc() will always return the child process.
503 *
504 * However dtrace_proc_selfpid() returns the parent pid to
505 * ensure that e.g. the proc:::create probe actions accrue
506 * to the parent. (Otherwise the child magically seems to
507 * have created itself!)
508 */
509 parent_uthread->uu_flag |= UT_VFORK | UT_VFORKING;
b0d623f7
A
510 parent_uthread->uu_proc = child_proc;
511 parent_uthread->uu_userstate = (void *)act_thread_csave();
512 parent_uthread->uu_vforkmask = parent_uthread->uu_sigmask;
0b4e3aa0 513
b0d623f7
A
514 /* temporarily drop thread-set-id state */
515 if (parent_uthread->uu_flag & UT_SETUID) {
516 parent_uthread->uu_flag |= UT_WASSETUID;
517 parent_uthread->uu_flag &= ~UT_SETUID;
518 }
0b4e3aa0 519
b0d623f7
A
520 /* blow thread state information */
521 /* XXX is this actually necessary, given syscall return? */
522 thread_set_child(parent_thread, child_proc->p_pid);
523
524 child_proc->p_acflag = AFORK; /* forked but not exec'ed */
525
526 /*
527 * Preserve synchronization semantics of vfork. If
528 * waiting for child to exec or exit, set P_PPWAIT
529 * on child, and sleep on our proc (in case of exit).
530 */
531 child_proc->p_lflag |= P_LPPWAIT;
532 pinsertchild(parent_proc, child_proc); /* set visible */
533
534 break;
535
536 case PROC_CREATE_SPAWN:
537 /*
538 * A spawned process differs from a forked process in that
539 * the spawned process does not carry around the parents
540 * baggage with regard to address space copying, dtrace,
541 * and so on.
542 */
543 spawn = 1;
544
545 /* FALLSTHROUGH */
546
547 case PROC_CREATE_FORK:
548 /*
549 * When we clone the parent process, we are going to inherit
550 * its task attributes and memory, since when we fork, we
551 * will, in effect, create a duplicate of it, with only minor
552 * differences. Contrarily, spawned processes do not inherit.
553 */
fe8ab488
A
554 if ((child_thread = cloneproc(parent_proc->task,
555 spawn ? coalition : COALITION_NULL,
556 parent_proc,
557 spawn ? FALSE : TRUE,
558 FALSE)) == NULL) {
b0d623f7
A
559 /* Failed to create thread */
560 err = EAGAIN;
561 goto bad;
562 }
563
564 /* copy current thread state into the child thread (only for fork) */
565 if (!spawn) {
566 thread_dup(child_thread);
567 }
568
569 /* child_proc = child_thread->task->proc; */
570 child_proc = (proc_t)(get_bsdtask_info(get_threadtask(child_thread)));
0b4e3aa0 571
b0d623f7
A
572// XXX BEGIN: wants to move to be common code (and safe)
573#if CONFIG_MACF
574 /*
575 * allow policies to associate the credential/label that
576 * we referenced from the parent ... with the child
577 * JMM - this really isn't safe, as we can drop that
578 * association without informing the policy in other
579 * situations (keep long enough to get policies changed)
580 */
581 mac_cred_label_associate_fork(child_proc->p_ucred, child_proc);
582#endif
583
584 /*
585 * Propogate change of PID - may get new cred if auditing.
586 *
587 * NOTE: This has no effect in the vfork case, since
588 * child_proc->task != current_task(), but we duplicate it
589 * because this is probably, ultimately, wrong, since we
590 * will be running in the "child" which is the parent task
591 * with the wrong token until we get to the execve() or
592 * _exit() call; a lot of "undefined" can happen before
593 * that.
594 *
595 * <rdar://6640530> disallow everything but exeve()/_exit()?
596 */
597 set_security_token(child_proc);
0b4e3aa0 598
b0d623f7 599 AUDIT_ARG(pid, child_proc->p_pid);
2d21ac55 600
b0d623f7
A
601// XXX END: wants to move to be common code (and safe)
602
603 /*
604 * Blow thread state information; this is what gives the child
605 * process its "return" value from a fork() call.
606 *
607 * Note: this should probably move to fork() proper, since it
608 * is not relevent to spawn, and the value won't matter
609 * until we resume the child there. If you are in here
610 * refactoring code, consider doing this at the same time.
611 */
612 thread_set_child(child_thread, child_proc->p_pid);
613
614 child_proc->p_acflag = AFORK; /* forked but not exec'ed */
615
616// <rdar://6598155> dtrace code cleanup needed
617#if CONFIG_DTRACE
618 /*
619 * This code applies to new processes who are copying the task
620 * and thread state and address spaces of their parent process.
621 */
622 if (!spawn) {
623// <rdar://6598155> call dtrace specific function here instead of all this...
624 /*
625 * APPLE NOTE: Solaris does a sprlock() and drops the
626 * proc_lock here. We're cheating a bit and only taking
627 * the p_dtrace_sprlock lock. A full sprlock would
628 * task_suspend the parent.
629 */
630 lck_mtx_lock(&parent_proc->p_dtrace_sprlock);
631
632 /*
633 * Remove all DTrace tracepoints from the child process. We
634 * need to do this _before_ duplicating USDT providers since
635 * any associated probes may be immediately enabled.
636 */
637 if (parent_proc->p_dtrace_count > 0) {
638 dtrace_fasttrap_fork(parent_proc, child_proc);
639 }
640
641 lck_mtx_unlock(&parent_proc->p_dtrace_sprlock);
642
643 /*
644 * Duplicate any lazy dof(s). This must be done while NOT
645 * holding the parent sprlock! Lock ordering is
646 * dtrace_dof_mode_lock, then sprlock. It is imperative we
647 * always call dtrace_lazy_dofs_duplicate, rather than null
648 * check and call if !NULL. If we NULL test, during lazy dof
649 * faulting we can race with the faulting code and proceed
650 * from here to beyond the helpers copy. The lazy dof
651 * faulting will then fail to copy the helpers to the child
652 * process.
653 */
654 dtrace_lazy_dofs_duplicate(parent_proc, child_proc);
655
656 /*
657 * Duplicate any helper actions and providers. The SFORKING
658 * we set above informs the code to enable USDT probes that
659 * sprlock() may fail because the child is being forked.
660 */
661 /*
662 * APPLE NOTE: As best I can tell, Apple's sprlock() equivalent
663 * never fails to find the child. We do not set SFORKING.
664 */
665 if (parent_proc->p_dtrace_helpers != NULL && dtrace_helpers_fork) {
666 (*dtrace_helpers_fork)(parent_proc, child_proc);
667 }
668
669 }
670#endif /* CONFIG_DTRACE */
671
672 break;
673
674 default:
675 panic("fork1 called with unknown kind %d", kind);
676 break;
677 }
678
679
680 /* return the thread pointer to the caller */
681 *child_threadp = child_thread;
682
683bad:
684 /*
685 * In the error case, we return a 0 value for the returned pid (but
686 * it is ignored in the trampoline due to the error return); this
687 * is probably not necessary.
688 */
689 if (err) {
690 (void)chgproccnt(uid, -1);
691 }
0b4e3aa0 692
b0d623f7 693 return (err);
1c79356b
A
694}
695
b0d623f7 696
0b4e3aa0 697/*
2d21ac55
A
698 * vfork_return
699 *
700 * Description: "Return" to parent vfork thread() following execve/_exit;
701 * this is done by reassociating the parent process structure
702 * with the task, thread, and uthread.
703 *
316670eb
A
704 * Refer to the ASCII art above vfork() to figure out the
705 * state we're undoing.
706 *
b0d623f7 707 * Parameters: child_proc Child process
2d21ac55
A
708 * retval System call return value array
709 * rval Return value to present to parent
710 *
711 * Returns: void
712 *
316670eb
A
713 * Notes: The caller resumes or exits the parent, as appropriate, after
714 * calling this function.
0b4e3aa0
A
715 */
716void
b0d623f7 717vfork_return(proc_t child_proc, int32_t *retval, int rval)
0b4e3aa0 718{
316670eb
A
719 task_t parent_task = get_threadtask(child_proc->p_vforkact);
720 proc_t parent_proc = get_bsdtask_info(parent_task);
721 thread_t th = current_thread();
722 uthread_t uth = get_bsdthread_info(th);
0b4e3aa0 723
316670eb 724 act_thread_catt(uth->uu_userstate);
0b4e3aa0 725
316670eb 726 /* clear vfork state in parent proc structure */
b0d623f7
A
727 proc_vfork_end(parent_proc);
728
729 /* REPATRIATE PARENT TASK, THREAD, UTHREAD */
316670eb
A
730 uth->uu_userstate = 0;
731 uth->uu_flag &= ~UT_VFORK;
91447636 732 /* restore thread-set-id state */
316670eb
A
733 if (uth->uu_flag & UT_WASSETUID) {
734 uth->uu_flag |= UT_SETUID;
735 uth->uu_flag &= UT_WASSETUID;
91447636 736 }
316670eb
A
737 uth->uu_proc = 0;
738 uth->uu_sigmask = uth->uu_vforkmask;
739
740 proc_lock(child_proc);
741 child_proc->p_lflag &= ~P_LINVFORK;
742 child_proc->p_vforkact = 0;
743 proc_unlock(child_proc);
0b4e3aa0 744
316670eb 745 thread_set_parent(th, rval);
0b4e3aa0
A
746
747 if (retval) {
2d21ac55 748 retval[0] = rval;
0b4e3aa0
A
749 retval[1] = 0; /* mark parent */
750 }
0b4e3aa0
A
751}
752
2d21ac55
A
753
754/*
755 * fork_create_child
756 *
757 * Description: Common operations associated with the creation of a child
758 * process
759 *
760 * Parameters: parent_task parent task
fe8ab488 761 * parent_coalition parent_coalition
b0d623f7 762 * child_proc child process
2d21ac55
A
763 * inherit_memory TRUE, if the parents address space is
764 * to be inherited by the child
765 * is64bit TRUE, if the child being created will
766 * be associated with a 64 bit process
767 * rather than a 32 bit process
768 *
769 * Note: This code is called in the fork() case, from the execve() call
770 * graph, if implementing an execve() following a vfork(), from
771 * the posix_spawn() call graph (which implicitly includes a
772 * vfork() equivalent call, and in the system bootstrap case.
773 *
774 * It creates a new task and thread (and as a side effect of the
fe8ab488
A
775 * thread creation, a uthread) in the parent coalition, which is
776 * then associated with the process 'child'. If the parent
777 * process address space is to be inherited, then a flag
778 * indicates that the newly created task should inherit this from
779 * the child task.
2d21ac55
A
780 *
781 * As a special concession to bootstrapping the initial process
782 * in the system, it's possible for 'parent_task' to be TASK_NULL;
783 * in this case, 'inherit_memory' MUST be FALSE.
784 */
91447636 785thread_t
fe8ab488 786fork_create_child(task_t parent_task, coalition_t parent_coalition, proc_t child_proc, int inherit_memory, int is64bit)
0b4e3aa0 787{
2d21ac55
A
788 thread_t child_thread = NULL;
789 task_t child_task;
790 kern_return_t result;
791
792 /* Create a new task for the child process */
793 result = task_create_internal(parent_task,
fe8ab488 794 parent_coalition,
2d21ac55
A
795 inherit_memory,
796 is64bit,
797 &child_task);
798 if (result != KERN_SUCCESS) {
39236c6e
A
799 printf("%s: task_create_internal failed. Code: %d\n",
800 __func__, result);
2d21ac55
A
801 goto bad;
802 }
0b4e3aa0 803
b0d623f7
A
804 /* Set the child process task to the new task */
805 child_proc->task = child_task;
2d21ac55 806
b0d623f7
A
807 /* Set child task process to child proc */
808 set_bsdtask_info(child_task, child_proc);
2d21ac55
A
809
810 /* Propagate CPU limit timer from parent */
b0d623f7 811 if (timerisset(&child_proc->p_rlim_cpu))
2d21ac55
A
812 task_vtimer_set(child_task, TASK_VTIMER_RLIM);
813
814 /* Set/clear 64 bit vm_map flag */
815 if (is64bit)
816 vm_map_set_64bit(get_task_map(child_task));
0b4e3aa0 817 else
2d21ac55
A
818 vm_map_set_32bit(get_task_map(child_task));
819
b0d623f7
A
820 /*
821 * Set child process BSD visible scheduler priority if nice value
822 * inherited from parent
823 */
824 if (child_proc->p_nice != 0)
825 resetpriority(child_proc);
0b4e3aa0 826
2d21ac55
A
827 /* Create a new thread for the child process */
828 result = thread_create(child_task, &child_thread);
829 if (result != KERN_SUCCESS) {
39236c6e
A
830 printf("%s: thread_create failed. Code: %d\n",
831 __func__, result);
2d21ac55
A
832 task_deallocate(child_task);
833 child_task = NULL;
834 }
4b17d6b6
A
835
836 /*
39236c6e
A
837 * Tag thread as being the first thread in its task.
838 */
4b17d6b6
A
839 thread_set_tag(child_thread, THREAD_TAG_MAINTHREAD);
840
2d21ac55
A
841bad:
842 thread_yield_internal(1);
843
844 return(child_thread);
0b4e3aa0
A
845}
846
847
2d21ac55
A
848/*
849 * fork
850 *
851 * Description: fork system call.
852 *
853 * Parameters: parent Parent process to fork
854 * uap (void) [unused]
855 * retval Return value
856 *
857 * Returns: 0 Success
858 * EAGAIN Resource unavailable, try again
b0d623f7
A
859 *
860 * Notes: Attempts to create a new child process which inherits state
861 * from the parent process. If successful, the call returns
862 * having created an initially suspended child process with an
863 * extra Mach task and thread reference, for which the thread
864 * is initially suspended. Until we resume the child process,
865 * it is not yet running.
866 *
867 * The return information to the child is contained in the
868 * thread state structure of the new child, and does not
869 * become visible to the child through a normal return process,
870 * since it never made the call into the kernel itself in the
871 * first place.
872 *
873 * After resuming the thread, this function returns directly to
874 * the parent process which invoked the fork() system call.
875 *
876 * Important: The child thread_resume occurs before the parent returns;
877 * depending on scheduling latency, this means that it is not
878 * deterministic as to whether the parent or child is scheduled
879 * to run first. It is entirely possible that the child could
880 * run to completion prior to the parent running.
2d21ac55
A
881 */
882int
b0d623f7 883fork(proc_t parent_proc, __unused struct fork_args *uap, int32_t *retval)
2d21ac55 884{
b0d623f7 885 thread_t child_thread;
2d21ac55 886 int err;
1c79356b 887
b0d623f7 888 retval[1] = 0; /* flag parent return for user space */
1c79356b 889
fe8ab488 890 if ((err = fork1(parent_proc, &child_thread, PROC_CREATE_FORK, COALITION_NULL)) == 0) {
b0d623f7
A
891 task_t child_task;
892 proc_t child_proc;
2d21ac55 893
b0d623f7
A
894 /* Return to the parent */
895 child_proc = (proc_t)get_bsdthreadtask_info(child_thread);
896 retval[0] = child_proc->p_pid;
2d21ac55 897
b0d623f7
A
898 /*
899 * Drop the signal lock on the child which was taken on our
900 * behalf by forkproc()/cloneproc() to prevent signals being
901 * received by the child in a partially constructed state.
902 */
903 proc_signalend(child_proc, 0);
904 proc_transend(child_proc, 0);
2d21ac55 905
b0d623f7
A
906 /* flag the fork has occurred */
907 proc_knote(parent_proc, NOTE_FORK | child_proc->p_pid);
908 DTRACE_PROC1(create, proc_t, child_proc);
2d21ac55 909
fe8ab488
A
910#if CONFIG_DTRACE
911 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL)
912 (*dtrace_proc_waitfor_hook)(child_proc);
913#endif
914
b0d623f7
A
915 /* "Return" to the child */
916 (void)thread_resume(child_thread);
2d21ac55 917
b0d623f7
A
918 /* drop the extra references we got during the creation */
919 if ((child_task = (task_t)get_threadtask(child_thread)) != NULL) {
920 task_deallocate(child_task);
921 }
922 thread_deallocate(child_thread);
2d21ac55
A
923 }
924
b0d623f7 925 return(err);
1c79356b
A
926}
927
b0d623f7 928
1c79356b 929/*
2d21ac55
A
930 * cloneproc
931 *
932 * Description: Create a new process from a specified process.
933 *
b0d623f7
A
934 * Parameters: parent_task The parent task to be cloned, or
935 * TASK_NULL is task characteristics
936 * are not to be inherited
937 * be cloned, or TASK_NULL if the new
938 * task is not to inherit the VM
939 * characteristics of the parent
940 * parent_proc The parent process to be cloned
941 * inherit_memory True if the child is to inherit
942 * memory from the parent; if this is
943 * non-NULL, then the parent_task must
944 * also be non-NULL
39236c6e
A
945 * memstat_internal Whether to track the process in the
946 * jetsam priority list (if configured)
1c79356b 947 *
2d21ac55
A
948 * Returns: !NULL pointer to new child thread
949 * NULL Failure (unspecified)
950 *
951 * Note: On return newly created child process has signal lock held
952 * to block delivery of signal to it if called with lock set.
953 * fork() code needs to explicity remove this lock before
954 * signals can be delivered
955 *
956 * In the case of bootstrap, this function can be called from
957 * bsd_utaskbootstrap() in order to bootstrap the first process;
958 * the net effect is to provide a uthread structure for the
b0d623f7
A
959 * kernel process associated with the kernel task.
960 *
961 * XXX: Tristating using the value parent_task as the major key
962 * and inherit_memory as the minor key is something we should
963 * refactor later; we owe the current semantics, ultimately,
964 * to the semantics of task_create_internal. For now, we will
965 * live with this being somewhat awkward.
1c79356b 966 */
91447636 967thread_t
fe8ab488 968cloneproc(task_t parent_task, coalition_t parent_coalition, proc_t parent_proc, int inherit_memory, int memstat_internal)
0b4e3aa0 969{
39236c6e
A
970#if !CONFIG_MEMORYSTATUS
971#pragma unused(memstat_internal)
972#endif
b0d623f7
A
973 task_t child_task;
974 proc_t child_proc;
975 thread_t child_thread = NULL;
0b4e3aa0 976
b0d623f7 977 if ((child_proc = forkproc(parent_proc)) == NULL) {
2d21ac55
A
978 /* Failed to allocate new process */
979 goto bad;
980 }
9bccf70c 981
fe8ab488 982 child_thread = fork_create_child(parent_task, parent_coalition, child_proc, inherit_memory, (parent_task == TASK_NULL) ? FALSE : (parent_proc->p_flag & P_LP64));
b0d623f7
A
983
984 if (child_thread == NULL) {
2d21ac55
A
985 /*
986 * Failed to create thread; now we must deconstruct the new
987 * process previously obtained from forkproc().
988 */
b0d623f7 989 forkproc_free(child_proc);
2d21ac55
A
990 goto bad;
991 }
9bccf70c 992
b0d623f7
A
993 child_task = get_threadtask(child_thread);
994 if (parent_proc->p_flag & P_LP64) {
995 task_set_64bit(child_task, TRUE);
996 OSBitOrAtomic(P_LP64, (UInt32 *)&child_proc->p_flag);
b0d623f7
A
997 } else {
998 task_set_64bit(child_task, FALSE);
999 OSBitAndAtomic(~((uint32_t)P_LP64), (UInt32 *)&child_proc->p_flag);
1000 }
1001
39236c6e
A
1002#if CONFIG_MEMORYSTATUS
1003 if (memstat_internal) {
1004 proc_list_lock();
1005 child_proc->p_memstat_state |= P_MEMSTAT_INTERNAL;
1006 proc_list_unlock();
1007 }
1008#endif
1009
2d21ac55 1010 /* make child visible */
b0d623f7 1011 pinsertchild(parent_proc, child_proc);
0b4e3aa0 1012
0b4e3aa0
A
1013 /*
1014 * Make child runnable, set start time.
1015 */
b0d623f7 1016 child_proc->p_stat = SRUN;
2d21ac55 1017bad:
b0d623f7 1018 return(child_thread);
0b4e3aa0
A
1019}
1020
b0d623f7 1021
2d21ac55
A
1022/*
1023 * Destroy a process structure that resulted from a call to forkproc(), but
1024 * which must be returned to the system because of a subsequent failure
1025 * preventing it from becoming active.
1026 *
1027 * Parameters: p The incomplete process from forkproc()
2d21ac55
A
1028 *
1029 * Returns: (void)
1030 *
1031 * Note: This function should only be used in an error handler following
b0d623f7 1032 * a call to forkproc().
2d21ac55
A
1033 *
1034 * Operations occur in reverse order of those in forkproc().
1035 */
1036void
b0d623f7 1037forkproc_free(proc_t p)
1c79356b 1038{
2d21ac55 1039
b0d623f7
A
1040 /* We held signal and a transition locks; drop them */
1041 proc_signalend(p, 0);
1042 proc_transend(p, 0);
1c79356b
A
1043
1044 /*
2d21ac55
A
1045 * If we have our own copy of the resource limits structure, we
1046 * need to free it. If it's a shared copy, we need to drop our
1047 * reference on it.
1c79356b 1048 */
2d21ac55
A
1049 proc_limitdrop(p, 0);
1050 p->p_limit = NULL;
1051
1052#if SYSV_SHM
1053 /* Need to drop references to the shared memory segment(s), if any */
1054 if (p->vm_shm) {
1055 /*
1056 * Use shmexec(): we have no address space, so no mappings
1057 *
1058 * XXX Yes, the routine is badly named.
1059 */
1060 shmexec(p);
1061 }
1062#endif
1063
1064 /* Need to undo the effects of the fdcopy(), if any */
1065 fdfree(p);
1066
1067 /*
1068 * Drop the reference on a text vnode pointer, if any
1069 * XXX This code is broken in forkproc(); see <rdar://4256419>;
1070 * XXX if anyone ever uses this field, we will be extremely unhappy.
1071 */
1072 if (p->p_textvp) {
1073 vnode_rele(p->p_textvp);
1074 p->p_textvp = NULL;
1075 }
1076
1077 /* Stop the profiling clock */
1078 stopprofclock(p);
1079
6d2010ae
A
1080 /* Update the audit session proc count */
1081 AUDIT_SESSION_PROCEXIT(p);
1082
2d21ac55
A
1083 /* Release the credential reference */
1084 kauth_cred_unref(&p->p_ucred);
1085
1086 proc_list_lock();
1087 /* Decrement the count of processes in the system */
1088 nprocs--;
1089 proc_list_unlock();
1090
1091 thread_call_free(p->p_rcall);
1092
1093 /* Free allocated memory */
1094 FREE_ZONE(p->p_sigacts, sizeof *p->p_sigacts, M_SIGACTS);
1095 FREE_ZONE(p->p_stats, sizeof *p->p_stats, M_PSTATS);
1096 proc_checkdeadrefs(p);
1097 FREE_ZONE(p, sizeof *p, M_PROC);
1098}
1099
1100
1101/*
1102 * forkproc
1103 *
1104 * Description: Create a new process structure, given a parent process
1105 * structure.
1106 *
b0d623f7 1107 * Parameters: parent_proc The parent process
2d21ac55
A
1108 *
1109 * Returns: !NULL The new process structure
1110 * NULL Error (insufficient free memory)
1111 *
1112 * Note: When successful, the newly created process structure is
1113 * partially initialized; if a caller needs to deconstruct the
1114 * returned structure, they must call forkproc_free() to do so.
1115 */
1116proc_t
b0d623f7 1117forkproc(proc_t parent_proc)
2d21ac55 1118{
b0d623f7 1119 proc_t child_proc; /* Our new process */
593a1d5f 1120 static int nextpid = 0, pidwrap = 0, nextpidversion = 0;
6d2010ae 1121 static uint64_t nextuniqueid = 0;
2d21ac55
A
1122 int error = 0;
1123 struct session *sessp;
b0d623f7 1124 uthread_t parent_uthread = (uthread_t)get_bsdthread_info(current_thread());
2d21ac55 1125
b0d623f7
A
1126 MALLOC_ZONE(child_proc, proc_t , sizeof *child_proc, M_PROC, M_WAITOK);
1127 if (child_proc == NULL) {
2d21ac55
A
1128 printf("forkproc: M_PROC zone exhausted\n");
1129 goto bad;
1130 }
1131 /* zero it out as we need to insert in hash */
b0d623f7 1132 bzero(child_proc, sizeof *child_proc);
2d21ac55 1133
b0d623f7
A
1134 MALLOC_ZONE(child_proc->p_stats, struct pstats *,
1135 sizeof *child_proc->p_stats, M_PSTATS, M_WAITOK);
1136 if (child_proc->p_stats == NULL) {
2d21ac55 1137 printf("forkproc: M_SUBPROC zone exhausted (p_stats)\n");
b0d623f7
A
1138 FREE_ZONE(child_proc, sizeof *child_proc, M_PROC);
1139 child_proc = NULL;
2d21ac55
A
1140 goto bad;
1141 }
b0d623f7
A
1142 MALLOC_ZONE(child_proc->p_sigacts, struct sigacts *,
1143 sizeof *child_proc->p_sigacts, M_SIGACTS, M_WAITOK);
1144 if (child_proc->p_sigacts == NULL) {
2d21ac55 1145 printf("forkproc: M_SUBPROC zone exhausted (p_sigacts)\n");
b0d623f7
A
1146 FREE_ZONE(child_proc->p_stats, sizeof *child_proc->p_stats, M_PSTATS);
1147 FREE_ZONE(child_proc, sizeof *child_proc, M_PROC);
1148 child_proc = NULL;
2d21ac55
A
1149 goto bad;
1150 }
b0d623f7
A
1151
1152 /* allocate a callout for use by interval timers */
1153 child_proc->p_rcall = thread_call_allocate((thread_call_func_t)realitexpire, child_proc);
1154 if (child_proc->p_rcall == NULL) {
1155 FREE_ZONE(child_proc->p_sigacts, sizeof *child_proc->p_sigacts, M_SIGACTS);
1156 FREE_ZONE(child_proc->p_stats, sizeof *child_proc->p_stats, M_PSTATS);
1157 FREE_ZONE(child_proc, sizeof *child_proc, M_PROC);
1158 child_proc = NULL;
2d21ac55
A
1159 goto bad;
1160 }
1161
1162
1163 /*
1164 * Find an unused PID.
1165 */
1166
1167 proc_list_lock();
1168
1c79356b
A
1169 nextpid++;
1170retry:
1171 /*
1172 * If the process ID prototype has wrapped around,
1173 * restart somewhat above 0, as the low-numbered procs
1174 * tend to include daemons that don't exit.
1175 */
1176 if (nextpid >= PID_MAX) {
1177 nextpid = 100;
2d21ac55 1178 pidwrap = 1;
1c79356b 1179 }
2d21ac55 1180 if (pidwrap != 0) {
1c79356b 1181
2d21ac55
A
1182 /* if the pid stays in hash both for zombie and runniing state */
1183 if (pfind_locked(nextpid) != PROC_NULL) {
1184 nextpid++;
1185 goto retry;
1c79356b 1186 }
1c79356b 1187
2d21ac55
A
1188 if (pgfind_internal(nextpid) != PGRP_NULL) {
1189 nextpid++;
1190 goto retry;
1191 }
1192 if (session_find_internal(nextpid) != SESSION_NULL) {
1193 nextpid++;
1194 goto retry;
1195 }
1196 }
1c79356b 1197 nprocs++;
b0d623f7
A
1198 child_proc->p_pid = nextpid;
1199 child_proc->p_idversion = nextpidversion++;
6d2010ae
A
1200 /* kernel process is handcrafted and not from fork, so start from 1 */
1201 child_proc->p_uniqueid = ++nextuniqueid;
2d21ac55 1202#if 1
b0d623f7
A
1203 if (child_proc->p_pid != 0) {
1204 if (pfind_locked(child_proc->p_pid) != PROC_NULL)
2d21ac55
A
1205 panic("proc in the list already\n");
1206 }
1207#endif
1208 /* Insert in the hash */
b0d623f7
A
1209 child_proc->p_listflag |= (P_LIST_INHASH | P_LIST_INCREATE);
1210 LIST_INSERT_HEAD(PIDHASH(child_proc->p_pid), child_proc, p_hash);
2d21ac55
A
1211 proc_list_unlock();
1212
1213
1214 /*
1215 * We've identified the PID we are going to use; initialize the new
1216 * process structure.
1217 */
b0d623f7
A
1218 child_proc->p_stat = SIDL;
1219 child_proc->p_pgrpid = PGRPID_DEAD;
1c79356b
A
1220
1221 /*
b0d623f7
A
1222 * The zero'ing of the proc was at the allocation time due to need
1223 * for insertion to hash. Copy the section that is to be copied
1224 * directly from the parent.
1c79356b 1225 */
b0d623f7
A
1226 bcopy(&parent_proc->p_startcopy, &child_proc->p_startcopy,
1227 (unsigned) ((caddr_t)&child_proc->p_endcopy - (caddr_t)&child_proc->p_startcopy));
1c79356b 1228
55e303ae 1229 /*
91447636 1230 * Some flags are inherited from the parent.
1c79356b
A
1231 * Duplicate sub-structures as needed.
1232 * Increase reference counts on shared objects.
1233 * The p_stats and p_sigacts substructs are set in vm_fork.
1234 */
316670eb 1235 child_proc->p_flag = (parent_proc->p_flag & (P_LP64 | P_TRANSLATED | P_AFFINITY | P_DISABLE_ASLR | P_DELAYIDLESLEEP));
b0d623f7
A
1236 if (parent_proc->p_flag & P_PROFIL)
1237 startprofclock(child_proc);
316670eb 1238
39236c6e 1239 child_proc->p_vfs_iopolicy = (parent_proc->p_vfs_iopolicy & (P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY));
316670eb 1240
91447636
A
1241 /*
1242 * Note that if the current thread has an assumed identity, this
1243 * credential will be granted to the new process.
1244 */
b0d623f7 1245 child_proc->p_ucred = kauth_cred_get_with_ref();
6d2010ae
A
1246 /* update cred on proc */
1247 PROC_UPDATE_CREDS_ONPROC(child_proc);
1248 /* update audit session proc count */
1249 AUDIT_SESSION_PROCNEW(child_proc);
91447636 1250
6d2010ae 1251#if CONFIG_FINE_LOCK_GROUPS
b0d623f7
A
1252 lck_mtx_init(&child_proc->p_mlock, proc_mlock_grp, proc_lck_attr);
1253 lck_mtx_init(&child_proc->p_fdmlock, proc_fdmlock_grp, proc_lck_attr);
1254#if CONFIG_DTRACE
1255 lck_mtx_init(&child_proc->p_dtrace_sprlock, proc_lck_grp, proc_lck_attr);
1256#endif
1257 lck_spin_init(&child_proc->p_slock, proc_slock_grp, proc_lck_attr);
6d2010ae
A
1258#else /* !CONFIG_FINE_LOCK_GROUPS */
1259 lck_mtx_init(&child_proc->p_mlock, proc_lck_grp, proc_lck_attr);
1260 lck_mtx_init(&child_proc->p_fdmlock, proc_lck_grp, proc_lck_attr);
1261#if CONFIG_DTRACE
1262 lck_mtx_init(&child_proc->p_dtrace_sprlock, proc_lck_grp, proc_lck_attr);
1263#endif
1264 lck_spin_init(&child_proc->p_slock, proc_lck_grp, proc_lck_attr);
1265#endif /* !CONFIG_FINE_LOCK_GROUPS */
b0d623f7 1266 klist_init(&child_proc->p_klist);
2d21ac55 1267
b0d623f7 1268 if (child_proc->p_textvp != NULLVP) {
2d21ac55
A
1269 /* bump references to the text vnode */
1270 /* Need to hold iocount across the ref call */
b0d623f7
A
1271 if (vnode_getwithref(child_proc->p_textvp) == 0) {
1272 error = vnode_ref(child_proc->p_textvp);
1273 vnode_put(child_proc->p_textvp);
2d21ac55 1274 if (error != 0)
b0d623f7 1275 child_proc->p_textvp = NULLVP;
2d21ac55 1276 }
91447636 1277 }
2d21ac55 1278
b0d623f7
A
1279 /*
1280 * Copy the parents per process open file table to the child; if
1281 * there is a per-thread current working directory, set the childs
1282 * per-process current working directory to that instead of the
1283 * parents.
1284 *
1285 * XXX may fail to copy descriptors to child
1286 */
1287 child_proc->p_fd = fdcopy(parent_proc, parent_uthread->uu_cdir);
91447636 1288
2d21ac55 1289#if SYSV_SHM
b0d623f7 1290 if (parent_proc->vm_shm) {
91447636 1291 /* XXX may fail to attach shm to child */
b0d623f7 1292 (void)shmfork(parent_proc, child_proc);
1c79356b 1293 }
2d21ac55 1294#endif
1c79356b 1295 /*
2d21ac55 1296 * inherit the limit structure to child
1c79356b 1297 */
b0d623f7 1298 proc_limitfork(parent_proc, child_proc);
2d21ac55 1299
b0d623f7
A
1300 if (child_proc->p_limit->pl_rlimit[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
1301 uint64_t rlim_cur = child_proc->p_limit->pl_rlimit[RLIMIT_CPU].rlim_cur;
1302 child_proc->p_rlim_cpu.tv_sec = (rlim_cur > __INT_MAX__) ? __INT_MAX__ : rlim_cur;
1c79356b
A
1303 }
1304
b0d623f7
A
1305 /* Intialize new process stats, including start time */
1306 /* <rdar://6640543> non-zeroed portion contains garbage AFAICT */
39236c6e
A
1307 bzero(child_proc->p_stats, sizeof(*child_proc->p_stats));
1308 microtime_with_abstime(&child_proc->p_start, &child_proc->p_stats->ps_start);
b0d623f7
A
1309
1310 if (parent_proc->p_sigacts != NULL)
1311 (void)memcpy(child_proc->p_sigacts,
1312 parent_proc->p_sigacts, sizeof *child_proc->p_sigacts);
1c79356b 1313 else
b0d623f7 1314 (void)memset(child_proc->p_sigacts, 0, sizeof *child_proc->p_sigacts);
1c79356b 1315
b0d623f7
A
1316 sessp = proc_session(parent_proc);
1317 if (sessp->s_ttyvp != NULL && parent_proc->p_flag & P_CONTROLT)
1318 OSBitOrAtomic(P_CONTROLT, &child_proc->p_flag);
2d21ac55 1319 session_rele(sessp);
1c79356b 1320
b0d623f7
A
1321 /*
1322 * block all signals to reach the process.
1323 * no transition race should be occuring with the child yet,
1324 * but indicate that the process is in (the creation) transition.
1325 */
1326 proc_signalstart(child_proc, 0);
fe8ab488
A
1327 proc_transstart(child_proc, 0, 0);
1328
1329 child_proc->p_pcaction = 0;
b0d623f7 1330
b0d623f7
A
1331 TAILQ_INIT(&child_proc->p_uthlist);
1332 TAILQ_INIT(&child_proc->p_aio_activeq);
1333 TAILQ_INIT(&child_proc->p_aio_doneq);
2d21ac55 1334
2d21ac55 1335 /* Inherit the parent flags for code sign */
c331a0be 1336 child_proc->p_csflags = (parent_proc->p_csflags & ~CS_KILLED);
b0d623f7
A
1337
1338 /*
1339 * All processes have work queue locks; cleaned up by
1340 * reap_child_locked()
1341 */
1342 workqueue_init_lock(child_proc);
1343
1344 /*
1345 * Copy work queue information
1346 *
1347 * Note: This should probably only happen in the case where we are
1348 * creating a child that is a copy of the parent; since this
1349 * routine is called in the non-duplication case of vfork()
1350 * or posix_spawn(), then this information should likely not
1351 * be duplicated.
1352 *
1353 * <rdar://6640553> Work queue pointers that no longer point to code
1354 */
1355 child_proc->p_wqthread = parent_proc->p_wqthread;
1356 child_proc->p_threadstart = parent_proc->p_threadstart;
1357 child_proc->p_pthsize = parent_proc->p_pthsize;
1358 child_proc->p_targconc = parent_proc->p_targconc;
1359 if ((parent_proc->p_lflag & P_LREGISTER) != 0) {
1360 child_proc->p_lflag |= P_LREGISTER;
1361 }
1362 child_proc->p_dispatchqueue_offset = parent_proc->p_dispatchqueue_offset;
39236c6e 1363 child_proc->p_dispatchqueue_serialno_offset = parent_proc->p_dispatchqueue_serialno_offset;
b0d623f7
A
1364#if PSYNCH
1365 pth_proc_hashinit(child_proc);
1366#endif /* PSYNCH */
2d21ac55
A
1367
1368#if CONFIG_LCTX
b0d623f7 1369 child_proc->p_lctx = NULL;
2d21ac55 1370 /* Add new process to login context (if any). */
b0d623f7
A
1371 if (parent_proc->p_lctx != NULL) {
1372 /*
1373 * <rdar://6640564> This should probably be delayed in the
1374 * vfork() or posix_spawn() cases.
1375 */
1376 LCTX_LOCK(parent_proc->p_lctx);
1377 enterlctx(child_proc, parent_proc->p_lctx, 0);
1c79356b
A
1378 }
1379#endif
1380
39236c6e
A
1381#if CONFIG_MEMORYSTATUS
1382 /* Memorystatus + jetsam init */
1383 child_proc->p_memstat_state = 0;
1384 child_proc->p_memstat_effectivepriority = JETSAM_PRIORITY_DEFAULT;
1385 child_proc->p_memstat_requestedpriority = JETSAM_PRIORITY_DEFAULT;
1386 child_proc->p_memstat_userdata = 0;
1387#if CONFIG_FREEZE
1388 child_proc->p_memstat_suspendedfootprint = 0;
1389#endif
1390 child_proc->p_memstat_dirty = 0;
1391 child_proc->p_memstat_idledeadline = 0;
1392#endif /* CONFIG_MEMORYSTATUS */
316670eb 1393
2d21ac55 1394bad:
b0d623f7 1395 return(child_proc);
1c79356b
A
1396}
1397
91447636
A
1398void
1399proc_lock(proc_t p)
1400{
1401 lck_mtx_lock(&p->p_mlock);
1402}
1403
1404void
1405proc_unlock(proc_t p)
1406{
1407 lck_mtx_unlock(&p->p_mlock);
1408}
1409
2d21ac55
A
1410void
1411proc_spinlock(proc_t p)
1412{
1413 lck_spin_lock(&p->p_slock);
1414}
1415
1416void
1417proc_spinunlock(proc_t p)
1418{
1419 lck_spin_unlock(&p->p_slock);
1420}
1421
1422void
1423proc_list_lock(void)
1424{
1425 lck_mtx_lock(proc_list_mlock);
1426}
1427
1428void
1429proc_list_unlock(void)
1430{
1431 lck_mtx_unlock(proc_list_mlock);
1432}
1433
1c79356b
A
1434#include <kern/zalloc.h>
1435
1436struct zone *uthread_zone;
2d21ac55 1437static int uthread_zone_inited = 0;
1c79356b 1438
2d21ac55 1439static void
91447636 1440uthread_zone_init(void)
1c79356b
A
1441{
1442 if (!uthread_zone_inited) {
1443 uthread_zone = zinit(sizeof(struct uthread),
b0d623f7 1444 thread_max * sizeof(struct uthread),
91447636
A
1445 THREAD_CHUNK * sizeof(struct uthread),
1446 "uthreads");
1c79356b
A
1447 uthread_zone_inited = 1;
1448 }
1449}
1450
1451void *
b0d623f7 1452uthread_alloc(task_t task, thread_t thread, int noinherit)
1c79356b 1453{
2d21ac55
A
1454 proc_t p;
1455 uthread_t uth;
1456 uthread_t uth_parent;
1c79356b
A
1457 void *ut;
1458
1459 if (!uthread_zone_inited)
1460 uthread_zone_init();
1461
1462 ut = (void *)zalloc(uthread_zone);
1463 bzero(ut, sizeof(struct uthread));
9bccf70c 1464
2d21ac55
A
1465 p = (proc_t) get_bsdtask_info(task);
1466 uth = (uthread_t)ut;
316670eb 1467 uth->uu_thread = thread;
9bccf70c 1468
91447636
A
1469 /*
1470 * Thread inherits credential from the creating thread, if both
1471 * are in the same task.
1472 *
1473 * If the creating thread has no credential or is from another
1474 * task we can leave the new thread credential NULL. If it needs
1475 * one later, it will be lazily assigned from the task's process.
1476 */
2d21ac55 1477 uth_parent = (uthread_t)get_bsdthread_info(current_thread());
b0d623f7 1478 if ((noinherit == 0) && task == current_task() &&
2d21ac55
A
1479 uth_parent != NULL &&
1480 IS_VALID_CRED(uth_parent->uu_ucred)) {
0c530ab8
A
1481 /*
1482 * XXX The new thread is, in theory, being created in context
1483 * XXX of parent thread, so a direct reference to the parent
1484 * XXX is OK.
1485 */
1486 kauth_cred_ref(uth_parent->uu_ucred);
91447636 1487 uth->uu_ucred = uth_parent->uu_ucred;
91447636
A
1488 /* the credential we just inherited is an assumed credential */
1489 if (uth_parent->uu_flag & UT_SETUID)
1490 uth->uu_flag |= UT_SETUID;
1491 } else {
b0d623f7
A
1492 /* sometimes workqueue threads are created out task context */
1493 if ((task != kernel_task) && (p != PROC_NULL))
1494 uth->uu_ucred = kauth_cred_proc_ref(p);
1495 else
1496 uth->uu_ucred = NOCRED;
91447636 1497 }
2d21ac55 1498
91447636 1499
2d21ac55 1500 if ((task != kernel_task) && p) {
91447636 1501
2d21ac55 1502 proc_lock(p);
b0d623f7
A
1503 if (noinherit != 0) {
1504 /* workq threads will not inherit masks */
1505 uth->uu_sigmask = ~workq_threadmask;
1506 } else if (uth_parent) {
91447636 1507 if (uth_parent->uu_flag & UT_SAS_OLDMASK)
9bccf70c
A
1508 uth->uu_sigmask = uth_parent->uu_oldmask;
1509 else
1510 uth->uu_sigmask = uth_parent->uu_sigmask;
1511 }
2d21ac55
A
1512 uth->uu_context.vc_thread = thread;
1513 TAILQ_INSERT_TAIL(&p->p_uthlist, uth, uu_list);
1514 proc_unlock(p);
1515
1516#if CONFIG_DTRACE
1517 if (p->p_dtrace_ptss_pages != NULL) {
1518 uth->t_dtrace_scratch = dtrace_ptss_claim_entry(p);
91447636 1519 }
316670eb
A
1520#endif
1521#if CONFIG_MACF
1522 mac_thread_label_init(uth);
2d21ac55 1523#endif
9bccf70c
A
1524 }
1525
1c79356b
A
1526 return (ut);
1527}
1528
0b4e3aa0 1529
2d21ac55
A
1530/*
1531 * This routine frees all the BSD context in uthread except the credential.
1532 * It does not free the uthread structure as well
1533 */
1c79356b 1534void
2d21ac55 1535uthread_cleanup(task_t task, void *uthread, void * bsd_info)
1c79356b
A
1536{
1537 struct _select *sel;
2d21ac55
A
1538 uthread_t uth = (uthread_t)uthread;
1539 proc_t p = (proc_t)bsd_info;
fe8ab488 1540 void *pth_name;
593a1d5f 1541
b0d623f7 1542 if (uth->uu_lowpri_window || uth->uu_throttle_info) {
593a1d5f
A
1543 /*
1544 * task is marked as a low priority I/O type
1545 * and we've somehow managed to not dismiss the throttle
1546 * through the normal exit paths back to user space...
1547 * no need to throttle this thread since its going away
1548 * but we do need to update our bookeeping w/r to throttled threads
b0d623f7
A
1549 *
1550 * Calling this routine will clean up any throttle info reference
1551 * still inuse by the thread.
593a1d5f 1552 */
39236c6e 1553 throttle_lowpri_io(0);
593a1d5f 1554 }
55e303ae
A
1555 /*
1556 * Per-thread audit state should never last beyond system
1557 * call return. Since we don't audit the thread creation/
1558 * removal, the thread state pointer should never be
1559 * non-NULL when we get here.
1560 */
1561 assert(uth->uu_ar == NULL);
1c79356b 1562
91447636 1563 sel = &uth->uu_select;
1c79356b
A
1564 /* cleanup the select bit space */
1565 if (sel->nbytes) {
1566 FREE(sel->ibits, M_TEMP);
1567 FREE(sel->obits, M_TEMP);
2d21ac55
A
1568 sel->nbytes = 0;
1569 }
1570
1571 if (uth->uu_cdir) {
1572 vnode_rele(uth->uu_cdir);
1573 uth->uu_cdir = NULLVP;
1c79356b
A
1574 }
1575
2d21ac55
A
1576 if (uth->uu_allocsize && uth->uu_wqset){
1577 kfree(uth->uu_wqset, uth->uu_allocsize);
2d21ac55
A
1578 uth->uu_allocsize = 0;
1579 uth->uu_wqset = 0;
0b4e3aa0 1580 }
fe8ab488
A
1581
1582 /*
1583 * <rdar://17834538>
1584 * Set pth_name to NULL before calling free().
1585 * Previously there was a race condition in the
1586 * case this code was executing during a stackshot
1587 * where the stackshot could try and copy pth_name
1588 * after it had been freed and before if was marked
1589 * as null.
1590 */
1591 if (uth->pth_name != NULL) {
1592 pth_name = uth->pth_name;
1593 uth->pth_name = NULL;
1594 kfree(pth_name, MAXTHREADNAMESIZE);
b0d623f7 1595 }
fe8ab488 1596
2d21ac55
A
1597 if ((task != kernel_task) && p) {
1598
1599 if (((uth->uu_flag & UT_VFORK) == UT_VFORK) && (uth->uu_proc != PROC_NULL)) {
1600 vfork_exit_internal(uth->uu_proc, 0, 1);
1601 }
b0d623f7
A
1602 /*
1603 * Remove the thread from the process list and
1604 * transfer [appropriate] pending signals to the process.
1605 */
2d21ac55
A
1606 if (get_bsdtask_info(task) == p) {
1607 proc_lock(p);
1608 TAILQ_REMOVE(&p->p_uthlist, uth, uu_list);
b0d623f7 1609 p->p_siglist |= (uth->uu_siglist & execmask & (~p->p_sigignore | sigcantmask));
2d21ac55
A
1610 proc_unlock(p);
1611 }
1612#if CONFIG_DTRACE
b0d623f7
A
1613 struct dtrace_ptss_page_entry *tmpptr = uth->t_dtrace_scratch;
1614 uth->t_dtrace_scratch = NULL;
1615 if (tmpptr != NULL) {
1616 dtrace_ptss_release_entry(p, tmpptr);
2d21ac55 1617 }
316670eb
A
1618#endif
1619#if CONFIG_MACF
1620 mac_thread_label_destroy(uth);
2d21ac55
A
1621#endif
1622 }
1623}
1624
1625/* This routine releases the credential stored in uthread */
1626void
1627uthread_cred_free(void *uthread)
1628{
1629 uthread_t uth = (uthread_t)uthread;
1630
1631 /* and free the uthread itself */
0c530ab8
A
1632 if (IS_VALID_CRED(uth->uu_ucred)) {
1633 kauth_cred_t oldcred = uth->uu_ucred;
1634 uth->uu_ucred = NOCRED;
1635 kauth_cred_unref(&oldcred);
1636 }
2d21ac55 1637}
e5568f75 1638
2d21ac55
A
1639/* This routine frees the uthread structure held in thread structure */
1640void
1641uthread_zone_free(void *uthread)
1642{
22ba694c
A
1643 uthread_t uth = (uthread_t)uthread;
1644
1645 if (uth->t_tombstone) {
1646 kfree(uth->t_tombstone, sizeof(struct doc_tombstone));
1647 uth->t_tombstone = NULL;
1648 }
1649
1c79356b 1650 /* and free the uthread itself */
91447636 1651 zfree(uthread_zone, uthread);
1c79356b 1652}