xref: /xnu-8019.80.24/bsd/kern/kern_exit.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 /*
2  * Copyright (c) 2000-2016 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_exit.c	8.7 (Berkeley) 2/12/94
67  */
68 /*
69  * NOTICE: This file was modified by SPARTA, Inc. in 2005 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 #include <machine/reg.h>
76 #include <machine/psl.h>
77 #include <stdatomic.h>
78 
79 #include "compat_43.h"
80 
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/ioctl.h>
84 #include <sys/proc_internal.h>
85 #include <sys/proc.h>
86 #include <sys/kauth.h>
87 #include <sys/tty.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/kernel.h>
91 #include <sys/wait.h>
92 #include <sys/file_internal.h>
93 #include <sys/vnode_internal.h>
94 #include <sys/syslog.h>
95 #include <sys/malloc.h>
96 #include <sys/resourcevar.h>
97 #include <sys/ptrace.h>
98 #include <sys/proc_info.h>
99 #include <sys/reason.h>
100 #include <sys/_types/_timeval64.h>
101 #include <sys/user.h>
102 #include <sys/aio_kern.h>
103 #include <sys/sysproto.h>
104 #include <sys/signalvar.h>
105 #include <sys/kdebug.h>
106 #include <sys/kdebug_triage.h>
107 #include <sys/acct.h> /* acct_process */
108 #include <sys/codesign.h>
109 #include <sys/event.h> /* kevent_proc_copy_uptrs */
110 #include <sys/sdt.h>
111 
112 #include <security/audit/audit.h>
113 #include <bsm/audit_kevents.h>
114 
115 #include <mach/mach_types.h>
116 #include <mach/task.h>
117 #include <mach/thread_act.h>
118 
119 #include <kern/exc_resource.h>
120 #include <kern/kern_types.h>
121 #include <kern/kalloc.h>
122 #include <kern/task.h>
123 #include <corpses/task_corpse.h>
124 #include <kern/thread.h>
125 #include <kern/thread_call.h>
126 #include <kern/sched_prim.h>
127 #include <kern/assert.h>
128 #include <kern/locks.h>
129 #include <kern/policy_internal.h>
130 #include <kern/exc_guard.h>
131 #include <kern/backtrace.h>
132 
133 #include <vm/vm_protos.h>
134 #include <os/log.h>
135 
136 #include <pexpert/pexpert.h>
137 
138 #if SYSV_SHM
139 #include <sys/shm_internal.h>   /* shmexit */
140 #endif /* SYSV_SHM */
141 #if CONFIG_PERSONAS
142 #include <sys/persona.h>
143 #endif /* CONFIG_PERSONAS */
144 #if CONFIG_MEMORYSTATUS
145 #include <sys/kern_memorystatus.h>
146 #endif /* CONFIG_MEMORYSTATUS */
147 #if CONFIG_DTRACE
148 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
149 void dtrace_proc_exit(proc_t p);
150 #include <sys/dtrace_ptss.h>
151 #endif /* CONFIG_DTRACE */
152 #if CONFIG_MACF
153 #include <security/mac_framework.h>
154 #include <security/mac_mach_internal.h>
155 #include <sys/syscall.h>
156 #endif /* CONFIG_MACF */
157 
158 #if CONFIG_MEMORYSTATUS
159 static void proc_memorystatus_remove(proc_t p);
160 #endif /* CONFIG_MEMORYSTATUS */
161 void proc_prepareexit(proc_t p, int rv, boolean_t perf_notify);
162 void gather_populate_corpse_crashinfo(proc_t p, task_t corpse_task,
163     mach_exception_data_type_t code, mach_exception_data_type_t subcode,
164     uint64_t *udata_buffer, int num_udata, void *reason, exception_type_t etype);
165 mach_exception_data_type_t proc_encode_exit_exception_code(proc_t p);
166 exception_type_t get_exception_from_corpse_crashinfo(kcdata_descriptor_t corpse_info);
167 __private_extern__ void munge_user64_rusage(struct rusage *a_rusage_p, struct user64_rusage *a_user_rusage_p);
168 __private_extern__ void munge_user32_rusage(struct rusage *a_rusage_p, struct user32_rusage *a_user_rusage_p);
169 static int reap_child_locked(proc_t parent, proc_t child, int deadparent, int reparentedtoinit, int locked, int droplock);
170 static void populate_corpse_crashinfo(proc_t p, task_t corpse_task,
171     struct rusage_superset *rup, mach_exception_data_type_t code,
172     mach_exception_data_type_t subcode, uint64_t *udata_buffer,
173     int num_udata, os_reason_t reason, exception_type_t etype);
174 static void proc_update_corpse_exception_codes(proc_t p, mach_exception_data_type_t *code, mach_exception_data_type_t *subcode);
175 extern int proc_pidpathinfo_internal(proc_t p, uint64_t arg, char *buffer, uint32_t buffersize, int32_t *retval);
176 static __attribute__((noinline)) void launchd_crashed_panic(proc_t p, int rv);
177 extern void proc_piduniqidentifierinfo(proc_t p, struct proc_uniqidentifierinfo *p_uniqidinfo);
178 extern void task_coalition_ids(task_t task, uint64_t ids[COALITION_NUM_TYPES]);
179 extern uint64_t get_task_phys_footprint_limit(task_t);
180 int proc_list_uptrs(void *p, uint64_t *udata_buffer, int size);
181 extern uint64_t task_corpse_get_crashed_thread_id(task_t corpse_task);
182 
183 static KALLOC_TYPE_DEFINE(zombie_zone, struct rusage_superset, KT_DEFAULT);
184 
185 /*
186  * Things which should have prototypes in headers, but don't
187  */
188 void    proc_exit(proc_t p);
189 int     wait1continue(int result);
190 int     waitidcontinue(int result);
191 kern_return_t sys_perf_notify(thread_t thread, int pid);
192 kern_return_t task_exception_notify(exception_type_t exception,
193     mach_exception_data_type_t code, mach_exception_data_type_t subcode);
194 kern_return_t task_violated_guard(mach_exception_code_t, mach_exception_subcode_t, void *);
195 void    delay(int);
196 
197 #if __has_feature(ptrauth_calls)
198 int exit_with_pac_exception(proc_t p, exception_type_t exception, mach_exception_code_t code,
199     mach_exception_subcode_t subcode);
200 #endif /* __has_feature(ptrauth_calls) */
201 
202 int exit_with_guard_exception(proc_t p, mach_exception_data_type_t code,
203     mach_exception_data_type_t subcode);
204 int exit_with_port_space_exception(proc_t p, mach_exception_data_type_t code,
205     mach_exception_data_type_t subcode);
206 static int exit_with_mach_exception(proc_t p, os_reason_t reason, exception_type_t exception,
207     mach_exception_code_t code, mach_exception_subcode_t subcode);
208 
209 #if DEVELOPMENT || DEBUG
210 static LCK_GRP_DECLARE(proc_exit_lpexit_spin_lock_grp, "proc_exit_lpexit_spin");
211 static LCK_MTX_DECLARE(proc_exit_lpexit_spin_lock, &proc_exit_lpexit_spin_lock_grp);
212 static pid_t proc_exit_lpexit_spin_pid = -1;            /* wakeup point */
213 static int proc_exit_lpexit_spin_pos = -1;              /* point to block */
214 static int proc_exit_lpexit_spinning = 0;
215 enum {
216 	PELS_POS_START = 0,             /* beginning of proc_exit */
217 	PELS_POS_PRE_TASK_DETACH,       /* before task/proc detach */
218 	PELS_POS_POST_TASK_DETACH,      /* after task/proc detach */
219 	PELS_POS_END,                   /* end of proc_exit */
220 	PELS_NPOS                       /* # valid values */
221 };
222 
223 /* Panic if matching processes (delimited by ',') exit on error. */
224 static TUNABLE_STR(panic_on_eexit_pcomms, 128, "panic_on_error_exit", "");
225 
226 static int
227 proc_exit_lpexit_spin_pid_sysctl SYSCTL_HANDLER_ARGS
228 {
229 #pragma unused(oidp, arg1, arg2)
230 	pid_t new_value;
231 	int changed;
232 	int error;
233 
234 	if (!PE_parse_boot_argn("enable_proc_exit_lpexit_spin", NULL, 0)) {
235 		return ENOENT;
236 	}
237 
238 	error = sysctl_io_number(req, proc_exit_lpexit_spin_pid,
239 	    sizeof(proc_exit_lpexit_spin_pid), &new_value, &changed);
240 	if (error == 0 && changed != 0) {
241 		if (new_value < -1) {
242 			return EINVAL;
243 		}
244 		lck_mtx_lock(&proc_exit_lpexit_spin_lock);
245 		proc_exit_lpexit_spin_pid = new_value;
246 		wakeup(&proc_exit_lpexit_spin_pid);
247 		proc_exit_lpexit_spinning = 0;
248 		lck_mtx_unlock(&proc_exit_lpexit_spin_lock);
249 	}
250 	return error;
251 }
252 
253 static int
254 proc_exit_lpexit_spin_pos_sysctl SYSCTL_HANDLER_ARGS
255 {
256 #pragma unused(oidp, arg1, arg2)
257 	int new_value;
258 	int changed;
259 	int error;
260 
261 	if (!PE_parse_boot_argn("enable_proc_exit_lpexit_spin", NULL, 0)) {
262 		return ENOENT;
263 	}
264 
265 	error = sysctl_io_number(req, proc_exit_lpexit_spin_pos,
266 	    sizeof(proc_exit_lpexit_spin_pos), &new_value, &changed);
267 	if (error == 0 && changed != 0) {
268 		if (new_value < -1 || new_value >= PELS_NPOS) {
269 			return EINVAL;
270 		}
271 		lck_mtx_lock(&proc_exit_lpexit_spin_lock);
272 		proc_exit_lpexit_spin_pos = new_value;
273 		wakeup(&proc_exit_lpexit_spin_pid);
274 		proc_exit_lpexit_spinning = 0;
275 		lck_mtx_unlock(&proc_exit_lpexit_spin_lock);
276 	}
277 	return error;
278 }
279 
280 static int
281 proc_exit_lpexit_spinning_sysctl SYSCTL_HANDLER_ARGS
282 {
283 #pragma unused(oidp, arg1, arg2)
284 	int new_value;
285 	int changed;
286 	int error;
287 
288 	if (!PE_parse_boot_argn("enable_proc_exit_lpexit_spin", NULL, 0)) {
289 		return ENOENT;
290 	}
291 
292 	error = sysctl_io_number(req, proc_exit_lpexit_spinning,
293 	    sizeof(proc_exit_lpexit_spinning), &new_value, &changed);
294 	if (error == 0 && changed != 0) {
295 		return EINVAL;
296 	}
297 	return error;
298 }
299 
300 SYSCTL_PROC(_debug, OID_AUTO, proc_exit_lpexit_spin_pid,
301     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
302     NULL, sizeof(pid_t),
303     proc_exit_lpexit_spin_pid_sysctl, "I", "PID to hold in proc_exit");
304 
305 SYSCTL_PROC(_debug, OID_AUTO, proc_exit_lpexit_spin_pos,
306     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
307     NULL, sizeof(int),
308     proc_exit_lpexit_spin_pos_sysctl, "I", "position to hold in proc_exit");
309 
310 SYSCTL_PROC(_debug, OID_AUTO, proc_exit_lpexit_spinning,
311     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED,
312     NULL, sizeof(int),
313     proc_exit_lpexit_spinning_sysctl, "I", "is a thread at requested pid/pos");
314 
315 static inline void
proc_exit_lpexit_check(pid_t pid,int pos)316 proc_exit_lpexit_check(pid_t pid, int pos)
317 {
318 	if (proc_exit_lpexit_spin_pid == pid) {
319 		bool slept = false;
320 		lck_mtx_lock(&proc_exit_lpexit_spin_lock);
321 		while (proc_exit_lpexit_spin_pid == pid &&
322 		    proc_exit_lpexit_spin_pos == pos) {
323 			if (!slept) {
324 				os_log(OS_LOG_DEFAULT,
325 				    "proc_exit_lpexit_check: Process[%d] waiting during proc_exit at pos %d as requested", pid, pos);
326 				slept = true;
327 			}
328 			proc_exit_lpexit_spinning = 1;
329 			msleep(&proc_exit_lpexit_spin_pid, &proc_exit_lpexit_spin_lock,
330 			    PWAIT, "proc_exit_lpexit_check", NULL);
331 			proc_exit_lpexit_spinning = 0;
332 		}
333 		lck_mtx_unlock(&proc_exit_lpexit_spin_lock);
334 		if (slept) {
335 			os_log(OS_LOG_DEFAULT,
336 			    "proc_exit_lpexit_check: Process[%d] driving on from pos %d", pid, pos);
337 		}
338 	}
339 }
340 #endif /* DEVELOPMENT || DEBUG */
341 
342 /*
343  * NOTE: Source and target may *NOT* overlap!
344  * XXX Should share code with bsd/dev/ppc/unix_signal.c
345  */
346 void
siginfo_user_to_user32(user_siginfo_t * in,user32_siginfo_t * out)347 siginfo_user_to_user32(user_siginfo_t *in, user32_siginfo_t *out)
348 {
349 	out->si_signo   = in->si_signo;
350 	out->si_errno   = in->si_errno;
351 	out->si_code    = in->si_code;
352 	out->si_pid     = in->si_pid;
353 	out->si_uid     = in->si_uid;
354 	out->si_status  = in->si_status;
355 	out->si_addr    = CAST_DOWN_EXPLICIT(user32_addr_t, in->si_addr);
356 	/* following cast works for sival_int because of padding */
357 	out->si_value.sival_ptr = CAST_DOWN_EXPLICIT(user32_addr_t, in->si_value.sival_ptr);
358 	out->si_band    = (user32_long_t)in->si_band;                  /* range reduction */
359 }
360 
361 void
siginfo_user_to_user64(user_siginfo_t * in,user64_siginfo_t * out)362 siginfo_user_to_user64(user_siginfo_t *in, user64_siginfo_t *out)
363 {
364 	out->si_signo   = in->si_signo;
365 	out->si_errno   = in->si_errno;
366 	out->si_code    = in->si_code;
367 	out->si_pid     = in->si_pid;
368 	out->si_uid     = in->si_uid;
369 	out->si_status  = in->si_status;
370 	out->si_addr    = in->si_addr;
371 	/* following cast works for sival_int because of padding */
372 	out->si_value.sival_ptr = in->si_value.sival_ptr;
373 	out->si_band    = in->si_band;                  /* range reduction */
374 }
375 
376 static int
copyoutsiginfo(user_siginfo_t * native,boolean_t is64,user_addr_t uaddr)377 copyoutsiginfo(user_siginfo_t *native, boolean_t is64, user_addr_t uaddr)
378 {
379 	if (is64) {
380 		user64_siginfo_t sinfo64;
381 
382 		bzero(&sinfo64, sizeof(sinfo64));
383 		siginfo_user_to_user64(native, &sinfo64);
384 		return copyout(&sinfo64, uaddr, sizeof(sinfo64));
385 	} else {
386 		user32_siginfo_t sinfo32;
387 
388 		bzero(&sinfo32, sizeof(sinfo32));
389 		siginfo_user_to_user32(native, &sinfo32);
390 		return copyout(&sinfo32, uaddr, sizeof(sinfo32));
391 	}
392 }
393 
394 void
gather_populate_corpse_crashinfo(proc_t p,task_t corpse_task,mach_exception_data_type_t code,mach_exception_data_type_t subcode,uint64_t * udata_buffer,int num_udata,void * reason,exception_type_t etype)395 gather_populate_corpse_crashinfo(proc_t p, task_t corpse_task,
396     mach_exception_data_type_t code, mach_exception_data_type_t subcode,
397     uint64_t *udata_buffer, int num_udata, void *reason, exception_type_t etype)
398 {
399 	struct rusage_superset rup;
400 
401 	gather_rusage_info(p, &rup.ri, RUSAGE_INFO_CURRENT);
402 	rup.ri.ri_phys_footprint = 0;
403 	populate_corpse_crashinfo(p, corpse_task, &rup, code, subcode,
404 	    udata_buffer, num_udata, reason, etype);
405 }
406 
407 static void
proc_update_corpse_exception_codes(proc_t p,mach_exception_data_type_t * code,mach_exception_data_type_t * subcode)408 proc_update_corpse_exception_codes(proc_t p, mach_exception_data_type_t *code, mach_exception_data_type_t *subcode)
409 {
410 	mach_exception_data_type_t code_update = *code;
411 	mach_exception_data_type_t subcode_update = *subcode;
412 	if (p->p_exit_reason == OS_REASON_NULL) {
413 		return;
414 	}
415 
416 	switch (p->p_exit_reason->osr_namespace) {
417 	case OS_REASON_JETSAM:
418 		if (p->p_exit_reason->osr_code == JETSAM_REASON_MEMORY_PERPROCESSLIMIT) {
419 			/* Update the code with EXC_RESOURCE code for high memory watermark */
420 			EXC_RESOURCE_ENCODE_TYPE(code_update, RESOURCE_TYPE_MEMORY);
421 			EXC_RESOURCE_ENCODE_FLAVOR(code_update, FLAVOR_HIGH_WATERMARK);
422 			EXC_RESOURCE_HWM_ENCODE_LIMIT(code_update, ((get_task_phys_footprint_limit(p->task)) >> 20));
423 			subcode_update = 0;
424 			break;
425 		}
426 
427 		break;
428 	default:
429 		break;
430 	}
431 
432 	*code = code_update;
433 	*subcode = subcode_update;
434 	return;
435 }
436 
437 mach_exception_data_type_t
proc_encode_exit_exception_code(proc_t p)438 proc_encode_exit_exception_code(proc_t p)
439 {
440 	uint64_t subcode = 0;
441 
442 	if (p->p_exit_reason == OS_REASON_NULL) {
443 		return 0;
444 	}
445 
446 	/* Embed first 32 bits of osr_namespace and osr_code in exception code */
447 	ENCODE_OSR_NAMESPACE_TO_MACH_EXCEPTION_CODE(subcode, p->p_exit_reason->osr_namespace);
448 	ENCODE_OSR_CODE_TO_MACH_EXCEPTION_CODE(subcode, p->p_exit_reason->osr_code);
449 	return (mach_exception_data_type_t)subcode;
450 }
451 
452 static void
populate_corpse_crashinfo(proc_t p,task_t corpse_task,struct rusage_superset * rup,mach_exception_data_type_t code,mach_exception_data_type_t subcode,uint64_t * udata_buffer,int num_udata,os_reason_t reason,exception_type_t etype)453 populate_corpse_crashinfo(proc_t p, task_t corpse_task, struct rusage_superset *rup,
454     mach_exception_data_type_t code, mach_exception_data_type_t subcode,
455     uint64_t *udata_buffer, int num_udata, os_reason_t reason, exception_type_t etype)
456 {
457 	mach_vm_address_t uaddr = 0;
458 	mach_exception_data_type_t exc_codes[EXCEPTION_CODE_MAX];
459 	exc_codes[0] = code;
460 	exc_codes[1] = subcode;
461 	cpu_type_t cputype;
462 	struct proc_uniqidentifierinfo p_uniqidinfo;
463 	struct proc_workqueueinfo pwqinfo;
464 	int retval = 0;
465 	uint64_t crashed_threadid = task_corpse_get_crashed_thread_id(corpse_task);
466 	bool is_corpse_fork;
467 	uint32_t csflags;
468 	unsigned int pflags = 0;
469 	uint64_t max_footprint_mb;
470 	uint64_t max_footprint;
471 
472 	uint64_t ledger_internal;
473 	uint64_t ledger_internal_compressed;
474 	uint64_t ledger_iokit_mapped;
475 	uint64_t ledger_alternate_accounting;
476 	uint64_t ledger_alternate_accounting_compressed;
477 	uint64_t ledger_purgeable_nonvolatile;
478 	uint64_t ledger_purgeable_nonvolatile_compressed;
479 	uint64_t ledger_page_table;
480 	uint64_t ledger_phys_footprint;
481 	uint64_t ledger_phys_footprint_lifetime_max;
482 	uint64_t ledger_network_nonvolatile;
483 	uint64_t ledger_network_nonvolatile_compressed;
484 	uint64_t ledger_wired_mem;
485 	uint64_t ledger_tagged_footprint;
486 	uint64_t ledger_tagged_footprint_compressed;
487 	uint64_t ledger_media_footprint;
488 	uint64_t ledger_media_footprint_compressed;
489 	uint64_t ledger_graphics_footprint;
490 	uint64_t ledger_graphics_footprint_compressed;
491 	uint64_t ledger_neural_footprint;
492 	uint64_t ledger_neural_footprint_compressed;
493 
494 	void *crash_info_ptr = task_get_corpseinfo(corpse_task);
495 
496 #if CONFIG_MEMORYSTATUS
497 	int memstat_dirty_flags = 0;
498 #endif
499 
500 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_EXCEPTION_CODES, sizeof(exc_codes), &uaddr)) {
501 		kcdata_memcpy(crash_info_ptr, uaddr, exc_codes, sizeof(exc_codes));
502 	}
503 
504 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PID, sizeof(pid_t), &uaddr)) {
505 		pid_t pid = proc_getpid(p);
506 		kcdata_memcpy(crash_info_ptr, uaddr, &pid, sizeof(pid));
507 	}
508 
509 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PPID, sizeof(p->p_ppid), &uaddr)) {
510 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_ppid, sizeof(p->p_ppid));
511 	}
512 
513 	/* Don't include the crashed thread ID if there's an exit reason that indicates it's irrelevant */
514 	if ((p->p_exit_reason == OS_REASON_NULL) || !(p->p_exit_reason->osr_flags & OS_REASON_FLAG_NO_CRASHED_TID)) {
515 		if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_CRASHED_THREADID, sizeof(uint64_t), &uaddr)) {
516 			kcdata_memcpy(crash_info_ptr, uaddr, &crashed_threadid, sizeof(uint64_t));
517 		}
518 	}
519 
520 	static_assert(sizeof(struct proc_uniqidentifierinfo) == sizeof(struct crashinfo_proc_uniqidentifierinfo));
521 	if (KERN_SUCCESS ==
522 	    kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_BSDINFOWITHUNIQID, sizeof(struct proc_uniqidentifierinfo), &uaddr)) {
523 		proc_piduniqidentifierinfo(p, &p_uniqidinfo);
524 		kcdata_memcpy(crash_info_ptr, uaddr, &p_uniqidinfo, sizeof(struct proc_uniqidentifierinfo));
525 	}
526 
527 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_RUSAGE_INFO, sizeof(rusage_info_current), &uaddr)) {
528 		kcdata_memcpy(crash_info_ptr, uaddr, &rup->ri, sizeof(rusage_info_current));
529 	}
530 
531 	csflags = (uint32_t)proc_getcsflags(p);
532 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_CSFLAGS, sizeof(csflags), &uaddr)) {
533 		kcdata_memcpy(crash_info_ptr, uaddr, &csflags, sizeof(csflags));
534 	}
535 
536 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_NAME, sizeof(p->p_comm), &uaddr)) {
537 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_comm, sizeof(p->p_comm));
538 	}
539 
540 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_STARTTIME, sizeof(p->p_start), &uaddr)) {
541 		struct timeval64 t64;
542 		t64.tv_sec = (int64_t)p->p_start.tv_sec;
543 		t64.tv_usec = (int64_t)p->p_start.tv_usec;
544 		kcdata_memcpy(crash_info_ptr, uaddr, &t64, sizeof(t64));
545 	}
546 
547 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_USERSTACK, sizeof(p->user_stack), &uaddr)) {
548 		kcdata_memcpy(crash_info_ptr, uaddr, &p->user_stack, sizeof(p->user_stack));
549 	}
550 
551 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_ARGSLEN, sizeof(p->p_argslen), &uaddr)) {
552 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_argslen, sizeof(p->p_argslen));
553 	}
554 
555 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_ARGC, sizeof(p->p_argc), &uaddr)) {
556 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_argc, sizeof(p->p_argc));
557 	}
558 
559 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_PATH, MAXPATHLEN, &uaddr)) {
560 		char *buf = zalloc_flags(ZV_NAMEI, Z_WAITOK | Z_ZERO);
561 		proc_pidpathinfo_internal(p, 0, buf, MAXPATHLEN, &retval);
562 		kcdata_memcpy(crash_info_ptr, uaddr, buf, MAXPATHLEN);
563 		zfree(ZV_NAMEI, buf);
564 	}
565 
566 	pflags = p->p_flag & (P_LP64 | P_SUGID | P_TRANSLATED);
567 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_FLAGS, sizeof(pflags), &uaddr)) {
568 		kcdata_memcpy(crash_info_ptr, uaddr, &pflags, sizeof(pflags));
569 	}
570 
571 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_UID, sizeof(p->p_uid), &uaddr)) {
572 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_uid, sizeof(p->p_uid));
573 	}
574 
575 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_GID, sizeof(p->p_gid), &uaddr)) {
576 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_gid, sizeof(p->p_gid));
577 	}
578 
579 	cputype = cpu_type() & ~CPU_ARCH_MASK;
580 	if (IS_64BIT_PROCESS(p)) {
581 		cputype |= CPU_ARCH_ABI64;
582 	}
583 
584 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_CPUTYPE, sizeof(cpu_type_t), &uaddr)) {
585 		kcdata_memcpy(crash_info_ptr, uaddr, &cputype, sizeof(cpu_type_t));
586 	}
587 
588 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_MEMORY_LIMIT, sizeof(max_footprint_mb), &uaddr)) {
589 		max_footprint = get_task_phys_footprint_limit(p->task);
590 		max_footprint_mb = max_footprint >> 20;
591 		kcdata_memcpy(crash_info_ptr, uaddr, &max_footprint_mb, sizeof(max_footprint_mb));
592 	}
593 
594 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_PHYS_FOOTPRINT_LIFETIME_MAX, sizeof(ledger_phys_footprint_lifetime_max), &uaddr)) {
595 		ledger_phys_footprint_lifetime_max = get_task_phys_footprint_lifetime_max(p->task);
596 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_phys_footprint_lifetime_max, sizeof(ledger_phys_footprint_lifetime_max));
597 	}
598 
599 	// In the forking case, the current ledger info is copied into the corpse while the original task is suspended for consistency
600 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_INTERNAL, sizeof(ledger_internal), &uaddr)) {
601 		ledger_internal = get_task_internal(corpse_task);
602 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_internal, sizeof(ledger_internal));
603 	}
604 
605 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_INTERNAL_COMPRESSED, sizeof(ledger_internal_compressed), &uaddr)) {
606 		ledger_internal_compressed = get_task_internal_compressed(corpse_task);
607 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_internal_compressed, sizeof(ledger_internal_compressed));
608 	}
609 
610 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_IOKIT_MAPPED, sizeof(ledger_iokit_mapped), &uaddr)) {
611 		ledger_iokit_mapped = get_task_iokit_mapped(corpse_task);
612 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_iokit_mapped, sizeof(ledger_iokit_mapped));
613 	}
614 
615 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_ALTERNATE_ACCOUNTING, sizeof(ledger_alternate_accounting), &uaddr)) {
616 		ledger_alternate_accounting = get_task_alternate_accounting(corpse_task);
617 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_alternate_accounting, sizeof(ledger_alternate_accounting));
618 	}
619 
620 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_ALTERNATE_ACCOUNTING_COMPRESSED, sizeof(ledger_alternate_accounting_compressed), &uaddr)) {
621 		ledger_alternate_accounting_compressed = get_task_alternate_accounting_compressed(corpse_task);
622 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_alternate_accounting_compressed, sizeof(ledger_alternate_accounting_compressed));
623 	}
624 
625 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_PURGEABLE_NONVOLATILE, sizeof(ledger_purgeable_nonvolatile), &uaddr)) {
626 		ledger_purgeable_nonvolatile = get_task_purgeable_nonvolatile(corpse_task);
627 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_purgeable_nonvolatile, sizeof(ledger_purgeable_nonvolatile));
628 	}
629 
630 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_PURGEABLE_NONVOLATILE_COMPRESSED, sizeof(ledger_purgeable_nonvolatile_compressed), &uaddr)) {
631 		ledger_purgeable_nonvolatile_compressed = get_task_purgeable_nonvolatile_compressed(corpse_task);
632 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_purgeable_nonvolatile_compressed, sizeof(ledger_purgeable_nonvolatile_compressed));
633 	}
634 
635 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_PAGE_TABLE, sizeof(ledger_page_table), &uaddr)) {
636 		ledger_page_table = get_task_page_table(corpse_task);
637 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_page_table, sizeof(ledger_page_table));
638 	}
639 
640 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_PHYS_FOOTPRINT, sizeof(ledger_phys_footprint), &uaddr)) {
641 		ledger_phys_footprint = get_task_phys_footprint(corpse_task);
642 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_phys_footprint, sizeof(ledger_phys_footprint));
643 	}
644 
645 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_NETWORK_NONVOLATILE, sizeof(ledger_network_nonvolatile), &uaddr)) {
646 		ledger_network_nonvolatile = get_task_network_nonvolatile(corpse_task);
647 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_network_nonvolatile, sizeof(ledger_network_nonvolatile));
648 	}
649 
650 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_NETWORK_NONVOLATILE_COMPRESSED, sizeof(ledger_network_nonvolatile_compressed), &uaddr)) {
651 		ledger_network_nonvolatile_compressed = get_task_network_nonvolatile_compressed(corpse_task);
652 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_network_nonvolatile_compressed, sizeof(ledger_network_nonvolatile_compressed));
653 	}
654 
655 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_WIRED_MEM, sizeof(ledger_wired_mem), &uaddr)) {
656 		ledger_wired_mem = get_task_wired_mem(corpse_task);
657 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_wired_mem, sizeof(ledger_wired_mem));
658 	}
659 
660 	bzero(&pwqinfo, sizeof(struct proc_workqueueinfo));
661 	retval = fill_procworkqueue(p, &pwqinfo);
662 	if (retval == 0) {
663 		if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_WORKQUEUEINFO, sizeof(struct proc_workqueueinfo), &uaddr)) {
664 			kcdata_memcpy(crash_info_ptr, uaddr, &pwqinfo, sizeof(struct proc_workqueueinfo));
665 		}
666 	}
667 
668 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_RESPONSIBLE_PID, sizeof(p->p_responsible_pid), &uaddr)) {
669 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_responsible_pid, sizeof(p->p_responsible_pid));
670 	}
671 
672 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_PERSONA_ID, sizeof(uid_t), &uaddr)) {
673 		uid_t persona_id = proc_persona_id(p);
674 		kcdata_memcpy(crash_info_ptr, uaddr, &persona_id, sizeof(persona_id));
675 	}
676 
677 #if CONFIG_COALITIONS
678 	if (KERN_SUCCESS == kcdata_get_memory_addr_for_array(crash_info_ptr, TASK_CRASHINFO_COALITION_ID, sizeof(uint64_t), COALITION_NUM_TYPES, &uaddr)) {
679 		uint64_t coalition_ids[COALITION_NUM_TYPES];
680 		task_coalition_ids(p->task, coalition_ids);
681 		kcdata_memcpy(crash_info_ptr, uaddr, coalition_ids, sizeof(coalition_ids));
682 	}
683 #endif /* CONFIG_COALITIONS */
684 
685 #if CONFIG_MEMORYSTATUS
686 	memstat_dirty_flags = memorystatus_dirty_get(p, FALSE);
687 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_DIRTY_FLAGS, sizeof(memstat_dirty_flags), &uaddr)) {
688 		kcdata_memcpy(crash_info_ptr, uaddr, &memstat_dirty_flags, sizeof(memstat_dirty_flags));
689 	}
690 #endif
691 
692 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_MEMORY_LIMIT_INCREASE, sizeof(p->p_memlimit_increase), &uaddr)) {
693 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_memlimit_increase, sizeof(p->p_memlimit_increase));
694 	}
695 
696 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_TAGGED_FOOTPRINT, sizeof(ledger_tagged_footprint), &uaddr)) {
697 		ledger_tagged_footprint = get_task_tagged_footprint(corpse_task);
698 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_tagged_footprint, sizeof(ledger_tagged_footprint));
699 	}
700 
701 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_TAGGED_FOOTPRINT_COMPRESSED, sizeof(ledger_tagged_footprint_compressed), &uaddr)) {
702 		ledger_tagged_footprint_compressed = get_task_tagged_footprint_compressed(corpse_task);
703 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_tagged_footprint_compressed, sizeof(ledger_tagged_footprint_compressed));
704 	}
705 
706 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_MEDIA_FOOTPRINT, sizeof(ledger_media_footprint), &uaddr)) {
707 		ledger_media_footprint = get_task_media_footprint(corpse_task);
708 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_media_footprint, sizeof(ledger_media_footprint));
709 	}
710 
711 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_MEDIA_FOOTPRINT_COMPRESSED, sizeof(ledger_media_footprint_compressed), &uaddr)) {
712 		ledger_media_footprint_compressed = get_task_media_footprint_compressed(corpse_task);
713 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_media_footprint_compressed, sizeof(ledger_media_footprint_compressed));
714 	}
715 
716 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_GRAPHICS_FOOTPRINT, sizeof(ledger_graphics_footprint), &uaddr)) {
717 		ledger_graphics_footprint = get_task_graphics_footprint(corpse_task);
718 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_graphics_footprint, sizeof(ledger_graphics_footprint));
719 	}
720 
721 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_GRAPHICS_FOOTPRINT_COMPRESSED, sizeof(ledger_graphics_footprint_compressed), &uaddr)) {
722 		ledger_graphics_footprint_compressed = get_task_graphics_footprint_compressed(corpse_task);
723 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_graphics_footprint_compressed, sizeof(ledger_graphics_footprint_compressed));
724 	}
725 
726 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_NEURAL_FOOTPRINT, sizeof(ledger_neural_footprint), &uaddr)) {
727 		ledger_neural_footprint = get_task_neural_footprint(corpse_task);
728 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_neural_footprint, sizeof(ledger_neural_footprint));
729 	}
730 
731 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_LEDGER_NEURAL_FOOTPRINT_COMPRESSED, sizeof(ledger_neural_footprint_compressed), &uaddr)) {
732 		ledger_neural_footprint_compressed = get_task_neural_footprint_compressed(corpse_task);
733 		kcdata_memcpy(crash_info_ptr, uaddr, &ledger_neural_footprint_compressed, sizeof(ledger_neural_footprint_compressed));
734 	}
735 
736 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_MEMORYSTATUS_EFFECTIVE_PRIORITY, sizeof(p->p_memstat_effectivepriority), &uaddr)) {
737 		kcdata_memcpy(crash_info_ptr, uaddr, &p->p_memstat_effectivepriority, sizeof(p->p_memstat_effectivepriority));
738 	}
739 
740 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_KERNEL_TRIAGE_INFO_V1, sizeof(struct kernel_triage_info_v1), &uaddr)) {
741 		char triage_strings[KDBG_TRIAGE_MAX_STRINGS][KDBG_TRIAGE_MAX_STRLEN];
742 		kernel_triage_extract(thread_tid(current_thread()), triage_strings, KDBG_TRIAGE_MAX_STRINGS * KDBG_TRIAGE_MAX_STRLEN);
743 		kcdata_memcpy(crash_info_ptr, uaddr, (void*) triage_strings, sizeof(struct kernel_triage_info_v1));
744 	}
745 
746 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_TASK_IS_CORPSE_FORK, sizeof(is_corpse_fork), &uaddr)) {
747 		is_corpse_fork = is_corpsefork(corpse_task);
748 		kcdata_memcpy(crash_info_ptr, uaddr, &is_corpse_fork, sizeof(is_corpse_fork));
749 	}
750 
751 	if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_EXCEPTION_TYPE, sizeof(etype), &uaddr)) {
752 		kcdata_memcpy(crash_info_ptr, uaddr, &etype, sizeof(etype));
753 	}
754 
755 	if (p->p_exit_reason != OS_REASON_NULL && reason == OS_REASON_NULL) {
756 		reason = p->p_exit_reason;
757 	}
758 	if (reason != OS_REASON_NULL) {
759 		if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, EXIT_REASON_SNAPSHOT, sizeof(struct exit_reason_snapshot), &uaddr)) {
760 			struct exit_reason_snapshot ers = {
761 				.ers_namespace = reason->osr_namespace,
762 				.ers_code = reason->osr_code,
763 				.ers_flags = reason->osr_flags
764 			};
765 
766 			kcdata_memcpy(crash_info_ptr, uaddr, &ers, sizeof(ers));
767 		}
768 
769 		if (reason->osr_kcd_buf != 0) {
770 			uint32_t reason_buf_size = (uint32_t)kcdata_memory_get_used_bytes(&reason->osr_kcd_descriptor);
771 			assert(reason_buf_size != 0);
772 
773 			if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, KCDATA_TYPE_NESTED_KCDATA, reason_buf_size, &uaddr)) {
774 				kcdata_memcpy(crash_info_ptr, uaddr, reason->osr_kcd_buf, reason_buf_size);
775 			}
776 		}
777 	}
778 
779 	if (num_udata > 0) {
780 		if (KERN_SUCCESS == kcdata_get_memory_addr_for_array(crash_info_ptr, TASK_CRASHINFO_UDATA_PTRS,
781 		    sizeof(uint64_t), num_udata, &uaddr)) {
782 			kcdata_memcpy(crash_info_ptr, uaddr, udata_buffer, sizeof(uint64_t) * num_udata);
783 		}
784 	}
785 }
786 
787 exception_type_t
get_exception_from_corpse_crashinfo(kcdata_descriptor_t corpse_info)788 get_exception_from_corpse_crashinfo(kcdata_descriptor_t corpse_info)
789 {
790 	kcdata_iter_t iter = kcdata_iter((void *)corpse_info->kcd_addr_begin,
791 	    corpse_info->kcd_length);
792 	__assert_only uint32_t type = kcdata_iter_type(iter);
793 	assert(type == KCDATA_BUFFER_BEGIN_CRASHINFO);
794 
795 	iter = kcdata_iter_find_type(iter, TASK_CRASHINFO_EXCEPTION_TYPE);
796 	exception_type_t *etype = kcdata_iter_payload(iter);
797 	return *etype;
798 }
799 
800 /*
801  * We only parse exit reason kcdata blobs for launchd when it dies
802  * and we're going to panic.
803  *
804  * Meant to be called immediately before panicking.
805  */
806 char *
launchd_exit_reason_get_string_desc(os_reason_t exit_reason)807 launchd_exit_reason_get_string_desc(os_reason_t exit_reason)
808 {
809 	kcdata_iter_t iter;
810 
811 	if (exit_reason == OS_REASON_NULL || exit_reason->osr_kcd_buf == NULL ||
812 	    exit_reason->osr_bufsize == 0) {
813 		return NULL;
814 	}
815 
816 	iter = kcdata_iter(exit_reason->osr_kcd_buf, exit_reason->osr_bufsize);
817 	if (!kcdata_iter_valid(iter)) {
818 #if DEBUG || DEVELOPMENT
819 		printf("launchd exit reason has invalid exit reason buffer\n");
820 #endif
821 		return NULL;
822 	}
823 
824 	if (kcdata_iter_type(iter) != KCDATA_BUFFER_BEGIN_OS_REASON) {
825 #if DEBUG || DEVELOPMENT
826 		printf("launchd exit reason buffer type mismatch, expected %d got %d\n",
827 		    KCDATA_BUFFER_BEGIN_OS_REASON, kcdata_iter_type(iter));
828 #endif
829 		return NULL;
830 	}
831 
832 	iter = kcdata_iter_find_type(iter, EXIT_REASON_USER_DESC);
833 	if (!kcdata_iter_valid(iter)) {
834 		return NULL;
835 	}
836 
837 	return (char *)kcdata_iter_payload(iter);
838 }
839 
840 static int initproc_spawned = 0;
841 
842 static int
sysctl_initproc_spawned(struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)843 sysctl_initproc_spawned(struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, struct sysctl_req *req)
844 {
845 	if (req->newptr != 0 && (proc_getpid(req->p) != 1 || initproc_spawned != 0)) {
846 		// Can only ever be set by launchd, and only once at boot
847 		return EPERM;
848 	}
849 	return sysctl_handle_int(oidp, &initproc_spawned, 0, req);
850 }
851 
852 SYSCTL_PROC(_kern, OID_AUTO, initproc_spawned,
853     CTLFLAG_RW | CTLFLAG_KERN | CTLTYPE_INT | CTLFLAG_LOCKED, 0, 0,
854     sysctl_initproc_spawned, "I", "Boolean indicator that launchd has reached main");
855 
856 
857 __abortlike
858 static void
launchd_crashed_panic(proc_t p,int rv)859 launchd_crashed_panic(proc_t p, int rv)
860 {
861 	char *launchd_exit_reason_desc = launchd_exit_reason_get_string_desc(p->p_exit_reason);
862 
863 	if (p->p_exit_reason == OS_REASON_NULL) {
864 		printf("pid 1 exited -- no exit reason available -- (signal %d, exit %d)\n",
865 		    WTERMSIG(rv), WEXITSTATUS(rv));
866 	} else {
867 		printf("pid 1 exited -- exit reason namespace %d subcode 0x%llx, description %s\n",
868 		    p->p_exit_reason->osr_namespace, p->p_exit_reason->osr_code, launchd_exit_reason_desc ?
869 		    launchd_exit_reason_desc : "none");
870 	}
871 
872 	const char *launchd_crashed_prefix_str;
873 
874 	if (strnstr(p->p_name, "preinit", sizeof(p->p_name))) {
875 		launchd_crashed_prefix_str = "LTE preinit process exited";
876 	} else if (initproc_spawned) {
877 		launchd_crashed_prefix_str = "initproc exited";
878 	} else {
879 		launchd_crashed_prefix_str = "initproc failed to start";
880 	}
881 
882 #if (DEVELOPMENT || DEBUG) && CONFIG_COREDUMP
883 	/*
884 	 * For debugging purposes, generate a core file of initproc before
885 	 * panicking. Leave at least 300 MB free on the root volume, and ignore
886 	 * the process's corefile ulimit. fsync() the file to ensure it lands on disk
887 	 * before the panic hits.
888 	 */
889 
890 	int             err;
891 	uint64_t        coredump_start = mach_absolute_time();
892 	uint64_t        coredump_end;
893 	clock_sec_t     tv_sec;
894 	clock_usec_t    tv_usec;
895 	uint32_t        tv_msec;
896 
897 
898 	err = coredump(p, 300, COREDUMP_IGNORE_ULIMIT | COREDUMP_FULLFSYNC);
899 
900 	coredump_end = mach_absolute_time();
901 
902 	absolutetime_to_microtime(coredump_end - coredump_start, &tv_sec, &tv_usec);
903 
904 	tv_msec = tv_usec / 1000;
905 
906 	if (err != 0) {
907 		printf("Failed to generate initproc core file: error %d, took %d.%03d seconds\n",
908 		    err, (uint32_t)tv_sec, tv_msec);
909 	} else {
910 		printf("Generated initproc core file in %d.%03d seconds\n",
911 		    (uint32_t)tv_sec, tv_msec);
912 	}
913 #endif /* (DEVELOPMENT || DEBUG) && CONFIG_COREDUMP */
914 
915 	sync(p, (void *)NULL, (int *)NULL);
916 
917 	if (p->p_exit_reason == OS_REASON_NULL) {
918 		panic_with_options(0, NULL, DEBUGGER_OPTION_INITPROC_PANIC, "%s -- no exit reason available -- (signal %d, exit status %d %s)",
919 		    launchd_crashed_prefix_str, WTERMSIG(rv), WEXITSTATUS(rv), ((proc_getcsflags(p) & CS_KILLED) ? "CS_KILLED" : ""));
920 	} else {
921 		panic_with_options(0, NULL, DEBUGGER_OPTION_INITPROC_PANIC, "%s %s -- exit reason namespace %d subcode 0x%llx description: %." LAUNCHD_PANIC_REASON_STRING_MAXLEN "s",
922 		    ((proc_getcsflags(p) & CS_KILLED) ? "CS_KILLED" : ""),
923 		    launchd_crashed_prefix_str, p->p_exit_reason->osr_namespace, p->p_exit_reason->osr_code,
924 		    launchd_exit_reason_desc ? launchd_exit_reason_desc : "none");
925 	}
926 }
927 
928 
929 #if DEVELOPMENT || DEBUG
930 
931 /* disable user faults */
932 static TUNABLE(bool, bootarg_disable_user_faults, "-disable_user_faults", false);
933 #endif /* DEVELOPMENT || DEBUG */
934 
935 #define OS_REASON_IFLAG_USER_FAULT 0x1
936 
937 #define OS_REASON_TOTAL_USER_FAULTS_PER_PROC  5
938 
939 static int
abort_with_payload_internal(proc_t p,uint32_t reason_namespace,uint64_t reason_code,user_addr_t payload,uint32_t payload_size,user_addr_t reason_string,uint64_t reason_flags,uint32_t internal_flags)940 abort_with_payload_internal(proc_t p,
941     uint32_t reason_namespace, uint64_t reason_code,
942     user_addr_t payload, uint32_t payload_size,
943     user_addr_t reason_string, uint64_t reason_flags,
944     uint32_t internal_flags)
945 {
946 	os_reason_t exit_reason = OS_REASON_NULL;
947 	kern_return_t kr = KERN_SUCCESS;
948 
949 	if (internal_flags & OS_REASON_IFLAG_USER_FAULT) {
950 		uint32_t old_value = atomic_load_explicit(&p->p_user_faults,
951 		    memory_order_relaxed);
952 
953 #if DEVELOPMENT || DEBUG
954 		if (bootarg_disable_user_faults) {
955 			return EQFULL;
956 		}
957 #endif /* DEVELOPMENT || DEBUG */
958 
959 		for (;;) {
960 			if (old_value >= OS_REASON_TOTAL_USER_FAULTS_PER_PROC) {
961 				return EQFULL;
962 			}
963 			// this reloads the value in old_value
964 			if (atomic_compare_exchange_strong_explicit(&p->p_user_faults,
965 			    &old_value, old_value + 1, memory_order_relaxed,
966 			    memory_order_relaxed)) {
967 				break;
968 			}
969 		}
970 	}
971 
972 	KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
973 	    proc_getpid(p), reason_namespace,
974 	    reason_code, 0, 0);
975 
976 	exit_reason = build_userspace_exit_reason(reason_namespace, reason_code,
977 	    payload, payload_size, reason_string, reason_flags | OS_REASON_FLAG_ABORT);
978 
979 	if (internal_flags & OS_REASON_IFLAG_USER_FAULT) {
980 		mach_exception_code_t code = 0;
981 
982 		EXC_GUARD_ENCODE_TYPE(code, GUARD_TYPE_USER); /* simulated EXC_GUARD */
983 		EXC_GUARD_ENCODE_FLAVOR(code, 0);
984 		EXC_GUARD_ENCODE_TARGET(code, reason_namespace);
985 
986 		if (exit_reason == OS_REASON_NULL) {
987 			kr = KERN_RESOURCE_SHORTAGE;
988 		} else {
989 			kr = task_violated_guard(code, reason_code, exit_reason);
990 		}
991 		os_reason_free(exit_reason);
992 	} else {
993 		/*
994 		 * We use SIGABRT (rather than calling exit directly from here) so that
995 		 * the debugger can catch abort_with_{reason,payload} calls.
996 		 */
997 		psignal_try_thread_with_reason(p, current_thread(), SIGABRT, exit_reason);
998 	}
999 
1000 	switch (kr) {
1001 	case KERN_SUCCESS:
1002 		return 0;
1003 	case KERN_NOT_SUPPORTED:
1004 		return ENOTSUP;
1005 	case KERN_INVALID_ARGUMENT:
1006 		return EINVAL;
1007 	case KERN_RESOURCE_SHORTAGE:
1008 	default:
1009 		return EBUSY;
1010 	}
1011 }
1012 
1013 int
abort_with_payload(struct proc * cur_proc,struct abort_with_payload_args * args,__unused void * retval)1014 abort_with_payload(struct proc *cur_proc, struct abort_with_payload_args *args,
1015     __unused void *retval)
1016 {
1017 	abort_with_payload_internal(cur_proc, args->reason_namespace,
1018 	    args->reason_code, args->payload, args->payload_size,
1019 	    args->reason_string, args->reason_flags, 0);
1020 
1021 	return 0;
1022 }
1023 
1024 int
os_fault_with_payload(struct proc * cur_proc,struct os_fault_with_payload_args * args,__unused int * retval)1025 os_fault_with_payload(struct proc *cur_proc,
1026     struct os_fault_with_payload_args *args, __unused int *retval)
1027 {
1028 	return abort_with_payload_internal(cur_proc, args->reason_namespace,
1029 	           args->reason_code, args->payload, args->payload_size,
1030 	           args->reason_string, args->reason_flags, OS_REASON_IFLAG_USER_FAULT);
1031 }
1032 
1033 
1034 /*
1035  * exit --
1036  *	Death of process.
1037  */
1038 __attribute__((noreturn))
1039 void
exit(proc_t p,struct exit_args * uap,int * retval)1040 exit(proc_t p, struct exit_args *uap, int *retval)
1041 {
1042 	p->p_xhighbits = ((uint32_t)(uap->rval) & 0xFF000000) >> 24;
1043 	exit1(p, W_EXITCODE((uint32_t)uap->rval, 0), retval);
1044 
1045 	thread_exception_return();
1046 	/* NOTREACHED */
1047 	while (TRUE) {
1048 		thread_block(THREAD_CONTINUE_NULL);
1049 	}
1050 	/* NOTREACHED */
1051 }
1052 
1053 /*
1054  * Exit: deallocate address space and other resources, change proc state
1055  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
1056  * status and rusage for wait().  Check for child processes and orphan them.
1057  */
1058 int
exit1(proc_t p,int rv,int * retval)1059 exit1(proc_t p, int rv, int *retval)
1060 {
1061 	return exit1_internal(p, rv, retval, TRUE, TRUE, 0);
1062 }
1063 
1064 int
exit1_internal(proc_t p,int rv,int * retval,boolean_t thread_can_terminate,boolean_t perf_notify,int jetsam_flags)1065 exit1_internal(proc_t p, int rv, int *retval, boolean_t thread_can_terminate, boolean_t perf_notify,
1066     int jetsam_flags)
1067 {
1068 	return exit_with_reason(p, rv, retval, thread_can_terminate, perf_notify, jetsam_flags, OS_REASON_NULL);
1069 }
1070 
1071 /*
1072  * NOTE: exit_with_reason drops a reference on the passed exit_reason
1073  */
1074 int
exit_with_reason(proc_t p,int rv,int * retval,boolean_t thread_can_terminate,boolean_t perf_notify,int jetsam_flags,struct os_reason * exit_reason)1075 exit_with_reason(proc_t p, int rv, int *retval, boolean_t thread_can_terminate, boolean_t perf_notify,
1076     int jetsam_flags, struct os_reason *exit_reason)
1077 {
1078 	thread_t self = current_thread();
1079 	struct task *task = p->task;
1080 	struct uthread *ut;
1081 	int error = 0;
1082 
1083 #if DEVELOPMENT || DEBUG
1084 	/*
1085 	 * Debug boot-arg: panic here if matching process is exiting with non-zero code.
1086 	 * Example usage: panic_on_error_exit=launchd,logd,watchdogd
1087 	 */
1088 	if (rv && strnstr(panic_on_eexit_pcomms, p->p_comm, sizeof(panic_on_eexit_pcomms))) {
1089 		panic("%s: Process %s with pid %d exited on error with code 0x%x.",
1090 		    __FUNCTION__, p->p_comm, proc_getpid(p), rv);
1091 	}
1092 #endif
1093 
1094 	/*
1095 	 * If a thread in this task has already
1096 	 * called exit(), then halt any others
1097 	 * right here.
1098 	 */
1099 
1100 	ut = get_bsdthread_info(self);
1101 	(void)retval;
1102 
1103 	/*
1104 	 * The parameter list of audit_syscall_exit() was augmented to
1105 	 * take the Darwin syscall number as the first parameter,
1106 	 * which is currently required by mac_audit_postselect().
1107 	 */
1108 
1109 	/*
1110 	 * The BSM token contains two components: an exit status as passed
1111 	 * to exit(), and a return value to indicate what sort of exit it
1112 	 * was.  The exit status is WEXITSTATUS(rv), but it's not clear
1113 	 * what the return value is.
1114 	 */
1115 	AUDIT_ARG(exit, WEXITSTATUS(rv), 0);
1116 	/*
1117 	 * TODO: what to audit here when jetsam calls exit and the uthread,
1118 	 * 'ut' does not belong to the proc, 'p'.
1119 	 */
1120 	AUDIT_SYSCALL_EXIT(SYS_exit, p, ut, 0); /* Exit is always successfull */
1121 
1122 	DTRACE_PROC1(exit, int, CLD_EXITED);
1123 
1124 	/* mark process is going to exit and pull out of DBG/disk throttle */
1125 	/* TODO: This should be done after becoming exit thread */
1126 	proc_set_task_policy(p->task, TASK_POLICY_ATTRIBUTE,
1127 	    TASK_POLICY_TERMINATED, TASK_POLICY_ENABLE);
1128 
1129 	proc_lock(p);
1130 	error = proc_transstart(p, 1, (jetsam_flags ? 1 : 0));
1131 	if (error == EDEADLK) {
1132 		/*
1133 		 * If proc_transstart() returns EDEADLK, then another thread
1134 		 * is either exec'ing or exiting. Return an error and allow
1135 		 * the other thread to continue.
1136 		 */
1137 		proc_unlock(p);
1138 		os_reason_free(exit_reason);
1139 		if (current_proc() == p) {
1140 			if (p->exit_thread == self) {
1141 				panic("exit_thread failed to exit");
1142 			}
1143 
1144 			if (thread_can_terminate) {
1145 				thread_exception_return();
1146 			}
1147 		}
1148 
1149 		return error;
1150 	}
1151 
1152 	while (p->exit_thread != self) {
1153 		if (sig_try_locked(p) <= 0) {
1154 			proc_transend(p, 1);
1155 			os_reason_free(exit_reason);
1156 
1157 			if (get_threadtask(self) != task) {
1158 				proc_unlock(p);
1159 				return 0;
1160 			}
1161 			proc_unlock(p);
1162 
1163 			thread_terminate(self);
1164 			if (!thread_can_terminate) {
1165 				return 0;
1166 			}
1167 
1168 			thread_exception_return();
1169 			/* NOTREACHED */
1170 		}
1171 		sig_lock_to_exit(p);
1172 	}
1173 
1174 	if (exit_reason != OS_REASON_NULL) {
1175 		KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_COMMIT) | DBG_FUNC_NONE,
1176 		    proc_getpid(p), exit_reason->osr_namespace,
1177 		    exit_reason->osr_code, 0, 0);
1178 	}
1179 
1180 	assert(p->p_exit_reason == OS_REASON_NULL);
1181 	p->p_exit_reason = exit_reason;
1182 
1183 	p->p_lflag |= P_LEXIT;
1184 	p->p_xstat = rv;
1185 	p->p_lflag |= jetsam_flags;
1186 
1187 	proc_transend(p, 1);
1188 	proc_unlock(p);
1189 
1190 	proc_prepareexit(p, rv, perf_notify);
1191 
1192 	/* Last thread to terminate will call proc_exit() */
1193 	task_terminate_internal(task);
1194 
1195 	return 0;
1196 }
1197 
1198 #if CONFIG_MEMORYSTATUS
1199 /*
1200  * Remove this process from jetsam bands for freezing or exiting. Note this will block, if the process
1201  * is currently being frozen.
1202  * The proc_list_lock is held by the caller.
1203  * NB: If the process should be ineligible for future freezing or jetsaming the caller should first set
1204  * the p_refcount P_REF_DEAD bit.
1205  */
1206 static void
proc_memorystatus_remove(proc_t p)1207 proc_memorystatus_remove(proc_t p)
1208 {
1209 	LCK_MTX_ASSERT(&proc_list_mlock, LCK_MTX_ASSERT_OWNED);
1210 	while (memorystatus_remove(p) == EAGAIN) {
1211 		os_log(OS_LOG_DEFAULT, "memorystatus_remove: Process[%d] tried to exit while being frozen. Blocking exit until freeze completes.", proc_getpid(p));
1212 		msleep(&p->p_memstat_state, &proc_list_mlock, PWAIT, "proc_memorystatus_remove", NULL);
1213 	}
1214 }
1215 #endif
1216 
1217 void
proc_prepareexit(proc_t p,int rv,boolean_t perf_notify)1218 proc_prepareexit(proc_t p, int rv, boolean_t perf_notify)
1219 {
1220 	mach_exception_data_type_t code = 0, subcode = 0;
1221 	exception_type_t etype;
1222 
1223 	struct uthread *ut;
1224 	thread_t self = current_thread();
1225 	ut = get_bsdthread_info(self);
1226 	struct rusage_superset *rup;
1227 	int kr = 0;
1228 	int create_corpse = FALSE;
1229 
1230 	if (p == initproc) {
1231 		launchd_crashed_panic(p, rv);
1232 		/* NOTREACHED */
1233 	}
1234 
1235 	/*
1236 	 * Generate a corefile/crashlog if:
1237 	 *      The process doesn't have an exit reason that indicates no crash report should be created
1238 	 *      AND any of the following are true:
1239 	 *	- The process was terminated due to a fatal signal that generates a core
1240 	 *	- The process was killed due to a code signing violation
1241 	 *	- The process has an exit reason that indicates we should generate a crash report
1242 	 *
1243 	 * The first condition is necessary because abort_with_reason()/payload() use SIGABRT
1244 	 * (which normally triggers a core) but may indicate that no crash report should be created.
1245 	 */
1246 	if (!(PROC_HAS_EXITREASON(p) && (PROC_EXITREASON_FLAGS(p) & OS_REASON_FLAG_NO_CRASH_REPORT)) &&
1247 	    (hassigprop(WTERMSIG(rv), SA_CORE) || ((proc_getcsflags(p) & CS_KILLED) != 0) ||
1248 	    (PROC_HAS_EXITREASON(p) && (PROC_EXITREASON_FLAGS(p) &
1249 	    OS_REASON_FLAG_GENERATE_CRASH_REPORT)))) {
1250 		/*
1251 		 * Workaround for processes checking up on PT_DENY_ATTACH:
1252 		 * should be backed out post-Leopard (details in 5431025).
1253 		 */
1254 		if ((SIGSEGV == WTERMSIG(rv)) &&
1255 		    (p->p_pptr->p_lflag & P_LNOATTACH)) {
1256 			goto skipcheck;
1257 		}
1258 
1259 		/*
1260 		 * Crash Reporter looks for the signal value, original exception
1261 		 * type, and low 20 bits of the original code in code[0]
1262 		 * (8, 4, and 20 bits respectively). code[1] is unmodified.
1263 		 */
1264 		code = ((WTERMSIG(rv) & 0xff) << 24) |
1265 		    ((ut->uu_exception & 0x0f) << 20) |
1266 		    ((int)ut->uu_code & 0xfffff);
1267 		subcode = ut->uu_subcode;
1268 		etype = ut->uu_exception;
1269 
1270 		/* Defualt to EXC_CRASH if the exception is not an EXC_RESOURCE or EXC_GUARD */
1271 		if (etype != EXC_RESOURCE || etype != EXC_GUARD) {
1272 			etype = EXC_CRASH;
1273 		}
1274 
1275 		kr = task_exception_notify(EXC_CRASH, code, subcode);
1276 
1277 		/* Nobody handled EXC_CRASH?? remember to make corpse */
1278 		if (kr != 0 && p == current_proc()) {
1279 			/*
1280 			 * Do not create corpse when exit is called from jetsam thread.
1281 			 * Corpse creation code requires that proc_prepareexit is
1282 			 * called by the exiting proc and not the kernel_proc.
1283 			 */
1284 			create_corpse = TRUE;
1285 		}
1286 
1287 		/*
1288 		 * Revalidate the code signing of the text pages around current PC.
1289 		 * This is an attempt to detect and repair faults due to memory
1290 		 * corruption of text pages.
1291 		 *
1292 		 * The goal here is to fixup infrequent memory corruptions due to
1293 		 * things like aging RAM bit flips. So the approach is to only expect
1294 		 * to have to fixup one thing per crash. This also limits the amount
1295 		 * of extra work we cause in case this is a development kernel with an
1296 		 * active memory stomp happening.
1297 		 */
1298 		task_t task = proc_task(p);
1299 		uintptr_t bt[2];
1300 		struct backtrace_user_info btinfo = BTUINFO_INIT;
1301 		unsigned int frame_count = backtrace_user(bt, 2, NULL, &btinfo);
1302 		int bt_err = btinfo.btui_error;
1303 		if (bt_err == 0 && frame_count >= 1) {
1304 			/*
1305 			 * First check at the page containing the current PC.
1306 			 * This passes if the page code signs -or- if we can't figure out
1307 			 * what is at that address. The latter action is so we continue checking
1308 			 * previous pages which may be corrupt and caused a wild branch.
1309 			 */
1310 			kr = revalidate_text_page(task, bt[0]);
1311 
1312 			/* No corruption found, check the previous sequential page */
1313 			if (kr == KERN_SUCCESS) {
1314 				kr = revalidate_text_page(task, bt[0] - get_task_page_size(task));
1315 			}
1316 
1317 			/* Still no corruption found, check the current function's caller */
1318 			if (kr == KERN_SUCCESS) {
1319 				if (frame_count > 1 &&
1320 				    atop(bt[0]) != atop(bt[1]) &&           /* don't recheck PC page */
1321 				    atop(bt[0]) - 1 != atop(bt[1])) {       /* don't recheck page before */
1322 					kr = revalidate_text_page(task, (vm_map_offset_t)bt[1]);
1323 				}
1324 			}
1325 
1326 			/*
1327 			 * Log that we found a corruption.
1328 			 */
1329 			if (kr != KERN_SUCCESS) {
1330 				os_log(OS_LOG_DEFAULT,
1331 				    "Text page corruption detected in dying process %d\n", proc_getpid(p));
1332 			}
1333 		}
1334 	}
1335 
1336 skipcheck:
1337 	/* Notify the perf server? */
1338 	if (perf_notify) {
1339 		(void)sys_perf_notify(self, proc_getpid(p));
1340 	}
1341 
1342 
1343 	/* stash the usage into corpse data if making_corpse == true */
1344 	if (create_corpse == TRUE) {
1345 		kr = task_mark_corpse(p->task);
1346 		if (kr != KERN_SUCCESS) {
1347 			if (kr == KERN_NO_SPACE) {
1348 				printf("Process[%d] has no vm space for corpse info.\n", proc_getpid(p));
1349 			} else if (kr == KERN_NOT_SUPPORTED) {
1350 				printf("Process[%d] was destined to be corpse. But corpse is disabled by config.\n", proc_getpid(p));
1351 			} else if (kr == KERN_TERMINATED) {
1352 				printf("Process[%d] has been terminated before it could be converted to a corpse.\n", proc_getpid(p));
1353 			} else {
1354 				printf("Process[%d] crashed: %s. Too many corpses being created.\n", proc_getpid(p), p->p_comm);
1355 			}
1356 			create_corpse = FALSE;
1357 		}
1358 	}
1359 
1360 	/*
1361 	 * Before this process becomes a zombie, stash resource usage
1362 	 * stats in the proc for external observers to query
1363 	 * via proc_pid_rusage().
1364 	 *
1365 	 * If the zombie allocation fails, just punt the stats.
1366 	 */
1367 	rup = zalloc(zombie_zone);
1368 	gather_rusage_info(p, &rup->ri, RUSAGE_INFO_CURRENT);
1369 	rup->ri.ri_phys_footprint = 0;
1370 	rup->ri.ri_proc_exit_abstime = mach_absolute_time();
1371 	/*
1372 	 * Make the rusage_info visible to external observers
1373 	 * only after it has been completely filled in.
1374 	 */
1375 	p->p_ru = rup;
1376 
1377 	if (create_corpse) {
1378 		int est_knotes = 0, num_knotes = 0;
1379 		uint64_t *buffer = NULL;
1380 		uint32_t buf_size = 0;
1381 
1382 		/* Get all the udata pointers from kqueue */
1383 		est_knotes = kevent_proc_copy_uptrs(p, NULL, 0);
1384 		if (est_knotes > 0) {
1385 			buf_size = (uint32_t)((est_knotes + 32) * sizeof(uint64_t));
1386 			buffer = kalloc_data(buf_size, Z_WAITOK);
1387 			if (buffer) {
1388 				num_knotes = kevent_proc_copy_uptrs(p, buffer, buf_size);
1389 				if (num_knotes > est_knotes + 32) {
1390 					num_knotes = est_knotes + 32;
1391 				}
1392 			}
1393 		}
1394 
1395 		/* Update the code, subcode based on exit reason */
1396 		proc_update_corpse_exception_codes(p, &code, &subcode);
1397 		populate_corpse_crashinfo(p, p->task, rup,
1398 		    code, subcode, buffer, num_knotes, NULL, etype);
1399 		kfree_data(buffer, buf_size);
1400 	}
1401 	/*
1402 	 * Remove proc from allproc queue and from pidhash chain.
1403 	 * Need to do this before we do anything that can block.
1404 	 * Not doing causes things like mount() find this on allproc
1405 	 * in partially cleaned state.
1406 	 */
1407 
1408 	proc_list_lock();
1409 
1410 #if CONFIG_MEMORYSTATUS
1411 	proc_memorystatus_remove(p);
1412 #endif
1413 
1414 	LIST_REMOVE(p, p_list);
1415 	LIST_INSERT_HEAD(&zombproc, p, p_list); /* Place onto zombproc. */
1416 	/* will not be visible via proc_find */
1417 	os_atomic_or(&p->p_refcount, P_REF_DEAD, relaxed);
1418 
1419 	proc_list_unlock();
1420 
1421 	/*
1422 	 * If parent is waiting for us to exit or exec,
1423 	 * P_LPPWAIT is set; we will wakeup the parent below.
1424 	 */
1425 	proc_lock(p);
1426 	p->p_lflag &= ~(P_LTRACED | P_LPPWAIT);
1427 	p->p_sigignore = ~(sigcantmask);
1428 	ut->uu_siglist = 0;
1429 	proc_unlock(p);
1430 }
1431 
1432 void
proc_exit(proc_t p)1433 proc_exit(proc_t p)
1434 {
1435 	proc_t q;
1436 	proc_t pp;
1437 	struct task *task = p->task;
1438 	vnode_t tvp = NULLVP;
1439 	struct pgrp * pg;
1440 	struct session *sessp;
1441 	struct uthread * uth;
1442 	pid_t pid;
1443 	int exitval;
1444 	int knote_hint;
1445 
1446 	uth = current_uthread();
1447 
1448 	proc_lock(p);
1449 	proc_transstart(p, 1, 0);
1450 	if (!(p->p_lflag & P_LEXIT)) {
1451 		/*
1452 		 * This can happen if a thread_terminate() occurs
1453 		 * in a single-threaded process.
1454 		 */
1455 		p->p_lflag |= P_LEXIT;
1456 		proc_transend(p, 1);
1457 		proc_unlock(p);
1458 		proc_prepareexit(p, 0, TRUE);
1459 		(void) task_terminate_internal(task);
1460 		proc_lock(p);
1461 	} else {
1462 		proc_transend(p, 1);
1463 	}
1464 
1465 	p->p_lflag |= P_LPEXIT;
1466 
1467 	/*
1468 	 * Other kernel threads may be in the middle of signalling this process.
1469 	 * Wait for those threads to wrap it up before making the process
1470 	 * disappear on them.
1471 	 */
1472 	if ((p->p_lflag & P_LINSIGNAL) || (p->p_sigwaitcnt > 0)) {
1473 		p->p_sigwaitcnt++;
1474 		while ((p->p_lflag & P_LINSIGNAL) || (p->p_sigwaitcnt > 1)) {
1475 			msleep(&p->p_sigmask, &p->p_mlock, PWAIT, "proc_sigdrain", NULL);
1476 		}
1477 		p->p_sigwaitcnt--;
1478 	}
1479 
1480 	proc_unlock(p);
1481 	pid = proc_getpid(p);
1482 	exitval = p->p_xstat;
1483 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON,
1484 	    BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXIT) | DBG_FUNC_START,
1485 	    pid, exitval, 0, 0, 0);
1486 
1487 #if DEVELOPMENT || DEBUG
1488 	proc_exit_lpexit_check(pid, PELS_POS_START);
1489 #endif
1490 
1491 #if CONFIG_DTRACE
1492 	dtrace_proc_exit(p);
1493 #endif
1494 
1495 	/*
1496 	 * need to cancel async IO requests that can be cancelled and wait for those
1497 	 * already active.  MAY BLOCK!
1498 	 */
1499 
1500 	proc_refdrain(p);
1501 
1502 	/* if any pending cpu limits action, clear it */
1503 	task_clear_cpuusage(p->task, TRUE);
1504 
1505 	workq_mark_exiting(p);
1506 
1507 	_aio_exit( p );
1508 
1509 	/*
1510 	 * Close open files and release open-file table.
1511 	 * This may block!
1512 	 */
1513 	fdt_invalidate(p);
1514 
1515 	/*
1516 	 * Once all the knotes, kqueues & workloops are destroyed, get rid of the
1517 	 * workqueue.
1518 	 */
1519 	workq_exit(p);
1520 
1521 	if (uth->uu_lowpri_window) {
1522 		/*
1523 		 * task is marked as a low priority I/O type
1524 		 * and the I/O we issued while in flushing files on close
1525 		 * collided with normal I/O operations...
1526 		 * no need to throttle this thread since its going away
1527 		 * but we do need to update our bookeeping w/r to throttled threads
1528 		 */
1529 		throttle_lowpri_io(0);
1530 	}
1531 
1532 	if (p->p_lflag & P_LNSPACE_RESOLVER) {
1533 		/*
1534 		 * The namespace resolver is exiting; there may be
1535 		 * outstanding materialization requests to clean up.
1536 		 */
1537 		nspace_resolver_exited(p);
1538 	}
1539 
1540 #if SYSV_SHM
1541 	/* Close ref SYSV Shared memory*/
1542 	if (p->vm_shm) {
1543 		shmexit(p);
1544 	}
1545 #endif
1546 #if SYSV_SEM
1547 	/* Release SYSV semaphores */
1548 	semexit(p);
1549 #endif
1550 
1551 #if PSYNCH
1552 	pth_proc_hashdelete(p);
1553 #endif /* PSYNCH */
1554 
1555 	pg = proc_pgrp(p, &sessp);
1556 	if (SESS_LEADER(p, sessp)) {
1557 		if (sessp->s_ttyvp != NULLVP) {
1558 			struct vnode *ttyvp;
1559 			int ttyvid;
1560 			int cttyflag = 0;
1561 			struct vfs_context context;
1562 			struct tty *tp;
1563 			struct pgrp *tpgrp = PGRP_NULL;
1564 
1565 			/*
1566 			 * Controlling process.
1567 			 * Signal foreground pgrp,
1568 			 * drain controlling terminal
1569 			 * and revoke access to controlling terminal.
1570 			 */
1571 
1572 			proc_list_lock(); /* prevent any t_pgrp from changing */
1573 			session_lock(sessp);
1574 			if (sessp->s_ttyp && sessp->s_ttyp->t_session == sessp) {
1575 				tpgrp = tty_pgrp_locked(sessp->s_ttyp);
1576 			}
1577 			proc_list_unlock();
1578 
1579 			if (tpgrp != PGRP_NULL) {
1580 				session_unlock(sessp);
1581 				pgsignal(tpgrp, SIGHUP, 1);
1582 				pgrp_rele(tpgrp);
1583 				session_lock(sessp);
1584 			}
1585 
1586 			cttyflag = (os_atomic_andnot_orig(&sessp->s_refcount,
1587 			    S_CTTYREF, relaxed) & S_CTTYREF);
1588 			ttyvp = sessp->s_ttyvp;
1589 			ttyvid = sessp->s_ttyvid;
1590 			tp = session_clear_tty_locked(sessp);
1591 			session_unlock(sessp);
1592 
1593 			if ((ttyvp != NULLVP) && (vnode_getwithvid(ttyvp, ttyvid) == 0)) {
1594 				if (tp != TTY_NULL) {
1595 					tty_lock(tp);
1596 					(void) ttywait(tp);
1597 					tty_unlock(tp);
1598 				}
1599 
1600 				context.vc_thread = NULL;
1601 				context.vc_ucred = kauth_cred_proc_ref(p);
1602 				VNOP_REVOKE(ttyvp, REVOKEALL, &context);
1603 				if (cttyflag) {
1604 					/*
1605 					 * Release the extra usecount taken in cttyopen.
1606 					 * usecount should be released after VNOP_REVOKE is called.
1607 					 * This usecount was taken to ensure that
1608 					 * the VNOP_REVOKE results in a close to
1609 					 * the tty since cttyclose is a no-op.
1610 					 */
1611 					vnode_rele(ttyvp);
1612 				}
1613 				vnode_put(ttyvp);
1614 				kauth_cred_unref(&context.vc_ucred);
1615 				ttyvp = NULLVP;
1616 			}
1617 			if (tp) {
1618 				ttyfree(tp);
1619 			}
1620 		}
1621 		session_lock(sessp);
1622 		sessp->s_leader = NULL;
1623 		session_unlock(sessp);
1624 	}
1625 
1626 	fixjobc(p, pg, 0);
1627 	pgrp_rele(pg);
1628 
1629 	/*
1630 	 * Change RLIMIT_FSIZE for accounting/debugging.
1631 	 */
1632 	proc_limitsetcur_fsize(p, RLIM_INFINITY);
1633 
1634 	(void)acct_process(p);
1635 
1636 	proc_list_lock();
1637 
1638 	if ((p->p_listflag & P_LIST_EXITCOUNT) == P_LIST_EXITCOUNT) {
1639 		p->p_listflag &= ~P_LIST_EXITCOUNT;
1640 		proc_shutdown_exitcount--;
1641 		if (proc_shutdown_exitcount == 0) {
1642 			wakeup(&proc_shutdown_exitcount);
1643 		}
1644 	}
1645 
1646 	/* wait till parentrefs are dropped and grant no more */
1647 	proc_childdrainstart(p);
1648 	while ((q = p->p_children.lh_first) != NULL) {
1649 		int reparentedtoinit = (q->p_listflag & P_LIST_DEADPARENT) ? 1 : 0;
1650 		if (q->p_stat == SZOMB) {
1651 			if (p != q->p_pptr) {
1652 				panic("parent child linkage broken");
1653 			}
1654 			/* check for sysctl zomb lookup */
1655 			while ((q->p_listflag & P_LIST_WAITING) == P_LIST_WAITING) {
1656 				msleep(&q->p_stat, &proc_list_mlock, PWAIT, "waitcoll", 0);
1657 			}
1658 			q->p_listflag |= P_LIST_WAITING;
1659 			/*
1660 			 * This is a named reference and it is not granted
1661 			 * if the reap is already in progress. So we get
1662 			 * the reference here exclusively and their can be
1663 			 * no waiters. So there is no need for a wakeup
1664 			 * after we are done.  Also the reap frees the structure
1665 			 * and the proc struct cannot be used for wakeups as well.
1666 			 * It is safe to use q here as this is system reap
1667 			 */
1668 			(void)reap_child_locked(p, q, 1, reparentedtoinit, 1, 0);
1669 		} else {
1670 			/*
1671 			 * Traced processes are killed
1672 			 * since their existence means someone is messing up.
1673 			 */
1674 			if (q->p_lflag & P_LTRACED) {
1675 				struct proc *opp;
1676 
1677 				/*
1678 				 * Take a reference on the child process to
1679 				 * ensure it doesn't exit and disappear between
1680 				 * the time we drop the list_lock and attempt
1681 				 * to acquire its proc_lock.
1682 				 */
1683 				if (proc_ref(q, true) != q) {
1684 					continue;
1685 				}
1686 
1687 				proc_list_unlock();
1688 
1689 				opp = proc_find(q->p_oppid);
1690 				if (opp != PROC_NULL) {
1691 					proc_list_lock();
1692 					q->p_oppid = 0;
1693 					proc_list_unlock();
1694 					proc_reparentlocked(q, opp, 0, 0);
1695 					proc_rele(opp);
1696 				} else {
1697 					/* original parent exited while traced */
1698 					proc_list_lock();
1699 					q->p_listflag |= P_LIST_DEADPARENT;
1700 					q->p_oppid = 0;
1701 					proc_list_unlock();
1702 					proc_reparentlocked(q, initproc, 0, 0);
1703 				}
1704 
1705 				proc_lock(q);
1706 				q->p_lflag &= ~P_LTRACED;
1707 
1708 				if (q->sigwait_thread) {
1709 					thread_t thread = q->sigwait_thread;
1710 
1711 					proc_unlock(q);
1712 					/*
1713 					 * The sigwait_thread could be stopped at a
1714 					 * breakpoint. Wake it up to kill.
1715 					 * Need to do this as it could be a thread which is not
1716 					 * the first thread in the task. So any attempts to kill
1717 					 * the process would result into a deadlock on q->sigwait.
1718 					 */
1719 					thread_resume(thread);
1720 					clear_wait(thread, THREAD_INTERRUPTED);
1721 					threadsignal(thread, SIGKILL, 0, TRUE);
1722 				} else {
1723 					proc_unlock(q);
1724 				}
1725 
1726 				psignal(q, SIGKILL);
1727 				proc_list_lock();
1728 				proc_rele(q);
1729 			} else {
1730 				q->p_listflag |= P_LIST_DEADPARENT;
1731 				proc_reparentlocked(q, initproc, 0, 1);
1732 			}
1733 		}
1734 	}
1735 
1736 	proc_childdrainend(p);
1737 	proc_list_unlock();
1738 
1739 #if CONFIG_MACF
1740 	/*
1741 	 * Notify MAC policies that proc is dead.
1742 	 * This should be replaced with proper label management
1743 	 * (rdar://problem/32126399).
1744 	 */
1745 	mac_proc_notify_exit(p);
1746 #endif
1747 
1748 	/*
1749 	 * Release reference to text vnode
1750 	 */
1751 	tvp = p->p_textvp;
1752 	p->p_textvp = NULL;
1753 	if (tvp != NULLVP) {
1754 		vnode_rele(tvp);
1755 	}
1756 
1757 	/*
1758 	 * Save exit status and final rusage info, adding in child rusage
1759 	 * info and self times.  If we were unable to allocate a zombie
1760 	 * structure, this information is lost.
1761 	 */
1762 	if (p->p_ru != NULL) {
1763 		calcru(p, &p->p_stats->p_ru.ru_utime, &p->p_stats->p_ru.ru_stime, NULL);
1764 		p->p_ru->ru = p->p_stats->p_ru;
1765 
1766 		ruadd(&(p->p_ru->ru), &p->p_stats->p_cru);
1767 	}
1768 
1769 	/*
1770 	 * Free up profiling buffers.
1771 	 */
1772 	{
1773 		struct uprof *p0 = &p->p_stats->p_prof, *p1, *pn;
1774 
1775 		p1 = p0->pr_next;
1776 		p0->pr_next = NULL;
1777 		p0->pr_scale = 0;
1778 
1779 		for (; p1 != NULL; p1 = pn) {
1780 			pn = p1->pr_next;
1781 			kfree_type(struct uprof, p1);
1782 		}
1783 	}
1784 
1785 	proc_free_realitimer(p);
1786 
1787 	/*
1788 	 * Other substructures are freed from wait().
1789 	 */
1790 	zfree(proc_stats_zone, p->p_stats);
1791 	p->p_stats = NULL;
1792 
1793 	zfree_ro(ZONE_ID_PROC_SIGACTS_RO, p->p_sigacts.ps_ro);
1794 
1795 	proc_limitdrop(p);
1796 
1797 #if DEVELOPMENT || DEBUG
1798 	proc_exit_lpexit_check(pid, PELS_POS_PRE_TASK_DETACH);
1799 #endif
1800 
1801 	/*
1802 	 * Finish up by terminating the task
1803 	 * and halt this thread (only if a
1804 	 * member of the task exiting).
1805 	 */
1806 	proc_set_task(p, TASK_NULL);
1807 	set_bsdtask_info(task, NULL);
1808 	clear_thread_ro_proc(get_machthread(uth));
1809 
1810 #if DEVELOPMENT || DEBUG
1811 	proc_exit_lpexit_check(pid, PELS_POS_POST_TASK_DETACH);
1812 #endif
1813 
1814 	knote_hint = NOTE_EXIT | (p->p_xstat & 0xffff);
1815 	proc_knote(p, knote_hint);
1816 
1817 	/* mark the thread as the one that is doing proc_exit
1818 	 * no need to hold proc lock in uthread_free
1819 	 */
1820 	uth->uu_flag |= UT_PROCEXIT;
1821 	/*
1822 	 * Notify parent that we're gone.
1823 	 */
1824 	pp = proc_parent(p);
1825 	if (pp->p_flag & P_NOCLDWAIT) {
1826 		if (p->p_ru != NULL) {
1827 			proc_lock(pp);
1828 #if 3839178
1829 			/*
1830 			 * If the parent is ignoring SIGCHLD, then POSIX requires
1831 			 * us to not add the resource usage to the parent process -
1832 			 * we are only going to hand it off to init to get reaped.
1833 			 * We should contest the standard in this case on the basis
1834 			 * of RLIMIT_CPU.
1835 			 */
1836 #else   /* !3839178 */
1837 			/*
1838 			 * Add child resource usage to parent before giving
1839 			 * zombie to init.  If we were unable to allocate a
1840 			 * zombie structure, this information is lost.
1841 			 */
1842 			ruadd(&pp->p_stats->p_cru, &p->p_ru->ru);
1843 #endif  /* !3839178 */
1844 			update_rusage_info_child(&pp->p_stats->ri_child, &p->p_ru->ri);
1845 			proc_unlock(pp);
1846 		}
1847 
1848 		/* kernel can reap this one, no need to move it to launchd */
1849 		proc_list_lock();
1850 		p->p_listflag |= P_LIST_DEADPARENT;
1851 		proc_list_unlock();
1852 	}
1853 	if ((p->p_listflag & P_LIST_DEADPARENT) == 0 || p->p_oppid) {
1854 		if (pp != initproc) {
1855 			proc_lock(pp);
1856 			pp->si_pid = proc_getpid(p);
1857 			pp->p_xhighbits = p->p_xhighbits;
1858 			p->p_xhighbits = 0;
1859 			pp->si_status = p->p_xstat;
1860 			pp->si_code = CLD_EXITED;
1861 			/*
1862 			 * p_ucred usage is safe as it is an exiting process
1863 			 * and reference is dropped in reap
1864 			 */
1865 			pp->si_uid = kauth_cred_getruid(proc_ucred(p));
1866 			proc_unlock(pp);
1867 		}
1868 		/* mark as a zombie */
1869 		/* No need to take proc lock as all refs are drained and
1870 		 * no one except parent (reaping ) can look at this.
1871 		 * The write is to an int and is coherent. Also parent is
1872 		 *  keyed off of list lock for reaping
1873 		 */
1874 		DTRACE_PROC2(exited, proc_t, p, int, exitval);
1875 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON,
1876 		    BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXIT) | DBG_FUNC_END,
1877 		    pid, exitval, 0, 0, 0);
1878 		p->p_stat = SZOMB;
1879 		/*
1880 		 * The current process can be reaped so, no one
1881 		 * can depend on this
1882 		 */
1883 
1884 		psignal(pp, SIGCHLD);
1885 
1886 		/* and now wakeup the parent */
1887 		proc_list_lock();
1888 		wakeup((caddr_t)pp);
1889 		proc_list_unlock();
1890 	} else {
1891 		/* should be fine as parent proc would be initproc */
1892 		/* mark as a zombie */
1893 		/* No need to take proc lock as all refs are drained and
1894 		 * no one except parent (reaping ) can look at this.
1895 		 * The write is to an int and is coherent. Also parent is
1896 		 *  keyed off of list lock for reaping
1897 		 */
1898 		DTRACE_PROC2(exited, proc_t, p, int, exitval);
1899 		proc_list_lock();
1900 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON,
1901 		    BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXIT) | DBG_FUNC_END,
1902 		    pid, exitval, 0, 0, 0);
1903 		/* check for sysctl zomb lookup */
1904 		while ((p->p_listflag & P_LIST_WAITING) == P_LIST_WAITING) {
1905 			msleep(&p->p_stat, &proc_list_mlock, PWAIT, "waitcoll", 0);
1906 		}
1907 		/* safe to use p as this is a system reap */
1908 		p->p_stat = SZOMB;
1909 		p->p_listflag |= P_LIST_WAITING;
1910 
1911 		/*
1912 		 * This is a named reference and it is not granted
1913 		 * if the reap is already in progress. So we get
1914 		 * the reference here exclusively and their can be
1915 		 * no waiters. So there is no need for a wakeup
1916 		 * after we are done. AlsO  the reap frees the structure
1917 		 * and the proc struct cannot be used for wakeups as well.
1918 		 * It is safe to use p here as this is system reap
1919 		 */
1920 		(void)reap_child_locked(pp, p, 1, 0, 1, 1);
1921 		/* list lock dropped by reap_child_locked */
1922 	}
1923 	if (uth->uu_lowpri_window) {
1924 		/*
1925 		 * task is marked as a low priority I/O type and we've
1926 		 * somehow picked up another throttle during exit processing...
1927 		 * no need to throttle this thread since its going away
1928 		 * but we do need to update our bookeeping w/r to throttled threads
1929 		 */
1930 		throttle_lowpri_io(0);
1931 	}
1932 
1933 	proc_rele(pp);
1934 #if DEVELOPMENT || DEBUG
1935 	proc_exit_lpexit_check(pid, PELS_POS_END);
1936 #endif
1937 }
1938 
1939 
1940 /*
1941  * reap_child_locked
1942  *
1943  * Description:	Given a process from which all status information needed
1944  *		has already been extracted, if the process is a ptrace
1945  *		attach process, detach it and give it back to its real
1946  *		parent, else recover all resources remaining associated
1947  *		with it.
1948  *
1949  * Parameters:	proc_t parent		Parent of process being reaped
1950  *		proc_t child		Process to reap
1951  *
1952  * Returns:	0			Process was not reaped because it
1953  *					came from an attach
1954  *		1			Process was reaped
1955  */
1956 static int
reap_child_locked(proc_t parent,proc_t child,int deadparent,int reparentedtoinit,int locked,int droplock)1957 reap_child_locked(proc_t parent, proc_t child, int deadparent, int reparentedtoinit, int locked, int droplock)
1958 {
1959 	proc_t trace_parent = PROC_NULL;        /* Traced parent process, if tracing */
1960 	struct pgrp *pg;
1961 	kauth_cred_t cred;
1962 
1963 	if (locked == 1) {
1964 		proc_list_unlock();
1965 	}
1966 
1967 	/*
1968 	 * If we got the child via a ptrace 'attach',
1969 	 * we need to give it back to the old parent.
1970 	 *
1971 	 * Exception: someone who has been reparented to launchd before being
1972 	 * ptraced can simply be reaped, refer to radar 5677288
1973 	 *      p_oppid                  -> ptraced
1974 	 *      trace_parent == initproc -> away from launchd
1975 	 *      reparentedtoinit	 -> came to launchd by reparenting
1976 	 */
1977 	if (child->p_oppid) {
1978 		int knote_hint;
1979 		pid_t oppid;
1980 
1981 		proc_lock(child);
1982 		oppid = child->p_oppid;
1983 		child->p_oppid = 0;
1984 		knote_hint = NOTE_EXIT | (child->p_xstat & 0xffff);
1985 		proc_unlock(child);
1986 
1987 		if ((trace_parent = proc_find(oppid))
1988 		    && !((trace_parent == initproc) && reparentedtoinit)) {
1989 			if (trace_parent != initproc) {
1990 				/*
1991 				 * proc internal fileds  and p_ucred usage safe
1992 				 * here as child is dead and is not reaped or
1993 				 * reparented yet
1994 				 */
1995 				proc_lock(trace_parent);
1996 				trace_parent->si_pid = proc_getpid(child);
1997 				trace_parent->si_status = child->p_xstat;
1998 				trace_parent->si_code = CLD_CONTINUED;
1999 				trace_parent->si_uid = kauth_cred_getruid(proc_ucred(child));
2000 				proc_unlock(trace_parent);
2001 			}
2002 			proc_reparentlocked(child, trace_parent, 1, 0);
2003 
2004 			/* resend knote to original parent (and others) after reparenting */
2005 			proc_knote(child, knote_hint);
2006 
2007 			psignal(trace_parent, SIGCHLD);
2008 			proc_list_lock();
2009 			wakeup((caddr_t)trace_parent);
2010 			child->p_listflag &= ~P_LIST_WAITING;
2011 			wakeup(&child->p_stat);
2012 			proc_list_unlock();
2013 			proc_rele(trace_parent);
2014 			if ((locked == 1) && (droplock == 0)) {
2015 				proc_list_lock();
2016 			}
2017 			return 0;
2018 		}
2019 
2020 		/*
2021 		 * If we can't reparent (e.g. the original parent exited while child was being debugged, or
2022 		 * original parent is the same as the debugger currently exiting), we still need to satisfy
2023 		 * the knote lifecycle for other observers on the system. While the debugger was attached,
2024 		 * the NOTE_EXIT would not have been broadcast during initial child termination.
2025 		 */
2026 		proc_knote(child, knote_hint);
2027 
2028 		if (trace_parent != PROC_NULL) {
2029 			proc_rele(trace_parent);
2030 		}
2031 	}
2032 
2033 #pragma clang diagnostic push
2034 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2035 	proc_knote(child, NOTE_REAP);
2036 #pragma clang diagnostic pop
2037 
2038 	proc_knote_drain(child);
2039 
2040 	child->p_xstat = 0;
2041 	if (child->p_ru) {
2042 		proc_lock(parent);
2043 #if 3839178
2044 		/*
2045 		 * If the parent is ignoring SIGCHLD, then POSIX requires
2046 		 * us to not add the resource usage to the parent process -
2047 		 * we are only going to hand it off to init to get reaped.
2048 		 * We should contest the standard in this case on the basis
2049 		 * of RLIMIT_CPU.
2050 		 */
2051 		if (!(parent->p_flag & P_NOCLDWAIT))
2052 #endif  /* 3839178 */
2053 		ruadd(&parent->p_stats->p_cru, &child->p_ru->ru);
2054 		update_rusage_info_child(&parent->p_stats->ri_child, &child->p_ru->ri);
2055 		proc_unlock(parent);
2056 		zfree(zombie_zone, child->p_ru);
2057 		child->p_ru = NULL;
2058 	} else {
2059 		printf("Warning : lost p_ru for %s\n", child->p_comm);
2060 	}
2061 
2062 	AUDIT_SESSION_PROCEXIT(child);
2063 
2064 	/*
2065 	 * Decrement the count of procs running with this uid.
2066 	 * p_ucred usage is safe here as it is an exited process.
2067 	 * and refernce is dropped after these calls down below
2068 	 * (locking protection is provided by list lock held in chgproccnt)
2069 	 */
2070 #if CONFIG_PERSONAS
2071 	/*
2072 	 * persona_proc_drop calls chgproccnt(-1) on the persona uid,
2073 	 * and (+1) on the child->p_ucred uid
2074 	 */
2075 	persona_proc_drop(child);
2076 #endif
2077 	(void)chgproccnt(kauth_cred_getruid(proc_ucred(child)), -1);
2078 
2079 	os_reason_free(child->p_exit_reason);
2080 
2081 	/*
2082 	 * Finally finished with old proc entry.
2083 	 */
2084 
2085 	proc_list_lock();
2086 
2087 	/* quit the group */
2088 	pg = pgrp_leave_locked(child);
2089 
2090 	LIST_REMOVE(child, p_list);     /* off zombproc */
2091 	parent->p_childrencnt--;
2092 	LIST_REMOVE(child, p_sibling);
2093 	/* If there are no more children wakeup parent */
2094 	if ((deadparent != 0) && (LIST_EMPTY(&parent->p_children))) {
2095 		wakeup((caddr_t)parent);        /* with list lock held */
2096 	}
2097 	child->p_listflag &= ~P_LIST_WAITING;
2098 	wakeup(&child->p_stat);
2099 
2100 	/* Take it out of process hash */
2101 	phash_remove_locked(proc_getpid(child), child);
2102 	proc_checkdeadrefs(child);
2103 	nprocs--;
2104 
2105 	if (deadparent) {
2106 		/*
2107 		 * If a child zombie is being reaped because its parent
2108 		 * is exiting, make sure we update the list flag
2109 		 */
2110 		child->p_listflag |= P_LIST_DEADPARENT;
2111 	}
2112 
2113 	cred = proc_ucred(child);
2114 	child->p_proc_ro = proc_ro_release_proc(child->p_proc_ro);
2115 
2116 	proc_list_unlock();
2117 
2118 	pgrp_rele(pg);
2119 
2120 	/* Free outside of proc_list_lock. */
2121 	if (child->p_proc_ro != NULL) {
2122 		proc_ro_free(child->p_proc_ro);
2123 		child->p_proc_ro = NULL;
2124 	}
2125 
2126 	/*
2127 	 * Free up credentials.
2128 	 */
2129 	kauth_cred_set(&cred, NOCRED);
2130 
2131 	fdt_destroy(child);
2132 	lck_mtx_destroy(&child->p_mlock, &proc_mlock_grp);
2133 	lck_mtx_destroy(&child->p_ucred_mlock, &proc_ucred_mlock_grp);
2134 #if CONFIG_DTRACE
2135 	lck_mtx_destroy(&child->p_dtrace_sprlock, &proc_lck_grp);
2136 #endif
2137 	lck_spin_destroy(&child->p_slock, &proc_slock_grp);
2138 
2139 	proc_wait_release(child);
2140 	if ((locked == 1) && (droplock == 0)) {
2141 		proc_list_lock();
2142 	}
2143 
2144 	return 1;
2145 }
2146 
2147 
2148 int
wait1continue(int result)2149 wait1continue(int result)
2150 {
2151 	proc_t p;
2152 	thread_t thread;
2153 	uthread_t uth;
2154 	struct _wait4_data *wait4_data;
2155 	struct wait4_nocancel_args *uap;
2156 	int *retval;
2157 
2158 	if (result) {
2159 		return result;
2160 	}
2161 
2162 	p = current_proc();
2163 	thread = current_thread();
2164 	uth = (struct uthread *)get_bsdthread_info(thread);
2165 
2166 	wait4_data = &uth->uu_save.uus_wait4_data;
2167 	uap = wait4_data->args;
2168 	retval = wait4_data->retval;
2169 	return wait4_nocancel(p, uap, retval);
2170 }
2171 
2172 int
wait4(proc_t q,struct wait4_args * uap,int32_t * retval)2173 wait4(proc_t q, struct wait4_args *uap, int32_t *retval)
2174 {
2175 	__pthread_testcancel(1);
2176 	return wait4_nocancel(q, (struct wait4_nocancel_args *)uap, retval);
2177 }
2178 
2179 int
wait4_nocancel(proc_t q,struct wait4_nocancel_args * uap,int32_t * retval)2180 wait4_nocancel(proc_t q, struct wait4_nocancel_args *uap, int32_t *retval)
2181 {
2182 	int nfound;
2183 	int sibling_count;
2184 	proc_t p;
2185 	int status, error;
2186 	uthread_t uth;
2187 	struct _wait4_data *wait4_data;
2188 
2189 	AUDIT_ARG(pid, uap->pid);
2190 
2191 	if (uap->pid == 0) {
2192 		uap->pid = -q->p_pgrpid;
2193 	}
2194 
2195 loop:
2196 	proc_list_lock();
2197 loop1:
2198 	nfound = 0;
2199 	sibling_count = 0;
2200 
2201 	PCHILDREN_FOREACH(q, p) {
2202 		if (p->p_sibling.le_next != 0) {
2203 			sibling_count++;
2204 		}
2205 		if (uap->pid != WAIT_ANY &&
2206 		    proc_getpid(p) != uap->pid &&
2207 		    p->p_pgrpid != -(uap->pid)) {
2208 			continue;
2209 		}
2210 
2211 		nfound++;
2212 
2213 		/* XXX This is racy because we don't get the lock!!!! */
2214 
2215 		if (p->p_listflag & P_LIST_WAITING) {
2216 			/* we're not using a continuation here but we still need to stash
2217 			 * the args for stackshot. */
2218 			uth = current_uthread();
2219 			wait4_data = &uth->uu_save.uus_wait4_data;
2220 			wait4_data->args = uap;
2221 			thread_set_pending_block_hint(current_thread(), kThreadWaitOnProcess);
2222 
2223 			(void)msleep(&p->p_stat, &proc_list_mlock, PWAIT, "waitcoll", 0);
2224 			goto loop1;
2225 		}
2226 		p->p_listflag |= P_LIST_WAITING;   /* only allow single thread to wait() */
2227 
2228 
2229 		if (p->p_stat == SZOMB) {
2230 			int reparentedtoinit = (p->p_listflag & P_LIST_DEADPARENT) ? 1 : 0;
2231 
2232 			proc_list_unlock();
2233 #if CONFIG_MACF
2234 			if ((error = mac_proc_check_wait(q, p)) != 0) {
2235 				goto out;
2236 			}
2237 #endif
2238 			retval[0] = proc_getpid(p);
2239 			if (uap->status) {
2240 				/* Legacy apps expect only 8 bits of status */
2241 				status = 0xffff & p->p_xstat;   /* convert to int */
2242 				error = copyout((caddr_t)&status,
2243 				    uap->status,
2244 				    sizeof(status));
2245 				if (error) {
2246 					goto out;
2247 				}
2248 			}
2249 			if (uap->rusage) {
2250 				if (p->p_ru == NULL) {
2251 					error = ENOMEM;
2252 				} else {
2253 					if (IS_64BIT_PROCESS(q)) {
2254 						struct user64_rusage    my_rusage = {};
2255 						munge_user64_rusage(&p->p_ru->ru, &my_rusage);
2256 						error = copyout((caddr_t)&my_rusage,
2257 						    uap->rusage,
2258 						    sizeof(my_rusage));
2259 					} else {
2260 						struct user32_rusage    my_rusage = {};
2261 						munge_user32_rusage(&p->p_ru->ru, &my_rusage);
2262 						error = copyout((caddr_t)&my_rusage,
2263 						    uap->rusage,
2264 						    sizeof(my_rusage));
2265 					}
2266 				}
2267 				/* information unavailable? */
2268 				if (error) {
2269 					goto out;
2270 				}
2271 			}
2272 
2273 			/* Conformance change for 6577252.
2274 			 * When SIGCHLD is blocked and wait() returns because the status
2275 			 * of a child process is available and there are no other
2276 			 * children processes, then any pending SIGCHLD signal is cleared.
2277 			 */
2278 			if (sibling_count == 0) {
2279 				int mask = sigmask(SIGCHLD);
2280 				uth = current_uthread();
2281 
2282 				if ((uth->uu_sigmask & mask) != 0) {
2283 					/* we are blocking SIGCHLD signals.  clear any pending SIGCHLD.
2284 					 * This locking looks funny but it is protecting access to the
2285 					 * thread via p_uthlist.
2286 					 */
2287 					proc_lock(q);
2288 					uth->uu_siglist &= ~mask;       /* clear pending signal */
2289 					proc_unlock(q);
2290 				}
2291 			}
2292 
2293 			/* Clean up */
2294 			(void)reap_child_locked(q, p, 0, reparentedtoinit, 0, 0);
2295 
2296 			return 0;
2297 		}
2298 		if (p->p_stat == SSTOP && (p->p_lflag & P_LWAITED) == 0 &&
2299 		    (p->p_lflag & P_LTRACED || uap->options & WUNTRACED)) {
2300 			proc_list_unlock();
2301 #if CONFIG_MACF
2302 			if ((error = mac_proc_check_wait(q, p)) != 0) {
2303 				goto out;
2304 			}
2305 #endif
2306 			proc_lock(p);
2307 			p->p_lflag |= P_LWAITED;
2308 			proc_unlock(p);
2309 			retval[0] = proc_getpid(p);
2310 			if (uap->status) {
2311 				status = W_STOPCODE(p->p_xstat);
2312 				error = copyout((caddr_t)&status,
2313 				    uap->status,
2314 				    sizeof(status));
2315 			} else {
2316 				error = 0;
2317 			}
2318 			goto out;
2319 		}
2320 		/*
2321 		 * If we are waiting for continued processses, and this
2322 		 * process was continued
2323 		 */
2324 		if ((uap->options & WCONTINUED) &&
2325 		    (p->p_flag & P_CONTINUED)) {
2326 			proc_list_unlock();
2327 #if CONFIG_MACF
2328 			if ((error = mac_proc_check_wait(q, p)) != 0) {
2329 				goto out;
2330 			}
2331 #endif
2332 
2333 			/* Prevent other process for waiting for this event */
2334 			OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
2335 			retval[0] = proc_getpid(p);
2336 			if (uap->status) {
2337 				status = W_STOPCODE(SIGCONT);
2338 				error = copyout((caddr_t)&status,
2339 				    uap->status,
2340 				    sizeof(status));
2341 			} else {
2342 				error = 0;
2343 			}
2344 			goto out;
2345 		}
2346 		p->p_listflag &= ~P_LIST_WAITING;
2347 		wakeup(&p->p_stat);
2348 	}
2349 	/* list lock is held when we get here any which way */
2350 	if (nfound == 0) {
2351 		proc_list_unlock();
2352 		return ECHILD;
2353 	}
2354 
2355 	if (uap->options & WNOHANG) {
2356 		retval[0] = 0;
2357 		proc_list_unlock();
2358 		return 0;
2359 	}
2360 
2361 	/* Save arguments for continuation. Backing storage is in uthread->uu_arg, and will not be deallocated */
2362 	uth = current_uthread();
2363 	wait4_data = &uth->uu_save.uus_wait4_data;
2364 	wait4_data->args = uap;
2365 	wait4_data->retval = retval;
2366 
2367 	thread_set_pending_block_hint(current_thread(), kThreadWaitOnProcess);
2368 	if ((error = msleep0((caddr_t)q, &proc_list_mlock, PWAIT | PCATCH | PDROP, "wait", 0, wait1continue))) {
2369 		return error;
2370 	}
2371 
2372 	goto loop;
2373 out:
2374 	proc_list_lock();
2375 	p->p_listflag &= ~P_LIST_WAITING;
2376 	wakeup(&p->p_stat);
2377 	proc_list_unlock();
2378 	return error;
2379 }
2380 
2381 #if DEBUG
2382 #define ASSERT_LCK_MTX_OWNED(lock)      \
2383 	                        lck_mtx_assert(lock, LCK_MTX_ASSERT_OWNED)
2384 #else
2385 #define ASSERT_LCK_MTX_OWNED(lock)      /* nothing */
2386 #endif
2387 
2388 int
waitidcontinue(int result)2389 waitidcontinue(int result)
2390 {
2391 	proc_t p;
2392 	thread_t thread;
2393 	uthread_t uth;
2394 	struct _waitid_data *waitid_data;
2395 	struct waitid_nocancel_args *uap;
2396 	int *retval;
2397 
2398 	if (result) {
2399 		return result;
2400 	}
2401 
2402 	p = current_proc();
2403 	thread = current_thread();
2404 	uth = (struct uthread *)get_bsdthread_info(thread);
2405 
2406 	waitid_data = &uth->uu_save.uus_waitid_data;
2407 	uap = waitid_data->args;
2408 	retval = waitid_data->retval;
2409 	return waitid_nocancel(p, uap, retval);
2410 }
2411 
2412 /*
2413  * Description:	Suspend the calling thread until one child of the process
2414  *		containing the calling thread changes state.
2415  *
2416  * Parameters:	uap->idtype		one of P_PID, P_PGID, P_ALL
2417  *		uap->id			pid_t or gid_t or ignored
2418  *		uap->infop		Address of siginfo_t struct in
2419  *					user space into which to return status
2420  *		uap->options		flag values
2421  *
2422  * Returns:	0			Success
2423  *		!0			Error returning status to user space
2424  */
2425 int
waitid(proc_t q,struct waitid_args * uap,int32_t * retval)2426 waitid(proc_t q, struct waitid_args *uap, int32_t *retval)
2427 {
2428 	__pthread_testcancel(1);
2429 	return waitid_nocancel(q, (struct waitid_nocancel_args *)uap, retval);
2430 }
2431 
2432 int
waitid_nocancel(proc_t q,struct waitid_nocancel_args * uap,__unused int32_t * retval)2433 waitid_nocancel(proc_t q, struct waitid_nocancel_args *uap,
2434     __unused int32_t *retval)
2435 {
2436 	user_siginfo_t  siginfo;        /* siginfo data to return to caller */
2437 	boolean_t caller64 = IS_64BIT_PROCESS(q);
2438 	int nfound;
2439 	proc_t p;
2440 	int error;
2441 	uthread_t uth;
2442 	struct _waitid_data *waitid_data;
2443 
2444 	if (uap->options == 0 ||
2445 	    (uap->options & ~(WNOHANG | WNOWAIT | WCONTINUED | WSTOPPED | WEXITED))) {
2446 		return EINVAL;        /* bits set that aren't recognized */
2447 	}
2448 	switch (uap->idtype) {
2449 	case P_PID:     /* child with process ID equal to... */
2450 	case P_PGID:    /* child with process group ID equal to... */
2451 		if (((int)uap->id) < 0) {
2452 			return EINVAL;
2453 		}
2454 		break;
2455 	case P_ALL:     /* any child */
2456 		break;
2457 	}
2458 
2459 loop:
2460 	proc_list_lock();
2461 loop1:
2462 	nfound = 0;
2463 
2464 	PCHILDREN_FOREACH(q, p) {
2465 		switch (uap->idtype) {
2466 		case P_PID:     /* child with process ID equal to... */
2467 			if (proc_getpid(p) != (pid_t)uap->id) {
2468 				continue;
2469 			}
2470 			break;
2471 		case P_PGID:    /* child with process group ID equal to... */
2472 			if (p->p_pgrpid != (pid_t)uap->id) {
2473 				continue;
2474 			}
2475 			break;
2476 		case P_ALL:     /* any child */
2477 			break;
2478 		}
2479 
2480 		/* XXX This is racy because we don't get the lock!!!! */
2481 
2482 		/*
2483 		 * Wait collision; go to sleep and restart; used to maintain
2484 		 * the single return for waited process guarantee.
2485 		 */
2486 		if (p->p_listflag & P_LIST_WAITING) {
2487 			(void) msleep(&p->p_stat, &proc_list_mlock,
2488 			    PWAIT, "waitidcoll", 0);
2489 			goto loop1;
2490 		}
2491 		p->p_listflag |= P_LIST_WAITING;                /* mark busy */
2492 
2493 		nfound++;
2494 
2495 		bzero(&siginfo, sizeof(siginfo));
2496 
2497 		switch (p->p_stat) {
2498 		case SZOMB:             /* Exited */
2499 			if (!(uap->options & WEXITED)) {
2500 				break;
2501 			}
2502 			proc_list_unlock();
2503 #if CONFIG_MACF
2504 			if ((error = mac_proc_check_wait(q, p)) != 0) {
2505 				goto out;
2506 			}
2507 #endif
2508 			siginfo.si_signo = SIGCHLD;
2509 			siginfo.si_pid = proc_getpid(p);
2510 
2511 			/* If the child terminated abnormally due to a signal, the signum
2512 			 * needs to be preserved in the exit status.
2513 			 */
2514 			if (WIFSIGNALED(p->p_xstat)) {
2515 				siginfo.si_code = WCOREDUMP(p->p_xstat) ?
2516 				    CLD_DUMPED : CLD_KILLED;
2517 				siginfo.si_status = WTERMSIG(p->p_xstat);
2518 			} else {
2519 				siginfo.si_code = CLD_EXITED;
2520 				siginfo.si_status = WEXITSTATUS(p->p_xstat) & 0x00FFFFFF;
2521 			}
2522 			siginfo.si_status |= (((uint32_t)(p->p_xhighbits) << 24) & 0xFF000000);
2523 			p->p_xhighbits = 0;
2524 
2525 			if ((error = copyoutsiginfo(&siginfo,
2526 			    caller64, uap->infop)) != 0) {
2527 				goto out;
2528 			}
2529 
2530 			/* Prevent other process for waiting for this event? */
2531 			if (!(uap->options & WNOWAIT)) {
2532 				(void) reap_child_locked(q, p, 0, 0, 0, 0);
2533 				return 0;
2534 			}
2535 			goto out;
2536 
2537 		case SSTOP:             /* Stopped */
2538 			/*
2539 			 * If we are not interested in stopped processes, then
2540 			 * ignore this one.
2541 			 */
2542 			if (!(uap->options & WSTOPPED)) {
2543 				break;
2544 			}
2545 
2546 			/*
2547 			 * If someone has already waited it, we lost a race
2548 			 * to be the one to return status.
2549 			 */
2550 			if ((p->p_lflag & P_LWAITED) != 0) {
2551 				break;
2552 			}
2553 			proc_list_unlock();
2554 #if CONFIG_MACF
2555 			if ((error = mac_proc_check_wait(q, p)) != 0) {
2556 				goto out;
2557 			}
2558 #endif
2559 			siginfo.si_signo = SIGCHLD;
2560 			siginfo.si_pid = proc_getpid(p);
2561 			siginfo.si_status = p->p_xstat; /* signal number */
2562 			siginfo.si_code = CLD_STOPPED;
2563 
2564 			if ((error = copyoutsiginfo(&siginfo,
2565 			    caller64, uap->infop)) != 0) {
2566 				goto out;
2567 			}
2568 
2569 			/* Prevent other process for waiting for this event? */
2570 			if (!(uap->options & WNOWAIT)) {
2571 				proc_lock(p);
2572 				p->p_lflag |= P_LWAITED;
2573 				proc_unlock(p);
2574 			}
2575 			goto out;
2576 
2577 		default:                /* All other states => Continued */
2578 			if (!(uap->options & WCONTINUED)) {
2579 				break;
2580 			}
2581 
2582 			/*
2583 			 * If the flag isn't set, then this process has not
2584 			 * been stopped and continued, or the status has
2585 			 * already been reaped by another caller of waitid().
2586 			 */
2587 			if ((p->p_flag & P_CONTINUED) == 0) {
2588 				break;
2589 			}
2590 			proc_list_unlock();
2591 #if CONFIG_MACF
2592 			if ((error = mac_proc_check_wait(q, p)) != 0) {
2593 				goto out;
2594 			}
2595 #endif
2596 			siginfo.si_signo = SIGCHLD;
2597 			siginfo.si_code = CLD_CONTINUED;
2598 			proc_lock(p);
2599 			siginfo.si_pid = p->p_contproc;
2600 			siginfo.si_status = p->p_xstat;
2601 			proc_unlock(p);
2602 
2603 			if ((error = copyoutsiginfo(&siginfo,
2604 			    caller64, uap->infop)) != 0) {
2605 				goto out;
2606 			}
2607 
2608 			/* Prevent other process for waiting for this event? */
2609 			if (!(uap->options & WNOWAIT)) {
2610 				OSBitAndAtomic(~((uint32_t)P_CONTINUED),
2611 				    &p->p_flag);
2612 			}
2613 			goto out;
2614 		}
2615 		ASSERT_LCK_MTX_OWNED(&proc_list_mlock);
2616 
2617 		/* Not a process we are interested in; go on to next child */
2618 
2619 		p->p_listflag &= ~P_LIST_WAITING;
2620 		wakeup(&p->p_stat);
2621 	}
2622 	ASSERT_LCK_MTX_OWNED(&proc_list_mlock);
2623 
2624 	/* No child processes that could possibly satisfy the request? */
2625 
2626 	if (nfound == 0) {
2627 		proc_list_unlock();
2628 		return ECHILD;
2629 	}
2630 
2631 	if (uap->options & WNOHANG) {
2632 		proc_list_unlock();
2633 #if CONFIG_MACF
2634 		if ((error = mac_proc_check_wait(q, p)) != 0) {
2635 			return error;
2636 		}
2637 #endif
2638 		/*
2639 		 * The state of the siginfo structure in this case
2640 		 * is undefined.  Some implementations bzero it, some
2641 		 * (like here) leave it untouched for efficiency.
2642 		 *
2643 		 * Thus the most portable check for "no matching pid with
2644 		 * WNOHANG" is to store a zero into si_pid before
2645 		 * invocation, then check for a non-zero value afterwards.
2646 		 */
2647 		return 0;
2648 	}
2649 
2650 	/* Save arguments for continuation. Backing storage is in uthread->uu_arg, and will not be deallocated */
2651 	uth = current_uthread();
2652 	waitid_data = &uth->uu_save.uus_waitid_data;
2653 	waitid_data->args = uap;
2654 	waitid_data->retval = retval;
2655 
2656 	if ((error = msleep0(q, &proc_list_mlock,
2657 	    PWAIT | PCATCH | PDROP, "waitid", 0, waitidcontinue)) != 0) {
2658 		return error;
2659 	}
2660 
2661 	goto loop;
2662 out:
2663 	proc_list_lock();
2664 	p->p_listflag &= ~P_LIST_WAITING;
2665 	wakeup(&p->p_stat);
2666 	proc_list_unlock();
2667 	return error;
2668 }
2669 
2670 /*
2671  * make process 'parent' the new parent of process 'child'.
2672  */
2673 void
proc_reparentlocked(proc_t child,proc_t parent,int signallable,int locked)2674 proc_reparentlocked(proc_t child, proc_t parent, int signallable, int locked)
2675 {
2676 	proc_t oldparent = PROC_NULL;
2677 
2678 	if (child->p_pptr == parent) {
2679 		return;
2680 	}
2681 
2682 	if (locked == 0) {
2683 		proc_list_lock();
2684 	}
2685 
2686 	oldparent = child->p_pptr;
2687 #if __PROC_INTERNAL_DEBUG
2688 	if (oldparent == PROC_NULL) {
2689 		panic("proc_reparent: process %p does not have a parent", child);
2690 	}
2691 #endif
2692 
2693 	LIST_REMOVE(child, p_sibling);
2694 #if __PROC_INTERNAL_DEBUG
2695 	if (oldparent->p_childrencnt == 0) {
2696 		panic("process children count already 0");
2697 	}
2698 #endif
2699 	oldparent->p_childrencnt--;
2700 #if __PROC_INTERNAL_DEBUG
2701 	if (oldparent->p_childrencnt < 0) {
2702 		panic("process children count -ve");
2703 	}
2704 #endif
2705 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
2706 	parent->p_childrencnt++;
2707 	child->p_pptr = parent;
2708 	child->p_ppid = proc_getpid(parent);
2709 
2710 	proc_list_unlock();
2711 
2712 	if ((signallable != 0) && (initproc == parent) && (child->p_stat == SZOMB)) {
2713 		psignal(initproc, SIGCHLD);
2714 	}
2715 	if (locked == 1) {
2716 		proc_list_lock();
2717 	}
2718 }
2719 
2720 /*
2721  * Exit: deallocate address space and other resources, change proc state
2722  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
2723  * status and rusage for wait().  Check for child processes and orphan them.
2724  */
2725 
2726 
2727 /*
2728  * munge_rusage
2729  *	LP64 support - long is 64 bits if we are dealing with a 64 bit user
2730  *	process.  We munge the kernel version of rusage into the
2731  *	64 bit version.
2732  */
2733 __private_extern__  void
munge_user64_rusage(struct rusage * a_rusage_p,struct user64_rusage * a_user_rusage_p)2734 munge_user64_rusage(struct rusage *a_rusage_p, struct user64_rusage *a_user_rusage_p)
2735 {
2736 	/* Zero-out struct so that padding is cleared */
2737 	bzero(a_user_rusage_p, sizeof(struct user64_rusage));
2738 
2739 	/* timeval changes size, so utime and stime need special handling */
2740 	a_user_rusage_p->ru_utime.tv_sec = a_rusage_p->ru_utime.tv_sec;
2741 	a_user_rusage_p->ru_utime.tv_usec = a_rusage_p->ru_utime.tv_usec;
2742 	a_user_rusage_p->ru_stime.tv_sec = a_rusage_p->ru_stime.tv_sec;
2743 	a_user_rusage_p->ru_stime.tv_usec = a_rusage_p->ru_stime.tv_usec;
2744 	/*
2745 	 * everything else can be a direct assign, since there is no loss
2746 	 * of precision implied boing 32->64.
2747 	 */
2748 	a_user_rusage_p->ru_maxrss = a_rusage_p->ru_maxrss;
2749 	a_user_rusage_p->ru_ixrss = a_rusage_p->ru_ixrss;
2750 	a_user_rusage_p->ru_idrss = a_rusage_p->ru_idrss;
2751 	a_user_rusage_p->ru_isrss = a_rusage_p->ru_isrss;
2752 	a_user_rusage_p->ru_minflt = a_rusage_p->ru_minflt;
2753 	a_user_rusage_p->ru_majflt = a_rusage_p->ru_majflt;
2754 	a_user_rusage_p->ru_nswap = a_rusage_p->ru_nswap;
2755 	a_user_rusage_p->ru_inblock = a_rusage_p->ru_inblock;
2756 	a_user_rusage_p->ru_oublock = a_rusage_p->ru_oublock;
2757 	a_user_rusage_p->ru_msgsnd = a_rusage_p->ru_msgsnd;
2758 	a_user_rusage_p->ru_msgrcv = a_rusage_p->ru_msgrcv;
2759 	a_user_rusage_p->ru_nsignals = a_rusage_p->ru_nsignals;
2760 	a_user_rusage_p->ru_nvcsw = a_rusage_p->ru_nvcsw;
2761 	a_user_rusage_p->ru_nivcsw = a_rusage_p->ru_nivcsw;
2762 }
2763 
2764 /* For a 64-bit kernel and 32-bit userspace, munging may be needed */
2765 __private_extern__  void
munge_user32_rusage(struct rusage * a_rusage_p,struct user32_rusage * a_user_rusage_p)2766 munge_user32_rusage(struct rusage *a_rusage_p, struct user32_rusage *a_user_rusage_p)
2767 {
2768 	bzero(a_user_rusage_p, sizeof(struct user32_rusage));
2769 
2770 	/* timeval changes size, so utime and stime need special handling */
2771 	a_user_rusage_p->ru_utime.tv_sec = (user32_time_t)a_rusage_p->ru_utime.tv_sec;
2772 	a_user_rusage_p->ru_utime.tv_usec = a_rusage_p->ru_utime.tv_usec;
2773 	a_user_rusage_p->ru_stime.tv_sec = (user32_time_t)a_rusage_p->ru_stime.tv_sec;
2774 	a_user_rusage_p->ru_stime.tv_usec = a_rusage_p->ru_stime.tv_usec;
2775 	/*
2776 	 * everything else can be a direct assign. We currently ignore
2777 	 * the loss of precision
2778 	 */
2779 	a_user_rusage_p->ru_maxrss = (user32_long_t)a_rusage_p->ru_maxrss;
2780 	a_user_rusage_p->ru_ixrss = (user32_long_t)a_rusage_p->ru_ixrss;
2781 	a_user_rusage_p->ru_idrss = (user32_long_t)a_rusage_p->ru_idrss;
2782 	a_user_rusage_p->ru_isrss = (user32_long_t)a_rusage_p->ru_isrss;
2783 	a_user_rusage_p->ru_minflt = (user32_long_t)a_rusage_p->ru_minflt;
2784 	a_user_rusage_p->ru_majflt = (user32_long_t)a_rusage_p->ru_majflt;
2785 	a_user_rusage_p->ru_nswap = (user32_long_t)a_rusage_p->ru_nswap;
2786 	a_user_rusage_p->ru_inblock = (user32_long_t)a_rusage_p->ru_inblock;
2787 	a_user_rusage_p->ru_oublock = (user32_long_t)a_rusage_p->ru_oublock;
2788 	a_user_rusage_p->ru_msgsnd = (user32_long_t)a_rusage_p->ru_msgsnd;
2789 	a_user_rusage_p->ru_msgrcv = (user32_long_t)a_rusage_p->ru_msgrcv;
2790 	a_user_rusage_p->ru_nsignals = (user32_long_t)a_rusage_p->ru_nsignals;
2791 	a_user_rusage_p->ru_nvcsw = (user32_long_t)a_rusage_p->ru_nvcsw;
2792 	a_user_rusage_p->ru_nivcsw = (user32_long_t)a_rusage_p->ru_nivcsw;
2793 }
2794 
2795 void
kdp_wait4_find_process(thread_t thread,__unused event64_t wait_event,thread_waitinfo_t * waitinfo)2796 kdp_wait4_find_process(thread_t thread, __unused event64_t wait_event, thread_waitinfo_t *waitinfo)
2797 {
2798 	assert(thread != NULL);
2799 	assert(waitinfo != NULL);
2800 
2801 	struct uthread *ut = get_bsdthread_info(thread);
2802 	waitinfo->context = 0;
2803 	// ensure wmesg is consistent with a thread waiting in wait4
2804 	assert(!strcmp(ut->uu_wmesg, "waitcoll") || !strcmp(ut->uu_wmesg, "wait"));
2805 	struct wait4_nocancel_args *args = ut->uu_save.uus_wait4_data.args;
2806 	// May not actually contain a pid; this is just the argument to wait4.
2807 	// See man wait4 for other valid wait4 arguments.
2808 	waitinfo->owner = args->pid;
2809 }
2810 
2811 int
exit_with_guard_exception(proc_t p,mach_exception_data_type_t code,mach_exception_data_type_t subcode)2812 exit_with_guard_exception(
2813 	proc_t p,
2814 	mach_exception_data_type_t code,
2815 	mach_exception_data_type_t subcode)
2816 {
2817 	os_reason_t reason = os_reason_create(OS_REASON_GUARD, (uint64_t)code);
2818 	assert(reason != OS_REASON_NULL);
2819 
2820 	return exit_with_mach_exception(p, reason, EXC_GUARD, code, subcode);
2821 }
2822 
2823 #if __has_feature(ptrauth_calls)
2824 int
exit_with_pac_exception(proc_t p,exception_type_t exception,mach_exception_code_t code,mach_exception_subcode_t subcode)2825 exit_with_pac_exception(proc_t p, exception_type_t exception, mach_exception_code_t code,
2826     mach_exception_subcode_t subcode)
2827 {
2828 	os_reason_t reason = os_reason_create(OS_REASON_PAC_EXCEPTION, (uint64_t)code);
2829 	assert(reason != OS_REASON_NULL);
2830 
2831 	return exit_with_mach_exception(p, reason, exception, code, subcode);
2832 }
2833 #endif /* __has_feature(ptrauth_calls) */
2834 
2835 int
exit_with_port_space_exception(proc_t p,mach_exception_data_type_t code,mach_exception_data_type_t subcode)2836 exit_with_port_space_exception(proc_t p, mach_exception_data_type_t code,
2837     mach_exception_data_type_t subcode)
2838 {
2839 	os_reason_t reason = os_reason_create(OS_REASON_PORT_SPACE, (uint64_t)code);
2840 	assert(reason != OS_REASON_NULL);
2841 
2842 	return exit_with_mach_exception(p, reason, EXC_RESOURCE, code, subcode);
2843 }
2844 
2845 static int
exit_with_mach_exception(proc_t p,os_reason_t reason,exception_type_t exception,mach_exception_code_t code,mach_exception_subcode_t subcode)2846 exit_with_mach_exception(proc_t p, os_reason_t reason, exception_type_t exception, mach_exception_code_t code,
2847     mach_exception_subcode_t subcode)
2848 {
2849 	thread_t self = current_thread();
2850 	struct uthread *ut = get_bsdthread_info(self);
2851 
2852 	ut->uu_exception = exception;
2853 	ut->uu_code = code;
2854 	ut->uu_subcode = subcode;
2855 
2856 	reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
2857 	return exit_with_reason(p, W_EXITCODE(0, SIGKILL), NULL,
2858 	           TRUE, FALSE, 0, reason);
2859 }
2860