1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
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
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
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 */
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 */
80
81 #include <kern/assert.h>
82 #include <kern/bits.h>
83 #include <sys/param.h>
84 #include <sys/systm.h>
85 #include <sys/filedesc.h>
86 #include <sys/kernel.h>
87 #include <sys/malloc.h>
88 #include <sys/proc_internal.h>
89 #include <sys/kauth.h>
90 #include <sys/user.h>
91 #include <sys/reason.h>
92 #include <sys/resourcevar.h>
93 #include <sys/vnode_internal.h>
94 #include <sys/file_internal.h>
95 #include <sys/acct.h>
96 #include <sys/codesign.h>
97 #include <sys/sysent.h>
98 #include <sys/sysproto.h>
99 #include <sys/ulock.h>
100 #if CONFIG_PERSONAS
101 #include <sys/persona.h>
102 #endif
103 #include <sys/doc_tombstone.h>
104 #if CONFIG_DTRACE
105 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
106 extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t);
107 extern void dtrace_proc_fork(proc_t, proc_t, int);
108
109 /*
110 * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c,
111 * we will store its value before actually calling it.
112 */
113 static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL;
114
115 #include <sys/dtrace_ptss.h>
116 #endif
117
118 #include <security/audit/audit.h>
119
120 #include <mach/mach_types.h>
121 #include <kern/coalition.h>
122 #include <kern/kern_types.h>
123 #include <kern/kalloc.h>
124 #include <kern/mach_param.h>
125 #include <kern/task.h>
126 #include <kern/thread.h>
127 #include <kern/thread_call.h>
128 #include <kern/zalloc.h>
129
130 #include <os/log.h>
131
132 #if CONFIG_MACF
133 #include <security/mac_framework.h>
134 #include <security/mac_mach_internal.h>
135 #endif
136
137 #include <vm/vm_map.h>
138 #include <vm/vm_protos.h>
139 #include <vm/vm_shared_region.h>
140
141 #include <sys/shm_internal.h> /* for shmfork() */
142 #include <mach/task.h> /* for thread_create() */
143 #include <mach/thread_act.h> /* for thread_resume() */
144
145 #include <sys/sdt.h>
146
147 #if CONFIG_MEMORYSTATUS
148 #include <sys/kern_memorystatus.h>
149 #endif
150
151 /* XXX routines which should have Mach prototypes, but don't */
152 extern void act_thread_catt(void *ctx);
153 void thread_set_child(thread_t child, int pid);
154 boolean_t thread_is_active(thread_t thread);
155 void *act_thread_csave(void);
156 extern boolean_t task_is_exec_copy(task_t);
157 int nextpidversion = 0;
158
159 void ipc_task_enable(task_t task);
160
161 proc_t forkproc(proc_t, cloneproc_flags_t);
162 void forkproc_free(proc_t);
163 thread_t fork_create_child(task_t parent_task,
164 coalition_t *parent_coalitions,
165 proc_t child,
166 int is_64bit_addr,
167 int is_64bit_data,
168 cloneproc_flags_t clone_flags);
169
170 __private_extern__ const size_t uthread_size = sizeof(struct uthread);
171 static LCK_GRP_DECLARE(rethrottle_lock_grp, "rethrottle");
172
173 os_refgrp_decl(, p_refgrp, "proc", NULL);
174
175 extern const size_t task_alignment;
176 const size_t proc_alignment = _Alignof(struct proc);
177
178 extern size_t task_struct_size;
179 size_t proc_struct_size = sizeof(struct proc);
180 size_t proc_and_task_size;
181
182 ZONE_DECLARE_ID(ZONE_ID_PROC_TASK, struct proc);
183 SECURITY_READ_ONLY_LATE(zone_t) proc_task_zone;
184
185 KALLOC_TYPE_DEFINE(proc_stats_zone, struct pstats, KT_DEFAULT);
186
187 /*
188 * fork1
189 *
190 * Description: common code used by all new process creation other than the
191 * bootstrap of the initial process on the system
192 *
193 * Parameters: parent_proc parent process of the process being
194 * child_threadp pointer to location to receive the
195 * Mach thread_t of the child process
196 * created
197 * kind kind of creation being requested
198 * coalitions if spawn, the set of coalitions the
199 * child process should join, or NULL to
200 * inherit the parent's. On non-spawns,
201 * this param is ignored and the child
202 * always inherits the parent's
203 * coalitions.
204 *
205 * Notes: Permissable values for 'kind':
206 *
207 * PROC_CREATE_FORK Create a complete process which will
208 * return actively running in both the
209 * parent and the child; the child copies
210 * the parent address space.
211 * PROC_CREATE_SPAWN Create a complete process which will
212 * return actively running in the parent
213 * only after returning actively running
214 * in the child; the child address space
215 * is newly created by an image activator,
216 * after which the child is run.
217 *
218 * At first it may seem strange that we return the child thread
219 * address rather than process structure, since the process is
220 * the only part guaranteed to be "new"; however, since we do
221 * not actualy adjust other references between Mach and BSD, this
222 * is the only method which guarantees us the ability to get
223 * back to the other information.
224 */
225 int
fork1(proc_t parent_proc,thread_t * child_threadp,int kind,coalition_t * coalitions)226 fork1(proc_t parent_proc, thread_t *child_threadp, int kind, coalition_t *coalitions)
227 {
228 proc_t child_proc = NULL; /* set in switch, but compiler... */
229 thread_t child_thread = NULL;
230 uid_t uid;
231 size_t count;
232 int err = 0;
233 int spawn = 0;
234 rlim_t rlimit_nproc_cur;
235
236 /*
237 * Although process entries are dynamically created, we still keep
238 * a global limit on the maximum number we will create. Don't allow
239 * a nonprivileged user to use the last process; don't let root
240 * exceed the limit. The variable nprocs is the current number of
241 * processes, maxproc is the limit.
242 */
243 uid = kauth_getruid();
244 proc_list_lock();
245 if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
246 #if (DEVELOPMENT || DEBUG) && !defined(XNU_TARGET_OS_OSX)
247 /*
248 * On the development kernel, panic so that the fact that we hit
249 * the process limit is obvious, as this may very well wedge the
250 * system.
251 */
252 panic("The process table is full; parent pid=%d", proc_getpid(parent_proc));
253 #endif
254 proc_list_unlock();
255 tablefull("proc");
256 return EAGAIN;
257 }
258 proc_list_unlock();
259
260 /*
261 * Increment the count of procs running with this uid. Don't allow
262 * a nonprivileged user to exceed their current limit, which is
263 * always less than what an rlim_t can hold.
264 * (locking protection is provided by list lock held in chgproccnt)
265 */
266 count = chgproccnt(uid, 1);
267 rlimit_nproc_cur = proc_limitgetcur(parent_proc, RLIMIT_NPROC);
268 if (uid != 0 &&
269 (rlim_t)count > rlimit_nproc_cur) {
270 #if (DEVELOPMENT || DEBUG) && !defined(XNU_TARGET_OS_OSX)
271 /*
272 * On the development kernel, panic so that the fact that we hit
273 * the per user process limit is obvious. This may be less dire
274 * than hitting the global process limit, but we cannot rely on
275 * that.
276 */
277 panic("The per-user process limit has been hit; parent pid=%d, uid=%d", proc_getpid(parent_proc), uid);
278 #endif
279 err = EAGAIN;
280 goto bad;
281 }
282
283 #if CONFIG_MACF
284 /*
285 * Determine if MAC policies applied to the process will allow
286 * it to fork. This is an advisory-only check.
287 */
288 err = mac_proc_check_fork(parent_proc);
289 if (err != 0) {
290 goto bad;
291 }
292 #endif
293
294 switch (kind) {
295 case PROC_CREATE_SPAWN:
296 /*
297 * A spawned process differs from a forked process in that
298 * the spawned process does not carry around the parents
299 * baggage with regard to address space copying, dtrace,
300 * and so on.
301 */
302 spawn = 1;
303
304 OS_FALLTHROUGH;
305
306 case PROC_CREATE_FORK:
307 /*
308 * When we clone the parent process, we are going to inherit
309 * its task attributes and memory, since when we fork, we
310 * will, in effect, create a duplicate of it, with only minor
311 * differences. Contrarily, spawned processes do not inherit.
312 */
313 if ((child_thread = cloneproc(proc_task(parent_proc),
314 spawn ? coalitions : NULL,
315 parent_proc,
316 spawn ? CLONEPROC_FLAGS_NONE : CLONEPROC_FLAGS_INHERIT_MEMORY)) == NULL) {
317 /* Failed to create thread */
318 err = EAGAIN;
319 goto bad;
320 }
321
322 /* child_proc = child_thread->task->proc; */
323 child_proc = (proc_t)(get_bsdtask_info(get_threadtask(child_thread)));
324
325 if (!spawn) {
326 /* Copy current thread state into the child thread (only for fork) */
327 thread_dup(child_thread);
328 }
329
330 // XXX BEGIN: wants to move to be common code (and safe)
331 #if CONFIG_MACF
332 /*
333 * allow policies to associate the credential/label that
334 * we referenced from the parent ... with the child
335 * JMM - this really isn't safe, as we can drop that
336 * association without informing the policy in other
337 * situations (keep long enough to get policies changed)
338 */
339 mac_cred_label_associate_fork(proc_ucred_unsafe(child_proc),
340 child_proc);
341 #endif
342
343 /*
344 * Propogate change of PID - may get new cred if auditing.
345 */
346 set_security_token(child_proc, proc_ucred_unsafe(child_proc));
347
348 AUDIT_ARG(pid, proc_getpid(child_proc));
349
350 // XXX END: wants to move to be common code (and safe)
351
352 /*
353 * Blow thread state information; this is what gives the child
354 * process its "return" value from a fork() call.
355 *
356 * Note: this should probably move to fork() proper, since it
357 * is not relevent to spawn, and the value won't matter
358 * until we resume the child there. If you are in here
359 * refactoring code, consider doing this at the same time.
360 */
361 thread_set_child(child_thread, proc_getpid(child_proc));
362
363 child_proc->p_acflag = AFORK; /* forked but not exec'ed */
364
365 #if CONFIG_DTRACE
366 dtrace_proc_fork(parent_proc, child_proc, spawn);
367 #endif /* CONFIG_DTRACE */
368 if (!spawn) {
369 /*
370 * Of note, we need to initialize the bank context behind
371 * the protection of the proc_trans lock to prevent a race with exit.
372 */
373 task_bank_init(get_threadtask(child_thread));
374 }
375
376 break;
377
378 default:
379 panic("fork1 called with unknown kind %d", kind);
380 break;
381 }
382
383
384 /* return the thread pointer to the caller */
385 *child_threadp = child_thread;
386
387 bad:
388 /*
389 * In the error case, we return a 0 value for the returned pid (but
390 * it is ignored in the trampoline due to the error return); this
391 * is probably not necessary.
392 */
393 if (err) {
394 (void)chgproccnt(uid, -1);
395 }
396
397 return err;
398 }
399
400
401
402
403 /*
404 * fork_create_child
405 *
406 * Description: Common operations associated with the creation of a child
407 * process. Return with new task and first thread's control port movable
408 * and not pinned.
409 *
410 * Parameters: parent_task parent task
411 * parent_coalitions parent's set of coalitions
412 * child_proc child process
413 * inherit_memory TRUE, if the parents address space is
414 * to be inherited by the child
415 * is_64bit_addr TRUE, if the child being created will
416 * be associated with a 64 bit address space
417 * is_64bit_data TRUE if the child being created will use a
418 * 64-bit register state
419 * in_exec TRUE, if called from execve or posix spawn set exec
420 * FALSE, if called from fork or vfexec
421 *
422 * Note: This code is called in the fork() case, from the execve() call
423 * graph, from the posix_spawn() call graph (which implicitly
424 * includes a vfork() equivalent call, and in the system
425 * bootstrap case.
426 *
427 * It creates a new task and thread (and as a side effect of the
428 * thread creation, a uthread) in the parent coalition set, which is
429 * then associated with the process 'child'. If the parent
430 * process address space is to be inherited, then a flag
431 * indicates that the newly created task should inherit this from
432 * the child task.
433 *
434 * As a special concession to bootstrapping the initial process
435 * in the system, it's possible for 'parent_task' to be TASK_NULL;
436 * in this case, 'inherit_memory' MUST be FALSE.
437 */
438 thread_t
fork_create_child(task_t parent_task,coalition_t * parent_coalitions,proc_t child_proc,int is_64bit_addr,int is_64bit_data,cloneproc_flags_t clone_flags)439 fork_create_child(task_t parent_task,
440 coalition_t *parent_coalitions,
441 proc_t child_proc,
442 int is_64bit_addr,
443 int is_64bit_data,
444 cloneproc_flags_t clone_flags)
445 {
446 thread_t child_thread = NULL;
447 task_t child_task;
448 kern_return_t result;
449 proc_ro_t proc_ro;
450 bool inherit_memory = !!(clone_flags & CLONEPROC_FLAGS_INHERIT_MEMORY);
451 bool in_exec = !!(clone_flags & CLONEPROC_FLAGS_FOR_EXEC);
452 /*
453 * Exec complete hook should be called for spawn and exec, but not for fork.
454 */
455 uint8_t returnwaitflags = (!inherit_memory ? TRW_LEXEC_COMPLETE : 0) |
456 (TRW_LRETURNWAIT | TRW_LRETURNWAITER);
457
458 proc_ro = proc_get_ro(child_proc);
459 if (proc_ro_task(proc_ro) != NULL) {
460 panic("Proc_ro_task for newly created proc %p is not NULL", child_proc);
461 }
462
463 child_task = proc_get_task_raw(child_proc);
464
465 /*
466 * Create a new task for the child process, IPC access to the new task will
467 * be set up after task has been fully initialized.
468 */
469 result = task_create_internal(parent_task,
470 proc_ro,
471 parent_coalitions,
472 inherit_memory,
473 is_64bit_addr,
474 is_64bit_data,
475 TF_NONE,
476 TF_NONE,
477 in_exec ? TPF_EXEC_COPY : TPF_NONE, /* Mark the task exec copy if in execve */
478 returnwaitflags, /* All created threads will wait in task_wait_to_return */
479 child_task);
480 if (result != KERN_SUCCESS) {
481 printf("%s: task_create_internal failed. Code: %d\n",
482 __func__, result);
483 goto bad;
484 }
485
486 /* Set the child proc process to child task */
487 proc_set_task(child_proc, child_task);
488
489 /* Set child task process to child proc */
490 set_bsdtask_info(child_task, child_proc);
491
492 /* Propagate CPU limit timer from parent */
493 if (timerisset(&child_proc->p_rlim_cpu)) {
494 task_vtimer_set(child_task, TASK_VTIMER_RLIM);
495 }
496
497 /*
498 * Set child process BSD visible scheduler priority if nice value
499 * inherited from parent
500 */
501 if (child_proc->p_nice != 0) {
502 resetpriority(child_proc);
503 }
504
505 /*
506 * Create main thread for the child process. Its control port is not immovable/pinned
507 * until main_thread_set_immovable_pinned().
508 *
509 * The new thread is waiting on the event triggered by 'task_clear_return_wait'
510 */
511 result = main_thread_create_waiting(child_task,
512 (thread_continue_t)task_wait_to_return,
513 task_get_return_wait_event(child_task),
514 &child_thread);
515
516 if (result != KERN_SUCCESS) {
517 printf("%s: thread_create failed. Code: %d\n",
518 __func__, result);
519 task_deallocate(child_task);
520 child_task = NULL;
521 }
522
523 /*
524 * Tag thread as being the first thread in its task.
525 */
526 thread_set_tag(child_thread, THREAD_TAG_MAINTHREAD);
527
528 bad:
529 thread_yield_internal(1);
530
531 return child_thread;
532 }
533
534
535 /*
536 * fork
537 *
538 * Description: fork system call.
539 *
540 * Parameters: parent Parent process to fork
541 * uap (void) [unused]
542 * retval Return value
543 *
544 * Returns: 0 Success
545 * EAGAIN Resource unavailable, try again
546 *
547 * Notes: Attempts to create a new child process which inherits state
548 * from the parent process. If successful, the call returns
549 * having created an initially suspended child process with an
550 * extra Mach task and thread reference, for which the thread
551 * is initially suspended. Until we resume the child process,
552 * it is not yet running.
553 *
554 * The return information to the child is contained in the
555 * thread state structure of the new child, and does not
556 * become visible to the child through a normal return process,
557 * since it never made the call into the kernel itself in the
558 * first place.
559 *
560 * After resuming the thread, this function returns directly to
561 * the parent process which invoked the fork() system call.
562 *
563 * Important: The child thread_resume occurs before the parent returns;
564 * depending on scheduling latency, this means that it is not
565 * deterministic as to whether the parent or child is scheduled
566 * to run first. It is entirely possible that the child could
567 * run to completion prior to the parent running.
568 */
569 int
fork(proc_t parent_proc,__unused struct fork_args * uap,int32_t * retval)570 fork(proc_t parent_proc, __unused struct fork_args *uap, int32_t *retval)
571 {
572 thread_t child_thread;
573 int err;
574
575 retval[1] = 0; /* flag parent return for user space */
576
577 if ((err = fork1(parent_proc, &child_thread, PROC_CREATE_FORK, NULL)) == 0) {
578 task_t child_task;
579 proc_t child_proc;
580
581 /* Return to the parent */
582 child_proc = (proc_t)get_bsdthreadtask_info(child_thread);
583 retval[0] = proc_getpid(child_proc);
584
585 child_task = (task_t)get_threadtask(child_thread);
586 assert(child_task != TASK_NULL);
587
588 /* task_control_port_options has been inherited from parent, apply it */
589 task_set_immovable_pinned(child_task);
590 main_thread_set_immovable_pinned(child_thread);
591
592 /*
593 * Since the task ports for this new task are now set to be immovable,
594 * we can enable them.
595 */
596 ipc_task_enable(get_threadtask(child_thread));
597
598 /*
599 * Drop the signal lock on the child which was taken on our
600 * behalf by forkproc()/cloneproc() to prevent signals being
601 * received by the child in a partially constructed state.
602 */
603 proc_signalend(child_proc, 0);
604 proc_transend(child_proc, 0);
605
606 /* flag the fork has occurred */
607 proc_knote(parent_proc, NOTE_FORK | proc_getpid(child_proc));
608 DTRACE_PROC1(create, proc_t, child_proc);
609
610 #if CONFIG_DTRACE
611 if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) {
612 (*dtrace_proc_waitfor_hook)(child_proc);
613 }
614 #endif
615
616 /*
617 * If current process died during the fork, the child would contain
618 * non consistent vmmap, kill the child and reap it internally.
619 */
620 if (parent_proc->p_lflag & P_LEXIT || !thread_is_active(current_thread())) {
621 task_terminate_internal(child_task);
622 proc_list_lock();
623 child_proc->p_listflag |= P_LIST_DEADPARENT;
624 proc_list_unlock();
625 }
626
627 /* "Return" to the child */
628 task_clear_return_wait(get_threadtask(child_thread), TCRW_CLEAR_ALL_WAIT);
629
630 /* drop the extra references we got during the creation */
631 task_deallocate(child_task);
632 thread_deallocate(child_thread);
633 }
634
635 return err;
636 }
637
638
639 /*
640 * cloneproc
641 *
642 * Description: Create a new process from a specified process.
643 *
644 * Parameters: parent_task The parent task to be cloned, or
645 * TASK_NULL is task characteristics
646 * are not to be inherited
647 * be cloned, or TASK_NULL if the new
648 * task is not to inherit the VM
649 * characteristics of the parent
650 * parent_proc The parent process to be cloned
651 * clone_flags Clone flags to specify if the cloned
652 * process should inherit memory,
653 * marked as memory stat internal,
654 * or if the cloneproc is called for exec.
655 *
656 * Returns: !NULL pointer to new child thread
657 * NULL Failure (unspecified)
658 *
659 * Note: On return newly created child process has signal lock held
660 * to block delivery of signal to it if called with lock set.
661 * fork() code needs to explicity remove this lock before
662 * signals can be delivered
663 *
664 * In the case of bootstrap, this function can be called from
665 * bsd_utaskbootstrap() in order to bootstrap the first process;
666 * the net effect is to provide a uthread structure for the
667 * kernel process associated with the kernel task.
668 *
669 * XXX: Tristating using the value parent_task as the major key
670 * and inherit_memory as the minor key is something we should
671 * refactor later; we owe the current semantics, ultimately,
672 * to the semantics of task_create_internal. For now, we will
673 * live with this being somewhat awkward.
674 */
675 thread_t
cloneproc(task_t parent_task,coalition_t * parent_coalitions,proc_t parent_proc,cloneproc_flags_t clone_flags)676 cloneproc(task_t parent_task, coalition_t *parent_coalitions, proc_t parent_proc, cloneproc_flags_t clone_flags)
677 {
678 #if !CONFIG_MEMORYSTATUS
679 #pragma unused(memstat_internal)
680 #endif
681 task_t child_task;
682 proc_t child_proc;
683 thread_t child_thread = NULL;
684 bool memstat_internal = !!(clone_flags & CLONEPROC_FLAGS_MEMSTAT_INTERNAL);
685 bool in_exec = !!(clone_flags & CLONEPROC_FLAGS_FOR_EXEC);
686
687 if ((child_proc = forkproc(parent_proc, clone_flags)) == NULL) {
688 /* Failed to allocate new process */
689 goto bad;
690 }
691
692 /*
693 * In the case where the parent_task is TASK_NULL (during the init path)
694 * we make the assumption that the register size will be the same as the
695 * address space size since there's no way to determine the possible
696 * register size until an image is exec'd.
697 *
698 * The only architecture that has different address space and register sizes
699 * (arm64_32) isn't being used within kernel-space, so the above assumption
700 * always holds true for the init path.
701 */
702 const int parent_64bit_addr = parent_proc->p_flag & P_LP64;
703 const int parent_64bit_data = (parent_task == TASK_NULL) ? parent_64bit_addr : task_get_64bit_data(parent_task);
704
705 child_thread = fork_create_child(parent_task,
706 parent_coalitions,
707 child_proc,
708 parent_64bit_addr,
709 parent_64bit_data,
710 clone_flags);
711
712 if (child_thread == NULL) {
713 /*
714 * Failed to create thread; now we must deconstruct the new
715 * process previously obtained from forkproc().
716 */
717 forkproc_free(child_proc);
718 goto bad;
719 }
720
721 child_task = get_threadtask(child_thread);
722 if (parent_64bit_addr) {
723 OSBitOrAtomic(P_LP64, (UInt32 *)&child_proc->p_flag);
724 get_bsdthread_info(child_thread)->uu_flag |= UT_LP64;
725 } else {
726 OSBitAndAtomic(~((uint32_t)P_LP64), (UInt32 *)&child_proc->p_flag);
727 get_bsdthread_info(child_thread)->uu_flag &= ~UT_LP64;
728 }
729
730 #if CONFIG_MEMORYSTATUS
731 if (memstat_internal ||
732 (in_exec && (parent_proc->p_memstat_state & P_MEMSTAT_INTERNAL))) {
733 proc_list_lock();
734 child_proc->p_memstat_state |= P_MEMSTAT_INTERNAL;
735 proc_list_unlock();
736 }
737 if (in_exec && parent_proc->p_memstat_relaunch_flags != P_MEMSTAT_RELAUNCH_UNKNOWN) {
738 memorystatus_relaunch_flags_update(child_proc, parent_proc->p_memstat_relaunch_flags);
739 }
740 #endif
741
742 /* make child visible */
743 pinsertchild(parent_proc, child_proc, in_exec);
744
745 /*
746 * Make child runnable, set start time.
747 */
748 child_proc->p_stat = SRUN;
749 bad:
750 return child_thread;
751 }
752
753 void
proc_set_sigact(proc_t p,int sig,user_addr_t sigact)754 proc_set_sigact(proc_t p, int sig, user_addr_t sigact)
755 {
756 assert((sig > 0) && (sig < NSIG));
757
758 p->p_sigacts.ps_sigact[sig] = sigact;
759 }
760
761 void
proc_set_trampact(proc_t p,int sig,user_addr_t trampact)762 proc_set_trampact(proc_t p, int sig, user_addr_t trampact)
763 {
764 assert((sig > 0) && (sig < NSIG));
765
766 p->p_sigacts.ps_trampact[sig] = trampact;
767 }
768
769 void
proc_set_sigact_trampact(proc_t p,int sig,user_addr_t sigact,user_addr_t trampact)770 proc_set_sigact_trampact(proc_t p, int sig, user_addr_t sigact, user_addr_t trampact)
771 {
772 assert((sig > 0) && (sig < NSIG));
773
774 p->p_sigacts.ps_sigact[sig] = sigact;
775 p->p_sigacts.ps_trampact[sig] = trampact;
776 }
777
778 void
proc_reset_sigact(proc_t p,sigset_t sigs)779 proc_reset_sigact(proc_t p, sigset_t sigs)
780 {
781 user_addr_t *sigacts = p->p_sigacts.ps_sigact;
782 int nc;
783
784 while (sigs) {
785 nc = ffs((unsigned int)sigs);
786 if (sigacts[nc] != SIG_DFL) {
787 sigacts[nc] = SIG_DFL;
788 }
789 sigs &= ~sigmask(nc);
790 }
791 }
792
793 /*
794 * Destroy a process structure that resulted from a call to forkproc(), but
795 * which must be returned to the system because of a subsequent failure
796 * preventing it from becoming active.
797 *
798 * Parameters: p The incomplete process from forkproc()
799 *
800 * Returns: (void)
801 *
802 * Note: This function should only be used in an error handler following
803 * a call to forkproc().
804 *
805 * Operations occur in reverse order of those in forkproc().
806 */
807 void
forkproc_free(proc_t p)808 forkproc_free(proc_t p)
809 {
810 struct pgrp *pg;
811
812 #if CONFIG_PERSONAS
813 persona_proc_drop(p);
814 #endif /* CONFIG_PERSONAS */
815
816 #if PSYNCH
817 pth_proc_hashdelete(p);
818 #endif /* PSYNCH */
819
820 /* We held signal and a transition locks; drop them */
821 proc_signalend(p, 0);
822 proc_transend(p, 0);
823
824 /*
825 * If we have our own copy of the resource limits structure, we
826 * need to free it. If it's a shared copy, we need to drop our
827 * reference on it.
828 */
829 proc_limitdrop(p);
830
831 #if SYSV_SHM
832 /* Need to drop references to the shared memory segment(s), if any */
833 if (p->vm_shm) {
834 /*
835 * Use shmexec(): we have no address space, so no mappings
836 *
837 * XXX Yes, the routine is badly named.
838 */
839 shmexec(p);
840 }
841 #endif
842
843 /* Need to undo the effects of the fdt_fork(), if any */
844 fdt_invalidate(p);
845 fdt_destroy(p);
846
847 /*
848 * Drop the reference on a text vnode pointer, if any
849 * XXX This code is broken in forkproc(); see <rdar://4256419>;
850 * XXX if anyone ever uses this field, we will be extremely unhappy.
851 */
852 if (p->p_textvp) {
853 vnode_rele(p->p_textvp);
854 p->p_textvp = NULL;
855 }
856
857 /* Update the audit session proc count */
858 AUDIT_SESSION_PROCEXIT(p);
859
860 lck_mtx_destroy(&p->p_mlock, &proc_mlock_grp);
861 lck_mtx_destroy(&p->p_ucred_mlock, &proc_ucred_mlock_grp);
862 #if CONFIG_AUDIT
863 lck_mtx_destroy(&p->p_audit_mlock, &proc_ucred_mlock_grp);
864 #endif /* CONFIG_AUDIT */
865 #if CONFIG_DTRACE
866 lck_mtx_destroy(&p->p_dtrace_sprlock, &proc_lck_grp);
867 #endif
868 lck_spin_destroy(&p->p_slock, &proc_slock_grp);
869
870 proc_list_lock();
871 /* Decrement the count of processes in the system */
872 nprocs--;
873
874 /* quit the group */
875 pg = pgrp_leave_locked(p);
876
877 /* Take it out of process hash */
878 assert((os_ref_get_raw_mask(&p->p_refcount) >> P_REF_BITS) == 1);
879 assert((os_ref_get_raw_mask(&p->p_refcount) & P_REF_NEW) == P_REF_NEW);
880 os_atomic_xor(&p->p_refcount, P_REF_NEW | P_REF_DEAD, relaxed);
881
882 /* Remove from hash if not a shadow proc */
883 if (!proc_is_shadow(p)) {
884 phash_remove_locked(p);
885 }
886
887 proc_list_unlock();
888
889 pgrp_rele(pg);
890
891 thread_call_free(p->p_rcall);
892
893 /* Free allocated memory */
894 zfree(proc_stats_zone, p->p_stats);
895 p->p_stats = NULL;
896 if (p->p_subsystem_root_path) {
897 zfree(ZV_NAMEI, p->p_subsystem_root_path);
898 p->p_subsystem_root_path = NULL;
899 }
900
901 proc_checkdeadrefs(p);
902 proc_wait_release(p);
903 }
904
905
906 /*
907 * forkproc
908 *
909 * Description: Create a new process structure, given a parent process
910 * structure.
911 *
912 * Parameters: parent_proc The parent process
913 *
914 * Returns: !NULL The new process structure
915 * NULL Error (insufficient free memory)
916 *
917 * Note: When successful, the newly created process structure is
918 * partially initialized; if a caller needs to deconstruct the
919 * returned structure, they must call forkproc_free() to do so.
920 */
921 proc_t
forkproc(proc_t parent_proc,cloneproc_flags_t clone_flags)922 forkproc(proc_t parent_proc, cloneproc_flags_t clone_flags)
923 {
924 static uint64_t nextuniqueid = 0;
925 static pid_t lastpid = 0;
926
927 proc_t child_proc; /* Our new process */
928 int error = 0;
929 struct pgrp *pg;
930 uthread_t parent_uthread = current_uthread();
931 rlim_t rlimit_cpu_cur;
932 pid_t pid;
933 struct proc_ro_data proc_ro_data = {};
934 bool in_exec = !!(clone_flags & CLONEPROC_FLAGS_FOR_EXEC);
935
936 child_proc = zalloc_flags(proc_task_zone, Z_WAITOK | Z_ZERO);
937
938 child_proc->p_stats = zalloc_flags(proc_stats_zone, Z_WAITOK | Z_ZERO);
939 child_proc->p_sigacts = parent_proc->p_sigacts;
940 os_ref_init_mask(&child_proc->p_refcount, P_REF_BITS, &p_refgrp, P_REF_NEW);
941 os_ref_init_raw(&child_proc->p_waitref, &p_refgrp);
942 proc_ref_hold_proc_task_struct(child_proc);
943
944 /* allocate a callout for use by interval timers */
945 child_proc->p_rcall = thread_call_allocate((thread_call_func_t)realitexpire, child_proc);
946
947
948 /*
949 * Find an unused PID.
950 */
951
952 fdt_init(child_proc);
953
954 proc_list_lock();
955
956 if (!in_exec) {
957 pid = lastpid;
958 do {
959 /*
960 * If the process ID prototype has wrapped around,
961 * restart somewhat above 0, as the low-numbered procs
962 * tend to include daemons that don't exit.
963 */
964 if (++pid >= PID_MAX) {
965 pid = 100;
966 }
967 if (pid == lastpid) {
968 panic("Unable to allocate a new pid");
969 }
970
971 /* if the pid stays in hash both for zombie and runniing state */
972 } while (phash_find_locked(pid) != PROC_NULL ||
973 pghash_exists_locked(pid) ||
974 session_find_locked(pid) != SESSION_NULL);
975
976 lastpid = pid;
977 nprocs++;
978
979 child_proc->p_pid = pid;
980 proc_ro_data.p_idversion = OSIncrementAtomic(&nextpidversion);
981 /* kernel process is handcrafted and not from fork, so start from 1 */
982 proc_ro_data.p_uniqueid = ++nextuniqueid;
983
984 /* Insert in the hash, and inherit our group (and session) */
985 phash_insert_locked(child_proc);
986
987 /* Check if the proc is from App Cryptex */
988 if (parent_proc->p_ladvflag & P_RSR) {
989 os_atomic_or(&child_proc->p_ladvflag, P_RSR, relaxed);
990 }
991 } else {
992 /* For exec copy of the proc, copy the pid, pidversion and uniqueid of original proc */
993 pid = parent_proc->p_pid;
994 child_proc->p_pid = pid;
995 proc_ro_data.p_idversion = parent_proc->p_proc_ro->p_idversion;
996 proc_ro_data.p_uniqueid = parent_proc->p_proc_ro->p_uniqueid;
997
998 nprocs++;
999 os_atomic_or(&child_proc->p_refcount, P_REF_SHADOW, relaxed);
1000 }
1001 pg = pgrp_enter_locked(parent_proc, child_proc);
1002 proc_list_unlock();
1003
1004 if (proc_ro_data.p_uniqueid == startup_serial_num_procs) {
1005 /*
1006 * Turn off startup serial logging now that we have reached
1007 * the defined number of startup processes.
1008 */
1009 startup_serial_logging_active = false;
1010 }
1011
1012 /*
1013 * We've identified the PID we are going to use;
1014 * initialize the new process structure.
1015 */
1016 child_proc->p_stat = SIDL;
1017
1018 /*
1019 * The zero'ing of the proc was at the allocation time due to need
1020 * for insertion to hash. Copy the section that is to be copied
1021 * directly from the parent.
1022 */
1023 child_proc->p_forkcopy = parent_proc->p_forkcopy;
1024
1025 proc_ro_data.syscall_filter_mask = proc_syscall_filter_mask(parent_proc);
1026 proc_ro_data.p_platform_data = proc_get_ro(parent_proc)->p_platform_data;
1027
1028 /*
1029 * Some flags are inherited from the parent.
1030 * Duplicate sub-structures as needed.
1031 * Increase reference counts on shared objects.
1032 * The p_stats substruct is set in vm_fork.
1033 */
1034 #if CONFIG_DELAY_IDLE_SLEEP
1035 child_proc->p_flag = (parent_proc->p_flag & (P_LP64 | P_TRANSLATED | P_DISABLE_ASLR | P_DELAYIDLESLEEP | P_SUGID | P_AFFINITY));
1036 #else /* CONFIG_DELAY_IDLE_SLEEP */
1037 child_proc->p_flag = (parent_proc->p_flag & (P_LP64 | P_TRANSLATED | P_DISABLE_ASLR | P_SUGID | P_AFFINITY));
1038 #endif /* CONFIG_DELAY_IDLE_SLEEP */
1039
1040 child_proc->p_vfs_iopolicy = (parent_proc->p_vfs_iopolicy & (P_VFS_IOPOLICY_INHERITED_MASK));
1041
1042 child_proc->p_responsible_pid = parent_proc->p_responsible_pid;
1043
1044 /*
1045 * Note that if the current thread has an assumed identity, this
1046 * credential will be granted to the new process.
1047 */
1048 kauth_cred_set(&proc_ro_data.p_ucred.__smr_ptr, kauth_cred_get());
1049
1050 lck_mtx_init(&child_proc->p_mlock, &proc_mlock_grp, &proc_lck_attr);
1051 lck_mtx_init(&child_proc->p_ucred_mlock, &proc_ucred_mlock_grp, &proc_lck_attr);
1052 #if CONFIG_AUDIT
1053 lck_mtx_init(&child_proc->p_audit_mlock, &proc_ucred_mlock_grp, &proc_lck_attr);
1054 #endif /* CONFIG_AUDIT */
1055 #if CONFIG_DTRACE
1056 lck_mtx_init(&child_proc->p_dtrace_sprlock, &proc_lck_grp, &proc_lck_attr);
1057 #endif
1058 lck_spin_init(&child_proc->p_slock, &proc_slock_grp, &proc_lck_attr);
1059
1060 klist_init(&child_proc->p_klist);
1061
1062 if (child_proc->p_textvp != NULLVP) {
1063 /* bump references to the text vnode */
1064 /* Need to hold iocount across the ref call */
1065 if ((error = vnode_getwithref(child_proc->p_textvp)) == 0) {
1066 error = vnode_ref(child_proc->p_textvp);
1067 vnode_put(child_proc->p_textvp);
1068 }
1069
1070 if (error != 0) {
1071 child_proc->p_textvp = NULLVP;
1072 }
1073 }
1074
1075 /* Inherit the parent flags for code sign */
1076 proc_ro_data.p_csflags = ((uint32_t)proc_getcsflags(parent_proc) & ~CS_KILLED);
1077
1078 child_proc->p_proc_ro = proc_ro_alloc(child_proc, &proc_ro_data, NULL, NULL);
1079
1080 /* update cred on proc */
1081 proc_update_creds_onproc(child_proc, proc_ucred_unsafe(child_proc));
1082
1083 /* update audit session proc count */
1084 AUDIT_SESSION_PROCNEW(child_proc);
1085
1086 /*
1087 * Copy the parents per process open file table to the child; if
1088 * there is a per-thread current working directory, set the childs
1089 * per-process current working directory to that instead of the
1090 * parents.
1091 */
1092 if (fdt_fork(&child_proc->p_fd, parent_proc, parent_uthread->uu_cdir, in_exec) != 0) {
1093 forkproc_free(child_proc);
1094 child_proc = NULL;
1095 goto bad;
1096 }
1097
1098 #if SYSV_SHM
1099 if (parent_proc->vm_shm && !in_exec) {
1100 /* XXX may fail to attach shm to child */
1101 (void)shmfork(parent_proc, child_proc);
1102 }
1103 #endif
1104
1105 /*
1106 * Child inherits the parent's plimit
1107 */
1108 proc_limitfork(parent_proc, child_proc);
1109
1110 rlimit_cpu_cur = proc_limitgetcur(child_proc, RLIMIT_CPU);
1111 if (rlimit_cpu_cur != RLIM_INFINITY) {
1112 child_proc->p_rlim_cpu.tv_sec = (rlimit_cpu_cur > __INT_MAX__) ? __INT_MAX__ : rlimit_cpu_cur;
1113 }
1114
1115 if (in_exec) {
1116 /* Keep the original start time for exec'ed proc */
1117 child_proc->p_stats->ps_start = parent_proc->p_stats->ps_start;
1118 child_proc->p_start.tv_sec = parent_proc->p_start.tv_sec;
1119 child_proc->p_start.tv_usec = parent_proc->p_start.tv_usec;
1120 } else {
1121 /* Intialize new process stats, including start time */
1122 /* <rdar://6640543> non-zeroed portion contains garbage AFAICT */
1123 microtime_with_abstime(&child_proc->p_start, &child_proc->p_stats->ps_start);
1124 }
1125
1126 if (pg->pg_session->s_ttyvp != NULL && parent_proc->p_flag & P_CONTROLT) {
1127 os_atomic_or(&child_proc->p_flag, P_CONTROLT, relaxed);
1128 }
1129
1130 /*
1131 * block all signals to reach the process.
1132 * no transition race should be occuring with the child yet,
1133 * but indicate that the process is in (the creation) transition.
1134 */
1135 proc_signalstart(child_proc, 0);
1136 proc_transstart(child_proc, 0, 0);
1137
1138 child_proc->p_pcaction = 0;
1139
1140 TAILQ_INIT(&child_proc->p_uthlist);
1141 TAILQ_INIT(&child_proc->p_aio_activeq);
1142 TAILQ_INIT(&child_proc->p_aio_doneq);
1143
1144 /*
1145 * Copy work queue information
1146 *
1147 * Note: This should probably only happen in the case where we are
1148 * creating a child that is a copy of the parent; since this
1149 * routine is called in the non-duplication case of vfork()
1150 * or posix_spawn(), then this information should likely not
1151 * be duplicated.
1152 *
1153 * <rdar://6640553> Work queue pointers that no longer point to code
1154 */
1155 child_proc->p_wqthread = parent_proc->p_wqthread;
1156 child_proc->p_threadstart = parent_proc->p_threadstart;
1157 child_proc->p_pthsize = parent_proc->p_pthsize;
1158 if ((parent_proc->p_lflag & P_LREGISTER) != 0) {
1159 child_proc->p_lflag |= P_LREGISTER;
1160 }
1161 child_proc->p_dispatchqueue_offset = parent_proc->p_dispatchqueue_offset;
1162 child_proc->p_dispatchqueue_serialno_offset = parent_proc->p_dispatchqueue_serialno_offset;
1163 child_proc->p_dispatchqueue_label_offset = parent_proc->p_dispatchqueue_label_offset;
1164 child_proc->p_return_to_kernel_offset = parent_proc->p_return_to_kernel_offset;
1165 child_proc->p_mach_thread_self_offset = parent_proc->p_mach_thread_self_offset;
1166 child_proc->p_pth_tsd_offset = parent_proc->p_pth_tsd_offset;
1167 child_proc->p_pthread_wq_quantum_offset = parent_proc->p_pthread_wq_quantum_offset;
1168 #if PSYNCH
1169 pth_proc_hashinit(child_proc);
1170 #endif /* PSYNCH */
1171
1172 #if CONFIG_PERSONAS
1173 child_proc->p_persona = NULL;
1174 if (parent_proc->p_persona) {
1175 struct persona *persona = proc_persona_get(parent_proc);
1176
1177 if (persona) {
1178 error = persona_proc_adopt(child_proc, persona, NULL);
1179 if (error != 0) {
1180 printf("forkproc: persona_proc_inherit failed (persona %d being destroyed?)\n",
1181 persona_get_id(persona));
1182 forkproc_free(child_proc);
1183 child_proc = NULL;
1184 goto bad;
1185 }
1186 }
1187 }
1188 #endif
1189
1190 #if CONFIG_MEMORYSTATUS
1191 /* Memorystatus init */
1192 child_proc->p_memstat_state = 0;
1193 child_proc->p_memstat_effectivepriority = JETSAM_PRIORITY_DEFAULT;
1194 child_proc->p_memstat_requestedpriority = JETSAM_PRIORITY_DEFAULT;
1195 child_proc->p_memstat_assertionpriority = 0;
1196 child_proc->p_memstat_userdata = 0;
1197 child_proc->p_memstat_idle_start = 0;
1198 child_proc->p_memstat_idle_delta = 0;
1199 child_proc->p_memstat_memlimit = 0;
1200 child_proc->p_memstat_memlimit_active = 0;
1201 child_proc->p_memstat_memlimit_inactive = 0;
1202 child_proc->p_memstat_relaunch_flags = P_MEMSTAT_RELAUNCH_UNKNOWN;
1203 #if CONFIG_FREEZE
1204 child_proc->p_memstat_freeze_sharedanon_pages = 0;
1205 #endif
1206 child_proc->p_memstat_dirty = 0;
1207 child_proc->p_memstat_idledeadline = 0;
1208 #endif /* CONFIG_MEMORYSTATUS */
1209
1210 if (parent_proc->p_subsystem_root_path) {
1211 size_t parent_length = strlen(parent_proc->p_subsystem_root_path) + 1;
1212 assert(parent_length <= MAXPATHLEN);
1213 child_proc->p_subsystem_root_path = zalloc_flags(ZV_NAMEI,
1214 Z_WAITOK | Z_ZERO);
1215 memcpy(child_proc->p_subsystem_root_path, parent_proc->p_subsystem_root_path, parent_length);
1216 }
1217
1218 bad:
1219 return child_proc;
1220 }
1221
1222 void
proc_lock(proc_t p)1223 proc_lock(proc_t p)
1224 {
1225 LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_NOTOWNED);
1226 lck_mtx_lock(&p->p_mlock);
1227 }
1228
1229 void
proc_unlock(proc_t p)1230 proc_unlock(proc_t p)
1231 {
1232 lck_mtx_unlock(&p->p_mlock);
1233 }
1234
1235 void
proc_spinlock(proc_t p)1236 proc_spinlock(proc_t p)
1237 {
1238 lck_spin_lock_grp(&p->p_slock, &proc_slock_grp);
1239 }
1240
1241 void
proc_spinunlock(proc_t p)1242 proc_spinunlock(proc_t p)
1243 {
1244 lck_spin_unlock(&p->p_slock);
1245 }
1246
1247 void
proc_list_lock(void)1248 proc_list_lock(void)
1249 {
1250 lck_mtx_lock(&proc_list_mlock);
1251 }
1252
1253 void
proc_list_unlock(void)1254 proc_list_unlock(void)
1255 {
1256 lck_mtx_unlock(&proc_list_mlock);
1257 }
1258
1259 void
proc_ucred_lock(proc_t p)1260 proc_ucred_lock(proc_t p)
1261 {
1262 lck_mtx_lock(&p->p_ucred_mlock);
1263 }
1264
1265 void
proc_ucred_unlock(proc_t p)1266 proc_ucred_unlock(proc_t p)
1267 {
1268 lck_mtx_unlock(&p->p_ucred_mlock);
1269 }
1270
1271 void
proc_update_creds_onproc(proc_t p,kauth_cred_t cred)1272 proc_update_creds_onproc(proc_t p, kauth_cred_t cred)
1273 {
1274 p->p_uid = kauth_cred_getuid(cred);
1275 p->p_gid = kauth_cred_getgid(cred);
1276 p->p_ruid = kauth_cred_getruid(cred);
1277 p->p_rgid = kauth_cred_getrgid(cred);
1278 p->p_svuid = kauth_cred_getsvuid(cred);
1279 p->p_svgid = kauth_cred_getsvgid(cred);
1280 }
1281
1282
1283 bool
uthread_is64bit(struct uthread * uth)1284 uthread_is64bit(struct uthread *uth)
1285 {
1286 return uth->uu_flag & UT_LP64;
1287 }
1288
1289 void
uthread_init(task_t task,uthread_t uth,thread_ro_t tro_tpl,int workq_thread)1290 uthread_init(task_t task, uthread_t uth, thread_ro_t tro_tpl, int workq_thread)
1291 {
1292 uthread_t uth_parent = current_uthread();
1293
1294 lck_spin_init(&uth->uu_rethrottle_lock, &rethrottle_lock_grp,
1295 LCK_ATTR_NULL);
1296
1297 /*
1298 * Lazily set the thread on the kernel VFS context
1299 * to the first thread made which will be vm_pageout_scan_thread.
1300 */
1301 if (__improbable(vfs_context0.vc_thread == NULL)) {
1302 extern thread_t vm_pageout_scan_thread;
1303
1304 assert(task == kernel_task);
1305 assert(get_machthread(uth) == vm_pageout_scan_thread);
1306 vfs_context0.vc_thread = get_machthread(uth);
1307 }
1308
1309 if (task_get_64bit_addr(task)) {
1310 uth->uu_flag |= UT_LP64;
1311 }
1312
1313 /*
1314 * Thread inherits credential from the creating thread, if both
1315 * are in the same task.
1316 *
1317 * If the creating thread has no credential or is from another
1318 * task we can leave the new thread credential NULL. If it needs
1319 * one later, it will be lazily assigned from the task's process.
1320 */
1321 if (task == kernel_task) {
1322 kauth_cred_set(&tro_tpl->tro_cred, vfs_context0.vc_ucred);
1323 tro_tpl->tro_proc = kernproc;
1324 tro_tpl->tro_proc_ro = kernproc->p_proc_ro;
1325 } else if (!task_is_a_corpse(task)) {
1326 thread_ro_t curtro = current_thread_ro();
1327 proc_t p = get_bsdtask_info(task);
1328
1329 if (task == curtro->tro_task &&
1330 ((curtro->tro_flags & TRO_SETUID) == 0 || !workq_thread)) {
1331 kauth_cred_set(&tro_tpl->tro_cred, curtro->tro_cred);
1332 tro_tpl->tro_flags = (curtro->tro_flags & TRO_SETUID);
1333 tro_tpl->tro_proc_ro = curtro->tro_proc_ro;
1334 } else {
1335 kauth_cred_t cred = kauth_cred_proc_ref(p);
1336 kauth_cred_set_and_unref(&tro_tpl->tro_cred, &cred);
1337 tro_tpl->tro_proc_ro = task_get_ro(task);
1338 }
1339 tro_tpl->tro_proc = p;
1340
1341 proc_lock(p);
1342 if (workq_thread) {
1343 /* workq_thread threads will not inherit masks */
1344 uth->uu_sigmask = ~workq_threadmask;
1345 } else if (uth_parent->uu_flag & UT_SAS_OLDMASK) {
1346 uth->uu_sigmask = uth_parent->uu_oldmask;
1347 } else {
1348 uth->uu_sigmask = uth_parent->uu_sigmask;
1349 }
1350
1351 TAILQ_INSERT_TAIL(&p->p_uthlist, uth, uu_list);
1352 proc_unlock(p);
1353
1354 #if CONFIG_DTRACE
1355 if (p->p_dtrace_ptss_pages != NULL) {
1356 uth->t_dtrace_scratch = dtrace_ptss_claim_entry(p);
1357 }
1358 #endif
1359 } else {
1360 tro_tpl->tro_proc_ro = task_get_ro(task);
1361 }
1362
1363 uth->uu_pending_sigreturn = 0;
1364 uthread_init_proc_refcount(uth);
1365 }
1366
1367 mach_port_name_t
uthread_joiner_port(struct uthread * uth)1368 uthread_joiner_port(struct uthread *uth)
1369 {
1370 return uth->uu_save.uus_bsdthread_terminate.kport;
1371 }
1372
1373 user_addr_t
uthread_joiner_address(uthread_t uth)1374 uthread_joiner_address(uthread_t uth)
1375 {
1376 return uth->uu_save.uus_bsdthread_terminate.ulock_addr;
1377 }
1378
1379 void
uthread_joiner_wake(task_t task,uthread_t uth)1380 uthread_joiner_wake(task_t task, uthread_t uth)
1381 {
1382 struct _bsdthread_terminate bts = uth->uu_save.uus_bsdthread_terminate;
1383
1384 assert(bts.ulock_addr);
1385 bzero(&uth->uu_save.uus_bsdthread_terminate, sizeof(bts));
1386
1387 int flags = UL_UNFAIR_LOCK | ULF_WAKE_ALL | ULF_WAKE_ALLOW_NON_OWNER;
1388 (void)ulock_wake(task, flags, bts.ulock_addr, 0);
1389 mach_port_deallocate(get_task_ipcspace(task), bts.kport);
1390 }
1391
1392 /*
1393 * This routine frees the thread name field of the uthread_t structure. Split out of
1394 * uthread_cleanup() so thread name does not get deallocated while generating a corpse fork.
1395 */
1396 void
uthread_cleanup_name(uthread_t uth)1397 uthread_cleanup_name(uthread_t uth)
1398 {
1399 /*
1400 * <rdar://17834538>
1401 * Set pth_name to NULL before calling free().
1402 * Previously there was a race condition in the
1403 * case this code was executing during a stackshot
1404 * where the stackshot could try and copy pth_name
1405 * after it had been freed and before if was marked
1406 * as null.
1407 */
1408 if (uth->pth_name != NULL) {
1409 void *pth_name = uth->pth_name;
1410 uth->pth_name = NULL;
1411 kfree_data(pth_name, MAXTHREADNAMESIZE);
1412 }
1413 return;
1414 }
1415
1416 /*
1417 * This routine frees all the BSD context in uthread except the credential.
1418 * It does not free the uthread structure as well
1419 */
1420 void
uthread_cleanup(uthread_t uth,thread_ro_t tro)1421 uthread_cleanup(uthread_t uth, thread_ro_t tro)
1422 {
1423 task_t task = tro->tro_task;
1424 proc_t p = tro->tro_proc;
1425
1426 uthread_assert_zero_proc_refcount(uth);
1427
1428 if (uth->uu_lowpri_window || uth->uu_throttle_info) {
1429 /*
1430 * task is marked as a low priority I/O type
1431 * and we've somehow managed to not dismiss the throttle
1432 * through the normal exit paths back to user space...
1433 * no need to throttle this thread since its going away
1434 * but we do need to update our bookeeping w/r to throttled threads
1435 *
1436 * Calling this routine will clean up any throttle info reference
1437 * still inuse by the thread.
1438 */
1439 throttle_lowpri_io(0);
1440 }
1441
1442 #if CONFIG_AUDIT
1443 /*
1444 * Per-thread audit state should never last beyond system
1445 * call return. Since we don't audit the thread creation/
1446 * removal, the thread state pointer should never be
1447 * non-NULL when we get here.
1448 */
1449 assert(uth->uu_ar == NULL);
1450 #endif
1451
1452 if (uth->uu_select.nbytes) {
1453 select_cleanup_uthread(&uth->uu_select);
1454 }
1455
1456 if (uth->uu_cdir) {
1457 vnode_rele(uth->uu_cdir);
1458 uth->uu_cdir = NULLVP;
1459 }
1460
1461 if (uth->uu_selset) {
1462 select_set_free(uth->uu_selset);
1463 uth->uu_selset = NULL;
1464 }
1465
1466 os_reason_free(uth->uu_exit_reason);
1467
1468 if ((task != kernel_task) && p) {
1469 /*
1470 * Remove the thread from the process list and
1471 * transfer [appropriate] pending signals to the process.
1472 * Do not remove the uthread from proc uthlist for exec
1473 * copy task, since they does not have a ref on proc and
1474 * would not have been added to the list.
1475 */
1476 if (uth->uu_kqr_bound) {
1477 kqueue_threadreq_unbind(p, uth->uu_kqr_bound);
1478 }
1479
1480 if (get_bsdtask_info(task) == p) {
1481 proc_lock(p);
1482 TAILQ_REMOVE(&p->p_uthlist, uth, uu_list);
1483 p->p_siglist |= (uth->uu_siglist & execmask & (~p->p_sigignore | sigcantmask));
1484 proc_unlock(p);
1485 }
1486
1487 #if CONFIG_DTRACE
1488 struct dtrace_ptss_page_entry *tmpptr = uth->t_dtrace_scratch;
1489 uth->t_dtrace_scratch = NULL;
1490 if (tmpptr != NULL) {
1491 dtrace_ptss_release_entry(p, tmpptr);
1492 }
1493 #endif
1494 } else {
1495 assert(!uth->uu_kqr_bound);
1496 }
1497 }
1498
1499 /* This routine releases the credential stored in uthread */
1500 void
uthread_cred_ref(struct ucred * ucred)1501 uthread_cred_ref(struct ucred *ucred)
1502 {
1503 kauth_cred_ref(ucred);
1504 }
1505
1506 void
uthread_cred_free(struct ucred * ucred)1507 uthread_cred_free(struct ucred *ucred)
1508 {
1509 kauth_cred_set(&ucred, NOCRED);
1510 }
1511
1512 /* This routine frees the uthread structure held in thread structure */
1513 void
uthread_destroy(uthread_t uth)1514 uthread_destroy(uthread_t uth)
1515 {
1516 uthread_destroy_proc_refcount(uth);
1517
1518 if (uth->t_tombstone) {
1519 kfree_type(struct doc_tombstone, uth->t_tombstone);
1520 uth->t_tombstone = NULL;
1521 }
1522
1523 #if CONFIG_DEBUG_SYSCALL_REJECTION
1524 size_t const bitstr_len = BITMAP_SIZE(mach_trap_count + nsysent);
1525
1526 if (uth->syscall_rejection_mask) {
1527 kfree_data(uth->syscall_rejection_mask, bitstr_len);
1528 uth->syscall_rejection_mask = NULL;
1529 }
1530
1531 if (uth->syscall_rejection_once_mask) {
1532 kfree_data(uth->syscall_rejection_once_mask, bitstr_len);
1533 uth->syscall_rejection_once_mask = NULL;
1534 }
1535 #endif /* CONFIG_DEBUG_SYSCALL_REJECTION */
1536
1537 lck_spin_destroy(&uth->uu_rethrottle_lock, &rethrottle_lock_grp);
1538
1539 uthread_cleanup_name(uth);
1540 }
1541
1542 user_addr_t
thread_get_sigreturn_token(thread_t thread)1543 thread_get_sigreturn_token(thread_t thread)
1544 {
1545 uthread_t ut = (struct uthread *) get_bsdthread_info(thread);
1546 return ut->uu_sigreturn_token;
1547 }
1548
1549 uint32_t
thread_get_sigreturn_diversifier(thread_t thread)1550 thread_get_sigreturn_diversifier(thread_t thread)
1551 {
1552 uthread_t ut = (struct uthread *) get_bsdthread_info(thread);
1553 return ut->uu_sigreturn_diversifier;
1554 }
1555