]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_exit.c
xnu-4570.71.2.tar.gz
[apple/xnu.git] / bsd / kern / kern_exit.c
1 /*
2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
29 /*
30 * Copyright (c) 1982, 1986, 1989, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)kern_exit.c 8.7 (Berkeley) 2/12/94
67 */
68 /*
69 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
70 * support for mandatory and extensible security protections. This notice
71 * is included in support of clause 2.2 (b) of the Apple Public License,
72 * Version 2.0.
73 */
74
75 #include <machine/reg.h>
76 #include <machine/psl.h>
77 #include <stdatomic.h>
78
79 #include "compat_43.h"
80
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/ioctl.h>
84 #include <sys/proc_internal.h>
85 #include <sys/proc.h>
86 #include <sys/kauth.h>
87 #include <sys/tty.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/kernel.h>
91 #include <sys/wait.h>
92 #include <sys/file_internal.h>
93 #include <sys/vnode_internal.h>
94 #include <sys/syslog.h>
95 #include <sys/malloc.h>
96 #include <sys/resourcevar.h>
97 #include <sys/ptrace.h>
98 #include <sys/proc_info.h>
99 #include <sys/reason.h>
100 #include <sys/_types/_timeval64.h>
101 #include <sys/user.h>
102 #include <sys/aio_kern.h>
103 #include <sys/sysproto.h>
104 #include <sys/signalvar.h>
105 #include <sys/kdebug.h>
106 #include <sys/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>
111
112 #include <security/audit/audit.h>
113 #include <bsm/audit_kevents.h>
114
115 #include <mach/mach_types.h>
116 #include <mach/task.h>
117 #include <mach/thread_act.h>
118
119 #include <kern/exc_resource.h>
120 #include <kern/kern_types.h>
121 #include <kern/kalloc.h>
122 #include <kern/task.h>
123 #include <corpses/task_corpse.h>
124 #include <kern/thread.h>
125 #include <kern/thread_call.h>
126 #include <kern/sched_prim.h>
127 #include <kern/assert.h>
128 #include <kern/policy_internal.h>
129 #include <kern/exc_guard.h>
130
131 #include <vm/vm_protos.h>
132
133 #include <pexpert/pexpert.h>
134
135 #if SYSV_SHM
136 #include <sys/shm_internal.h> /* shmexit */
137 #endif /* SYSV_SHM */
138 #if CONFIG_PERSONAS
139 #include <sys/persona.h>
140 #endif /* CONFIG_PERSONAS */
141 #if CONFIG_MEMORYSTATUS
142 #include <sys/kern_memorystatus.h>
143 #endif /* CONFIG_MEMORYSTATUS */
144 #if CONFIG_DTRACE
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 */
149 #if CONFIG_MACF
150 #include <security/mac_framework.h>
151 #include <security/mac_mach_internal.h>
152 #include <sys/syscall.h>
153 #endif /* CONFIG_MACF */
154
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);
176
177
178 /*
179 * Things which should have prototypes in headers, but don't
180 */
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 *);
188 void delay(int);
189 void gather_rusage_info(proc_t p, rusage_info_current *ru, int flavor);
190
191 /*
192 * NOTE: Source and target may *NOT* overlap!
193 * XXX Should share code with bsd/dev/ppc/unix_signal.c
194 */
195 void
196 siginfo_user_to_user32(user_siginfo_t *in, user32_siginfo_t *out)
197 {
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 */
208 }
209
210 void
211 siginfo_user_to_user64(user_siginfo_t *in, user64_siginfo_t *out)
212 {
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 */
223 }
224
225 static int
226 copyoutsiginfo(user_siginfo_t *native, boolean_t is64, user_addr_t uaddr)
227 {
228 if (is64) {
229 user64_siginfo_t sinfo64;
230
231 bzero(&sinfo64, sizeof (sinfo64));
232 siginfo_user_to_user64(native, &sinfo64);
233 return (copyout(&sinfo64, uaddr, sizeof (sinfo64)));
234 } else {
235 user32_siginfo_t sinfo32;
236
237 bzero(&sinfo32, sizeof (sinfo32));
238 siginfo_user_to_user32(native, &sinfo32);
239 return (copyout(&sinfo32, uaddr, sizeof (sinfo32)));
240 }
241 }
242
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)
246 {
247 struct rusage_superset rup;
248
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);
253 }
254
255 static void proc_update_corpse_exception_codes(proc_t p, mach_exception_data_type_t *code, mach_exception_data_type_t *subcode)
256 {
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) {
260 return;
261 }
262
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));
270 subcode_update = 0;
271 break;
272 }
273
274 break;
275 default:
276 break;
277 }
278
279 *code = code_update;
280 *subcode = subcode_update;
281 return;
282 }
283
284 mach_exception_data_type_t proc_encode_exit_exception_code(proc_t p)
285 {
286 uint64_t subcode = 0;
287
288 if (p->p_exit_reason == OS_REASON_NULL) {
289 return 0;
290 }
291
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;
296 }
297
298 static void
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)
302 {
303 mach_vm_address_t uaddr = 0;
304 mach_exception_data_type_t exc_codes[EXCEPTION_CODE_MAX];
305 exc_codes[0] = code;
306 exc_codes[1] = subcode;
307 cpu_type_t cputype;
308 struct proc_uniqidentifierinfo p_uniqidinfo;
309 struct proc_workqueueinfo pwqinfo;
310 int retval = 0;
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);
316
317 #if CONFIG_MEMORYSTATUS
318 int memstat_dirty_flags = 0;
319 #endif
320
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));
323 }
324
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));
327 }
328
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));
331 }
332
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));
337 }
338 }
339
340 static_assert(sizeof(struct proc_uniqidentifierinfo) == sizeof(struct crashinfo_proc_uniqidentifierinfo));
341 if (KERN_SUCCESS ==
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));
345 }
346
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));
349 }
350
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));
353 }
354
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));
357 }
358
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));
364 }
365
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));
368 }
369
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));
372 }
373
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));
376 }
377
378 if (KERN_SUCCESS == kcdata_get_memory_addr(crash_info_ptr, TASK_CRASHINFO_PROC_PATH, MAXPATHLEN, &uaddr)) {
379 char *buf = (char *) kalloc(MAXPATHLEN);
380 if (buf != NULL) {
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);
385 }
386 }
387
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));
391 }
392
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));
395 }
396
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));
399 }
400
401 cputype = cpu_type() & ~CPU_ARCH_MASK;
402 if (IS_64BIT_PROCESS(p))
403 cputype |= CPU_ARCH_ABI64;
404
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));
407 }
408
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));
413 }
414
415 bzero(&pwqinfo, sizeof(struct proc_workqueueinfo));
416 retval = fill_procworkqueue(p, &pwqinfo);
417 if (retval == 0) {
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));
420 }
421 }
422
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));
425 }
426
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));
432 }
433 #endif /* CONFIG_COALITIONS */
434
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));
439 }
440 #endif
441
442 if (p->p_exit_reason != OS_REASON_NULL && reason == OS_REASON_NULL) {
443 reason = p->p_exit_reason;
444 }
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
451 };
452
453 kcdata_memcpy(crash_info_ptr, uaddr, &ers, sizeof(ers));
454 }
455
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);
459
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);
462 }
463 }
464 }
465
466 if (num_udata > 0) {
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);
470 }
471 }
472 }
473
474 /*
475 * We only parse exit reason kcdata blobs for launchd when it dies
476 * and we're going to panic.
477 *
478 * Meant to be called immediately before panicking.
479 */
480 char *
481 launchd_exit_reason_get_string_desc(os_reason_t exit_reason)
482 {
483 kcdata_iter_t iter;
484
485 if (exit_reason == OS_REASON_NULL || exit_reason->osr_kcd_buf == NULL ||
486 exit_reason->osr_bufsize == 0) {
487 return NULL;
488 }
489
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");
494 #endif
495 return NULL;
496 }
497
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));
502 #endif
503 return NULL;
504 }
505
506 iter = kcdata_iter_find_type(iter, EXIT_REASON_USER_DESC);
507 if (!kcdata_iter_valid(iter)) {
508 return NULL;
509 }
510
511 return (char *)kcdata_iter_payload(iter);
512 }
513
514 static __attribute__((noinline)) void
515 launchd_crashed_panic(proc_t p, int rv)
516 {
517 char *launchd_exit_reason_desc = launchd_exit_reason_get_string_desc(p->p_exit_reason);
518
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));
522 } else {
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");
526 }
527
528 const char *launchd_crashed_prefix_str;
529
530 if (strnstr(p->p_name, "preinit", sizeof(p->p_name))) {
531 launchd_crashed_prefix_str = "LTE preinit process exited";
532 } else {
533 launchd_crashed_prefix_str = "initproc exited";
534 }
535
536 #if (DEVELOPMENT || DEBUG) && CONFIG_COREDUMP
537 /*
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.
542 */
543
544 int err;
545 uint64_t coredump_start = mach_absolute_time();
546 uint64_t coredump_end;
547 clock_sec_t tv_sec;
548 clock_usec_t tv_usec;
549 uint32_t tv_msec;
550
551
552 err = coredump(p, 300, COREDUMP_IGNORE_ULIMIT | COREDUMP_FULLFSYNC);
553
554 coredump_end = mach_absolute_time();
555
556 absolutetime_to_microtime(coredump_end - coredump_start, &tv_sec, &tv_usec);
557
558 tv_msec = tv_usec / 1000;
559
560 if (err != 0) {
561 printf("Failed to generate initproc core file: error %d, took %d.%03d seconds\n",
562 err, (uint32_t)tv_sec, tv_msec);
563 } else {
564 printf("Generated initproc core file in %d.%03d seconds\n",
565 (uint32_t)tv_sec, tv_msec);
566 }
567 #endif /* (DEVELOPMENT || DEBUG) && CONFIG_COREDUMP */
568
569 sync(p, (void *)NULL, (int *)NULL);
570
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" : ""));
574 } else {
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");
579 }
580 }
581
582 #define OS_REASON_IFLAG_USER_FAULT 0x1
583
584 #define OS_REASON_TOTAL_USER_FAULTS_PER_PROC 5
585
586 static int
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)
592 {
593 os_reason_t exit_reason = OS_REASON_NULL;
594 kern_return_t kr = KERN_SUCCESS;
595
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);
599 for (;;) {
600 if (old_value >= OS_REASON_TOTAL_USER_FAULTS_PER_PROC) {
601 return EQFULL;
602 }
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)) {
607 break;
608 }
609 }
610 }
611
612 KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE,
613 p->p_pid, reason_namespace,
614 reason_code, 0, 0);
615
616 exit_reason = build_userspace_exit_reason(reason_namespace, reason_code,
617 payload, payload_size, reason_string, reason_flags);
618
619 if (internal_flags & OS_REASON_IFLAG_USER_FAULT) {
620 mach_exception_code_t code = 0;
621
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);
625
626 if (exit_reason == OS_REASON_NULL) {
627 kr = KERN_RESOURCE_SHORTAGE;
628 } else {
629 kr = task_violated_guard(code, reason_code, exit_reason);
630 }
631 os_reason_free(exit_reason);
632 } else {
633 /*
634 * We use SIGABRT (rather than calling exit directly from here) so that
635 * the debugger can catch abort_with_{reason,payload} calls.
636 */
637 psignal_try_thread_with_reason(p, current_thread(), SIGABRT, exit_reason);
638 }
639
640 switch (kr) {
641 case KERN_SUCCESS:
642 return 0;
643 case KERN_NOT_SUPPORTED:
644 return ENOTSUP;
645 case KERN_INVALID_ARGUMENT:
646 return EINVAL;
647 case KERN_RESOURCE_SHORTAGE:
648 default:
649 return EBUSY;
650 }
651 }
652
653 int
654 abort_with_payload(struct proc *cur_proc, struct abort_with_payload_args *args,
655 __unused void *retval)
656 {
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);
660
661 return 0;
662 }
663
664 int
665 os_fault_with_payload(struct proc *cur_proc,
666 struct os_fault_with_payload_args *args, __unused int *retval)
667 {
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);
671 }
672
673
674 /*
675 * exit --
676 * Death of process.
677 */
678 __attribute__((noreturn))
679 void
680 exit(proc_t p, struct exit_args *uap, int *retval)
681 {
682 p->p_xhighbits = ((uint32_t)(uap->rval) & 0xFF000000) >> 24;
683 exit1(p, W_EXITCODE(uap->rval, 0), retval);
684
685 thread_exception_return();
686 /* NOTREACHED */
687 while (TRUE)
688 thread_block(THREAD_CONTINUE_NULL);
689 /* NOTREACHED */
690 }
691
692 /*
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.
696 */
697 int
698 exit1(proc_t p, int rv, int *retval)
699 {
700 return exit1_internal(p, rv, retval, TRUE, TRUE, 0);
701 }
702
703 int
704 exit1_internal(proc_t p, int rv, int *retval, boolean_t thread_can_terminate, boolean_t perf_notify,
705 int jetsam_flags)
706 {
707 return exit_with_reason(p, rv, retval, thread_can_terminate, perf_notify, jetsam_flags, OS_REASON_NULL);
708 }
709
710 /*
711 * NOTE: exit_with_reason drops a reference on the passed exit_reason
712 */
713 int
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)
716 {
717 thread_t self = current_thread();
718 struct task *task = p->task;
719 struct uthread *ut;
720 int error = 0;
721
722 /*
723 * If a thread in this task has already
724 * called exit(), then halt any others
725 * right here.
726 */
727
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) {
733 return EINVAL;
734 }
735
736 vfork_exit(p, rv);
737 vfork_return(p , retval, p->p_pid);
738 unix_syscall_return(0);
739 /* NOT REACHED */
740 }
741
742 /*
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().
746 */
747
748 /*
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.
753 */
754 AUDIT_ARG(exit, WEXITSTATUS(rv), 0);
755 /*
756 * TODO: what to audit here when jetsam calls exit and the uthread,
757 * 'ut' does not belong to the proc, 'p'.
758 */
759 AUDIT_SYSCALL_EXIT(SYS_exit, p, ut, 0); /* Exit is always successfull */
760
761 DTRACE_PROC1(exit, int, CLD_EXITED);
762
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);
767
768 proc_lock(p);
769 error = proc_transstart(p, 1, (jetsam_flags ? 1 : 0));
770 if (error == EDEADLK) {
771 /*
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.
775 */
776 proc_unlock(p);
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);
782 }
783
784 if (thread_can_terminate) {
785 thread_exception_return();
786 }
787 }
788
789 return error;
790 }
791
792 while (p->exit_thread != self) {
793 if (sig_try_locked(p) <= 0) {
794 proc_transend(p, 1);
795 os_reason_free(exit_reason);
796
797 if (get_threadtask(self) != task) {
798 proc_unlock(p);
799 return(0);
800 }
801 proc_unlock(p);
802
803 thread_terminate(self);
804 if (!thread_can_terminate) {
805 return 0;
806 }
807
808 thread_exception_return();
809 /* NOTREACHED */
810 }
811 sig_lock_to_exit(p);
812 }
813
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);
818 }
819
820 assert(p->p_exit_reason == OS_REASON_NULL);
821 p->p_exit_reason = exit_reason;
822
823 p->p_lflag |= P_LEXIT;
824 p->p_xstat = rv;
825 p->p_lflag |= jetsam_flags;
826
827 proc_transend(p, 1);
828 proc_unlock(p);
829
830 proc_prepareexit(p, rv, perf_notify);
831
832 /* Last thread to terminate will call proc_exit() */
833 task_terminate_internal(task);
834
835 return(0);
836 }
837
838 void
839 proc_prepareexit(proc_t p, int rv, boolean_t perf_notify)
840 {
841 mach_exception_data_type_t code = 0, subcode = 0;
842
843 struct uthread *ut;
844 thread_t self = current_thread();
845 ut = get_bsdthread_info(self);
846 struct rusage_superset *rup;
847 int kr = 0;
848 int create_corpse = FALSE;
849
850 if (p == initproc) {
851 launchd_crashed_panic(p, rv);
852 /* NOTREACHED */
853 }
854
855 /*
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
862 *
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.
865 */
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)))) {
870 /*
871 * Workaround for processes checking up on PT_DENY_ATTACH:
872 * should be backed out post-Leopard (details in 5431025).
873 */
874 if ((SIGSEGV == WTERMSIG(rv)) &&
875 (p->p_pptr->p_lflag & P_LNOATTACH)) {
876 goto skipcheck;
877 }
878
879 /*
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.
883 */
884 code = ((WTERMSIG(rv) & 0xff) << 24) |
885 ((ut->uu_exception & 0x0f) << 20) |
886 ((int)ut->uu_code & 0xfffff);
887 subcode = ut->uu_subcode;
888
889 kr = task_exception_notify(EXC_CRASH, code, subcode);
890
891 /* Nobody handled EXC_CRASH?? remember to make corpse */
892 if (kr != 0) {
893 create_corpse = TRUE;
894 }
895 }
896
897 skipcheck:
898 /* Notify the perf server? */
899 if (perf_notify) {
900 (void)sys_perf_notify(self, p->p_pid);
901 }
902
903
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);
912 } else {
913 printf("Process[%d] crashed: %s. Too many corpses being created.\n", p->p_pid, p->p_comm);
914 }
915 create_corpse = FALSE;
916 }
917 }
918
919 /*
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().
923 *
924 * If the zombie allocation fails, just punt the stats.
925 */
926 MALLOC_ZONE(rup, struct rusage_superset *,
927 sizeof (*rup), M_ZOMBIE, M_WAITOK);
928 if (rup != NULL) {
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();
932
933 /*
934 * Make the rusage_info visible to external observers
935 * only after it has been completely filled in.
936 */
937 p->p_ru = rup;
938 }
939 if (create_corpse) {
940 int est_knotes = 0, num_knotes = 0;
941 uint64_t *buffer = NULL;
942 int buf_size = 0;
943
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;
952 }
953 }
954
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);
961 }
962 }
963 /*
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.
968 */
969
970 proc_list_lock();
971
972 #if CONFIG_MEMORYSTATUS
973 memorystatus_remove(p, TRUE);
974 #endif
975
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;
980
981 proc_list_unlock();
982
983
984 #ifdef PGINPROF
985 vmsizmon();
986 #endif
987 /*
988 * If parent is waiting for us to exit or exec,
989 * P_LPPWAIT is set; we will wakeup the parent below.
990 */
991 proc_lock(p);
992 p->p_lflag &= ~(P_LTRACED | P_LPPWAIT);
993 p->p_sigignore = ~(sigcantmask);
994 ut->uu_siglist = 0;
995 proc_unlock(p);
996 }
997
998 void
999 proc_exit(proc_t p)
1000 {
1001 proc_t q;
1002 proc_t pp;
1003 struct task *task = p->task;
1004 vnode_t tvp = NULLVP;
1005 struct pgrp * pg;
1006 struct session *sessp;
1007 struct uthread * uth;
1008 pid_t pid;
1009 int exitval;
1010 int knote_hint;
1011
1012 uth = current_uthread();
1013
1014 proc_lock(p);
1015 proc_transstart(p, 1, 0);
1016 if( !(p->p_lflag & P_LEXIT)) {
1017 /*
1018 * This can happen if a thread_terminate() occurs
1019 * in a single-threaded process.
1020 */
1021 p->p_lflag |= P_LEXIT;
1022 proc_transend(p, 1);
1023 proc_unlock(p);
1024 proc_prepareexit(p, 0, TRUE);
1025 (void) task_terminate_internal(task);
1026 proc_lock(p);
1027 } else {
1028 proc_transend(p, 1);
1029 }
1030
1031 p->p_lflag |= P_LPEXIT;
1032
1033 /*
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.
1037 */
1038 if ((p->p_lflag & P_LINSIGNAL) || (p->p_sigwaitcnt > 0)) {
1039 p->p_sigwaitcnt++;
1040 while ((p->p_lflag & P_LINSIGNAL) || (p->p_sigwaitcnt > 1))
1041 msleep(&p->p_sigmask, &p->p_mlock, PWAIT, "proc_sigdrain", NULL);
1042 p->p_sigwaitcnt--;
1043 }
1044
1045 proc_unlock(p);
1046 pid = p->p_pid;
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);
1051
1052 #if CONFIG_DTRACE
1053 dtrace_proc_exit(p);
1054 #endif
1055
1056 nspace_proc_exit(p);
1057
1058 /*
1059 * need to cancel async IO requests that can be cancelled and wait for those
1060 * already active. MAY BLOCK!
1061 */
1062
1063 proc_refdrain(p);
1064
1065 /* if any pending cpu limits action, clear it */
1066 task_clear_cpuusage(p->task, TRUE);
1067
1068 workqueue_mark_exiting(p);
1069
1070 _aio_exit( p );
1071
1072 /*
1073 * Close open files and release open-file table.
1074 * This may block!
1075 */
1076 fdfree(p);
1077
1078 /*
1079 * Once all the knotes, kqueues & workloops are destroyed, get rid of the
1080 * workqueue.
1081 */
1082 workqueue_exit(p);
1083
1084 if (uth->uu_lowpri_window) {
1085 /*
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
1091 */
1092 throttle_lowpri_io(0);
1093 }
1094
1095 #if SYSV_SHM
1096 /* Close ref SYSV Shared memory*/
1097 if (p->vm_shm)
1098 shmexit(p);
1099 #endif
1100 #if SYSV_SEM
1101 /* Release SYSV semaphores */
1102 semexit(p);
1103 #endif
1104
1105 #if PSYNCH
1106 pth_proc_hashdelete(p);
1107 #endif /* PSYNCH */
1108
1109 sessp = proc_session(p);
1110 if (SESS_LEADER(p, sessp)) {
1111
1112 if (sessp->s_ttyvp != NULLVP) {
1113 struct vnode *ttyvp;
1114 int ttyvid;
1115 int cttyflag = 0;
1116 struct vfs_context context;
1117 struct tty *tp;
1118
1119 /*
1120 * Controlling process.
1121 * Signal foreground pgrp,
1122 * drain controlling terminal
1123 * and revoke access to controlling terminal.
1124 */
1125 session_lock(sessp);
1126 tp = SESSION_TP(sessp);
1127 if ((tp != TTY_NULL) && (tp->t_session == sessp)) {
1128 session_unlock(sessp);
1129
1130 /*
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
1136 */
1137 tty_lock(tp);
1138 ttysetpgrphup(tp);
1139 tty_unlock(tp);
1140
1141 tty_pgsignal(tp, SIGHUP, 1);
1142
1143 session_lock(sessp);
1144 tp = SESSION_TP(sessp);
1145 }
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);
1155
1156 if ((ttyvp != NULLVP) && (vnode_getwithvid(ttyvp, ttyvid) == 0)) {
1157 if (tp != TTY_NULL) {
1158 tty_lock(tp);
1159 (void) ttywait(tp);
1160 tty_unlock(tp);
1161 }
1162 context.vc_thread = proc_thread(p); /* XXX */
1163 context.vc_ucred = kauth_cred_proc_ref(p);
1164 VNOP_REVOKE(ttyvp, REVOKEALL, &context);
1165 if (cttyflag) {
1166 /*
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.
1172 */
1173 vnode_rele(ttyvp);
1174 }
1175 vnode_put(ttyvp);
1176 kauth_cred_unref(&context.vc_ucred);
1177 ttyvp = NULLVP;
1178 }
1179 if (tp) {
1180 /*
1181 * This is cleared even if not set. This is also done in
1182 * spec_close to ensure that the flag is cleared.
1183 */
1184 tty_lock(tp);
1185 ttyclrpgrphup(tp);
1186 tty_unlock(tp);
1187
1188 ttyfree(tp);
1189 }
1190 }
1191 session_lock(sessp);
1192 sessp->s_leader = NULL;
1193 session_unlock(sessp);
1194 }
1195 session_rele(sessp);
1196
1197 pg = proc_pgrp(p);
1198 fixjobc(p, pg, 0);
1199 pg_rele(pg);
1200
1201 p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
1202 (void)acct_process(p);
1203
1204 proc_list_lock();
1205
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);
1211 }
1212
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) {
1218 if (p != q->p_pptr)
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);
1223 }
1224 q->p_listflag |= P_LIST_WAITING;
1225 /*
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
1233 */
1234 (void)reap_child_locked(p, q, 1, reparentedtoinit, 1, 0);
1235 } else {
1236 /*
1237 * Traced processes are killed
1238 * since their existence means someone is messing up.
1239 */
1240 if (q->p_lflag & P_LTRACED) {
1241 struct proc *opp;
1242
1243 /*
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.
1248 */
1249 if (proc_ref_locked(q) != q)
1250 continue;
1251
1252 proc_list_unlock();
1253
1254 opp = proc_find(q->p_oppid);
1255 if (opp != PROC_NULL) {
1256 proc_list_lock();
1257 q->p_oppid = 0;
1258 proc_list_unlock();
1259 proc_reparentlocked(q, opp, 0, 0);
1260 proc_rele(opp);
1261 } else {
1262 /* original parent exited while traced */
1263 proc_list_lock();
1264 q->p_listflag |= P_LIST_DEADPARENT;
1265 q->p_oppid = 0;
1266 proc_list_unlock();
1267 proc_reparentlocked(q, initproc, 0, 0);
1268 }
1269
1270 proc_lock(q);
1271 q->p_lflag &= ~P_LTRACED;
1272
1273 if (q->sigwait_thread) {
1274 thread_t thread = q->sigwait_thread;
1275
1276 proc_unlock(q);
1277 /*
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.
1283 */
1284 thread_resume(thread);
1285 clear_wait(thread, THREAD_INTERRUPTED);
1286 threadsignal(thread, SIGKILL, 0, TRUE);
1287 } else {
1288 proc_unlock(q);
1289 }
1290
1291 psignal(q, SIGKILL);
1292 proc_list_lock();
1293 proc_rele_locked(q);
1294 } else {
1295 q->p_listflag |= P_LIST_DEADPARENT;
1296 proc_reparentlocked(q, initproc, 0, 1);
1297 }
1298 }
1299 }
1300
1301 proc_childdrainend(p);
1302 proc_list_unlock();
1303
1304 #if CONFIG_MACF
1305 /*
1306 * Notify MAC policies that proc is dead.
1307 * This should be replaced with proper label management
1308 * (rdar://problem/32126399).
1309 */
1310 mac_proc_notify_exit(p);
1311 #endif
1312
1313 /*
1314 * Release reference to text vnode
1315 */
1316 tvp = p->p_textvp;
1317 p->p_textvp = NULL;
1318 if (tvp != NULLVP) {
1319 vnode_rele(tvp);
1320 }
1321
1322 /*
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.
1326 */
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;
1330
1331 ruadd(&(p->p_ru->ru), &p->p_stats->p_cru);
1332 }
1333
1334 /*
1335 * Free up profiling buffers.
1336 */
1337 {
1338 struct uprof *p0 = &p->p_stats->p_prof, *p1, *pn;
1339
1340 p1 = p0->pr_next;
1341 p0->pr_next = NULL;
1342 p0->pr_scale = 0;
1343
1344 for (; p1 != NULL; p1 = pn) {
1345 pn = p1->pr_next;
1346 kfree(p1, sizeof *p1);
1347 }
1348 }
1349
1350 proc_free_realitimer(p);
1351
1352 /*
1353 * Other substructures are freed from wait().
1354 */
1355 FREE_ZONE(p->p_stats, sizeof *p->p_stats, M_PSTATS);
1356 p->p_stats = NULL;
1357
1358 FREE_ZONE(p->p_sigacts, sizeof *p->p_sigacts, M_SIGACTS);
1359 p->p_sigacts = NULL;
1360
1361 proc_limitdrop(p, 1);
1362 p->p_limit = NULL;
1363
1364 vm_purgeable_disown(p->task);
1365
1366 /*
1367 * Finish up by terminating the task
1368 * and halt this thread (only if a
1369 * member of the task exiting).
1370 */
1371 p->task = TASK_NULL;
1372 set_bsdtask_info(task, NULL);
1373
1374 knote_hint = NOTE_EXIT | (p->p_xstat & 0xffff);
1375 proc_knote(p, knote_hint);
1376
1377 /* mark the thread as the one that is doing proc_exit
1378 * no need to hold proc lock in uthread_free
1379 */
1380 uth->uu_flag |= UT_PROCEXIT;
1381 /*
1382 * Notify parent that we're gone.
1383 */
1384 pp = proc_parent(p);
1385 if (pp->p_flag & P_NOCLDWAIT) {
1386
1387 if (p->p_ru != NULL) {
1388 proc_lock(pp);
1389 #if 3839178
1390 /*
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
1395 * of RLIMIT_CPU.
1396 */
1397 #else /* !3839178 */
1398 /*
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.
1402 */
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);
1406 proc_unlock(pp);
1407 }
1408
1409 /* kernel can reap this one, no need to move it to launchd */
1410 proc_list_lock();
1411 p->p_listflag |= P_LIST_DEADPARENT;
1412 proc_list_unlock();
1413 }
1414 if ((p->p_listflag & P_LIST_DEADPARENT) == 0 || p->p_oppid) {
1415 if (pp != initproc) {
1416 proc_lock(pp);
1417 pp->si_pid = p->p_pid;
1418 pp->p_xhighbits = p->p_xhighbits;
1419 p->p_xhighbits = 0;
1420 pp->si_status = p->p_xstat;
1421 pp->si_code = CLD_EXITED;
1422 /*
1423 * p_ucred usage is safe as it is an exiting process
1424 * and reference is dropped in reap
1425 */
1426 pp->si_uid = kauth_cred_getruid(p->p_ucred);
1427 proc_unlock(pp);
1428 }
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
1434 */
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);
1438 p->p_stat = SZOMB;
1439 /*
1440 * The current process can be reaped so, no one
1441 * can depend on this
1442 */
1443
1444 psignal(pp, SIGCHLD);
1445
1446 /* and now wakeup the parent */
1447 proc_list_lock();
1448 wakeup((caddr_t)pp);
1449 proc_list_unlock();
1450 } else {
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
1457 */
1458 proc_list_lock();
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);
1465 }
1466 /* safe to use p as this is a system reap */
1467 p->p_stat = SZOMB;
1468 p->p_listflag |= P_LIST_WAITING;
1469
1470 /*
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
1478 */
1479 (void)reap_child_locked(pp, p, 1, 0, 1, 1);
1480 /* list lock dropped by reap_child_locked */
1481 }
1482 if (uth->uu_lowpri_window) {
1483 /*
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
1488 */
1489 throttle_lowpri_io(0);
1490 }
1491
1492 proc_rele(pp);
1493
1494 }
1495
1496
1497 /*
1498 * reap_child_locked
1499 *
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
1504 * with it.
1505 *
1506 * Parameters: proc_t parent Parent of process being reaped
1507 * proc_t child Process to reap
1508 *
1509 * Returns: 0 Process was not reaped because it
1510 * came from an attach
1511 * 1 Process was reaped
1512 */
1513 static int
1514 reap_child_locked(proc_t parent, proc_t child, int deadparent, int reparentedtoinit, int locked, int droplock)
1515 {
1516 proc_t trace_parent = PROC_NULL; /* Traced parent process, if tracing */
1517
1518 if (locked == 1)
1519 proc_list_unlock();
1520
1521 /*
1522 * If we got the child via a ptrace 'attach',
1523 * we need to give it back to the old parent.
1524 *
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
1530 */
1531 if (child->p_oppid) {
1532 int knote_hint;
1533 pid_t oppid;
1534
1535 proc_lock(child);
1536 oppid = child->p_oppid;
1537 child->p_oppid = 0;
1538 knote_hint = NOTE_EXIT | (child->p_xstat & 0xffff);
1539 proc_unlock(child);
1540
1541 if ((trace_parent = proc_find(oppid))
1542 && !((trace_parent == initproc) && reparentedtoinit)) {
1543
1544 if (trace_parent != initproc) {
1545 /*
1546 * proc internal fileds and p_ucred usage safe
1547 * here as child is dead and is not reaped or
1548 * reparented yet
1549 */
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);
1556 }
1557 proc_reparentlocked(child, trace_parent, 1, 0);
1558
1559 /* resend knote to original parent (and others) after reparenting */
1560 proc_knote(child, knote_hint);
1561
1562 psignal(trace_parent, SIGCHLD);
1563 proc_list_lock();
1564 wakeup((caddr_t)trace_parent);
1565 child->p_listflag &= ~P_LIST_WAITING;
1566 wakeup(&child->p_stat);
1567 proc_list_unlock();
1568 proc_rele(trace_parent);
1569 if ((locked == 1) && (droplock == 0))
1570 proc_list_lock();
1571 return (0);
1572 }
1573
1574 /*
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.
1579 */
1580 proc_knote(child, knote_hint);
1581
1582 if (trace_parent != PROC_NULL) {
1583 proc_rele(trace_parent);
1584 }
1585 }
1586
1587 #pragma clang diagnostic push
1588 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1589 proc_knote(child, NOTE_REAP);
1590 #pragma clang diagnostic pop
1591
1592 proc_knote_drain(child);
1593
1594 child->p_xstat = 0;
1595 if (child->p_ru) {
1596 proc_lock(parent);
1597 #if 3839178
1598 /*
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
1603 * of RLIMIT_CPU.
1604 */
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);
1611 child->p_ru = NULL;
1612 } else {
1613 printf("Warning : lost p_ru for %s\n", child->p_comm);
1614 }
1615
1616 AUDIT_SESSION_PROCEXIT(child);
1617
1618 /*
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)
1623 */
1624 #if CONFIG_PERSONAS
1625 /*
1626 * persona_proc_drop calls chgproccnt(-1) on the persona uid,
1627 * and (+1) on the child->p_ucred uid
1628 */
1629 persona_proc_drop(child);
1630 #endif
1631 (void)chgproccnt(kauth_cred_getruid(child->p_ucred), -1);
1632
1633 os_reason_free(child->p_exit_reason);
1634
1635 /*
1636 * Free up credentials.
1637 */
1638 if (IS_VALID_CRED(child->p_ucred)) {
1639 kauth_cred_unref(&child->p_ucred);
1640 }
1641
1642 /* XXXX Note NOT SAFE TO USE p_ucred from this point onwards */
1643
1644 /*
1645 * Finally finished with old proc entry.
1646 * Unlink it from its process group and free it.
1647 */
1648 leavepgrp(child);
1649
1650 proc_list_lock();
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);
1659
1660 /* Take it out of process hash */
1661 LIST_REMOVE(child, p_hash);
1662 child->p_listflag &= ~P_LIST_INHASH;
1663 proc_checkdeadrefs(child);
1664 nprocs--;
1665
1666 if (deadparent) {
1667 /*
1668 * If a child zombie is being reaped because its parent
1669 * is exiting, make sure we update the list flag
1670 */
1671 child->p_listflag |= P_LIST_DEADPARENT;
1672 }
1673
1674 proc_list_unlock();
1675
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);
1680 #if CONFIG_DTRACE
1681 lck_mtx_destroy(&child->p_dtrace_sprlock, proc_lck_grp);
1682 #endif
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);
1688 #if CONFIG_DTRACE
1689 lck_mtx_destroy(&child->p_dtrace_sprlock, proc_lck_grp);
1690 #endif
1691 lck_spin_destroy(&child->p_slock, proc_lck_grp);
1692 #endif /* CONFIG_FINE_LOCK_GROUPS */
1693
1694 FREE_ZONE(child, sizeof *child, M_PROC);
1695 if ((locked == 1) && (droplock == 0))
1696 proc_list_lock();
1697
1698 return (1);
1699 }
1700
1701
1702 int
1703 wait1continue(int result)
1704 {
1705 proc_t p;
1706 thread_t thread;
1707 uthread_t uth;
1708 struct _wait4_data *wait4_data;
1709 struct wait4_nocancel_args *uap;
1710 int *retval;
1711
1712 if (result)
1713 return(result);
1714
1715 p = current_proc();
1716 thread = current_thread();
1717 uth = (struct uthread *)get_bsdthread_info(thread);
1718
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));
1723 }
1724
1725 int
1726 wait4(proc_t q, struct wait4_args *uap, int32_t *retval)
1727 {
1728 __pthread_testcancel(1);
1729 return(wait4_nocancel(q, (struct wait4_nocancel_args *)uap, retval));
1730 }
1731
1732 int
1733 wait4_nocancel(proc_t q, struct wait4_nocancel_args *uap, int32_t *retval)
1734 {
1735 int nfound;
1736 int sibling_count;
1737 proc_t p;
1738 int status, error;
1739 uthread_t uth;
1740 struct _wait4_data *wait4_data;
1741
1742 AUDIT_ARG(pid, uap->pid);
1743
1744 if (uap->pid == 0)
1745 uap->pid = -q->p_pgrpid;
1746
1747 loop:
1748 proc_list_lock();
1749 loop1:
1750 nfound = 0;
1751 sibling_count = 0;
1752
1753 PCHILDREN_FOREACH(q, p) {
1754 if ( p->p_sibling.le_next != 0 )
1755 sibling_count++;
1756 if (uap->pid != WAIT_ANY &&
1757 p->p_pid != uap->pid &&
1758 p->p_pgrpid != -(uap->pid))
1759 continue;
1760
1761 nfound++;
1762
1763 /* XXX This is racy because we don't get the lock!!!! */
1764
1765 if (p->p_listflag & P_LIST_WAITING) {
1766 (void)msleep(&p->p_stat, proc_list_mlock, PWAIT, "waitcoll", 0);
1767 goto loop1;
1768 }
1769 p->p_listflag |= P_LIST_WAITING; /* only allow single thread to wait() */
1770
1771
1772 if (p->p_stat == SZOMB) {
1773 int reparentedtoinit = (p->p_listflag & P_LIST_DEADPARENT) ? 1 : 0;
1774
1775 proc_list_unlock();
1776 #if CONFIG_MACF
1777 if ((error = mac_proc_check_wait(q, p)) != 0)
1778 goto out;
1779 #endif
1780 retval[0] = p->p_pid;
1781 if (uap->status) {
1782 /* Legacy apps expect only 8 bits of status */
1783 status = 0xffff & p->p_xstat; /* convert to int */
1784 error = copyout((caddr_t)&status,
1785 uap->status,
1786 sizeof(status));
1787 if (error)
1788 goto out;
1789 }
1790 if (uap->rusage) {
1791 if (p->p_ru == NULL) {
1792 error = ENOMEM;
1793 } else {
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,
1798 uap->rusage,
1799 sizeof (my_rusage));
1800 }
1801 else {
1802 struct user32_rusage my_rusage = {};
1803 munge_user32_rusage(&p->p_ru->ru, &my_rusage);
1804 error = copyout((caddr_t)&my_rusage,
1805 uap->rusage,
1806 sizeof (my_rusage));
1807 }
1808 }
1809 /* information unavailable? */
1810 if (error)
1811 goto out;
1812 }
1813
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.
1818 */
1819 if ( sibling_count == 0 ) {
1820 int mask = sigmask(SIGCHLD);
1821 uth = current_uthread();
1822
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.
1827 */
1828 proc_lock(q);
1829 uth->uu_siglist &= ~mask; /* clear pending signal */
1830 proc_unlock(q);
1831 }
1832 }
1833
1834 /* Clean up */
1835 (void)reap_child_locked(q, p, 0, reparentedtoinit, 0, 0);
1836
1837 return (0);
1838 }
1839 if (p->p_stat == SSTOP && (p->p_lflag & P_LWAITED) == 0 &&
1840 (p->p_lflag & P_LTRACED || uap->options & WUNTRACED)) {
1841 proc_list_unlock();
1842 #if CONFIG_MACF
1843 if ((error = mac_proc_check_wait(q, p)) != 0)
1844 goto out;
1845 #endif
1846 proc_lock(p);
1847 p->p_lflag |= P_LWAITED;
1848 proc_unlock(p);
1849 retval[0] = p->p_pid;
1850 if (uap->status) {
1851 status = W_STOPCODE(p->p_xstat);
1852 error = copyout((caddr_t)&status,
1853 uap->status,
1854 sizeof(status));
1855 } else
1856 error = 0;
1857 goto out;
1858 }
1859 /*
1860 * If we are waiting for continued processses, and this
1861 * process was continued
1862 */
1863 if ((uap->options & WCONTINUED) &&
1864 (p->p_flag & P_CONTINUED)) {
1865 proc_list_unlock();
1866 #if CONFIG_MACF
1867 if ((error = mac_proc_check_wait(q, p)) != 0)
1868 goto out;
1869 #endif
1870
1871 /* Prevent other process for waiting for this event */
1872 OSBitAndAtomic(~((uint32_t)P_CONTINUED), &p->p_flag);
1873 retval[0] = p->p_pid;
1874 if (uap->status) {
1875 status = W_STOPCODE(SIGCONT);
1876 error = copyout((caddr_t)&status,
1877 uap->status,
1878 sizeof(status));
1879 } else
1880 error = 0;
1881 goto out;
1882 }
1883 p->p_listflag &= ~P_LIST_WAITING;
1884 wakeup(&p->p_stat);
1885 }
1886 /* list lock is held when we get here any which way */
1887 if (nfound == 0) {
1888 proc_list_unlock();
1889 return (ECHILD);
1890 }
1891
1892 if (uap->options & WNOHANG) {
1893 retval[0] = 0;
1894 proc_list_unlock();
1895 return (0);
1896 }
1897
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;
1903
1904 if ((error = msleep0((caddr_t)q, proc_list_mlock, PWAIT | PCATCH | PDROP, "wait", 0, wait1continue)))
1905 return (error);
1906
1907 goto loop;
1908 out:
1909 proc_list_lock();
1910 p->p_listflag &= ~P_LIST_WAITING;
1911 wakeup(&p->p_stat);
1912 proc_list_unlock();
1913 return (error);
1914 }
1915
1916 #if DEBUG
1917 #define ASSERT_LCK_MTX_OWNED(lock) \
1918 lck_mtx_assert(lock, LCK_MTX_ASSERT_OWNED)
1919 #else
1920 #define ASSERT_LCK_MTX_OWNED(lock) /* nothing */
1921 #endif
1922
1923 int
1924 waitidcontinue(int result)
1925 {
1926 proc_t p;
1927 thread_t thread;
1928 uthread_t uth;
1929 struct _waitid_data *waitid_data;
1930 struct waitid_nocancel_args *uap;
1931 int *retval;
1932
1933 if (result)
1934 return (result);
1935
1936 p = current_proc();
1937 thread = current_thread();
1938 uth = (struct uthread *)get_bsdthread_info(thread);
1939
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));
1944 }
1945
1946 /*
1947 * Description: Suspend the calling thread until one child of the process
1948 * containing the calling thread changes state.
1949 *
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
1955 *
1956 * Returns: 0 Success
1957 * !0 Error returning status to user space
1958 */
1959 int
1960 waitid(proc_t q, struct waitid_args *uap, int32_t *retval)
1961 {
1962 __pthread_testcancel(1);
1963 return (waitid_nocancel(q, (struct waitid_nocancel_args *)uap, retval));
1964 }
1965
1966 int
1967 waitid_nocancel(proc_t q, struct waitid_nocancel_args *uap,
1968 __unused int32_t *retval)
1969 {
1970 user_siginfo_t siginfo; /* siginfo data to return to caller */
1971 boolean_t caller64 = IS_64BIT_PROCESS(q);
1972 int nfound;
1973 proc_t p;
1974 int error;
1975 uthread_t uth;
1976 struct _waitid_data *waitid_data;
1977
1978 if (uap->options == 0 ||
1979 (uap->options & ~(WNOHANG|WNOWAIT|WCONTINUED|WSTOPPED|WEXITED)))
1980 return (EINVAL); /* bits set that aren't recognized */
1981
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)
1986 return (EINVAL);
1987 break;
1988 case P_ALL: /* any child */
1989 break;
1990 }
1991
1992 loop:
1993 proc_list_lock();
1994 loop1:
1995 nfound = 0;
1996
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)
2001 continue;
2002 break;
2003 case P_PGID: /* child with process group ID equal to... */
2004 if (p->p_pgrpid != (pid_t)uap->id)
2005 continue;
2006 break;
2007 case P_ALL: /* any child */
2008 break;
2009 }
2010
2011 /* XXX This is racy because we don't get the lock!!!! */
2012
2013 /*
2014 * Wait collision; go to sleep and restart; used to maintain
2015 * the single return for waited process guarantee.
2016 */
2017 if (p->p_listflag & P_LIST_WAITING) {
2018 (void) msleep(&p->p_stat, proc_list_mlock,
2019 PWAIT, "waitidcoll", 0);
2020 goto loop1;
2021 }
2022 p->p_listflag |= P_LIST_WAITING; /* mark busy */
2023
2024 nfound++;
2025
2026 bzero(&siginfo, sizeof (siginfo));
2027
2028 switch (p->p_stat) {
2029 case SZOMB: /* Exited */
2030 if (!(uap->options & WEXITED))
2031 break;
2032 proc_list_unlock();
2033 #if CONFIG_MACF
2034 if ((error = mac_proc_check_wait(q, p)) != 0)
2035 goto out;
2036 #endif
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);
2040 p->p_xhighbits = 0;
2041 if (WIFSIGNALED(p->p_xstat)) {
2042 siginfo.si_code = WCOREDUMP(p->p_xstat) ?
2043 CLD_DUMPED : CLD_KILLED;
2044 } else
2045 siginfo.si_code = CLD_EXITED;
2046
2047 if ((error = copyoutsiginfo(&siginfo,
2048 caller64, uap->infop)) != 0)
2049 goto out;
2050
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);
2054 return (0);
2055 }
2056 goto out;
2057
2058 case SSTOP: /* Stopped */
2059 /*
2060 * If we are not interested in stopped processes, then
2061 * ignore this one.
2062 */
2063 if (!(uap->options & WSTOPPED))
2064 break;
2065
2066 /*
2067 * If someone has already waited it, we lost a race
2068 * to be the one to return status.
2069 */
2070 if ((p->p_lflag & P_LWAITED) != 0)
2071 break;
2072 proc_list_unlock();
2073 #if CONFIG_MACF
2074 if ((error = mac_proc_check_wait(q, p)) != 0)
2075 goto out;
2076 #endif
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;
2081
2082 if ((error = copyoutsiginfo(&siginfo,
2083 caller64, uap->infop)) != 0)
2084 goto out;
2085
2086 /* Prevent other process for waiting for this event? */
2087 if (!(uap->options & WNOWAIT)) {
2088 proc_lock(p);
2089 p->p_lflag |= P_LWAITED;
2090 proc_unlock(p);
2091 }
2092 goto out;
2093
2094 default: /* All other states => Continued */
2095 if (!(uap->options & WCONTINUED))
2096 break;
2097
2098 /*
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().
2102 */
2103 if ((p->p_flag & P_CONTINUED) == 0)
2104 break;
2105 proc_list_unlock();
2106 #if CONFIG_MACF
2107 if ((error = mac_proc_check_wait(q, p)) != 0)
2108 goto out;
2109 #endif
2110 siginfo.si_signo = SIGCHLD;
2111 siginfo.si_code = CLD_CONTINUED;
2112 proc_lock(p);
2113 siginfo.si_pid = p->p_contproc;
2114 siginfo.si_status = p->p_xstat;
2115 proc_unlock(p);
2116
2117 if ((error = copyoutsiginfo(&siginfo,
2118 caller64, uap->infop)) != 0)
2119 goto out;
2120
2121 /* Prevent other process for waiting for this event? */
2122 if (!(uap->options & WNOWAIT)) {
2123 OSBitAndAtomic(~((uint32_t)P_CONTINUED),
2124 &p->p_flag);
2125 }
2126 goto out;
2127 }
2128 ASSERT_LCK_MTX_OWNED(proc_list_mlock);
2129
2130 /* Not a process we are interested in; go on to next child */
2131
2132 p->p_listflag &= ~P_LIST_WAITING;
2133 wakeup(&p->p_stat);
2134 }
2135 ASSERT_LCK_MTX_OWNED(proc_list_mlock);
2136
2137 /* No child processes that could possibly satisfy the request? */
2138
2139 if (nfound == 0) {
2140 proc_list_unlock();
2141 return (ECHILD);
2142 }
2143
2144 if (uap->options & WNOHANG) {
2145 proc_list_unlock();
2146 #if CONFIG_MACF
2147 if ((error = mac_proc_check_wait(q, p)) != 0)
2148 return (error);
2149 #endif
2150 /*
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.
2154 *
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.
2158 */
2159 return (0);
2160 }
2161
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;
2167
2168 if ((error = msleep0(q, proc_list_mlock,
2169 PWAIT | PCATCH | PDROP, "waitid", 0, waitidcontinue)) != 0)
2170 return (error);
2171
2172 goto loop;
2173 out:
2174 proc_list_lock();
2175 p->p_listflag &= ~P_LIST_WAITING;
2176 wakeup(&p->p_stat);
2177 proc_list_unlock();
2178 return (error);
2179 }
2180
2181 /*
2182 * make process 'parent' the new parent of process 'child'.
2183 */
2184 void
2185 proc_reparentlocked(proc_t child, proc_t parent, int signallable, int locked)
2186 {
2187 proc_t oldparent = PROC_NULL;
2188
2189 if (child->p_pptr == parent)
2190 return;
2191
2192 if (locked == 0)
2193 proc_list_lock();
2194
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);
2199 #endif
2200
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");
2205 #endif
2206 oldparent->p_childrencnt--;
2207 #if __PROC_INTERNAL_DEBUG1
2208 if (oldparent->p_childrencnt < 0)
2209 panic("process children count -ve\n");
2210 #endif
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;
2215
2216 proc_list_unlock();
2217
2218 if ((signallable != 0) && (initproc == parent) && (child->p_stat == SZOMB))
2219 psignal(initproc, SIGCHLD);
2220 if (locked == 1)
2221 proc_list_lock();
2222 }
2223
2224 /*
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.
2228 */
2229
2230 void
2231 vfork_exit(proc_t p, int rv)
2232 {
2233 vfork_exit_internal(p, rv, 0);
2234 }
2235
2236 void
2237 vfork_exit_internal(proc_t p, int rv, int forceexit)
2238 {
2239 thread_t self = current_thread();
2240 #ifdef FIXME
2241 struct task *task = p->task;
2242 #endif
2243 struct uthread *ut;
2244
2245 /*
2246 * If a thread in this task has already
2247 * called exit(), then halt any others
2248 * right here.
2249 */
2250
2251 ut = get_bsdthread_info(self);
2252
2253
2254 proc_lock(p);
2255 if ((p->p_lflag & P_LPEXIT) == P_LPEXIT) {
2256 /*
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()
2259 */
2260 proc_unlock(p);
2261 return;
2262 }
2263 p->p_lflag |= (P_LEXIT | P_LPEXIT);
2264 proc_unlock(p);
2265
2266 if (forceexit == 0) {
2267 /*
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.
2273 */
2274 /* Notify the perf server */
2275 (void)sys_perf_notify(self, p->p_pid);
2276 }
2277
2278 /*
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.
2283 */
2284
2285 proc_list_lock();
2286
2287 #if CONFIG_MEMORYSTATUS
2288 memorystatus_remove(p, TRUE);
2289 #endif
2290
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;
2295
2296 proc_list_unlock();
2297
2298 proc_lock(p);
2299 p->p_xstat = rv;
2300 p->p_lflag &= ~(P_LTRACED | P_LPPWAIT);
2301 p->p_sigignore = ~0;
2302 proc_unlock(p);
2303
2304 ut->uu_siglist = 0;
2305
2306 /* begin vproc_exit */
2307
2308 proc_t q;
2309 proc_t pp;
2310
2311 vnode_t tvp;
2312
2313 struct pgrp * pg;
2314 struct session *sessp;
2315 struct rusage_superset *rup;
2316
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);
2320
2321 proc_refdrain(p);
2322
2323 /*
2324 * Close open files and release open-file table.
2325 * This may block!
2326 */
2327 fdfree(p);
2328
2329 sessp = proc_session(p);
2330 if (SESS_LEADER(p, sessp)) {
2331
2332 if (sessp->s_ttyvp != NULLVP) {
2333 struct vnode *ttyvp;
2334 int ttyvid;
2335 int cttyflag = 0;
2336 struct vfs_context context;
2337 struct tty *tp;
2338
2339 /*
2340 * Controlling process.
2341 * Signal foreground pgrp,
2342 * drain controlling terminal
2343 * and revoke access to controlling terminal.
2344 */
2345 session_lock(sessp);
2346 tp = SESSION_TP(sessp);
2347 if ((tp != TTY_NULL) && (tp->t_session == sessp)) {
2348 session_unlock(sessp);
2349
2350 /*
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
2356 */
2357 tty_lock(tp);
2358 ttysetpgrphup(tp);
2359 tty_unlock(tp);
2360
2361 tty_pgsignal(tp, SIGHUP, 1);
2362
2363 session_lock(sessp);
2364 tp = SESSION_TP(sessp);
2365 }
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);
2375
2376 if ((ttyvp != NULLVP) && (vnode_getwithvid(ttyvp, ttyvid) == 0)) {
2377 if (tp != TTY_NULL) {
2378 tty_lock(tp);
2379 (void) ttywait(tp);
2380 tty_unlock(tp);
2381 }
2382 context.vc_thread = proc_thread(p); /* XXX */
2383 context.vc_ucred = kauth_cred_proc_ref(p);
2384 VNOP_REVOKE(ttyvp, REVOKEALL, &context);
2385 if (cttyflag) {
2386 /*
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.
2392 */
2393 vnode_rele(ttyvp);
2394 }
2395 vnode_put(ttyvp);
2396 kauth_cred_unref(&context.vc_ucred);
2397 ttyvp = NULLVP;
2398 }
2399 if (tp) {
2400 /*
2401 * This is cleared even if not set. This is also done in
2402 * spec_close to ensure that the flag is cleared.
2403 */
2404 tty_lock(tp);
2405 ttyclrpgrphup(tp);
2406 tty_unlock(tp);
2407
2408 ttyfree(tp);
2409 }
2410 }
2411 session_lock(sessp);
2412 sessp->s_leader = NULL;
2413 session_unlock(sessp);
2414 }
2415 session_rele(sessp);
2416
2417 pg = proc_pgrp(p);
2418 fixjobc(p, pg, 0);
2419 pg_rele(pg);
2420
2421 p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
2422
2423 proc_list_lock();
2424 proc_childdrainstart(p);
2425 while ((q = p->p_children.lh_first) != NULL) {
2426 if (q->p_stat == SZOMB) {
2427 if (p != q->p_pptr)
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);
2432 }
2433 q->p_listflag |= P_LIST_WAITING;
2434 /*
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
2442 */
2443 (void)reap_child_locked(p, q, 1, 0, 1, 0);
2444 } else {
2445 /*
2446 * Traced processes are killed
2447 * since their existence means someone is messing up.
2448 */
2449 if (q->p_lflag & P_LTRACED) {
2450 struct proc *opp;
2451
2452 proc_list_unlock();
2453
2454 opp = proc_find(q->p_oppid);
2455 if (opp != PROC_NULL) {
2456 proc_list_lock();
2457 q->p_oppid = 0;
2458 proc_list_unlock();
2459 proc_reparentlocked(q, opp, 0, 0);
2460 proc_rele(opp);
2461 } else {
2462 /* original parent exited while traced */
2463 proc_list_lock();
2464 q->p_listflag |= P_LIST_DEADPARENT;
2465 q->p_oppid = 0;
2466 proc_list_unlock();
2467 proc_reparentlocked(q, initproc, 0, 0);
2468 }
2469
2470 proc_lock(q);
2471 q->p_lflag &= ~P_LTRACED;
2472
2473 if (q->sigwait_thread) {
2474 thread_t thread = q->sigwait_thread;
2475
2476 proc_unlock(q);
2477 /*
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.
2483 */
2484 thread_resume(thread);
2485 clear_wait(thread, THREAD_INTERRUPTED);
2486 threadsignal(thread, SIGKILL, 0, TRUE);
2487 } else {
2488 proc_unlock(q);
2489 }
2490
2491 psignal(q, SIGKILL);
2492 proc_list_lock();
2493 } else {
2494 q->p_listflag |= P_LIST_DEADPARENT;
2495 proc_reparentlocked(q, initproc, 0, 1);
2496 }
2497 }
2498 }
2499
2500 proc_childdrainend(p);
2501 proc_list_unlock();
2502
2503 /*
2504 * Release reference to text vnode
2505 */
2506 tvp = p->p_textvp;
2507 p->p_textvp = NULL;
2508 if (tvp != NULLVP) {
2509 vnode_rele(tvp);
2510 }
2511
2512 /*
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.
2516 */
2517 if (rup != NULL) {
2518 rup->ru = p->p_stats->p_ru;
2519 timerclear(&rup->ru.ru_utime);
2520 timerclear(&rup->ru.ru_stime);
2521
2522 #ifdef FIXME
2523 if (task) {
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;
2528
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;
2536
2537 task_ttimes_stuff = TASK_THREAD_TIMES_INFO_COUNT;
2538 task_info(task, TASK_THREAD_TIMES_INFO,
2539 &ttimesinfo, &task_ttimes_stuff);
2540
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);
2547 }
2548 #endif /* FIXME */
2549
2550 ruadd(&rup->ru, &p->p_stats->p_cru);
2551
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();
2555
2556 /*
2557 * Now that we have filled in the rusage info, make it
2558 * visible to an external observer via proc_pid_rusage().
2559 */
2560 p->p_ru = rup;
2561 }
2562
2563 /*
2564 * Free up profiling buffers.
2565 */
2566 {
2567 struct uprof *p0 = &p->p_stats->p_prof, *p1, *pn;
2568
2569 p1 = p0->pr_next;
2570 p0->pr_next = NULL;
2571 p0->pr_scale = 0;
2572
2573 for (; p1 != NULL; p1 = pn) {
2574 pn = p1->pr_next;
2575 kfree(p1, sizeof *p1);
2576 }
2577 }
2578
2579 #if PSYNCH
2580 pth_proc_hashdelete(p);
2581 #endif /* PSYNCH */
2582
2583 proc_free_realitimer(p);
2584
2585 /*
2586 * Other substructures are freed from wait().
2587 */
2588 FREE_ZONE(p->p_stats, sizeof *p->p_stats, M_PSTATS);
2589 p->p_stats = NULL;
2590
2591 FREE_ZONE(p->p_sigacts, sizeof *p->p_sigacts, M_SIGACTS);
2592 p->p_sigacts = NULL;
2593
2594 proc_limitdrop(p, 1);
2595 p->p_limit = NULL;
2596
2597 /*
2598 * Finish up by terminating the task
2599 * and halt this thread (only if a
2600 * member of the task exiting).
2601 */
2602 p->task = TASK_NULL;
2603
2604 /*
2605 * Notify parent that we're gone.
2606 */
2607 pp = proc_parent(p);
2608 if ((p->p_listflag & P_LIST_DEADPARENT) == 0) {
2609 if (pp != initproc) {
2610 proc_lock(pp);
2611 pp->si_pid = p->p_pid;
2612 pp->p_xhighbits = p->p_xhighbits;
2613 p->p_xhighbits = 0;
2614 pp->si_status = p->p_xstat;
2615 pp->si_code = CLD_EXITED;
2616 /*
2617 * p_ucred usage is safe as it is an exiting process
2618 * and reference is dropped in reap
2619 */
2620 pp->si_uid = kauth_cred_getruid(p->p_ucred);
2621 proc_unlock(pp);
2622 }
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
2629 */
2630 p->p_stat = SZOMB;
2631
2632 psignal(pp, SIGCHLD);
2633
2634 /* and now wakeup the parent */
2635 proc_list_lock();
2636 wakeup((caddr_t)pp);
2637 proc_list_unlock();
2638 } else {
2639 proc_list_lock();
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);
2643 }
2644 p->p_stat = SZOMB;
2645 p->p_listflag |= P_LIST_WAITING;
2646
2647 /*
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
2655 */
2656 (void)reap_child_locked(pp, p, 0, 0, 1, 1);
2657 /* list lock dropped by reap_child_locked */
2658 }
2659 proc_rele(pp);
2660 }
2661
2662
2663 /*
2664 * munge_rusage
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
2667 * 64 bit version.
2668 */
2669 __private_extern__ void
2670 munge_user64_rusage(struct rusage *a_rusage_p, struct user64_rusage *a_user_rusage_p)
2671 {
2672 /* Zero-out struct so that padding is cleared */
2673 bzero(a_user_rusage_p, sizeof(struct user64_rusage));
2674
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;
2680 /*
2681 * everything else can be a direct assign, since there is no loss
2682 * of precision implied boing 32->64.
2683 */
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;
2698 }
2699
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)
2703 {
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;
2709 /*
2710 * everything else can be a direct assign. We currently ignore
2711 * the loss of precision
2712 */
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;
2727 }