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