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