2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
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.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
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.
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
66 * @(#)kern_exit.c 8.7 (Berkeley) 2/12/94
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,
75 #include <machine/reg.h>
76 #include <machine/psl.h>
77 #include <stdatomic.h>
79 #include "compat_43.h"
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/ioctl.h>
84 #include <sys/proc_internal.h>
86 #include <sys/kauth.h>
89 #include <sys/resource.h>
90 #include <sys/kernel.h>
92 #include <sys/file_internal.h>
93 #include <sys/vnode_internal.h>
94 #include <sys/syslog.h>
95 #include <sys/malloc.h>
96 #include <sys/resourcevar.h>
97 #include <sys/ptrace.h>
98 #include <sys/proc_info.h>
99 #include <sys/reason.h>
100 #include <sys/_types/_timeval64.h>
101 #include <sys/user.h>
102 #include <sys/aio_kern.h>
103 #include <sys/sysproto.h>
104 #include <sys/signalvar.h>
105 #include <sys/kdebug.h>
106 #include <sys/filedesc.h> /* fdfree */
107 #include <sys/acct.h> /* acct_process */
108 #include <sys/codesign.h>
109 #include <sys/event.h> /* kevent_proc_copy_uptrs */
112 #include <security/audit/audit.h>
113 #include <bsm/audit_kevents.h>
115 #include <mach/mach_types.h>
116 #include <mach/task.h>
117 #include <mach/thread_act.h>
119 #include <kern/exc_resource.h>
120 #include <kern/kern_types.h>
121 #include <kern/kalloc.h>
122 #include <kern/task.h>
123 #include <corpses/task_corpse.h>
124 #include <kern/thread.h>
125 #include <kern/thread_call.h>
126 #include <kern/sched_prim.h>
127 #include <kern/assert.h>
128 #include <kern/policy_internal.h>
129 #include <kern/exc_guard.h>
131 #include <vm/vm_protos.h>
133 #include <pexpert/pexpert.h>
136 #include <sys/shm_internal.h> /* shmexit */
137 #endif /* SYSV_SHM */
139 #include <sys/persona.h>
140 #endif /* CONFIG_PERSONAS */
141 #if CONFIG_MEMORYSTATUS
142 #include <sys/kern_memorystatus.h>
143 #endif /* CONFIG_MEMORYSTATUS */
145 /* Do not include dtrace.h, it redefines kmem_[alloc/free] */
146 void dtrace_proc_exit(proc_t p
);
147 #include <sys/dtrace_ptss.h>
148 #endif /* CONFIG_DTRACE */
150 #include <security/mac_framework.h>
151 #include <security/mac_mach_internal.h>
152 #include <sys/syscall.h>
153 #endif /* CONFIG_MACF */
155 void proc_prepareexit(proc_t p
, int rv
, boolean_t perf_notify
);
156 void gather_populate_corpse_crashinfo(proc_t p
, task_t corpse_task
,
157 mach_exception_data_type_t code
, mach_exception_data_type_t subcode
,
158 uint64_t *udata_buffer
, int num_udata
, void *reason
);
159 mach_exception_data_type_t
proc_encode_exit_exception_code(proc_t p
);
160 void vfork_exit(proc_t p
, int rv
);
161 __private_extern__
void munge_user64_rusage(struct rusage
*a_rusage_p
, struct user64_rusage
*a_user_rusage_p
);
162 __private_extern__
void munge_user32_rusage(struct rusage
*a_rusage_p
, struct user32_rusage
*a_user_rusage_p
);
163 static int reap_child_locked(proc_t parent
, proc_t child
, int deadparent
, int reparentedtoinit
, int locked
, int droplock
);
164 static void populate_corpse_crashinfo(proc_t p
, task_t corpse_task
,
165 struct rusage_superset
*rup
, mach_exception_data_type_t code
,
166 mach_exception_data_type_t subcode
, uint64_t *udata_buffer
,
167 int num_udata
, os_reason_t reason
);
168 static void proc_update_corpse_exception_codes(proc_t p
, mach_exception_data_type_t
*code
, mach_exception_data_type_t
*subcode
);
169 extern int proc_pidpathinfo_internal(proc_t p
, uint64_t arg
, char *buffer
, uint32_t buffersize
, int32_t *retval
);
170 static __attribute__((noinline
)) void launchd_crashed_panic(proc_t p
, int rv
);
171 extern void proc_piduniqidentifierinfo(proc_t p
, struct proc_uniqidentifierinfo
*p_uniqidinfo
);
172 extern void task_coalition_ids(task_t task
, uint64_t ids
[COALITION_NUM_TYPES
]);
173 extern uint64_t get_task_phys_footprint_limit(task_t
);
174 int proc_list_uptrs(void *p
, uint64_t *udata_buffer
, int size
);
175 extern uint64_t task_corpse_get_crashed_thread_id(task_t corpse_task
);
179 * Things which should have prototypes in headers, but don't
181 void proc_exit(proc_t p
);
182 int wait1continue(int result
);
183 int waitidcontinue(int result
);
184 kern_return_t
sys_perf_notify(thread_t thread
, int pid
);
185 kern_return_t
task_exception_notify(exception_type_t exception
,
186 mach_exception_data_type_t code
, mach_exception_data_type_t subcode
);
187 kern_return_t
task_violated_guard(mach_exception_code_t
, mach_exception_subcode_t
, void *);
189 void gather_rusage_info(proc_t p
, rusage_info_current
*ru
, int flavor
);
192 * NOTE: Source and target may *NOT* overlap!
193 * XXX Should share code with bsd/dev/ppc/unix_signal.c
196 siginfo_user_to_user32(user_siginfo_t
*in
, user32_siginfo_t
*out
)
198 out
->si_signo
= in
->si_signo
;
199 out
->si_errno
= in
->si_errno
;
200 out
->si_code
= in
->si_code
;
201 out
->si_pid
= in
->si_pid
;
202 out
->si_uid
= in
->si_uid
;
203 out
->si_status
= in
->si_status
;
204 out
->si_addr
= CAST_DOWN_EXPLICIT(user32_addr_t
,in
->si_addr
);
205 /* following cast works for sival_int because of padding */
206 out
->si_value
.sival_ptr
= CAST_DOWN_EXPLICIT(user32_addr_t
,in
->si_value
.sival_ptr
);
207 out
->si_band
= in
->si_band
; /* range reduction */
211 siginfo_user_to_user64(user_siginfo_t
*in
, user64_siginfo_t
*out
)
213 out
->si_signo
= in
->si_signo
;
214 out
->si_errno
= in
->si_errno
;
215 out
->si_code
= in
->si_code
;
216 out
->si_pid
= in
->si_pid
;
217 out
->si_uid
= in
->si_uid
;
218 out
->si_status
= in
->si_status
;
219 out
->si_addr
= in
->si_addr
;
220 /* following cast works for sival_int because of padding */
221 out
->si_value
.sival_ptr
= in
->si_value
.sival_ptr
;
222 out
->si_band
= in
->si_band
; /* range reduction */
226 copyoutsiginfo(user_siginfo_t
*native
, boolean_t is64
, user_addr_t uaddr
)
229 user64_siginfo_t sinfo64
;
231 bzero(&sinfo64
, sizeof (sinfo64
));
232 siginfo_user_to_user64(native
, &sinfo64
);
233 return (copyout(&sinfo64
, uaddr
, sizeof (sinfo64
)));
235 user32_siginfo_t sinfo32
;
237 bzero(&sinfo32
, sizeof (sinfo32
));
238 siginfo_user_to_user32(native
, &sinfo32
);
239 return (copyout(&sinfo32
, uaddr
, sizeof (sinfo32
)));
243 void gather_populate_corpse_crashinfo(proc_t p
, task_t corpse_task
,
244 mach_exception_data_type_t code
, mach_exception_data_type_t subcode
,
245 uint64_t *udata_buffer
, int num_udata
, void *reason
)
247 struct rusage_superset rup
;
249 gather_rusage_info(p
, &rup
.ri
, RUSAGE_INFO_CURRENT
);
250 rup
.ri
.ri_phys_footprint
= 0;
251 populate_corpse_crashinfo(p
, corpse_task
, &rup
, code
, subcode
,
252 udata_buffer
, num_udata
, reason
);
255 static void proc_update_corpse_exception_codes(proc_t p
, mach_exception_data_type_t
*code
, mach_exception_data_type_t
*subcode
)
257 mach_exception_data_type_t code_update
= *code
;
258 mach_exception_data_type_t subcode_update
= *subcode
;
259 if (p
->p_exit_reason
== OS_REASON_NULL
) {
263 switch (p
->p_exit_reason
->osr_namespace
) {
264 case OS_REASON_JETSAM
:
265 if (p
->p_exit_reason
->osr_code
== JETSAM_REASON_MEMORY_PERPROCESSLIMIT
) {
266 /* Update the code with EXC_RESOURCE code for high memory watermark */
267 EXC_RESOURCE_ENCODE_TYPE(code_update
, RESOURCE_TYPE_MEMORY
);
268 EXC_RESOURCE_ENCODE_FLAVOR(code_update
, FLAVOR_HIGH_WATERMARK
);
269 EXC_RESOURCE_HWM_ENCODE_LIMIT(code_update
, ((get_task_phys_footprint_limit(p
->task
)) >> 20));
280 *subcode
= subcode_update
;
284 mach_exception_data_type_t
proc_encode_exit_exception_code(proc_t p
)
286 uint64_t subcode
= 0;
288 if (p
->p_exit_reason
== OS_REASON_NULL
) {
292 /* Embed first 32 bits of osr_namespace and osr_code in exception code */
293 ENCODE_OSR_NAMESPACE_TO_MACH_EXCEPTION_CODE(subcode
, p
->p_exit_reason
->osr_namespace
);
294 ENCODE_OSR_CODE_TO_MACH_EXCEPTION_CODE(subcode
, p
->p_exit_reason
->osr_code
);
295 return (mach_exception_data_type_t
)subcode
;
299 populate_corpse_crashinfo(proc_t p
, task_t corpse_task
, struct rusage_superset
*rup
,
300 mach_exception_data_type_t code
, mach_exception_data_type_t subcode
,
301 uint64_t *udata_buffer
, int num_udata
, os_reason_t reason
)
303 mach_vm_address_t uaddr
= 0;
304 mach_exception_data_type_t exc_codes
[EXCEPTION_CODE_MAX
];
306 exc_codes
[1] = subcode
;
308 struct proc_uniqidentifierinfo p_uniqidinfo
;
309 struct proc_workqueueinfo pwqinfo
;
311 uint64_t crashed_threadid
= task_corpse_get_crashed_thread_id(corpse_task
);
312 unsigned int pflags
= 0;
313 uint64_t max_footprint_mb
;
314 uint64_t max_footprint
;
315 void *crash_info_ptr
= task_get_corpseinfo(corpse_task
);
317 #if CONFIG_MEMORYSTATUS
318 int memstat_dirty_flags
= 0;
321 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_EXCEPTION_CODES
, sizeof(exc_codes
), &uaddr
)) {
322 kcdata_memcpy(crash_info_ptr
, uaddr
, exc_codes
, sizeof(exc_codes
));
325 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PID
, sizeof(p
->p_pid
), &uaddr
)) {
326 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_pid
, sizeof(p
->p_pid
));
329 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PPID
, sizeof(p
->p_ppid
), &uaddr
)) {
330 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_ppid
, sizeof(p
->p_ppid
));
333 /* Don't include the crashed thread ID if there's an exit reason that indicates it's irrelevant */
334 if ((p
->p_exit_reason
== OS_REASON_NULL
) || !(p
->p_exit_reason
->osr_flags
& OS_REASON_FLAG_NO_CRASHED_TID
)) {
335 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_CRASHED_THREADID
, sizeof(uint64_t), &uaddr
)) {
336 kcdata_memcpy(crash_info_ptr
, uaddr
, &crashed_threadid
, sizeof(uint64_t));
340 static_assert(sizeof(struct proc_uniqidentifierinfo
) == sizeof(struct crashinfo_proc_uniqidentifierinfo
));
342 kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_BSDINFOWITHUNIQID
, sizeof(struct proc_uniqidentifierinfo
), &uaddr
)) {
343 proc_piduniqidentifierinfo(p
, &p_uniqidinfo
);
344 kcdata_memcpy(crash_info_ptr
, uaddr
, &p_uniqidinfo
, sizeof(struct proc_uniqidentifierinfo
));
347 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_RUSAGE_INFO
, sizeof(rusage_info_current
), &uaddr
)) {
348 kcdata_memcpy(crash_info_ptr
, uaddr
, &rup
->ri
, sizeof(rusage_info_current
));
351 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PROC_CSFLAGS
, sizeof(p
->p_csflags
), &uaddr
)) {
352 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_csflags
, sizeof(p
->p_csflags
));
355 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PROC_NAME
, sizeof(p
->p_comm
), &uaddr
)) {
356 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_comm
, sizeof(p
->p_comm
));
359 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PROC_STARTTIME
, sizeof(p
->p_start
), &uaddr
)) {
360 struct timeval64 t64
;
361 t64
.tv_sec
= (int64_t)p
->p_start
.tv_sec
;
362 t64
.tv_usec
= (int64_t)p
->p_start
.tv_usec
;
363 kcdata_memcpy(crash_info_ptr
, uaddr
, &t64
, sizeof(t64
));
366 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_USERSTACK
, sizeof(p
->user_stack
), &uaddr
)) {
367 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->user_stack
, sizeof(p
->user_stack
));
370 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_ARGSLEN
, sizeof(p
->p_argslen
), &uaddr
)) {
371 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_argslen
, sizeof(p
->p_argslen
));
374 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PROC_ARGC
, sizeof(p
->p_argc
), &uaddr
)) {
375 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_argc
, sizeof(p
->p_argc
));
378 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PROC_PATH
, MAXPATHLEN
, &uaddr
)) {
379 char *buf
= (char *) kalloc(MAXPATHLEN
);
381 bzero(buf
, MAXPATHLEN
);
382 proc_pidpathinfo_internal(p
, 0, buf
, MAXPATHLEN
, &retval
);
383 kcdata_memcpy(crash_info_ptr
, uaddr
, buf
, MAXPATHLEN
);
384 kfree(buf
, MAXPATHLEN
);
388 pflags
= p
->p_flag
& (P_LP64
| P_SUGID
);
389 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_PROC_FLAGS
, sizeof(pflags
), &uaddr
)) {
390 kcdata_memcpy(crash_info_ptr
, uaddr
, &pflags
, sizeof(pflags
));
393 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_UID
, sizeof(p
->p_uid
), &uaddr
)) {
394 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_uid
, sizeof(p
->p_uid
));
397 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_GID
, sizeof(p
->p_gid
), &uaddr
)) {
398 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_gid
, sizeof(p
->p_gid
));
401 cputype
= cpu_type() & ~CPU_ARCH_MASK
;
402 if (IS_64BIT_PROCESS(p
))
403 cputype
|= CPU_ARCH_ABI64
;
405 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_CPUTYPE
, sizeof(cpu_type_t
), &uaddr
)) {
406 kcdata_memcpy(crash_info_ptr
, uaddr
, &cputype
, sizeof(cpu_type_t
));
409 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_MEMORY_LIMIT
, sizeof(max_footprint_mb
), &uaddr
)) {
410 max_footprint
= get_task_phys_footprint_limit(p
->task
);
411 max_footprint_mb
= max_footprint
>> 20;
412 kcdata_memcpy(crash_info_ptr
, uaddr
, &max_footprint_mb
, sizeof(max_footprint_mb
));
415 bzero(&pwqinfo
, sizeof(struct proc_workqueueinfo
));
416 retval
= fill_procworkqueue(p
, &pwqinfo
);
418 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_WORKQUEUEINFO
, sizeof(struct proc_workqueueinfo
), &uaddr
)) {
419 kcdata_memcpy(crash_info_ptr
, uaddr
, &pwqinfo
, sizeof(struct proc_workqueueinfo
));
423 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_RESPONSIBLE_PID
, sizeof(p
->p_responsible_pid
), &uaddr
)) {
424 kcdata_memcpy(crash_info_ptr
, uaddr
, &p
->p_responsible_pid
, sizeof(p
->p_responsible_pid
));
427 #if CONFIG_COALITIONS
428 if (KERN_SUCCESS
== kcdata_get_memory_addr_for_array(crash_info_ptr
, TASK_CRASHINFO_COALITION_ID
, sizeof(uint64_t), COALITION_NUM_TYPES
, &uaddr
)) {
429 uint64_t coalition_ids
[COALITION_NUM_TYPES
];
430 task_coalition_ids(p
->task
, coalition_ids
);
431 kcdata_memcpy(crash_info_ptr
, uaddr
, coalition_ids
, sizeof(coalition_ids
));
433 #endif /* CONFIG_COALITIONS */
435 #if CONFIG_MEMORYSTATUS
436 memstat_dirty_flags
= memorystatus_dirty_get(p
);
437 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, TASK_CRASHINFO_DIRTY_FLAGS
, sizeof(memstat_dirty_flags
), &uaddr
)) {
438 kcdata_memcpy(crash_info_ptr
, uaddr
, &memstat_dirty_flags
, sizeof(memstat_dirty_flags
));
442 if (p
->p_exit_reason
!= OS_REASON_NULL
&& reason
== OS_REASON_NULL
) {
443 reason
= p
->p_exit_reason
;
445 if (reason
!= OS_REASON_NULL
) {
446 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, EXIT_REASON_SNAPSHOT
, sizeof(struct exit_reason_snapshot
), &uaddr
)) {
447 struct exit_reason_snapshot ers
= {
448 .ers_namespace
= reason
->osr_namespace
,
449 .ers_code
= reason
->osr_code
,
450 .ers_flags
= reason
->osr_flags
453 kcdata_memcpy(crash_info_ptr
, uaddr
, &ers
, sizeof(ers
));
456 if (reason
->osr_kcd_buf
!= 0) {
457 uint32_t reason_buf_size
= kcdata_memory_get_used_bytes(&reason
->osr_kcd_descriptor
);
458 assert(reason_buf_size
!= 0);
460 if (KERN_SUCCESS
== kcdata_get_memory_addr(crash_info_ptr
, KCDATA_TYPE_NESTED_KCDATA
, reason_buf_size
, &uaddr
)) {
461 kcdata_memcpy(crash_info_ptr
, uaddr
, reason
->osr_kcd_buf
, reason_buf_size
);
467 if (KERN_SUCCESS
== kcdata_get_memory_addr_for_array(crash_info_ptr
, TASK_CRASHINFO_UDATA_PTRS
,
468 sizeof(uint64_t), num_udata
, &uaddr
)) {
469 kcdata_memcpy(crash_info_ptr
, uaddr
, udata_buffer
, sizeof(uint64_t) * num_udata
);
475 * We only parse exit reason kcdata blobs for launchd when it dies
476 * and we're going to panic.
478 * Meant to be called immediately before panicking.
481 launchd_exit_reason_get_string_desc(os_reason_t exit_reason
)
485 if (exit_reason
== OS_REASON_NULL
|| exit_reason
->osr_kcd_buf
== NULL
||
486 exit_reason
->osr_bufsize
== 0) {
490 iter
= kcdata_iter(exit_reason
->osr_kcd_buf
, exit_reason
->osr_bufsize
);
491 if (!kcdata_iter_valid(iter
)) {
492 #if DEBUG || DEVELOPMENT
493 printf("launchd exit reason has invalid exit reason buffer\n");
498 if (kcdata_iter_type(iter
) != KCDATA_BUFFER_BEGIN_OS_REASON
) {
499 #if DEBUG || DEVELOPMENT
500 printf("launchd exit reason buffer type mismatch, expected %d got %d\n",
501 KCDATA_BUFFER_BEGIN_OS_REASON
, kcdata_iter_type(iter
));
506 iter
= kcdata_iter_find_type(iter
, EXIT_REASON_USER_DESC
);
507 if (!kcdata_iter_valid(iter
)) {
511 return (char *)kcdata_iter_payload(iter
);
514 static __attribute__((noinline
)) void
515 launchd_crashed_panic(proc_t p
, int rv
)
517 char *launchd_exit_reason_desc
= launchd_exit_reason_get_string_desc(p
->p_exit_reason
);
519 if (p
->p_exit_reason
== OS_REASON_NULL
) {
520 printf("pid 1 exited -- no exit reason available -- (signal %d, exit %d)\n",
521 WTERMSIG(rv
), WEXITSTATUS(rv
));
523 printf("pid 1 exited -- exit reason namespace %d subcode 0x%llx, description %s\n",
524 p
->p_exit_reason
->osr_namespace
, p
->p_exit_reason
->osr_code
, launchd_exit_reason_desc
?
525 launchd_exit_reason_desc
: "none");
528 const char *launchd_crashed_prefix_str
;
530 if (strnstr(p
->p_name
, "preinit", sizeof(p
->p_name
))) {
531 launchd_crashed_prefix_str
= "LTE preinit process exited";
533 launchd_crashed_prefix_str
= "initproc exited";
536 #if (DEVELOPMENT || DEBUG) && CONFIG_COREDUMP
538 * For debugging purposes, generate a core file of initproc before
539 * panicking. Leave at least 300 MB free on the root volume, and ignore
540 * the process's corefile ulimit. fsync() the file to ensure it lands on disk
541 * before the panic hits.
545 uint64_t coredump_start
= mach_absolute_time();
546 uint64_t coredump_end
;
548 clock_usec_t tv_usec
;
552 err
= coredump(p
, 300, COREDUMP_IGNORE_ULIMIT
| COREDUMP_FULLFSYNC
);
554 coredump_end
= mach_absolute_time();
556 absolutetime_to_microtime(coredump_end
- coredump_start
, &tv_sec
, &tv_usec
);
558 tv_msec
= tv_usec
/ 1000;
561 printf("Failed to generate initproc core file: error %d, took %d.%03d seconds\n",
562 err
, (uint32_t)tv_sec
, tv_msec
);
564 printf("Generated initproc core file in %d.%03d seconds\n",
565 (uint32_t)tv_sec
, tv_msec
);
567 #endif /* (DEVELOPMENT || DEBUG) && CONFIG_COREDUMP */
569 sync(p
, (void *)NULL
, (int *)NULL
);
571 if (p
->p_exit_reason
== OS_REASON_NULL
) {
572 panic_with_options(0, NULL
, DEBUGGER_OPTION_INITPROC_PANIC
, "%s -- no exit reason available -- (signal %d, exit status %d %s)",
573 launchd_crashed_prefix_str
, WTERMSIG(rv
), WEXITSTATUS(rv
), ((p
->p_csflags
& CS_KILLED
) ? "CS_KILLED" : ""));
575 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",
576 ((p
->p_csflags
& CS_KILLED
) ? "CS_KILLED" : ""),
577 launchd_crashed_prefix_str
, p
->p_exit_reason
->osr_namespace
, p
->p_exit_reason
->osr_code
,
578 launchd_exit_reason_desc
? launchd_exit_reason_desc
: "none");
582 #define OS_REASON_IFLAG_USER_FAULT 0x1
584 #define OS_REASON_TOTAL_USER_FAULTS_PER_PROC 5
587 abort_with_payload_internal(proc_t p
,
588 uint32_t reason_namespace
, uint64_t reason_code
,
589 user_addr_t payload
, uint32_t payload_size
,
590 user_addr_t reason_string
, uint64_t reason_flags
,
591 uint32_t internal_flags
)
593 os_reason_t exit_reason
= OS_REASON_NULL
;
594 kern_return_t kr
= KERN_SUCCESS
;
596 if (internal_flags
& OS_REASON_IFLAG_USER_FAULT
) {
597 uint32_t old_value
= atomic_load_explicit(&p
->p_user_faults
,
598 memory_order_relaxed
);
600 if (old_value
>= OS_REASON_TOTAL_USER_FAULTS_PER_PROC
) {
603 // this reloads the value in old_value
604 if (atomic_compare_exchange_strong_explicit(&p
->p_user_faults
,
605 &old_value
, old_value
+ 1, memory_order_relaxed
,
606 memory_order_relaxed
)) {
612 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_CREATE
) | DBG_FUNC_NONE
,
613 p
->p_pid
, reason_namespace
,
616 exit_reason
= build_userspace_exit_reason(reason_namespace
, reason_code
,
617 payload
, payload_size
, reason_string
, reason_flags
);
619 if (internal_flags
& OS_REASON_IFLAG_USER_FAULT
) {
620 mach_exception_code_t code
= 0;
622 EXC_GUARD_ENCODE_TYPE(code
, GUARD_TYPE_USER
); /* simulated EXC_GUARD */
623 EXC_GUARD_ENCODE_FLAVOR(code
, 0);
624 EXC_GUARD_ENCODE_TARGET(code
, reason_namespace
);
626 if (exit_reason
== OS_REASON_NULL
) {
627 kr
= KERN_RESOURCE_SHORTAGE
;
629 kr
= task_violated_guard(code
, reason_code
, exit_reason
);
631 os_reason_free(exit_reason
);
634 * We use SIGABRT (rather than calling exit directly from here) so that
635 * the debugger can catch abort_with_{reason,payload} calls.
637 psignal_try_thread_with_reason(p
, current_thread(), SIGABRT
, exit_reason
);
643 case KERN_NOT_SUPPORTED
:
645 case KERN_INVALID_ARGUMENT
:
647 case KERN_RESOURCE_SHORTAGE
:
654 abort_with_payload(struct proc
*cur_proc
, struct abort_with_payload_args
*args
,
655 __unused
void *retval
)
657 abort_with_payload_internal(cur_proc
, args
->reason_namespace
,
658 args
->reason_code
, args
->payload
, args
->payload_size
,
659 args
->reason_string
, args
->reason_flags
, 0);
665 os_fault_with_payload(struct proc
*cur_proc
,
666 struct os_fault_with_payload_args
*args
, __unused
int *retval
)
668 return abort_with_payload_internal(cur_proc
, args
->reason_namespace
,
669 args
->reason_code
, args
->payload
, args
->payload_size
,
670 args
->reason_string
, args
->reason_flags
, OS_REASON_IFLAG_USER_FAULT
);
678 __attribute__((noreturn
))
680 exit(proc_t p
, struct exit_args
*uap
, int *retval
)
682 p
->p_xhighbits
= ((uint32_t)(uap
->rval
) & 0xFF000000) >> 24;
683 exit1(p
, W_EXITCODE(uap
->rval
, 0), retval
);
685 thread_exception_return();
688 thread_block(THREAD_CONTINUE_NULL
);
693 * Exit: deallocate address space and other resources, change proc state
694 * to zombie, and unlink proc from allproc and parent's lists. Save exit
695 * status and rusage for wait(). Check for child processes and orphan them.
698 exit1(proc_t p
, int rv
, int *retval
)
700 return exit1_internal(p
, rv
, retval
, TRUE
, TRUE
, 0);
704 exit1_internal(proc_t p
, int rv
, int *retval
, boolean_t thread_can_terminate
, boolean_t perf_notify
,
707 return exit_with_reason(p
, rv
, retval
, thread_can_terminate
, perf_notify
, jetsam_flags
, OS_REASON_NULL
);
711 * NOTE: exit_with_reason drops a reference on the passed exit_reason
714 exit_with_reason(proc_t p
, int rv
, int *retval
, boolean_t thread_can_terminate
, boolean_t perf_notify
,
715 int jetsam_flags
, struct os_reason
*exit_reason
)
717 thread_t self
= current_thread();
718 struct task
*task
= p
->task
;
723 * If a thread in this task has already
724 * called exit(), then halt any others
728 ut
= get_bsdthread_info(self
);
729 if ((p
== current_proc()) &&
730 (ut
->uu_flag
& UT_VFORK
)) {
731 os_reason_free(exit_reason
);
732 if (!thread_can_terminate
) {
737 vfork_return(p
, retval
, p
->p_pid
);
738 unix_syscall_return(0);
743 * The parameter list of audit_syscall_exit() was augmented to
744 * take the Darwin syscall number as the first parameter,
745 * which is currently required by mac_audit_postselect().
749 * The BSM token contains two components: an exit status as passed
750 * to exit(), and a return value to indicate what sort of exit it
751 * was. The exit status is WEXITSTATUS(rv), but it's not clear
752 * what the return value is.
754 AUDIT_ARG(exit
, WEXITSTATUS(rv
), 0);
756 * TODO: what to audit here when jetsam calls exit and the uthread,
757 * 'ut' does not belong to the proc, 'p'.
759 AUDIT_SYSCALL_EXIT(SYS_exit
, p
, ut
, 0); /* Exit is always successfull */
761 DTRACE_PROC1(exit
, int, CLD_EXITED
);
763 /* mark process is going to exit and pull out of DBG/disk throttle */
764 /* TODO: This should be done after becoming exit thread */
765 proc_set_task_policy(p
->task
, TASK_POLICY_ATTRIBUTE
,
766 TASK_POLICY_TERMINATED
, TASK_POLICY_ENABLE
);
769 error
= proc_transstart(p
, 1, (jetsam_flags
? 1 : 0));
770 if (error
== EDEADLK
) {
772 * If proc_transstart() returns EDEADLK, then another thread
773 * is either exec'ing or exiting. Return an error and allow
774 * the other thread to continue.
777 os_reason_free(exit_reason
);
778 if (current_proc() == p
){
779 if (p
->exit_thread
== self
) {
780 printf("exit_thread failed to exit, leaving process %s[%d] in unkillable limbo\n",
781 p
->p_comm
, p
->p_pid
);
784 if (thread_can_terminate
) {
785 thread_exception_return();
792 while (p
->exit_thread
!= self
) {
793 if (sig_try_locked(p
) <= 0) {
795 os_reason_free(exit_reason
);
797 if (get_threadtask(self
) != task
) {
803 thread_terminate(self
);
804 if (!thread_can_terminate
) {
808 thread_exception_return();
814 if (exit_reason
!= OS_REASON_NULL
) {
815 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXITREASON_COMMIT
) | DBG_FUNC_NONE
,
816 p
->p_pid
, exit_reason
->osr_namespace
,
817 exit_reason
->osr_code
, 0, 0);
820 assert(p
->p_exit_reason
== OS_REASON_NULL
);
821 p
->p_exit_reason
= exit_reason
;
823 p
->p_lflag
|= P_LEXIT
;
825 p
->p_lflag
|= jetsam_flags
;
830 proc_prepareexit(p
, rv
, perf_notify
);
832 /* Last thread to terminate will call proc_exit() */
833 task_terminate_internal(task
);
839 proc_prepareexit(proc_t p
, int rv
, boolean_t perf_notify
)
841 mach_exception_data_type_t code
= 0, subcode
= 0;
844 thread_t self
= current_thread();
845 ut
= get_bsdthread_info(self
);
846 struct rusage_superset
*rup
;
848 int create_corpse
= FALSE
;
851 launchd_crashed_panic(p
, rv
);
856 * Generate a corefile/crashlog if:
857 * The process doesn't have an exit reason that indicates no crash report should be created
858 * AND any of the following are true:
859 * - The process was terminated due to a fatal signal that generates a core
860 * - The process was killed due to a code signing violation
861 * - The process has an exit reason that indicates we should generate a crash report
863 * The first condition is necessary because abort_with_reason()/payload() use SIGABRT
864 * (which normally triggers a core) but may indicate that no crash report should be created.
866 if (!(PROC_HAS_EXITREASON(p
) && (PROC_EXITREASON_FLAGS(p
) & OS_REASON_FLAG_NO_CRASH_REPORT
)) &&
867 (hassigprop(WTERMSIG(rv
), SA_CORE
) || ((p
->p_csflags
& CS_KILLED
) != 0) ||
868 (PROC_HAS_EXITREASON(p
) && (PROC_EXITREASON_FLAGS(p
) &
869 OS_REASON_FLAG_GENERATE_CRASH_REPORT
)))) {
871 * Workaround for processes checking up on PT_DENY_ATTACH:
872 * should be backed out post-Leopard (details in 5431025).
874 if ((SIGSEGV
== WTERMSIG(rv
)) &&
875 (p
->p_pptr
->p_lflag
& P_LNOATTACH
)) {
880 * Crash Reporter looks for the signal value, original exception
881 * type, and low 20 bits of the original code in code[0]
882 * (8, 4, and 20 bits respectively). code[1] is unmodified.
884 code
= ((WTERMSIG(rv
) & 0xff) << 24) |
885 ((ut
->uu_exception
& 0x0f) << 20) |
886 ((int)ut
->uu_code
& 0xfffff);
887 subcode
= ut
->uu_subcode
;
889 kr
= task_exception_notify(EXC_CRASH
, code
, subcode
);
891 /* Nobody handled EXC_CRASH?? remember to make corpse */
893 create_corpse
= TRUE
;
898 /* Notify the perf server? */
900 (void)sys_perf_notify(self
, p
->p_pid
);
904 /* stash the usage into corpse data if making_corpse == true */
905 if (create_corpse
== TRUE
) {
906 kr
= task_mark_corpse(p
->task
);
907 if (kr
!= KERN_SUCCESS
) {
908 if (kr
== KERN_NO_SPACE
) {
909 printf("Process[%d] has no vm space for corpse info.\n", p
->p_pid
);
910 } else if (kr
== KERN_NOT_SUPPORTED
) {
911 printf("Process[%d] was destined to be corpse. But corpse is disabled by config.\n", p
->p_pid
);
913 printf("Process[%d] crashed: %s. Too many corpses being created.\n", p
->p_pid
, p
->p_comm
);
915 create_corpse
= FALSE
;
920 * Before this process becomes a zombie, stash resource usage
921 * stats in the proc for external observers to query
922 * via proc_pid_rusage().
924 * If the zombie allocation fails, just punt the stats.
926 MALLOC_ZONE(rup
, struct rusage_superset
*,
927 sizeof (*rup
), M_ZOMBIE
, M_WAITOK
);
929 gather_rusage_info(p
, &rup
->ri
, RUSAGE_INFO_CURRENT
);
930 rup
->ri
.ri_phys_footprint
= 0;
931 rup
->ri
.ri_proc_exit_abstime
= mach_absolute_time();
934 * Make the rusage_info visible to external observers
935 * only after it has been completely filled in.
940 int est_knotes
= 0, num_knotes
= 0;
941 uint64_t *buffer
= NULL
;
944 /* Get all the udata pointers from kqueue */
945 est_knotes
= kevent_proc_copy_uptrs(p
, NULL
, 0);
946 if (est_knotes
> 0) {
947 buf_size
= (est_knotes
+ 32) * sizeof(uint64_t);
948 buffer
= (uint64_t *) kalloc(buf_size
);
949 num_knotes
= kevent_proc_copy_uptrs(p
, buffer
, buf_size
);
950 if (num_knotes
> est_knotes
+ 32) {
951 num_knotes
= est_knotes
+ 32;
955 /* Update the code, subcode based on exit reason */
956 proc_update_corpse_exception_codes(p
, &code
, &subcode
);
957 populate_corpse_crashinfo(p
, p
->task
, rup
,
958 code
, subcode
, buffer
, num_knotes
, NULL
);
959 if (buffer
!= NULL
) {
960 kfree(buffer
, buf_size
);
964 * Remove proc from allproc queue and from pidhash chain.
965 * Need to do this before we do anything that can block.
966 * Not doing causes things like mount() find this on allproc
967 * in partially cleaned state.
972 #if CONFIG_MEMORYSTATUS
973 memorystatus_remove(p
, TRUE
);
976 LIST_REMOVE(p
, p_list
);
977 LIST_INSERT_HEAD(&zombproc
, p
, p_list
); /* Place onto zombproc. */
978 /* will not be visible via proc_find */
979 p
->p_listflag
|= P_LIST_EXITED
;
988 * If parent is waiting for us to exit or exec,
989 * P_LPPWAIT is set; we will wakeup the parent below.
992 p
->p_lflag
&= ~(P_LTRACED
| P_LPPWAIT
);
993 p
->p_sigignore
= ~(sigcantmask
);
1003 struct task
*task
= p
->task
;
1004 vnode_t tvp
= NULLVP
;
1006 struct session
*sessp
;
1007 struct uthread
* uth
;
1012 uth
= current_uthread();
1015 proc_transstart(p
, 1, 0);
1016 if( !(p
->p_lflag
& P_LEXIT
)) {
1018 * This can happen if a thread_terminate() occurs
1019 * in a single-threaded process.
1021 p
->p_lflag
|= P_LEXIT
;
1022 proc_transend(p
, 1);
1024 proc_prepareexit(p
, 0, TRUE
);
1025 (void) task_terminate_internal(task
);
1028 proc_transend(p
, 1);
1031 p
->p_lflag
|= P_LPEXIT
;
1034 * Other kernel threads may be in the middle of signalling this process.
1035 * Wait for those threads to wrap it up before making the process
1036 * disappear on them.
1038 if ((p
->p_lflag
& P_LINSIGNAL
) || (p
->p_sigwaitcnt
> 0)) {
1040 while ((p
->p_lflag
& P_LINSIGNAL
) || (p
->p_sigwaitcnt
> 1))
1041 msleep(&p
->p_sigmask
, &p
->p_mlock
, PWAIT
, "proc_sigdrain", NULL
);
1047 exitval
= p
->p_xstat
;
1048 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON
,
1049 BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXIT
) | DBG_FUNC_START
,
1050 pid
, exitval
, 0, 0, 0);
1053 dtrace_proc_exit(p
);
1056 nspace_proc_exit(p
);
1059 * need to cancel async IO requests that can be cancelled and wait for those
1060 * already active. MAY BLOCK!
1065 /* if any pending cpu limits action, clear it */
1066 task_clear_cpuusage(p
->task
, TRUE
);
1068 workqueue_mark_exiting(p
);
1073 * Close open files and release open-file table.
1079 * Once all the knotes, kqueues & workloops are destroyed, get rid of the
1084 if (uth
->uu_lowpri_window
) {
1086 * task is marked as a low priority I/O type
1087 * and the I/O we issued while in flushing files on close
1088 * collided with normal I/O operations...
1089 * no need to throttle this thread since its going away
1090 * but we do need to update our bookeeping w/r to throttled threads
1092 throttle_lowpri_io(0);
1096 /* Close ref SYSV Shared memory*/
1101 /* Release SYSV semaphores */
1106 pth_proc_hashdelete(p
);
1109 sessp
= proc_session(p
);
1110 if (SESS_LEADER(p
, sessp
)) {
1112 if (sessp
->s_ttyvp
!= NULLVP
) {
1113 struct vnode
*ttyvp
;
1116 struct vfs_context context
;
1120 * Controlling process.
1121 * Signal foreground pgrp,
1122 * drain controlling terminal
1123 * and revoke access to controlling terminal.
1125 session_lock(sessp
);
1126 tp
= SESSION_TP(sessp
);
1127 if ((tp
!= TTY_NULL
) && (tp
->t_session
== sessp
)) {
1128 session_unlock(sessp
);
1131 * We're going to SIGHUP the foreground process
1132 * group. It can't change from this point on
1133 * until the revoke is complete.
1134 * The process group changes under both the tty
1135 * lock and proc_list_lock but we need only one
1141 tty_pgsignal(tp
, SIGHUP
, 1);
1143 session_lock(sessp
);
1144 tp
= SESSION_TP(sessp
);
1146 cttyflag
= sessp
->s_flags
& S_CTTYREF
;
1147 sessp
->s_flags
&= ~S_CTTYREF
;
1148 ttyvp
= sessp
->s_ttyvp
;
1149 ttyvid
= sessp
->s_ttyvid
;
1150 sessp
->s_ttyvp
= NULLVP
;
1151 sessp
->s_ttyvid
= 0;
1152 sessp
->s_ttyp
= TTY_NULL
;
1153 sessp
->s_ttypgrpid
= NO_PID
;
1154 session_unlock(sessp
);
1156 if ((ttyvp
!= NULLVP
) && (vnode_getwithvid(ttyvp
, ttyvid
) == 0)) {
1157 if (tp
!= TTY_NULL
) {
1162 context
.vc_thread
= proc_thread(p
); /* XXX */
1163 context
.vc_ucred
= kauth_cred_proc_ref(p
);
1164 VNOP_REVOKE(ttyvp
, REVOKEALL
, &context
);
1167 * Release the extra usecount taken in cttyopen.
1168 * usecount should be released after VNOP_REVOKE is called.
1169 * This usecount was taken to ensure that
1170 * the VNOP_REVOKE results in a close to
1171 * the tty since cttyclose is a no-op.
1176 kauth_cred_unref(&context
.vc_ucred
);
1181 * This is cleared even if not set. This is also done in
1182 * spec_close to ensure that the flag is cleared.
1191 session_lock(sessp
);
1192 sessp
->s_leader
= NULL
;
1193 session_unlock(sessp
);
1195 session_rele(sessp
);
1201 p
->p_rlimit
[RLIMIT_FSIZE
].rlim_cur
= RLIM_INFINITY
;
1202 (void)acct_process(p
);
1206 if ((p
->p_listflag
& P_LIST_EXITCOUNT
) == P_LIST_EXITCOUNT
) {
1207 p
->p_listflag
&= ~P_LIST_EXITCOUNT
;
1208 proc_shutdown_exitcount
--;
1209 if (proc_shutdown_exitcount
== 0)
1210 wakeup(&proc_shutdown_exitcount
);
1213 /* wait till parentrefs are dropped and grant no more */
1214 proc_childdrainstart(p
);
1215 while ((q
= p
->p_children
.lh_first
) != NULL
) {
1216 int reparentedtoinit
= (q
->p_listflag
& P_LIST_DEADPARENT
) ? 1 : 0;
1217 if (q
->p_stat
== SZOMB
) {
1219 panic("parent child linkage broken");
1220 /* check for sysctl zomb lookup */
1221 while ((q
->p_listflag
& P_LIST_WAITING
) == P_LIST_WAITING
) {
1222 msleep(&q
->p_stat
, proc_list_mlock
, PWAIT
, "waitcoll", 0);
1224 q
->p_listflag
|= P_LIST_WAITING
;
1226 * This is a named reference and it is not granted
1227 * if the reap is already in progress. So we get
1228 * the reference here exclusively and their can be
1229 * no waiters. So there is no need for a wakeup
1230 * after we are done. Also the reap frees the structure
1231 * and the proc struct cannot be used for wakeups as well.
1232 * It is safe to use q here as this is system reap
1234 (void)reap_child_locked(p
, q
, 1, reparentedtoinit
, 1, 0);
1237 * Traced processes are killed
1238 * since their existence means someone is messing up.
1240 if (q
->p_lflag
& P_LTRACED
) {
1244 * Take a reference on the child process to
1245 * ensure it doesn't exit and disappear between
1246 * the time we drop the list_lock and attempt
1247 * to acquire its proc_lock.
1249 if (proc_ref_locked(q
) != q
)
1254 opp
= proc_find(q
->p_oppid
);
1255 if (opp
!= PROC_NULL
) {
1259 proc_reparentlocked(q
, opp
, 0, 0);
1262 /* original parent exited while traced */
1264 q
->p_listflag
|= P_LIST_DEADPARENT
;
1267 proc_reparentlocked(q
, initproc
, 0, 0);
1271 q
->p_lflag
&= ~P_LTRACED
;
1273 if (q
->sigwait_thread
) {
1274 thread_t thread
= q
->sigwait_thread
;
1278 * The sigwait_thread could be stopped at a
1279 * breakpoint. Wake it up to kill.
1280 * Need to do this as it could be a thread which is not
1281 * the first thread in the task. So any attempts to kill
1282 * the process would result into a deadlock on q->sigwait.
1284 thread_resume(thread
);
1285 clear_wait(thread
, THREAD_INTERRUPTED
);
1286 threadsignal(thread
, SIGKILL
, 0, TRUE
);
1291 psignal(q
, SIGKILL
);
1293 proc_rele_locked(q
);
1295 q
->p_listflag
|= P_LIST_DEADPARENT
;
1296 proc_reparentlocked(q
, initproc
, 0, 1);
1301 proc_childdrainend(p
);
1306 * Notify MAC policies that proc is dead.
1307 * This should be replaced with proper label management
1308 * (rdar://problem/32126399).
1310 mac_proc_notify_exit(p
);
1314 * Release reference to text vnode
1318 if (tvp
!= NULLVP
) {
1323 * Save exit status and final rusage info, adding in child rusage
1324 * info and self times. If we were unable to allocate a zombie
1325 * structure, this information is lost.
1327 if (p
->p_ru
!= NULL
) {
1328 calcru(p
, &p
->p_stats
->p_ru
.ru_utime
, &p
->p_stats
->p_ru
.ru_stime
, NULL
);
1329 p
->p_ru
->ru
= p
->p_stats
->p_ru
;
1331 ruadd(&(p
->p_ru
->ru
), &p
->p_stats
->p_cru
);
1335 * Free up profiling buffers.
1338 struct uprof
*p0
= &p
->p_stats
->p_prof
, *p1
, *pn
;
1344 for (; p1
!= NULL
; p1
= pn
) {
1346 kfree(p1
, sizeof *p1
);
1350 proc_free_realitimer(p
);
1353 * Other substructures are freed from wait().
1355 FREE_ZONE(p
->p_stats
, sizeof *p
->p_stats
, M_PSTATS
);
1358 FREE_ZONE(p
->p_sigacts
, sizeof *p
->p_sigacts
, M_SIGACTS
);
1359 p
->p_sigacts
= NULL
;
1361 proc_limitdrop(p
, 1);
1364 vm_purgeable_disown(p
->task
);
1367 * Finish up by terminating the task
1368 * and halt this thread (only if a
1369 * member of the task exiting).
1371 p
->task
= TASK_NULL
;
1372 set_bsdtask_info(task
, NULL
);
1374 knote_hint
= NOTE_EXIT
| (p
->p_xstat
& 0xffff);
1375 proc_knote(p
, knote_hint
);
1377 /* mark the thread as the one that is doing proc_exit
1378 * no need to hold proc lock in uthread_free
1380 uth
->uu_flag
|= UT_PROCEXIT
;
1382 * Notify parent that we're gone.
1384 pp
= proc_parent(p
);
1385 if (pp
->p_flag
& P_NOCLDWAIT
) {
1387 if (p
->p_ru
!= NULL
) {
1391 * If the parent is ignoring SIGCHLD, then POSIX requires
1392 * us to not add the resource usage to the parent process -
1393 * we are only going to hand it off to init to get reaped.
1394 * We should contest the standard in this case on the basis
1397 #else /* !3839178 */
1399 * Add child resource usage to parent before giving
1400 * zombie to init. If we were unable to allocate a
1401 * zombie structure, this information is lost.
1403 ruadd(&pp
->p_stats
->p_cru
, &p
->p_ru
->ru
);
1404 #endif /* !3839178 */
1405 update_rusage_info_child(&pp
->p_stats
->ri_child
, &p
->p_ru
->ri
);
1409 /* kernel can reap this one, no need to move it to launchd */
1411 p
->p_listflag
|= P_LIST_DEADPARENT
;
1414 if ((p
->p_listflag
& P_LIST_DEADPARENT
) == 0 || p
->p_oppid
) {
1415 if (pp
!= initproc
) {
1417 pp
->si_pid
= p
->p_pid
;
1418 pp
->p_xhighbits
= p
->p_xhighbits
;
1420 pp
->si_status
= p
->p_xstat
;
1421 pp
->si_code
= CLD_EXITED
;
1423 * p_ucred usage is safe as it is an exiting process
1424 * and reference is dropped in reap
1426 pp
->si_uid
= kauth_cred_getruid(p
->p_ucred
);
1429 /* mark as a zombie */
1430 /* No need to take proc lock as all refs are drained and
1431 * no one except parent (reaping ) can look at this.
1432 * The write is to an int and is coherent. Also parent is
1433 * keyed off of list lock for reaping
1435 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON
,
1436 BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXIT
) | DBG_FUNC_END
,
1437 pid
, exitval
, 0, 0, 0);
1440 * The current process can be reaped so, no one
1441 * can depend on this
1444 psignal(pp
, SIGCHLD
);
1446 /* and now wakeup the parent */
1448 wakeup((caddr_t
)pp
);
1451 /* should be fine as parent proc would be initproc */
1452 /* mark as a zombie */
1453 /* No need to take proc lock as all refs are drained and
1454 * no one except parent (reaping ) can look at this.
1455 * The write is to an int and is coherent. Also parent is
1456 * keyed off of list lock for reaping
1459 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON
,
1460 BSDDBG_CODE(DBG_BSD_PROC
, BSD_PROC_EXIT
) | DBG_FUNC_END
,
1461 pid
, exitval
, 0, 0, 0);
1462 /* check for sysctl zomb lookup */
1463 while ((p
->p_listflag
& P_LIST_WAITING
) == P_LIST_WAITING
) {
1464 msleep(&p
->p_stat
, proc_list_mlock
, PWAIT
, "waitcoll", 0);
1466 /* safe to use p as this is a system reap */
1468 p
->p_listflag
|= P_LIST_WAITING
;
1471 * This is a named reference and it is not granted
1472 * if the reap is already in progress. So we get
1473 * the reference here exclusively and their can be
1474 * no waiters. So there is no need for a wakeup
1475 * after we are done. AlsO the reap frees the structure
1476 * and the proc struct cannot be used for wakeups as well.
1477 * It is safe to use p here as this is system reap
1479 (void)reap_child_locked(pp
, p
, 1, 0, 1, 1);
1480 /* list lock dropped by reap_child_locked */
1482 if (uth
->uu_lowpri_window
) {
1484 * task is marked as a low priority I/O type and we've
1485 * somehow picked up another throttle during exit processing...
1486 * no need to throttle this thread since its going away
1487 * but we do need to update our bookeeping w/r to throttled threads
1489 throttle_lowpri_io(0);
1500 * Description: Given a process from which all status information needed
1501 * has already been extracted, if the process is a ptrace
1502 * attach process, detach it and give it back to its real
1503 * parent, else recover all resources remaining associated
1506 * Parameters: proc_t parent Parent of process being reaped
1507 * proc_t child Process to reap
1509 * Returns: 0 Process was not reaped because it
1510 * came from an attach
1511 * 1 Process was reaped
1514 reap_child_locked(proc_t parent
, proc_t child
, int deadparent
, int reparentedtoinit
, int locked
, int droplock
)
1516 proc_t trace_parent
= PROC_NULL
; /* Traced parent process, if tracing */
1522 * If we got the child via a ptrace 'attach',
1523 * we need to give it back to the old parent.
1525 * Exception: someone who has been reparented to launchd before being
1526 * ptraced can simply be reaped, refer to radar 5677288
1527 * p_oppid -> ptraced
1528 * trace_parent == initproc -> away from launchd
1529 * reparentedtoinit -> came to launchd by reparenting
1531 if (child
->p_oppid
) {
1536 oppid
= child
->p_oppid
;
1538 knote_hint
= NOTE_EXIT
| (child
->p_xstat
& 0xffff);
1541 if ((trace_parent
= proc_find(oppid
))
1542 && !((trace_parent
== initproc
) && reparentedtoinit
)) {
1544 if (trace_parent
!= initproc
) {
1546 * proc internal fileds and p_ucred usage safe
1547 * here as child is dead and is not reaped or
1550 proc_lock(trace_parent
);
1551 trace_parent
->si_pid
= child
->p_pid
;
1552 trace_parent
->si_status
= child
->p_xstat
;
1553 trace_parent
->si_code
= CLD_CONTINUED
;
1554 trace_parent
->si_uid
= kauth_cred_getruid(child
->p_ucred
);
1555 proc_unlock(trace_parent
);
1557 proc_reparentlocked(child
, trace_parent
, 1, 0);
1559 /* resend knote to original parent (and others) after reparenting */
1560 proc_knote(child
, knote_hint
);
1562 psignal(trace_parent
, SIGCHLD
);
1564 wakeup((caddr_t
)trace_parent
);
1565 child
->p_listflag
&= ~P_LIST_WAITING
;
1566 wakeup(&child
->p_stat
);
1568 proc_rele(trace_parent
);
1569 if ((locked
== 1) && (droplock
== 0))
1575 * If we can't reparent (e.g. the original parent exited while child was being debugged, or
1576 * original parent is the same as the debugger currently exiting), we still need to satisfy
1577 * the knote lifecycle for other observers on the system. While the debugger was attached,
1578 * the NOTE_EXIT would not have been broadcast during initial child termination.
1580 proc_knote(child
, knote_hint
);
1582 if (trace_parent
!= PROC_NULL
) {
1583 proc_rele(trace_parent
);
1587 #pragma clang diagnostic push
1588 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1589 proc_knote(child
, NOTE_REAP
);
1590 #pragma clang diagnostic pop
1592 proc_knote_drain(child
);
1599 * If the parent is ignoring SIGCHLD, then POSIX requires
1600 * us to not add the resource usage to the parent process -
1601 * we are only going to hand it off to init to get reaped.
1602 * We should contest the standard in this case on the basis
1605 if (!(parent
->p_flag
& P_NOCLDWAIT
))
1606 #endif /* 3839178 */
1607 ruadd(&parent
->p_stats
->p_cru
, &child
->p_ru
->ru
);
1608 update_rusage_info_child(&parent
->p_stats
->ri_child
, &child
->p_ru
->ri
);
1609 proc_unlock(parent
);
1610 FREE_ZONE(child
->p_ru
, sizeof *child
->p_ru
, M_ZOMBIE
);
1613 printf("Warning : lost p_ru for %s\n", child
->p_comm
);
1616 AUDIT_SESSION_PROCEXIT(child
);
1619 * Decrement the count of procs running with this uid.
1620 * p_ucred usage is safe here as it is an exited process.
1621 * and refernce is dropped after these calls down below
1622 * (locking protection is provided by list lock held in chgproccnt)
1626 * persona_proc_drop calls chgproccnt(-1) on the persona uid,
1627 * and (+1) on the child->p_ucred uid
1629 persona_proc_drop(child
);
1631 (void)chgproccnt(kauth_cred_getruid(child
->p_ucred
), -1);
1633 os_reason_free(child
->p_exit_reason
);
1636 * Free up credentials.
1638 if (IS_VALID_CRED(child
->p_ucred
)) {
1639 kauth_cred_unref(&child
->p_ucred
);
1642 /* XXXX Note NOT SAFE TO USE p_ucred from this point onwards */
1645 * Finally finished with old proc entry.
1646 * Unlink it from its process group and free it.
1651 LIST_REMOVE(child
, p_list
); /* off zombproc */
1652 parent
->p_childrencnt
--;
1653 LIST_REMOVE(child
, p_sibling
);
1654 /* If there are no more children wakeup parent */
1655 if ((deadparent
!= 0) && (LIST_EMPTY(&parent
->p_children
)))
1656 wakeup((caddr_t
)parent
); /* with list lock held */
1657 child
->p_listflag
&= ~P_LIST_WAITING
;
1658 wakeup(&child
->p_stat
);
1660 /* Take it out of process hash */
1661 LIST_REMOVE(child
, p_hash
);
1662 child
->p_listflag
&= ~P_LIST_INHASH
;
1663 proc_checkdeadrefs(child
);
1668 * If a child zombie is being reaped because its parent
1669 * is exiting, make sure we update the list flag
1671 child
->p_listflag
|= P_LIST_DEADPARENT
;
1676 #if CONFIG_FINE_LOCK_GROUPS
1677 lck_mtx_destroy(&child
->p_mlock
, proc_mlock_grp
);
1678 lck_mtx_destroy(&child
->p_ucred_mlock
, proc_ucred_mlock_grp
);
1679 lck_mtx_destroy(&child
->p_fdmlock
, proc_fdmlock_grp
);
1681 lck_mtx_destroy(&child
->p_dtrace_sprlock
, proc_lck_grp
);
1683 lck_spin_destroy(&child
->p_slock
, proc_slock_grp
);
1684 #else /* CONFIG_FINE_LOCK_GROUPS */
1685 lck_mtx_destroy(&child
->p_mlock
, proc_lck_grp
);
1686 lck_mtx_destroy(&child
->p_ucred_mlock
, proc_lck_grp
);
1687 lck_mtx_destroy(&child
->p_fdmlock
, proc_lck_grp
);
1689 lck_mtx_destroy(&child
->p_dtrace_sprlock
, proc_lck_grp
);
1691 lck_spin_destroy(&child
->p_slock
, proc_lck_grp
);
1692 #endif /* CONFIG_FINE_LOCK_GROUPS */
1694 FREE_ZONE(child
, sizeof *child
, M_PROC
);
1695 if ((locked
== 1) && (droplock
== 0))
1703 wait1continue(int result
)
1708 struct _wait4_data
*wait4_data
;
1709 struct wait4_nocancel_args
*uap
;
1716 thread
= current_thread();
1717 uth
= (struct uthread
*)get_bsdthread_info(thread
);
1719 wait4_data
= &uth
->uu_kevent
.uu_wait4_data
;
1720 uap
= wait4_data
->args
;
1721 retval
= wait4_data
->retval
;
1722 return(wait4_nocancel(p
, uap
, retval
));
1726 wait4(proc_t q
, struct wait4_args
*uap
, int32_t *retval
)
1728 __pthread_testcancel(1);
1729 return(wait4_nocancel(q
, (struct wait4_nocancel_args
*)uap
, retval
));
1733 wait4_nocancel(proc_t q
, struct wait4_nocancel_args
*uap
, int32_t *retval
)
1740 struct _wait4_data
*wait4_data
;
1742 AUDIT_ARG(pid
, uap
->pid
);
1745 uap
->pid
= -q
->p_pgrpid
;
1753 PCHILDREN_FOREACH(q
, p
) {
1754 if ( p
->p_sibling
.le_next
!= 0 )
1756 if (uap
->pid
!= WAIT_ANY
&&
1757 p
->p_pid
!= uap
->pid
&&
1758 p
->p_pgrpid
!= -(uap
->pid
))
1763 /* XXX This is racy because we don't get the lock!!!! */
1765 if (p
->p_listflag
& P_LIST_WAITING
) {
1766 (void)msleep(&p
->p_stat
, proc_list_mlock
, PWAIT
, "waitcoll", 0);
1769 p
->p_listflag
|= P_LIST_WAITING
; /* only allow single thread to wait() */
1772 if (p
->p_stat
== SZOMB
) {
1773 int reparentedtoinit
= (p
->p_listflag
& P_LIST_DEADPARENT
) ? 1 : 0;
1777 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
1780 retval
[0] = p
->p_pid
;
1782 /* Legacy apps expect only 8 bits of status */
1783 status
= 0xffff & p
->p_xstat
; /* convert to int */
1784 error
= copyout((caddr_t
)&status
,
1791 if (p
->p_ru
== NULL
) {
1794 if (IS_64BIT_PROCESS(q
)) {
1795 struct user64_rusage my_rusage
= {};
1796 munge_user64_rusage(&p
->p_ru
->ru
, &my_rusage
);
1797 error
= copyout((caddr_t
)&my_rusage
,
1799 sizeof (my_rusage
));
1802 struct user32_rusage my_rusage
= {};
1803 munge_user32_rusage(&p
->p_ru
->ru
, &my_rusage
);
1804 error
= copyout((caddr_t
)&my_rusage
,
1806 sizeof (my_rusage
));
1809 /* information unavailable? */
1814 /* Conformance change for 6577252.
1815 * When SIGCHLD is blocked and wait() returns because the status
1816 * of a child process is available and there are no other
1817 * children processes, then any pending SIGCHLD signal is cleared.
1819 if ( sibling_count
== 0 ) {
1820 int mask
= sigmask(SIGCHLD
);
1821 uth
= current_uthread();
1823 if ( (uth
->uu_sigmask
& mask
) != 0 ) {
1824 /* we are blocking SIGCHLD signals. clear any pending SIGCHLD.
1825 * This locking looks funny but it is protecting access to the
1826 * thread via p_uthlist.
1829 uth
->uu_siglist
&= ~mask
; /* clear pending signal */
1835 (void)reap_child_locked(q
, p
, 0, reparentedtoinit
, 0, 0);
1839 if (p
->p_stat
== SSTOP
&& (p
->p_lflag
& P_LWAITED
) == 0 &&
1840 (p
->p_lflag
& P_LTRACED
|| uap
->options
& WUNTRACED
)) {
1843 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
1847 p
->p_lflag
|= P_LWAITED
;
1849 retval
[0] = p
->p_pid
;
1851 status
= W_STOPCODE(p
->p_xstat
);
1852 error
= copyout((caddr_t
)&status
,
1860 * If we are waiting for continued processses, and this
1861 * process was continued
1863 if ((uap
->options
& WCONTINUED
) &&
1864 (p
->p_flag
& P_CONTINUED
)) {
1867 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
1871 /* Prevent other process for waiting for this event */
1872 OSBitAndAtomic(~((uint32_t)P_CONTINUED
), &p
->p_flag
);
1873 retval
[0] = p
->p_pid
;
1875 status
= W_STOPCODE(SIGCONT
);
1876 error
= copyout((caddr_t
)&status
,
1883 p
->p_listflag
&= ~P_LIST_WAITING
;
1886 /* list lock is held when we get here any which way */
1892 if (uap
->options
& WNOHANG
) {
1898 /* Save arguments for continuation. Backing storage is in uthread->uu_arg, and will not be deallocated */
1899 uth
= current_uthread();
1900 wait4_data
= &uth
->uu_kevent
.uu_wait4_data
;
1901 wait4_data
->args
= uap
;
1902 wait4_data
->retval
= retval
;
1904 if ((error
= msleep0((caddr_t
)q
, proc_list_mlock
, PWAIT
| PCATCH
| PDROP
, "wait", 0, wait1continue
)))
1910 p
->p_listflag
&= ~P_LIST_WAITING
;
1917 #define ASSERT_LCK_MTX_OWNED(lock) \
1918 lck_mtx_assert(lock, LCK_MTX_ASSERT_OWNED)
1920 #define ASSERT_LCK_MTX_OWNED(lock) /* nothing */
1924 waitidcontinue(int result
)
1929 struct _waitid_data
*waitid_data
;
1930 struct waitid_nocancel_args
*uap
;
1937 thread
= current_thread();
1938 uth
= (struct uthread
*)get_bsdthread_info(thread
);
1940 waitid_data
= &uth
->uu_kevent
.uu_waitid_data
;
1941 uap
= waitid_data
->args
;
1942 retval
= waitid_data
->retval
;
1943 return(waitid_nocancel(p
, uap
, retval
));
1947 * Description: Suspend the calling thread until one child of the process
1948 * containing the calling thread changes state.
1950 * Parameters: uap->idtype one of P_PID, P_PGID, P_ALL
1951 * uap->id pid_t or gid_t or ignored
1952 * uap->infop Address of siginfo_t struct in
1953 * user space into which to return status
1954 * uap->options flag values
1956 * Returns: 0 Success
1957 * !0 Error returning status to user space
1960 waitid(proc_t q
, struct waitid_args
*uap
, int32_t *retval
)
1962 __pthread_testcancel(1);
1963 return (waitid_nocancel(q
, (struct waitid_nocancel_args
*)uap
, retval
));
1967 waitid_nocancel(proc_t q
, struct waitid_nocancel_args
*uap
,
1968 __unused
int32_t *retval
)
1970 user_siginfo_t siginfo
; /* siginfo data to return to caller */
1971 boolean_t caller64
= IS_64BIT_PROCESS(q
);
1976 struct _waitid_data
*waitid_data
;
1978 if (uap
->options
== 0 ||
1979 (uap
->options
& ~(WNOHANG
|WNOWAIT
|WCONTINUED
|WSTOPPED
|WEXITED
)))
1980 return (EINVAL
); /* bits set that aren't recognized */
1982 switch (uap
->idtype
) {
1983 case P_PID
: /* child with process ID equal to... */
1984 case P_PGID
: /* child with process group ID equal to... */
1985 if (((int)uap
->id
) < 0)
1988 case P_ALL
: /* any child */
1997 PCHILDREN_FOREACH(q
, p
) {
1998 switch (uap
->idtype
) {
1999 case P_PID
: /* child with process ID equal to... */
2000 if (p
->p_pid
!= (pid_t
)uap
->id
)
2003 case P_PGID
: /* child with process group ID equal to... */
2004 if (p
->p_pgrpid
!= (pid_t
)uap
->id
)
2007 case P_ALL
: /* any child */
2011 /* XXX This is racy because we don't get the lock!!!! */
2014 * Wait collision; go to sleep and restart; used to maintain
2015 * the single return for waited process guarantee.
2017 if (p
->p_listflag
& P_LIST_WAITING
) {
2018 (void) msleep(&p
->p_stat
, proc_list_mlock
,
2019 PWAIT
, "waitidcoll", 0);
2022 p
->p_listflag
|= P_LIST_WAITING
; /* mark busy */
2026 bzero(&siginfo
, sizeof (siginfo
));
2028 switch (p
->p_stat
) {
2029 case SZOMB
: /* Exited */
2030 if (!(uap
->options
& WEXITED
))
2034 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
2037 siginfo
.si_signo
= SIGCHLD
;
2038 siginfo
.si_pid
= p
->p_pid
;
2039 siginfo
.si_status
= (WEXITSTATUS(p
->p_xstat
) & 0x00FFFFFF) | (((uint32_t)(p
->p_xhighbits
) << 24) & 0xFF000000);
2041 if (WIFSIGNALED(p
->p_xstat
)) {
2042 siginfo
.si_code
= WCOREDUMP(p
->p_xstat
) ?
2043 CLD_DUMPED
: CLD_KILLED
;
2045 siginfo
.si_code
= CLD_EXITED
;
2047 if ((error
= copyoutsiginfo(&siginfo
,
2048 caller64
, uap
->infop
)) != 0)
2051 /* Prevent other process for waiting for this event? */
2052 if (!(uap
->options
& WNOWAIT
)) {
2053 (void) reap_child_locked(q
, p
, 0, 0, 0, 0);
2058 case SSTOP
: /* Stopped */
2060 * If we are not interested in stopped processes, then
2063 if (!(uap
->options
& WSTOPPED
))
2067 * If someone has already waited it, we lost a race
2068 * to be the one to return status.
2070 if ((p
->p_lflag
& P_LWAITED
) != 0)
2074 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
2077 siginfo
.si_signo
= SIGCHLD
;
2078 siginfo
.si_pid
= p
->p_pid
;
2079 siginfo
.si_status
= p
->p_xstat
; /* signal number */
2080 siginfo
.si_code
= CLD_STOPPED
;
2082 if ((error
= copyoutsiginfo(&siginfo
,
2083 caller64
, uap
->infop
)) != 0)
2086 /* Prevent other process for waiting for this event? */
2087 if (!(uap
->options
& WNOWAIT
)) {
2089 p
->p_lflag
|= P_LWAITED
;
2094 default: /* All other states => Continued */
2095 if (!(uap
->options
& WCONTINUED
))
2099 * If the flag isn't set, then this process has not
2100 * been stopped and continued, or the status has
2101 * already been reaped by another caller of waitid().
2103 if ((p
->p_flag
& P_CONTINUED
) == 0)
2107 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
2110 siginfo
.si_signo
= SIGCHLD
;
2111 siginfo
.si_code
= CLD_CONTINUED
;
2113 siginfo
.si_pid
= p
->p_contproc
;
2114 siginfo
.si_status
= p
->p_xstat
;
2117 if ((error
= copyoutsiginfo(&siginfo
,
2118 caller64
, uap
->infop
)) != 0)
2121 /* Prevent other process for waiting for this event? */
2122 if (!(uap
->options
& WNOWAIT
)) {
2123 OSBitAndAtomic(~((uint32_t)P_CONTINUED
),
2128 ASSERT_LCK_MTX_OWNED(proc_list_mlock
);
2130 /* Not a process we are interested in; go on to next child */
2132 p
->p_listflag
&= ~P_LIST_WAITING
;
2135 ASSERT_LCK_MTX_OWNED(proc_list_mlock
);
2137 /* No child processes that could possibly satisfy the request? */
2144 if (uap
->options
& WNOHANG
) {
2147 if ((error
= mac_proc_check_wait(q
, p
)) != 0)
2151 * The state of the siginfo structure in this case
2152 * is undefined. Some implementations bzero it, some
2153 * (like here) leave it untouched for efficiency.
2155 * Thus the most portable check for "no matching pid with
2156 * WNOHANG" is to store a zero into si_pid before
2157 * invocation, then check for a non-zero value afterwards.
2162 /* Save arguments for continuation. Backing storage is in uthread->uu_arg, and will not be deallocated */
2163 uth
= current_uthread();
2164 waitid_data
= &uth
->uu_kevent
.uu_waitid_data
;
2165 waitid_data
->args
= uap
;
2166 waitid_data
->retval
= retval
;
2168 if ((error
= msleep0(q
, proc_list_mlock
,
2169 PWAIT
| PCATCH
| PDROP
, "waitid", 0, waitidcontinue
)) != 0)
2175 p
->p_listflag
&= ~P_LIST_WAITING
;
2182 * make process 'parent' the new parent of process 'child'.
2185 proc_reparentlocked(proc_t child
, proc_t parent
, int signallable
, int locked
)
2187 proc_t oldparent
= PROC_NULL
;
2189 if (child
->p_pptr
== parent
)
2195 oldparent
= child
->p_pptr
;
2196 #if __PROC_INTERNAL_DEBUG
2197 if (oldparent
== PROC_NULL
)
2198 panic("proc_reparent: process %p does not have a parent\n", child
);
2201 LIST_REMOVE(child
, p_sibling
);
2202 #if __PROC_INTERNAL_DEBUG
2203 if (oldparent
->p_childrencnt
== 0)
2204 panic("process children count already 0\n");
2206 oldparent
->p_childrencnt
--;
2207 #if __PROC_INTERNAL_DEBUG1
2208 if (oldparent
->p_childrencnt
< 0)
2209 panic("process children count -ve\n");
2211 LIST_INSERT_HEAD(&parent
->p_children
, child
, p_sibling
);
2212 parent
->p_childrencnt
++;
2213 child
->p_pptr
= parent
;
2214 child
->p_ppid
= parent
->p_pid
;
2218 if ((signallable
!= 0) && (initproc
== parent
) && (child
->p_stat
== SZOMB
))
2219 psignal(initproc
, SIGCHLD
);
2225 * Exit: deallocate address space and other resources, change proc state
2226 * to zombie, and unlink proc from allproc and parent's lists. Save exit
2227 * status and rusage for wait(). Check for child processes and orphan them.
2231 vfork_exit(proc_t p
, int rv
)
2233 vfork_exit_internal(p
, rv
, 0);
2237 vfork_exit_internal(proc_t p
, int rv
, int forceexit
)
2239 thread_t self
= current_thread();
2241 struct task
*task
= p
->task
;
2246 * If a thread in this task has already
2247 * called exit(), then halt any others
2251 ut
= get_bsdthread_info(self
);
2255 if ((p
->p_lflag
& P_LPEXIT
) == P_LPEXIT
) {
2257 * This happens when a parent exits/killed and vfork is in progress
2258 * other threads. But shutdown code for ex has already called exit1()
2263 p
->p_lflag
|= (P_LEXIT
| P_LPEXIT
);
2266 if (forceexit
== 0) {
2268 * parent of a vfork child has already called exit() and the
2269 * thread that has vfork in proress terminates. So there is no
2270 * separate address space here and it has already been marked for
2271 * termination. This was never covered before and could cause problems
2272 * if we block here for outside code.
2274 /* Notify the perf server */
2275 (void)sys_perf_notify(self
, p
->p_pid
);
2279 * Remove proc from allproc queue and from pidhash chain.
2280 * Need to do this before we do anything that can block.
2281 * Not doing causes things like mount() find this on allproc
2282 * in partially cleaned state.
2287 #if CONFIG_MEMORYSTATUS
2288 memorystatus_remove(p
, TRUE
);
2291 LIST_REMOVE(p
, p_list
);
2292 LIST_INSERT_HEAD(&zombproc
, p
, p_list
); /* Place onto zombproc. */
2293 /* will not be visible via proc_find */
2294 p
->p_listflag
|= P_LIST_EXITED
;
2300 p
->p_lflag
&= ~(P_LTRACED
| P_LPPWAIT
);
2301 p
->p_sigignore
= ~0;
2306 /* begin vproc_exit */
2314 struct session
*sessp
;
2315 struct rusage_superset
*rup
;
2317 /* XXX Zombie allocation may fail, in which case stats get lost */
2318 MALLOC_ZONE(rup
, struct rusage_superset
*,
2319 sizeof (*rup
), M_ZOMBIE
, M_WAITOK
);
2324 * Close open files and release open-file table.
2329 sessp
= proc_session(p
);
2330 if (SESS_LEADER(p
, sessp
)) {
2332 if (sessp
->s_ttyvp
!= NULLVP
) {
2333 struct vnode
*ttyvp
;
2336 struct vfs_context context
;
2340 * Controlling process.
2341 * Signal foreground pgrp,
2342 * drain controlling terminal
2343 * and revoke access to controlling terminal.
2345 session_lock(sessp
);
2346 tp
= SESSION_TP(sessp
);
2347 if ((tp
!= TTY_NULL
) && (tp
->t_session
== sessp
)) {
2348 session_unlock(sessp
);
2351 * We're going to SIGHUP the foreground process
2352 * group. It can't change from this point on
2353 * until the revoke is complete.
2354 * The process group changes under both the tty
2355 * lock and proc_list_lock but we need only one
2361 tty_pgsignal(tp
, SIGHUP
, 1);
2363 session_lock(sessp
);
2364 tp
= SESSION_TP(sessp
);
2366 cttyflag
= sessp
->s_flags
& S_CTTYREF
;
2367 sessp
->s_flags
&= ~S_CTTYREF
;
2368 ttyvp
= sessp
->s_ttyvp
;
2369 ttyvid
= sessp
->s_ttyvid
;
2370 sessp
->s_ttyvp
= NULL
;
2371 sessp
->s_ttyvid
= 0;
2372 sessp
->s_ttyp
= TTY_NULL
;
2373 sessp
->s_ttypgrpid
= NO_PID
;
2374 session_unlock(sessp
);
2376 if ((ttyvp
!= NULLVP
) && (vnode_getwithvid(ttyvp
, ttyvid
) == 0)) {
2377 if (tp
!= TTY_NULL
) {
2382 context
.vc_thread
= proc_thread(p
); /* XXX */
2383 context
.vc_ucred
= kauth_cred_proc_ref(p
);
2384 VNOP_REVOKE(ttyvp
, REVOKEALL
, &context
);
2387 * Release the extra usecount taken in cttyopen.
2388 * usecount should be released after VNOP_REVOKE is called.
2389 * This usecount was taken to ensure that
2390 * the VNOP_REVOKE results in a close to
2391 * the tty since cttyclose is a no-op.
2396 kauth_cred_unref(&context
.vc_ucred
);
2401 * This is cleared even if not set. This is also done in
2402 * spec_close to ensure that the flag is cleared.
2411 session_lock(sessp
);
2412 sessp
->s_leader
= NULL
;
2413 session_unlock(sessp
);
2415 session_rele(sessp
);
2421 p
->p_rlimit
[RLIMIT_FSIZE
].rlim_cur
= RLIM_INFINITY
;
2424 proc_childdrainstart(p
);
2425 while ((q
= p
->p_children
.lh_first
) != NULL
) {
2426 if (q
->p_stat
== SZOMB
) {
2428 panic("parent child linkage broken");
2429 /* check for lookups by zomb sysctl */
2430 while ((q
->p_listflag
& P_LIST_WAITING
) == P_LIST_WAITING
) {
2431 msleep(&q
->p_stat
, proc_list_mlock
, PWAIT
, "waitcoll", 0);
2433 q
->p_listflag
|= P_LIST_WAITING
;
2435 * This is a named reference and it is not granted
2436 * if the reap is already in progress. So we get
2437 * the reference here exclusively and their can be
2438 * no waiters. So there is no need for a wakeup
2439 * after we are done. AlsO the reap frees the structure
2440 * and the proc struct cannot be used for wakeups as well.
2441 * It is safe to use q here as this is system reap
2443 (void)reap_child_locked(p
, q
, 1, 0, 1, 0);
2446 * Traced processes are killed
2447 * since their existence means someone is messing up.
2449 if (q
->p_lflag
& P_LTRACED
) {
2454 opp
= proc_find(q
->p_oppid
);
2455 if (opp
!= PROC_NULL
) {
2459 proc_reparentlocked(q
, opp
, 0, 0);
2462 /* original parent exited while traced */
2464 q
->p_listflag
|= P_LIST_DEADPARENT
;
2467 proc_reparentlocked(q
, initproc
, 0, 0);
2471 q
->p_lflag
&= ~P_LTRACED
;
2473 if (q
->sigwait_thread
) {
2474 thread_t thread
= q
->sigwait_thread
;
2478 * The sigwait_thread could be stopped at a
2479 * breakpoint. Wake it up to kill.
2480 * Need to do this as it could be a thread which is not
2481 * the first thread in the task. So any attempts to kill
2482 * the process would result into a deadlock on q->sigwait.
2484 thread_resume(thread
);
2485 clear_wait(thread
, THREAD_INTERRUPTED
);
2486 threadsignal(thread
, SIGKILL
, 0, TRUE
);
2491 psignal(q
, SIGKILL
);
2494 q
->p_listflag
|= P_LIST_DEADPARENT
;
2495 proc_reparentlocked(q
, initproc
, 0, 1);
2500 proc_childdrainend(p
);
2504 * Release reference to text vnode
2508 if (tvp
!= NULLVP
) {
2513 * Save exit status and final rusage info, adding in child rusage
2514 * info and self times. If we were unable to allocate a zombie
2515 * structure, this information is lost.
2518 rup
->ru
= p
->p_stats
->p_ru
;
2519 timerclear(&rup
->ru
.ru_utime
);
2520 timerclear(&rup
->ru
.ru_stime
);
2524 mach_task_basic_info_data_t tinfo
;
2525 task_thread_times_info_data_t ttimesinfo
;
2526 int task_info_stuff
, task_ttimes_stuff
;
2527 struct timeval ut
,st
;
2529 task_info_stuff
= MACH_TASK_BASIC_INFO_COUNT
;
2530 task_info(task
, MACH_TASK_BASIC_INFO
,
2531 &tinfo
, &task_info_stuff
);
2532 p
->p_ru
->ru
.ru_utime
.tv_sec
= tinfo
.user_time
.seconds
;
2533 p
->p_ru
->ru
.ru_utime
.tv_usec
= tinfo
.user_time
.microseconds
;
2534 p
->p_ru
->ru
.ru_stime
.tv_sec
= tinfo
.system_time
.seconds
;
2535 p
->p_ru
->ru
.ru_stime
.tv_usec
= tinfo
.system_time
.microseconds
;
2537 task_ttimes_stuff
= TASK_THREAD_TIMES_INFO_COUNT
;
2538 task_info(task
, TASK_THREAD_TIMES_INFO
,
2539 &ttimesinfo
, &task_ttimes_stuff
);
2541 ut
.tv_sec
= ttimesinfo
.user_time
.seconds
;
2542 ut
.tv_usec
= ttimesinfo
.user_time
.microseconds
;
2543 st
.tv_sec
= ttimesinfo
.system_time
.seconds
;
2544 st
.tv_usec
= ttimesinfo
.system_time
.microseconds
;
2545 timeradd(&ut
,&p
->p_ru
->ru
.ru_utime
,&p
->p_ru
->ru
.ru_utime
);
2546 timeradd(&st
,&p
->p_ru
->ru
.ru_stime
,&p
->p_ru
->ru
.ru_stime
);
2550 ruadd(&rup
->ru
, &p
->p_stats
->p_cru
);
2552 gather_rusage_info(p
, &rup
->ri
, RUSAGE_INFO_CURRENT
);
2553 rup
->ri
.ri_phys_footprint
= 0;
2554 rup
->ri
.ri_proc_exit_abstime
= mach_absolute_time();
2557 * Now that we have filled in the rusage info, make it
2558 * visible to an external observer via proc_pid_rusage().
2564 * Free up profiling buffers.
2567 struct uprof
*p0
= &p
->p_stats
->p_prof
, *p1
, *pn
;
2573 for (; p1
!= NULL
; p1
= pn
) {
2575 kfree(p1
, sizeof *p1
);
2580 pth_proc_hashdelete(p
);
2583 proc_free_realitimer(p
);
2586 * Other substructures are freed from wait().
2588 FREE_ZONE(p
->p_stats
, sizeof *p
->p_stats
, M_PSTATS
);
2591 FREE_ZONE(p
->p_sigacts
, sizeof *p
->p_sigacts
, M_SIGACTS
);
2592 p
->p_sigacts
= NULL
;
2594 proc_limitdrop(p
, 1);
2598 * Finish up by terminating the task
2599 * and halt this thread (only if a
2600 * member of the task exiting).
2602 p
->task
= TASK_NULL
;
2605 * Notify parent that we're gone.
2607 pp
= proc_parent(p
);
2608 if ((p
->p_listflag
& P_LIST_DEADPARENT
) == 0) {
2609 if (pp
!= initproc
) {
2611 pp
->si_pid
= p
->p_pid
;
2612 pp
->p_xhighbits
= p
->p_xhighbits
;
2614 pp
->si_status
= p
->p_xstat
;
2615 pp
->si_code
= CLD_EXITED
;
2617 * p_ucred usage is safe as it is an exiting process
2618 * and reference is dropped in reap
2620 pp
->si_uid
= kauth_cred_getruid(p
->p_ucred
);
2623 /* mark as a zombie */
2624 /* mark as a zombie */
2625 /* No need to take proc lock as all refs are drained and
2626 * no one except parent (reaping ) can look at this.
2627 * The write is to an int and is coherent. Also parent is
2628 * keyed off of list lock for reaping
2632 psignal(pp
, SIGCHLD
);
2634 /* and now wakeup the parent */
2636 wakeup((caddr_t
)pp
);
2640 /* check for lookups by zomb sysctl */
2641 while ((p
->p_listflag
& P_LIST_WAITING
) == P_LIST_WAITING
) {
2642 msleep(&p
->p_stat
, proc_list_mlock
, PWAIT
, "waitcoll", 0);
2645 p
->p_listflag
|= P_LIST_WAITING
;
2648 * This is a named reference and it is not granted
2649 * if the reap is already in progress. So we get
2650 * the reference here exclusively and their can be
2651 * no waiters. So there is no need for a wakeup
2652 * after we are done. AlsO the reap frees the structure
2653 * and the proc struct cannot be used for wakeups as well.
2654 * It is safe to use p here as this is system reap
2656 (void)reap_child_locked(pp
, p
, 0, 0, 1, 1);
2657 /* list lock dropped by reap_child_locked */
2665 * LP64 support - long is 64 bits if we are dealing with a 64 bit user
2666 * process. We munge the kernel version of rusage into the
2669 __private_extern__
void
2670 munge_user64_rusage(struct rusage
*a_rusage_p
, struct user64_rusage
*a_user_rusage_p
)
2672 /* Zero-out struct so that padding is cleared */
2673 bzero(a_user_rusage_p
, sizeof(struct user64_rusage
));
2675 /* timeval changes size, so utime and stime need special handling */
2676 a_user_rusage_p
->ru_utime
.tv_sec
= a_rusage_p
->ru_utime
.tv_sec
;
2677 a_user_rusage_p
->ru_utime
.tv_usec
= a_rusage_p
->ru_utime
.tv_usec
;
2678 a_user_rusage_p
->ru_stime
.tv_sec
= a_rusage_p
->ru_stime
.tv_sec
;
2679 a_user_rusage_p
->ru_stime
.tv_usec
= a_rusage_p
->ru_stime
.tv_usec
;
2681 * everything else can be a direct assign, since there is no loss
2682 * of precision implied boing 32->64.
2684 a_user_rusage_p
->ru_maxrss
= a_rusage_p
->ru_maxrss
;
2685 a_user_rusage_p
->ru_ixrss
= a_rusage_p
->ru_ixrss
;
2686 a_user_rusage_p
->ru_idrss
= a_rusage_p
->ru_idrss
;
2687 a_user_rusage_p
->ru_isrss
= a_rusage_p
->ru_isrss
;
2688 a_user_rusage_p
->ru_minflt
= a_rusage_p
->ru_minflt
;
2689 a_user_rusage_p
->ru_majflt
= a_rusage_p
->ru_majflt
;
2690 a_user_rusage_p
->ru_nswap
= a_rusage_p
->ru_nswap
;
2691 a_user_rusage_p
->ru_inblock
= a_rusage_p
->ru_inblock
;
2692 a_user_rusage_p
->ru_oublock
= a_rusage_p
->ru_oublock
;
2693 a_user_rusage_p
->ru_msgsnd
= a_rusage_p
->ru_msgsnd
;
2694 a_user_rusage_p
->ru_msgrcv
= a_rusage_p
->ru_msgrcv
;
2695 a_user_rusage_p
->ru_nsignals
= a_rusage_p
->ru_nsignals
;
2696 a_user_rusage_p
->ru_nvcsw
= a_rusage_p
->ru_nvcsw
;
2697 a_user_rusage_p
->ru_nivcsw
= a_rusage_p
->ru_nivcsw
;
2700 /* For a 64-bit kernel and 32-bit userspace, munging may be needed */
2701 __private_extern__
void
2702 munge_user32_rusage(struct rusage
*a_rusage_p
, struct user32_rusage
*a_user_rusage_p
)
2704 /* timeval changes size, so utime and stime need special handling */
2705 a_user_rusage_p
->ru_utime
.tv_sec
= a_rusage_p
->ru_utime
.tv_sec
;
2706 a_user_rusage_p
->ru_utime
.tv_usec
= a_rusage_p
->ru_utime
.tv_usec
;
2707 a_user_rusage_p
->ru_stime
.tv_sec
= a_rusage_p
->ru_stime
.tv_sec
;
2708 a_user_rusage_p
->ru_stime
.tv_usec
= a_rusage_p
->ru_stime
.tv_usec
;
2710 * everything else can be a direct assign. We currently ignore
2711 * the loss of precision
2713 a_user_rusage_p
->ru_maxrss
= a_rusage_p
->ru_maxrss
;
2714 a_user_rusage_p
->ru_ixrss
= a_rusage_p
->ru_ixrss
;
2715 a_user_rusage_p
->ru_idrss
= a_rusage_p
->ru_idrss
;
2716 a_user_rusage_p
->ru_isrss
= a_rusage_p
->ru_isrss
;
2717 a_user_rusage_p
->ru_minflt
= a_rusage_p
->ru_minflt
;
2718 a_user_rusage_p
->ru_majflt
= a_rusage_p
->ru_majflt
;
2719 a_user_rusage_p
->ru_nswap
= a_rusage_p
->ru_nswap
;
2720 a_user_rusage_p
->ru_inblock
= a_rusage_p
->ru_inblock
;
2721 a_user_rusage_p
->ru_oublock
= a_rusage_p
->ru_oublock
;
2722 a_user_rusage_p
->ru_msgsnd
= a_rusage_p
->ru_msgsnd
;
2723 a_user_rusage_p
->ru_msgrcv
= a_rusage_p
->ru_msgrcv
;
2724 a_user_rusage_p
->ru_nsignals
= a_rusage_p
->ru_nsignals
;
2725 a_user_rusage_p
->ru_nvcsw
= a_rusage_p
->ru_nvcsw
;
2726 a_user_rusage_p
->ru_nivcsw
= a_rusage_p
->ru_nivcsw
;