xref: /xnu-8796.101.5/osfmk/corpses/corpse.c (revision aca3beaa3dfbd42498b42c5e5ce20a938e6554e5)
1 /*
2  * Copyright (c) 2012-2013, 2015 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 
29 
30 /*
31  * Corpses Overview
32  * ================
33  *
34  * A corpse is a state of process that is past the point of its death. This means that process has
35  * completed all its termination operations like releasing file descriptors, mach ports, sockets and
36  * other constructs used to identify a process. For all the processes this mimics the behavior as if
37  * the process has died and no longer available by any means.
38  *
39  * Why do we need Corpses?
40  * -----------------------
41  * For crash inspection we need to inspect the state and data that is associated with process so that
42  * crash reporting infrastructure can build backtraces, find leaks etc. For example a crash
43  *
44  * Corpses functionality in kernel
45  * ===============================
46  * The corpse functionality is an extension of existing exception reporting mechanisms we have. The
47  * exception_triage calls will try to deliver the first round of exceptions allowing
48  * task/debugger/ReportCrash/launchd level exception handlers to  respond to exception. If even after
49  * notification the exception is not handled, then the process begins the death operations and during
50  * proc_prepareexit, we decide to create a corpse for inspection. Following is a sample run through
51  * of events and data shuffling that happens when corpses is enabled.
52  *
53  *   * a process causes an exception during normal execution of threads.
54  *   * The exception generated by either mach(e.g GUARDED_MARCHPORT) or bsd(eg SIGABORT, GUARDED_FD
55  *     etc) side is passed through the exception_triage() function to follow the thread -> task -> host
56  *     level exception handling system. This set of steps are same as before and allow for existing
57  *     crash reporting systems (both internal and 3rd party) to catch and create reports as required.
58  *   * If above exception handling returns failed (when nobody handles the notification), then the
59  *     proc_prepareexit path has logic to decide to create corpse.
60  *   * The task_mark_corpse function allocates userspace vm memory and attaches the information
61  *     kcdata_descriptor_t to task->corpse_info field of task.
62  *     - All the task's threads are marked with the "inspection" flag which signals the termination
63  *       daemon to not reap them but hold until they are being inspected.
64  *     - task flags t_flags reflect the corpse bit and also a PENDING_CORPSE bit. PENDING_CORPSE
65  *       prevents task_terminate from stripping important data from task.
66  *     - It marks all the threads to terminate and return to AST for termination.
67  *     - The allocation logic takes into account the rate limiting policy of allowing only
68  *       TOTAL_CORPSES_ALLOWED in flight.
69  *   * The proc exit threads continues and collects required information in the allocated vm region.
70  *     Once complete it marks itself for termination.
71  *   * In the thread_terminate_self(), the last thread to enter will do a call to proc_exit().
72  *     Following this is a check to see if task is marked for corpse notification and will
73  *     invoke the the task_deliver_crash_notification().
74  *   * Once EXC_CORPSE_NOTIFY is delivered, it removes the PENDING_CORPSE flag from task (and
75  *     inspection flag from all its threads) and allows task_terminate to go ahead and continue
76  *     the mach task termination process.
77  *   * ASIDE: The rest of the threads that are reaching the thread_terminate_daemon() with the
78  *     inspection flag set are just bounced to another holding queue (crashed_threads_queue).
79  *     Only after the corpse notification these are pulled out from holding queue and enqueued
80  *     back to termination queue
81  *
82  *
83  * Corpse info format
84  * ==================
85  * The kernel (task_mark_corpse()) makes a vm allocation in the dead task's vm space (with tag
86  *     VM_MEMORY_CORPSEINFO (80)). Within this memory all corpse information is saved by various
87  *     subsystems like
88  *   * bsd proc exit path may write down pid, parent pid, number of file descriptors etc
89  *   * mach side may append data regarding ledger usage, memory stats etc
90  * See detailed info about the memory structure and format in kern_cdata.h documentation.
91  *
92  * Configuring Corpses functionality
93  * =================================
94  *   boot-arg: -no_corpses disables the corpse generation. This can be added/removed without affecting
95  *     any other subsystem.
96  *   TOTAL_CORPSES_ALLOWED : (recompilation required) - Changing this number allows for controlling
97  *     the number of corpse instances to be held for inspection before allowing memory to be reclaimed
98  *     by system.
99  *   CORPSEINFO_ALLOCATION_SIZE: is the default size of vm allocation. If in future there is much more
100  *     data to be put in, then please re-tune this parameter.
101  *
102  * Debugging/Visibility
103  * ====================
104  *   * lldbmacros for thread and task summary are updated to show "C" flag for corpse task/threads.
105  *   * there are macros to see list of threads in termination queue (dumpthread_terminate_queue)
106  *     and holding queue (dumpcrashed_thread_queue).
107  *   * In case of corpse creation is disabled of ignored then the system log is updated with
108  *     printf data with reason.
109  *
110  * Limitations of Corpses
111  * ======================
112  *   With holding off memory for inspection, it creates vm pressure which might not be desirable
113  *   on low memory devices. There are limits to max corpses being inspected at a time which is
114  *   marked by TOTAL_CORPSES_ALLOWED.
115  *
116  */
117 
118 
119 #include <stdatomic.h>
120 #include <kern/assert.h>
121 #include <mach/mach_types.h>
122 #include <mach/boolean.h>
123 #include <mach/vm_param.h>
124 #include <mach/task.h>
125 #include <mach/thread_act.h>
126 #include <mach/host_priv.h>
127 #include <kern/host.h>
128 #include <kern/kern_types.h>
129 #include <kern/mach_param.h>
130 #include <kern/thread.h>
131 #include <kern/task.h>
132 #include <corpses/task_corpse.h>
133 #include <kern/kalloc.h>
134 #include <kern/kern_cdata.h>
135 #include <mach/mach_vm.h>
136 #include <kern/exc_guard.h>
137 #include <os/log.h>
138 
139 #if CONFIG_MACF
140 #include <security/mac_mach_internal.h>
141 #endif
142 
143 /*
144  * Exported interfaces
145  */
146 #include <mach/task_server.h>
147 
148 union corpse_creation_gate {
149 	struct {
150 		uint16_t user_faults;
151 		uint16_t corpses;
152 	};
153 	uint32_t value;
154 };
155 
156 static _Atomic uint32_t inflight_corpses;
157 unsigned long  total_corpses_created = 0;
158 
159 static TUNABLE(bool, corpses_disabled, "-no_corpses", false);
160 
161 #if !XNU_TARGET_OS_OSX
162 /* Use lightweight corpse on embedded */
163 static TUNABLE(bool, lw_corpses_enabled, "lw_corpses", true);
164 #else
165 static TUNABLE(bool, lw_corpses_enabled, "lw_corpses", false);
166 #endif
167 
168 #if DEBUG || DEVELOPMENT
169 /* bootarg to generate corpse with size up to max_footprint_mb */
170 TUNABLE(bool, corpse_threshold_system_limit, "corpse_threshold_system_limit", false);
171 #endif /* DEBUG || DEVELOPMENT */
172 
173 /* bootarg to turn on corpse forking for EXC_RESOURCE */
174 TUNABLE(bool, exc_via_corpse_forking, "exc_via_corpse_forking", true);
175 
176 /* bootarg to generate corpse for fatal high memory watermark violation */
177 TUNABLE(bool, corpse_for_fatal_memkill, "corpse_for_fatal_memkill", true);
178 
179 extern int IS_64BIT_PROCESS(void *);
180 extern void gather_populate_corpse_crashinfo(void *p, task_t task,
181     mach_exception_data_type_t code, mach_exception_data_type_t subcode,
182     uint64_t *udata_buffer, int num_udata, void *reason, exception_type_t etype);
183 extern void *proc_find(int pid);
184 extern int proc_rele(void *p);
185 extern task_t proc_get_task_raw(void *proc);
186 extern char *proc_best_name(struct proc *proc);
187 
188 
189 /*
190  * Routine: corpses_enabled
191  * returns FALSE if not enabled
192  */
193 boolean_t
corpses_enabled(void)194 corpses_enabled(void)
195 {
196 	return !corpses_disabled;
197 }
198 
199 unsigned long
total_corpses_count(void)200 total_corpses_count(void)
201 {
202 	union corpse_creation_gate gate;
203 
204 	gate.value = atomic_load_explicit(&inflight_corpses, memory_order_relaxed);
205 	return gate.corpses;
206 }
207 
208 extern char *proc_best_name(struct proc *);
209 extern int proc_pid(struct proc *);
210 
211 /*
212  * Routine: task_crashinfo_get_ref()
213  *          Grab a slot at creating a corpse.
214  * Returns: KERN_SUCCESS if the policy allows for creating a corpse.
215  */
216 static kern_return_t
task_crashinfo_get_ref(corpse_flags_t kcd_u_flags)217 task_crashinfo_get_ref(corpse_flags_t kcd_u_flags)
218 {
219 	union corpse_creation_gate oldgate, newgate;
220 	struct proc *p = (void *)current_proc();
221 
222 	assert(kcd_u_flags & CORPSE_CRASHINFO_HAS_REF);
223 
224 	oldgate.value = atomic_load_explicit(&inflight_corpses, memory_order_relaxed);
225 	for (;;) {
226 		newgate = oldgate;
227 		if (kcd_u_flags & CORPSE_CRASHINFO_USER_FAULT) {
228 			if (newgate.user_faults++ >= TOTAL_USER_FAULTS_ALLOWED) {
229 				os_log(OS_LOG_DEFAULT, "%s[%d] Corpse failure, too many faults %d\n",
230 				    proc_best_name(p), proc_pid(p), newgate.user_faults);
231 				return KERN_RESOURCE_SHORTAGE;
232 			}
233 		}
234 		if (newgate.corpses++ >= TOTAL_CORPSES_ALLOWED) {
235 			os_log(OS_LOG_DEFAULT, "%s[%d] Corpse failure, too many %d\n",
236 			    proc_best_name(p), proc_pid(p), newgate.corpses);
237 			return KERN_RESOURCE_SHORTAGE;
238 		}
239 
240 		// this reloads the value in oldgate
241 		if (atomic_compare_exchange_strong_explicit(&inflight_corpses,
242 		    &oldgate.value, newgate.value, memory_order_relaxed,
243 		    memory_order_relaxed)) {
244 			os_log(OS_LOG_DEFAULT, "%s[%d] Corpse allowed %d of %d\n",
245 			    proc_best_name(p), proc_pid(p), newgate.corpses, TOTAL_CORPSES_ALLOWED);
246 			return KERN_SUCCESS;
247 		}
248 	}
249 }
250 
251 /*
252  * Routine: task_crashinfo_release_ref
253  *          release the slot for corpse being used.
254  */
255 static kern_return_t
task_crashinfo_release_ref(corpse_flags_t kcd_u_flags)256 task_crashinfo_release_ref(corpse_flags_t kcd_u_flags)
257 {
258 	union corpse_creation_gate oldgate, newgate;
259 
260 	assert(kcd_u_flags & CORPSE_CRASHINFO_HAS_REF);
261 
262 	oldgate.value = atomic_load_explicit(&inflight_corpses, memory_order_relaxed);
263 	for (;;) {
264 		newgate = oldgate;
265 		if (kcd_u_flags & CORPSE_CRASHINFO_USER_FAULT) {
266 			if (newgate.user_faults-- == 0) {
267 				panic("corpse in flight count over-release");
268 			}
269 		}
270 		if (newgate.corpses-- == 0) {
271 			panic("corpse in flight count over-release");
272 		}
273 		// this reloads the value in oldgate
274 		if (atomic_compare_exchange_strong_explicit(&inflight_corpses,
275 		    &oldgate.value, newgate.value, memory_order_relaxed,
276 		    memory_order_relaxed)) {
277 			os_log(OS_LOG_DEFAULT, "Corpse released, count at %d\n", newgate.corpses);
278 			return KERN_SUCCESS;
279 		}
280 	}
281 }
282 
283 
284 kcdata_descriptor_t
task_crashinfo_alloc_init(mach_vm_address_t crash_data_p,unsigned size,corpse_flags_t kc_u_flags,unsigned kc_flags)285 task_crashinfo_alloc_init(mach_vm_address_t crash_data_p, unsigned size,
286     corpse_flags_t kc_u_flags, unsigned kc_flags)
287 {
288 	kcdata_descriptor_t kcdata;
289 
290 	if (kc_u_flags & CORPSE_CRASHINFO_HAS_REF) {
291 		if (KERN_SUCCESS != task_crashinfo_get_ref(kc_u_flags)) {
292 			return NULL;
293 		}
294 	}
295 
296 	kcdata = kcdata_memory_alloc_init(crash_data_p, TASK_CRASHINFO_BEGIN, size,
297 	    kc_flags);
298 	if (kcdata) {
299 		kcdata->kcd_user_flags = kc_u_flags;
300 	} else if (kc_u_flags & CORPSE_CRASHINFO_HAS_REF) {
301 		task_crashinfo_release_ref(kc_u_flags);
302 	}
303 	return kcdata;
304 }
305 
306 kcdata_descriptor_t
task_btinfo_alloc_init(mach_vm_address_t addr,unsigned size)307 task_btinfo_alloc_init(mach_vm_address_t addr, unsigned size)
308 {
309 	kcdata_descriptor_t kcdata;
310 
311 	kcdata = kcdata_memory_alloc_init(addr, TASK_BTINFO_BEGIN, size, KCFLAG_USE_MEMCOPY);
312 
313 	return kcdata;
314 }
315 
316 
317 /*
318  * Free up the memory associated with task_crashinfo_data
319  */
320 kern_return_t
task_crashinfo_destroy(kcdata_descriptor_t data)321 task_crashinfo_destroy(kcdata_descriptor_t data)
322 {
323 	if (!data) {
324 		return KERN_INVALID_ARGUMENT;
325 	}
326 	if (data->kcd_user_flags & CORPSE_CRASHINFO_HAS_REF) {
327 		task_crashinfo_release_ref(data->kcd_user_flags);
328 	}
329 	return kcdata_memory_destroy(data);
330 }
331 
332 /*
333  * Routine: task_get_corpseinfo
334  * params: task - task which has corpse info setup.
335  * returns: crash info data attached to task.
336  *          NULL if task is null or has no corpse info
337  */
338 kcdata_descriptor_t
task_get_corpseinfo(task_t task)339 task_get_corpseinfo(task_t task)
340 {
341 	kcdata_descriptor_t retval = NULL;
342 	if (task != NULL) {
343 		retval = task->corpse_info;
344 	}
345 	return retval;
346 }
347 
348 /*
349  * Routine: task_add_to_corpse_task_list
350  * params: task - task to be added to corpse task list
351  * returns: None.
352  */
353 void
task_add_to_corpse_task_list(task_t corpse_task)354 task_add_to_corpse_task_list(task_t corpse_task)
355 {
356 	lck_mtx_lock(&tasks_corpse_lock);
357 	queue_enter(&corpse_tasks, corpse_task, task_t, corpse_tasks);
358 	lck_mtx_unlock(&tasks_corpse_lock);
359 }
360 
361 /*
362  * Routine: task_remove_from_corpse_task_list
363  * params: task - task to be removed from corpse task list
364  * returns: None.
365  */
366 void
task_remove_from_corpse_task_list(task_t corpse_task)367 task_remove_from_corpse_task_list(task_t corpse_task)
368 {
369 	lck_mtx_lock(&tasks_corpse_lock);
370 	queue_remove(&corpse_tasks, corpse_task, task_t, corpse_tasks);
371 	lck_mtx_unlock(&tasks_corpse_lock);
372 }
373 
374 /*
375  * Routine: task_purge_all_corpses
376  * params: None.
377  * returns: None.
378  */
379 void
task_purge_all_corpses(void)380 task_purge_all_corpses(void)
381 {
382 	task_t task;
383 
384 	lck_mtx_lock(&tasks_corpse_lock);
385 	/* Iterate through all the corpse tasks and clear all map entries */
386 	queue_iterate(&corpse_tasks, task, task_t, corpse_tasks) {
387 		os_log(OS_LOG_DEFAULT, "Memory pressure corpse purge for pid %d.\n", task_pid(task));
388 		vm_map_terminate(task->map);
389 	}
390 	lck_mtx_unlock(&tasks_corpse_lock);
391 }
392 
393 /*
394  * Routine: find_corpse_task_by_uniqueid_grp
395  * params: task_uniqueid - uniqueid of the corpse
396  *         target - target task [Out Param]
397  *                 grp - task reference group
398  * returns:
399  *         KERN_SUCCESS if a matching corpse if found, gives a ref.
400  *         KERN_FAILURE corpse with given uniqueid is not found.
401  */
402 kern_return_t
find_corpse_task_by_uniqueid_grp(uint64_t task_uniqueid,task_t * target,task_grp_t grp)403 find_corpse_task_by_uniqueid_grp(
404 	uint64_t   task_uniqueid,
405 	task_t     *target,
406 	task_grp_t grp)
407 {
408 	task_t task;
409 
410 	lck_mtx_lock(&tasks_corpse_lock);
411 
412 	queue_iterate(&corpse_tasks, task, task_t, corpse_tasks) {
413 		if (task->task_uniqueid == task_uniqueid) {
414 			lck_mtx_unlock(&tasks_corpse_lock);
415 			task_reference_grp(task, grp);
416 			*target = task;
417 			return KERN_SUCCESS;
418 		}
419 	}
420 
421 	lck_mtx_unlock(&tasks_corpse_lock);
422 	return KERN_FAILURE;
423 }
424 
425 /*
426  * Routine: task_generate_corpse
427  * params: task - task to fork a corpse
428  *         corpse_task - task port of the generated corpse
429  * returns: KERN_SUCCESS on Success.
430  *          KERN_FAILURE on Failure.
431  *          KERN_NOT_SUPPORTED on corpse disabled.
432  *          KERN_RESOURCE_SHORTAGE on memory alloc failure or reaching max corpse.
433  */
434 kern_return_t
task_generate_corpse(task_t task,ipc_port_t * corpse_task_port)435 task_generate_corpse(
436 	task_t task,
437 	ipc_port_t *corpse_task_port)
438 {
439 	task_t new_task;
440 	kern_return_t kr;
441 	thread_t thread, th_iter;
442 	ipc_port_t corpse_port;
443 
444 	if (task == kernel_task || task == TASK_NULL) {
445 		return KERN_INVALID_ARGUMENT;
446 	}
447 
448 	task_lock(task);
449 	if (task_is_a_corpse_fork(task)) {
450 		task_unlock(task);
451 		return KERN_INVALID_ARGUMENT;
452 	}
453 	task_unlock(task);
454 
455 	/* Generate a corpse for the given task, will return with a ref on corpse task */
456 	kr = task_generate_corpse_internal(task, &new_task, &thread, 0, 0, 0, NULL);
457 	if (kr != KERN_SUCCESS) {
458 		return kr;
459 	}
460 	if (thread != THREAD_NULL) {
461 		thread_deallocate(thread);
462 	}
463 
464 	/* wait for all the threads in the task to terminate */
465 	task_lock(new_task);
466 	task_wait_till_threads_terminate_locked(new_task);
467 
468 	/* Reset thread ports of all the threads in task */
469 	queue_iterate(&new_task->threads, th_iter, thread_t, task_threads)
470 	{
471 		/* Do not reset the thread port for inactive threads */
472 		if (th_iter->corpse_dup == FALSE) {
473 			ipc_thread_reset(th_iter);
474 		}
475 	}
476 	task_unlock(new_task);
477 
478 	/* transfer the task ref to port and arm the no-senders notification */
479 	corpse_port = convert_corpse_to_port_and_nsrequest(new_task);
480 	assert(IP_NULL != corpse_port);
481 
482 	*corpse_task_port = corpse_port;
483 	return KERN_SUCCESS;
484 }
485 
486 /*
487  * Only generate lightweight corpse if any of thread, task, or host level registers
488  * EXC_CORPSE_NOTIFY with behavior EXCEPTION_BACKTRACE.
489  *
490  * Save a send right and behavior of those ports on out param EXC_PORTS.
491  */
492 static boolean_t
task_should_generate_lightweight_corpse(task_t task,ipc_port_t exc_ports[static BT_EXC_PORTS_COUNT])493 task_should_generate_lightweight_corpse(
494 	task_t task,
495 	ipc_port_t exc_ports[static BT_EXC_PORTS_COUNT])
496 {
497 	kern_return_t kr;
498 	boolean_t should_generate = FALSE;
499 
500 	exception_mask_t mask;
501 	mach_msg_type_number_t nmasks;
502 	exception_port_t exc_port = IP_NULL;
503 	exception_behavior_t behavior;
504 	thread_state_flavor_t flavor;
505 
506 	if (task != current_task()) {
507 		return FALSE;
508 	}
509 
510 	if (!lw_corpses_enabled) {
511 		return FALSE;
512 	}
513 
514 	for (unsigned int i = 0; i < BT_EXC_PORTS_COUNT; i++) {
515 		nmasks = 1;
516 
517 		/* thread, task, and host level, in this order */
518 		if (i == 0) {
519 			kr = thread_get_exception_ports(current_thread(), EXC_MASK_CORPSE_NOTIFY,
520 			    &mask, &nmasks, &exc_port, &behavior, &flavor);
521 		} else if (i == 1) {
522 			kr = task_get_exception_ports(current_task(), EXC_MASK_CORPSE_NOTIFY,
523 			    &mask, &nmasks, &exc_port, &behavior, &flavor);
524 		} else {
525 			kr = host_get_exception_ports(host_priv_self(), EXC_MASK_CORPSE_NOTIFY,
526 			    &mask, &nmasks, &exc_port, &behavior, &flavor);
527 		}
528 
529 		if (kr != KERN_SUCCESS || nmasks == 0) {
530 			exc_port = IP_NULL;
531 		}
532 
533 		/* thread level can return KERN_SUCCESS && nmasks 0 */
534 		assert(nmasks == 1 || i == 0);
535 
536 		if (IP_VALID(exc_port) && (behavior & MACH_EXCEPTION_BACKTRACE_PREFERRED)) {
537 			assert(behavior & MACH_EXCEPTION_CODES);
538 			exc_ports[i] = exc_port; /* transfers right to array */
539 			exc_port = NULL;
540 			should_generate = TRUE;
541 		} else {
542 			exc_ports[i] = IP_NULL;
543 		}
544 
545 		ipc_port_release_send(exc_port);
546 	}
547 
548 	return should_generate;
549 }
550 
551 /*
552  * Routine: task_enqueue_exception_with_corpse
553  * params: task - task to generate a corpse and enqueue it
554  *         etype - EXC_RESOURCE or EXC_GUARD
555  *         code - exception code to be enqueued
556  *         codeCnt - code array count - code and subcode
557  *
558  * returns: KERN_SUCCESS on Success.
559  *          KERN_FAILURE on Failure.
560  *          KERN_INVALID_ARGUMENT on invalid arguments passed.
561  *          KERN_NOT_SUPPORTED on corpse disabled.
562  *          KERN_RESOURCE_SHORTAGE on memory alloc failure or reaching max corpse.
563  */
564 kern_return_t
task_enqueue_exception_with_corpse(task_t task,exception_type_t etype,mach_exception_data_t code,mach_msg_type_number_t codeCnt,void * reason,boolean_t lightweight)565 task_enqueue_exception_with_corpse(
566 	task_t task,
567 	exception_type_t etype,
568 	mach_exception_data_t code,
569 	mach_msg_type_number_t codeCnt,
570 	void *reason,
571 	boolean_t lightweight)
572 {
573 	kern_return_t kr;
574 	ipc_port_t exc_ports[BT_EXC_PORTS_COUNT]; /* send rights in thread, task, host order */
575 	const char *procname = proc_best_name(get_bsdtask_info(task));
576 
577 	if (codeCnt < 2) {
578 		return KERN_INVALID_ARGUMENT;
579 	}
580 
581 	if (lightweight && task_should_generate_lightweight_corpse(task, exc_ports)) {
582 		/* port rights captured in exc_ports */
583 		kcdata_descriptor_t desc = NULL;
584 		kcdata_object_t obj = KCDATA_OBJECT_NULL;
585 		bool lw_corpse_enqueued = false;
586 
587 		assert(task == current_task());
588 		assert(etype == EXC_GUARD);
589 
590 		kr = kcdata_object_throttle_get(KCDATA_OBJECT_TYPE_LW_CORPSE);
591 		if (kr != KERN_SUCCESS) {
592 			goto out;
593 		}
594 
595 		kr = current_thread_collect_backtrace_info(&desc, etype, code, codeCnt, reason);
596 		if (kr != KERN_SUCCESS) {
597 			kcdata_object_throttle_release(KCDATA_OBJECT_TYPE_LW_CORPSE);
598 			goto out;
599 		}
600 
601 		kr = kcdata_create_object(desc, KCDATA_OBJECT_TYPE_LW_CORPSE, BTINFO_ALLOCATION_SIZE, &obj);
602 		assert(kr == KERN_SUCCESS);
603 		/* desc ref and throttle slot captured in obj ref */
604 
605 		thread_backtrace_enqueue(obj, exc_ports, etype);
606 		os_log(OS_LOG_DEFAULT, "Lightweight corpse enqueued for %s\n", procname);
607 		/* obj ref and exc_ports send rights consumed */
608 		lw_corpse_enqueued = true;
609 
610 out:
611 		if (!lw_corpse_enqueued) {
612 			for (unsigned int i = 0; i < BT_EXC_PORTS_COUNT; i++) {
613 				ipc_port_release_send(exc_ports[i]);
614 			}
615 		}
616 	} else {
617 		task_t corpse = TASK_NULL;
618 		thread_t thread = THREAD_NULL;
619 
620 		/* Generate a corpse for the given task, will return with a ref on corpse task */
621 		kr = task_generate_corpse_internal(task, &corpse, &thread, etype,
622 		    code[0], code[1], reason);
623 		if (kr == KERN_SUCCESS) {
624 			if (thread == THREAD_NULL) {
625 				return KERN_FAILURE;
626 			}
627 			assert(corpse != TASK_NULL);
628 			assert(etype == EXC_RESOURCE || etype == EXC_GUARD);
629 			thread_exception_enqueue(corpse, thread, etype);
630 			os_log(OS_LOG_DEFAULT, "Full corpse enqueued for %s\n", procname);
631 		}
632 	}
633 
634 	return kr;
635 }
636 
637 /*
638  * Routine: task_generate_corpse_internal
639  * params: task - task to fork a corpse
640  *         corpse_task - task of the generated corpse
641  *         exc_thread - equivalent thread in corpse enqueuing exception
642  *         etype - EXC_RESOURCE or EXC_GUARD or 0
643  *         code - mach exception code to be passed in corpse blob
644  *         subcode - mach exception subcode to be passed in corpse blob
645  * returns: KERN_SUCCESS on Success.
646  *          KERN_FAILURE on Failure.
647  *          KERN_NOT_SUPPORTED on corpse disabled.
648  *          KERN_RESOURCE_SHORTAGE on memory alloc failure or reaching max corpse.
649  */
650 kern_return_t
task_generate_corpse_internal(task_t task,task_t * corpse_task,thread_t * exc_thread,exception_type_t etype,mach_exception_data_type_t code,mach_exception_data_type_t subcode,void * reason)651 task_generate_corpse_internal(
652 	task_t task,
653 	task_t *corpse_task,
654 	thread_t *exc_thread,
655 	exception_type_t etype,
656 	mach_exception_data_type_t code,
657 	mach_exception_data_type_t subcode,
658 	void *reason)
659 {
660 	task_t new_task = TASK_NULL;
661 	thread_t thread = THREAD_NULL;
662 	thread_t thread_next = THREAD_NULL;
663 	kern_return_t kr;
664 	struct proc *p = NULL;
665 	int is_64bit_addr;
666 	int is_64bit_data;
667 	uint32_t t_flags;
668 	uint32_t t_flags_ro;
669 	uint64_t *udata_buffer = NULL;
670 	int size = 0;
671 	int num_udata = 0;
672 	corpse_flags_t kc_u_flags = CORPSE_CRASHINFO_HAS_REF;
673 	void *corpse_proc = NULL;
674 
675 #if CONFIG_MACF
676 	struct label *label = NULL;
677 #endif
678 
679 	if (!corpses_enabled()) {
680 		return KERN_NOT_SUPPORTED;
681 	}
682 
683 	if (task_corpse_forking_disabled(task)) {
684 		os_log(OS_LOG_DEFAULT, "corpse for pid %d disabled via SPI\n", task_pid(task));
685 		return KERN_FAILURE;
686 	}
687 
688 	if (etype == EXC_GUARD && EXC_GUARD_DECODE_GUARD_TYPE(code) == GUARD_TYPE_USER) {
689 		kc_u_flags |= CORPSE_CRASHINFO_USER_FAULT;
690 	}
691 
692 	kr = task_crashinfo_get_ref(kc_u_flags);
693 	if (kr != KERN_SUCCESS) {
694 		return kr;
695 	}
696 
697 	/* Having a task reference does not guarantee a proc reference */
698 	p = proc_find(task_pid(task));
699 	if (p == NULL) {
700 		kr = KERN_INVALID_TASK;
701 		goto error_task_generate_corpse;
702 	}
703 
704 	is_64bit_addr = IS_64BIT_PROCESS(p);
705 	is_64bit_data = (task == TASK_NULL) ? is_64bit_addr : task_get_64bit_data(task);
706 	t_flags = TF_CORPSE_FORK |
707 	    TF_PENDING_CORPSE |
708 	    (is_64bit_addr ? TF_64B_ADDR : TF_NONE) |
709 	    (is_64bit_data ? TF_64B_DATA : TF_NONE);
710 	t_flags_ro = TFRO_CORPSE;
711 
712 #if CONFIG_MACF
713 	/* Create the corpse label credentials from the process. */
714 	label = mac_exc_create_label_for_proc(p);
715 #endif
716 
717 	corpse_proc = zalloc_flags(proc_task_zone, Z_WAITOK | Z_ZERO);
718 	new_task = proc_get_task_raw(corpse_proc);
719 
720 	/* Create a task for corpse */
721 	kr = task_create_internal(task,
722 	    NULL,
723 	    NULL,
724 	    TRUE,
725 	    is_64bit_addr,
726 	    is_64bit_data,
727 	    t_flags,
728 	    t_flags_ro,
729 	    TPF_NONE,
730 	    TWF_NONE,
731 	    new_task);
732 	if (kr != KERN_SUCCESS) {
733 		goto error_task_generate_corpse;
734 	}
735 
736 	/* Enable IPC access to the corpse task */
737 	ipc_task_enable(new_task);
738 
739 	/* new task is now referenced, do not free the struct in error case */
740 	corpse_proc = NULL;
741 
742 	/* Create and copy threads from task, returns a ref to thread */
743 	kr = task_duplicate_map_and_threads(task, p, new_task, &thread,
744 	    &udata_buffer, &size, &num_udata, (etype != 0));
745 	if (kr != KERN_SUCCESS) {
746 		goto error_task_generate_corpse;
747 	}
748 
749 	kr = task_collect_crash_info(new_task,
750 #if CONFIG_MACF
751 	    label,
752 #endif
753 	    TRUE);
754 	if (kr != KERN_SUCCESS) {
755 		goto error_task_generate_corpse;
756 	}
757 
758 	/* transfer our references to the corpse info */
759 	assert(new_task->corpse_info->kcd_user_flags == 0);
760 	new_task->corpse_info->kcd_user_flags = kc_u_flags;
761 	kc_u_flags = 0;
762 
763 	kr = task_start_halt(new_task);
764 	if (kr != KERN_SUCCESS) {
765 		goto error_task_generate_corpse;
766 	}
767 
768 	/* terminate the ipc space */
769 	ipc_space_terminate(new_task->itk_space);
770 
771 	/* Populate the corpse blob, use the proc struct of task instead of corpse task */
772 	gather_populate_corpse_crashinfo(p, new_task,
773 	    code, subcode, udata_buffer, num_udata, reason, etype);
774 
775 	/* Add it to global corpse task list */
776 	task_add_to_corpse_task_list(new_task);
777 
778 	*corpse_task = new_task;
779 	*exc_thread = thread;
780 
781 error_task_generate_corpse:
782 #if CONFIG_MACF
783 	if (label) {
784 		mac_exc_free_label(label);
785 	}
786 #endif
787 
788 	/* Release the proc reference */
789 	if (p != NULL) {
790 		proc_rele(p);
791 	}
792 
793 	if (corpse_proc != NULL) {
794 		zfree(proc_task_zone, corpse_proc);
795 	}
796 
797 	if (kr != KERN_SUCCESS) {
798 		if (thread != THREAD_NULL) {
799 			thread_deallocate(thread);
800 		}
801 		if (new_task != TASK_NULL) {
802 			task_lock(new_task);
803 			/* Terminate all the other threads in the task. */
804 			queue_iterate(&new_task->threads, thread_next, thread_t, task_threads)
805 			{
806 				thread_terminate_internal(thread_next);
807 			}
808 			/* wait for all the threads in the task to terminate */
809 			task_wait_till_threads_terminate_locked(new_task);
810 			task_unlock(new_task);
811 
812 			task_clear_corpse(new_task);
813 			task_terminate_internal(new_task);
814 			task_deallocate(new_task);
815 		}
816 		if (kc_u_flags) {
817 			task_crashinfo_release_ref(kc_u_flags);
818 		}
819 	}
820 	/* Free the udata buffer allocated in task_duplicate_map_and_threads */
821 	kfree_data(udata_buffer, size);
822 
823 	return kr;
824 }
825 
826 static kern_return_t
task_map_kcdata_64(task_t task,void * kcdata_addr,mach_vm_address_t * uaddr,mach_vm_size_t kcd_size,vm_tag_t tag)827 task_map_kcdata_64(
828 	task_t task,
829 	void *kcdata_addr,
830 	mach_vm_address_t *uaddr,
831 	mach_vm_size_t kcd_size,
832 	vm_tag_t tag)
833 {
834 	kern_return_t kr;
835 	mach_vm_offset_t udata_ptr;
836 
837 	kr = mach_vm_allocate_kernel(task->map, &udata_ptr, (size_t)kcd_size,
838 	    VM_FLAGS_ANYWHERE, tag);
839 	if (kr != KERN_SUCCESS) {
840 		return kr;
841 	}
842 	copyout(kcdata_addr, (user_addr_t)udata_ptr, (size_t)kcd_size);
843 	*uaddr = udata_ptr;
844 
845 	return KERN_SUCCESS;
846 }
847 
848 /*
849  * Routine: task_map_corpse_info
850  * params: task - Map the corpse info in task's address space
851  *         corpse_task - task port of the corpse
852  *         kcd_addr_begin - address of the mapped corpse info
853  *         kcd_addr_begin - size of the mapped corpse info
854  * returns: KERN_SUCCESS on Success.
855  *          KERN_FAILURE on Failure.
856  *          KERN_INVALID_ARGUMENT on invalid arguments.
857  * Note: Temporary function, will be deleted soon.
858  */
859 kern_return_t
task_map_corpse_info(task_t task,task_t corpse_task,vm_address_t * kcd_addr_begin,uint32_t * kcd_size)860 task_map_corpse_info(
861 	task_t task,
862 	task_t corpse_task,
863 	vm_address_t *kcd_addr_begin,
864 	uint32_t *kcd_size)
865 {
866 	kern_return_t kr;
867 	mach_vm_address_t kcd_addr_begin_64;
868 	mach_vm_size_t size_64;
869 
870 	kr = task_map_corpse_info_64(task, corpse_task, &kcd_addr_begin_64, &size_64);
871 	if (kr != KERN_SUCCESS) {
872 		return kr;
873 	}
874 
875 	*kcd_addr_begin = (vm_address_t)kcd_addr_begin_64;
876 	*kcd_size = (uint32_t) size_64;
877 	return KERN_SUCCESS;
878 }
879 
880 /*
881  * Routine: task_map_corpse_info_64
882  * params: task - Map the corpse info in task's address space
883  *         corpse_task - task port of the corpse
884  *         kcd_addr_begin - address of the mapped corpse info (takes mach_vm_addess_t *)
885  *         kcd_size - size of the mapped corpse info (takes mach_vm_size_t *)
886  * returns: KERN_SUCCESS on Success.
887  *          KERN_FAILURE on Failure.
888  *          KERN_INVALID_ARGUMENT on invalid arguments.
889  */
890 kern_return_t
task_map_corpse_info_64(task_t task,task_t corpse_task,mach_vm_address_t * kcd_addr_begin,mach_vm_size_t * kcd_size)891 task_map_corpse_info_64(
892 	task_t task,
893 	task_t corpse_task,
894 	mach_vm_address_t *kcd_addr_begin,
895 	mach_vm_size_t *kcd_size)
896 {
897 	kern_return_t kr;
898 	mach_vm_offset_t crash_data_ptr = 0;
899 	const mach_vm_size_t size = CORPSEINFO_ALLOCATION_SIZE;
900 	void *corpse_info_kernel = NULL;
901 
902 	if (task == TASK_NULL || task_is_a_corpse(task) ||
903 	    corpse_task == TASK_NULL || !task_is_a_corpse(corpse_task)) {
904 		return KERN_INVALID_ARGUMENT;
905 	}
906 
907 	corpse_info_kernel = kcdata_memory_get_begin_addr(corpse_task->corpse_info);
908 	if (corpse_info_kernel == NULL) {
909 		return KERN_INVALID_ARGUMENT;
910 	}
911 
912 	kr = task_map_kcdata_64(task, corpse_info_kernel, &crash_data_ptr, size,
913 	    VM_MEMORY_CORPSEINFO);
914 
915 	if (kr == KERN_SUCCESS) {
916 		*kcd_addr_begin = crash_data_ptr;
917 		*kcd_size = size;
918 	}
919 
920 	return kr;
921 }
922 
923 /*
924  * Routine: task_map_kcdata_object_64
925  * params: task - Map the underlying kcdata in task's address space
926  *         kcdata_obj - Object representing the data
927  *         kcd_addr_begin - Address of the mapped kcdata
928  *         kcd_size - Size of the mapped kcdata
929  * returns: KERN_SUCCESS on Success.
930  *          KERN_FAILURE on Failure.
931  *          KERN_INVALID_ARGUMENT on invalid arguments.
932  */
933 kern_return_t
task_map_kcdata_object_64(task_t task,kcdata_object_t kcdata_obj,mach_vm_address_t * kcd_addr_begin,mach_vm_size_t * kcd_size)934 task_map_kcdata_object_64(
935 	task_t task,
936 	kcdata_object_t kcdata_obj,
937 	mach_vm_address_t *kcd_addr_begin,
938 	mach_vm_size_t *kcd_size)
939 {
940 	kern_return_t kr;
941 	mach_vm_offset_t bt_data_ptr = 0;
942 	const mach_vm_size_t size = BTINFO_ALLOCATION_SIZE;
943 	void *bt_info_kernel = NULL;
944 
945 	if (task == TASK_NULL || task_is_a_corpse(task) ||
946 	    kcdata_obj == KCDATA_OBJECT_NULL) {
947 		return KERN_INVALID_ARGUMENT;
948 	}
949 
950 	bt_info_kernel = kcdata_memory_get_begin_addr(kcdata_obj->ko_data);
951 	if (bt_info_kernel == NULL) {
952 		return KERN_INVALID_ARGUMENT;
953 	}
954 
955 	kr = task_map_kcdata_64(task, bt_info_kernel, &bt_data_ptr, size,
956 	    VM_MEMORY_BTINFO);
957 
958 	if (kr == KERN_SUCCESS) {
959 		*kcd_addr_begin = bt_data_ptr;
960 		*kcd_size = size;
961 	}
962 
963 	return kr;
964 }
965 
966 uint64_t
task_corpse_get_crashed_thread_id(task_t corpse_task)967 task_corpse_get_crashed_thread_id(task_t corpse_task)
968 {
969 	return corpse_task->crashed_thread_id;
970 }
971