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