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