xref: /xnu-8792.41.9/osfmk/corpses/corpse.c (revision 5c2921b07a2480ab43ec66f5b9e41cb872bc554f)
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 
187 /*
188  * Routine: corpses_enabled
189  * returns FALSE if not enabled
190  */
191 boolean_t
corpses_enabled(void)192 corpses_enabled(void)
193 {
194 	return !corpses_disabled;
195 }
196 
197 unsigned long
total_corpses_count(void)198 total_corpses_count(void)
199 {
200 	union corpse_creation_gate gate;
201 
202 	gate.value = atomic_load_explicit(&inflight_corpses, memory_order_relaxed);
203 	return gate.corpses;
204 }
205 
206 extern char *proc_best_name(struct proc *);
207 extern int proc_pid(struct proc *);
208 
209 /*
210  * Routine: task_crashinfo_get_ref()
211  *          Grab a slot at creating a corpse.
212  * Returns: KERN_SUCCESS if the policy allows for creating a corpse.
213  */
214 static kern_return_t
task_crashinfo_get_ref(corpse_flags_t kcd_u_flags)215 task_crashinfo_get_ref(corpse_flags_t kcd_u_flags)
216 {
217 	union corpse_creation_gate oldgate, newgate;
218 	struct proc *p = (void *)current_proc();
219 
220 	assert(kcd_u_flags & CORPSE_CRASHINFO_HAS_REF);
221 
222 	oldgate.value = atomic_load_explicit(&inflight_corpses, memory_order_relaxed);
223 	for (;;) {
224 		newgate = oldgate;
225 		if (kcd_u_flags & CORPSE_CRASHINFO_USER_FAULT) {
226 			if (newgate.user_faults++ >= TOTAL_USER_FAULTS_ALLOWED) {
227 				os_log(OS_LOG_DEFAULT, "%s[%d] Corpse failure, too many faults %d\n",
228 				    proc_best_name(p), proc_pid(p), newgate.user_faults);
229 				return KERN_RESOURCE_SHORTAGE;
230 			}
231 		}
232 		if (newgate.corpses++ >= TOTAL_CORPSES_ALLOWED) {
233 			os_log(OS_LOG_DEFAULT, "%s[%d] Corpse failure, too many %d\n",
234 			    proc_best_name(p), proc_pid(p), newgate.corpses);
235 			return KERN_RESOURCE_SHORTAGE;
236 		}
237 
238 		// this reloads the value in oldgate
239 		if (atomic_compare_exchange_strong_explicit(&inflight_corpses,
240 		    &oldgate.value, newgate.value, memory_order_relaxed,
241 		    memory_order_relaxed)) {
242 			os_log(OS_LOG_DEFAULT, "%s[%d] Corpse allowed %d of %d\n",
243 			    proc_best_name(p), proc_pid(p), newgate.corpses, TOTAL_CORPSES_ALLOWED);
244 			return KERN_SUCCESS;
245 		}
246 	}
247 }
248 
249 /*
250  * Routine: task_crashinfo_release_ref
251  *          release the slot for corpse being used.
252  */
253 static kern_return_t
task_crashinfo_release_ref(corpse_flags_t kcd_u_flags)254 task_crashinfo_release_ref(corpse_flags_t kcd_u_flags)
255 {
256 	union corpse_creation_gate oldgate, newgate;
257 
258 	assert(kcd_u_flags & CORPSE_CRASHINFO_HAS_REF);
259 
260 	oldgate.value = atomic_load_explicit(&inflight_corpses, memory_order_relaxed);
261 	for (;;) {
262 		newgate = oldgate;
263 		if (kcd_u_flags & CORPSE_CRASHINFO_USER_FAULT) {
264 			if (newgate.user_faults-- == 0) {
265 				panic("corpse in flight count over-release");
266 			}
267 		}
268 		if (newgate.corpses-- == 0) {
269 			panic("corpse in flight count over-release");
270 		}
271 		// this reloads the value in oldgate
272 		if (atomic_compare_exchange_strong_explicit(&inflight_corpses,
273 		    &oldgate.value, newgate.value, memory_order_relaxed,
274 		    memory_order_relaxed)) {
275 			os_log(OS_LOG_DEFAULT, "Corpse released, count at %d\n", newgate.corpses);
276 			return KERN_SUCCESS;
277 		}
278 	}
279 }
280 
281 
282 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)283 task_crashinfo_alloc_init(mach_vm_address_t crash_data_p, unsigned size,
284     corpse_flags_t kc_u_flags, unsigned kc_flags)
285 {
286 	kcdata_descriptor_t kcdata;
287 
288 	if (kc_u_flags & CORPSE_CRASHINFO_HAS_REF) {
289 		if (KERN_SUCCESS != task_crashinfo_get_ref(kc_u_flags)) {
290 			return NULL;
291 		}
292 	}
293 
294 	kcdata = kcdata_memory_alloc_init(crash_data_p, TASK_CRASHINFO_BEGIN, size,
295 	    kc_flags);
296 	if (kcdata) {
297 		kcdata->kcd_user_flags = kc_u_flags;
298 	} else if (kc_u_flags & CORPSE_CRASHINFO_HAS_REF) {
299 		task_crashinfo_release_ref(kc_u_flags);
300 	}
301 	return kcdata;
302 }
303 
304 kcdata_descriptor_t
task_btinfo_alloc_init(mach_vm_address_t addr,unsigned size)305 task_btinfo_alloc_init(mach_vm_address_t addr, unsigned size)
306 {
307 	kcdata_descriptor_t kcdata;
308 
309 	kcdata = kcdata_memory_alloc_init(addr, TASK_BTINFO_BEGIN, size, KCFLAG_USE_MEMCOPY);
310 
311 	return kcdata;
312 }
313 
314 
315 /*
316  * Free up the memory associated with task_crashinfo_data
317  */
318 kern_return_t
task_crashinfo_destroy(kcdata_descriptor_t data)319 task_crashinfo_destroy(kcdata_descriptor_t data)
320 {
321 	if (!data) {
322 		return KERN_INVALID_ARGUMENT;
323 	}
324 	if (data->kcd_user_flags & CORPSE_CRASHINFO_HAS_REF) {
325 		task_crashinfo_release_ref(data->kcd_user_flags);
326 	}
327 	return kcdata_memory_destroy(data);
328 }
329 
330 /*
331  * Routine: task_get_corpseinfo
332  * params: task - task which has corpse info setup.
333  * returns: crash info data attached to task.
334  *          NULL if task is null or has no corpse info
335  */
336 kcdata_descriptor_t
task_get_corpseinfo(task_t task)337 task_get_corpseinfo(task_t task)
338 {
339 	kcdata_descriptor_t retval = NULL;
340 	if (task != NULL) {
341 		retval = task->corpse_info;
342 	}
343 	return retval;
344 }
345 
346 /*
347  * Routine: task_add_to_corpse_task_list
348  * params: task - task to be added to corpse task list
349  * returns: None.
350  */
351 void
task_add_to_corpse_task_list(task_t corpse_task)352 task_add_to_corpse_task_list(task_t corpse_task)
353 {
354 	lck_mtx_lock(&tasks_corpse_lock);
355 	queue_enter(&corpse_tasks, corpse_task, task_t, corpse_tasks);
356 	lck_mtx_unlock(&tasks_corpse_lock);
357 }
358 
359 /*
360  * Routine: task_remove_from_corpse_task_list
361  * params: task - task to be removed from corpse task list
362  * returns: None.
363  */
364 void
task_remove_from_corpse_task_list(task_t corpse_task)365 task_remove_from_corpse_task_list(task_t corpse_task)
366 {
367 	lck_mtx_lock(&tasks_corpse_lock);
368 	queue_remove(&corpse_tasks, corpse_task, task_t, corpse_tasks);
369 	lck_mtx_unlock(&tasks_corpse_lock);
370 }
371 
372 /*
373  * Routine: task_purge_all_corpses
374  * params: None.
375  * returns: None.
376  */
377 void
task_purge_all_corpses(void)378 task_purge_all_corpses(void)
379 {
380 	task_t task;
381 
382 	lck_mtx_lock(&tasks_corpse_lock);
383 	/* Iterate through all the corpse tasks and clear all map entries */
384 	queue_iterate(&corpse_tasks, task, task_t, corpse_tasks) {
385 		os_log(OS_LOG_DEFAULT, "Memory pressure corpse purge for pid %d.\n", task_pid(task));
386 		vm_map_terminate(task->map);
387 	}
388 	lck_mtx_unlock(&tasks_corpse_lock);
389 }
390 
391 /*
392  * Routine: find_corpse_task_by_uniqueid_grp
393  * params: task_uniqueid - uniqueid of the corpse
394  *         target - target task [Out Param]
395  *                 grp - task reference group
396  * returns:
397  *         KERN_SUCCESS if a matching corpse if found, gives a ref.
398  *         KERN_FAILURE corpse with given uniqueid is not found.
399  */
400 kern_return_t
find_corpse_task_by_uniqueid_grp(uint64_t task_uniqueid,task_t * target,task_grp_t grp)401 find_corpse_task_by_uniqueid_grp(
402 	uint64_t   task_uniqueid,
403 	task_t     *target,
404 	task_grp_t grp)
405 {
406 	task_t task;
407 
408 	lck_mtx_lock(&tasks_corpse_lock);
409 
410 	queue_iterate(&corpse_tasks, task, task_t, corpse_tasks) {
411 		if (task->task_uniqueid == task_uniqueid) {
412 			lck_mtx_unlock(&tasks_corpse_lock);
413 			task_reference_grp(task, grp);
414 			*target = task;
415 			return KERN_SUCCESS;
416 		}
417 	}
418 
419 	lck_mtx_unlock(&tasks_corpse_lock);
420 	return KERN_FAILURE;
421 }
422 
423 /*
424  * Routine: task_generate_corpse
425  * params: task - task to fork a corpse
426  *         corpse_task - task port of the generated corpse
427  * returns: KERN_SUCCESS on Success.
428  *          KERN_FAILURE on Failure.
429  *          KERN_NOT_SUPPORTED on corpse disabled.
430  *          KERN_RESOURCE_SHORTAGE on memory alloc failure or reaching max corpse.
431  */
432 kern_return_t
task_generate_corpse(task_t task,ipc_port_t * corpse_task_port)433 task_generate_corpse(
434 	task_t task,
435 	ipc_port_t *corpse_task_port)
436 {
437 	task_t new_task;
438 	kern_return_t kr;
439 	thread_t thread, th_iter;
440 	ipc_port_t corpse_port;
441 
442 	if (task == kernel_task || task == TASK_NULL) {
443 		return KERN_INVALID_ARGUMENT;
444 	}
445 
446 	task_lock(task);
447 	if (task_is_a_corpse_fork(task)) {
448 		task_unlock(task);
449 		return KERN_INVALID_ARGUMENT;
450 	}
451 	task_unlock(task);
452 
453 	/* Generate a corpse for the given task, will return with a ref on corpse task */
454 	kr = task_generate_corpse_internal(task, &new_task, &thread, 0, 0, 0, NULL);
455 	if (kr != KERN_SUCCESS) {
456 		return kr;
457 	}
458 	if (thread != THREAD_NULL) {
459 		thread_deallocate(thread);
460 	}
461 
462 	/* wait for all the threads in the task to terminate */
463 	task_lock(new_task);
464 	task_wait_till_threads_terminate_locked(new_task);
465 
466 	/* Reset thread ports of all the threads in task */
467 	queue_iterate(&new_task->threads, th_iter, thread_t, task_threads)
468 	{
469 		/* Do not reset the thread port for inactive threads */
470 		if (th_iter->corpse_dup == FALSE) {
471 			ipc_thread_reset(th_iter);
472 		}
473 	}
474 	task_unlock(new_task);
475 
476 	/* transfer the task ref to port and arm the no-senders notification */
477 	corpse_port = convert_corpse_to_port_and_nsrequest(new_task);
478 	assert(IP_NULL != corpse_port);
479 
480 	*corpse_task_port = corpse_port;
481 	return KERN_SUCCESS;
482 }
483 
484 /*
485  * Only generate lightweight corpse if any of thread, task, or host level registers
486  * EXC_CORPSE_NOTIFY with behavior EXCEPTION_BACKTRACE.
487  *
488  * Save a send right and behavior of those ports on out param EXC_PORTS.
489  */
490 static boolean_t
task_should_generate_lightweight_corpse(task_t task,ipc_port_t exc_ports[static BT_EXC_PORTS_COUNT])491 task_should_generate_lightweight_corpse(
492 	task_t task,
493 	ipc_port_t exc_ports[static BT_EXC_PORTS_COUNT])
494 {
495 	kern_return_t kr;
496 	boolean_t should_generate = FALSE;
497 
498 	exception_mask_t mask;
499 	mach_msg_type_number_t nmasks;
500 	exception_port_t exc_port = IP_NULL;
501 	exception_behavior_t behavior;
502 	thread_state_flavor_t flavor;
503 
504 	if (task != current_task()) {
505 		return FALSE;
506 	}
507 
508 	if (!lw_corpses_enabled) {
509 		return FALSE;
510 	}
511 
512 	for (unsigned int i = 0; i < BT_EXC_PORTS_COUNT; i++) {
513 		nmasks = 1;
514 
515 		/* thread, task, and host level, in this order */
516 		if (i == 0) {
517 			kr = thread_get_exception_ports(current_thread(), EXC_MASK_CORPSE_NOTIFY,
518 			    &mask, &nmasks, &exc_port, &behavior, &flavor);
519 		} else if (i == 1) {
520 			kr = task_get_exception_ports(current_task(), EXC_MASK_CORPSE_NOTIFY,
521 			    &mask, &nmasks, &exc_port, &behavior, &flavor);
522 		} else {
523 			kr = host_get_exception_ports(host_priv_self(), EXC_MASK_CORPSE_NOTIFY,
524 			    &mask, &nmasks, &exc_port, &behavior, &flavor);
525 		}
526 
527 		if (kr != KERN_SUCCESS || nmasks == 0) {
528 			exc_port = IP_NULL;
529 		}
530 
531 		/* thread level can return KERN_SUCCESS && nmasks 0 */
532 		assert(nmasks == 1 || i == 0);
533 
534 		if (IP_VALID(exc_port) && (behavior & MACH_EXCEPTION_BACKTRACE_PREFERRED)) {
535 			assert(behavior & MACH_EXCEPTION_CODES);
536 			exc_ports[i] = exc_port; /* transfers right to array */
537 			exc_port = NULL;
538 			should_generate = TRUE;
539 		} else {
540 			exc_ports[i] = IP_NULL;
541 		}
542 
543 		ipc_port_release_send(exc_port);
544 	}
545 
546 	return should_generate;
547 }
548 
549 /*
550  * Routine: task_enqueue_exception_with_corpse
551  * params: task - task to generate a corpse and enqueue it
552  *         etype - EXC_RESOURCE or EXC_GUARD
553  *         code - exception code to be enqueued
554  *         codeCnt - code array count - code and subcode
555  *
556  * returns: KERN_SUCCESS on Success.
557  *          KERN_FAILURE on Failure.
558  *          KERN_INVALID_ARGUMENT on invalid arguments passed.
559  *          KERN_NOT_SUPPORTED on corpse disabled.
560  *          KERN_RESOURCE_SHORTAGE on memory alloc failure or reaching max corpse.
561  */
562 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)563 task_enqueue_exception_with_corpse(
564 	task_t task,
565 	exception_type_t etype,
566 	mach_exception_data_t code,
567 	mach_msg_type_number_t codeCnt,
568 	void *reason,
569 	boolean_t lightweight)
570 {
571 	kern_return_t kr;
572 	ipc_port_t exc_ports[BT_EXC_PORTS_COUNT]; /* send rights in thread, task, host order */
573 
574 	if (codeCnt < 2) {
575 		return KERN_INVALID_ARGUMENT;
576 	}
577 
578 	if (lightweight && task_should_generate_lightweight_corpse(task, exc_ports)) {
579 		/* port rights captured in exc_ports */
580 		kcdata_descriptor_t desc = NULL;
581 		kcdata_object_t obj = KCDATA_OBJECT_NULL;
582 		bool lw_corpse_enqueued = false;
583 
584 		assert(task == current_task());
585 		assert(etype == EXC_GUARD);
586 
587 		kr = kcdata_object_throttle_get(KCDATA_OBJECT_TYPE_LW_CORPSE);
588 		if (kr != KERN_SUCCESS) {
589 			goto out;
590 		}
591 
592 		kr = current_thread_collect_backtrace_info(&desc, etype, code, codeCnt, reason);
593 		if (kr != KERN_SUCCESS) {
594 			kcdata_object_throttle_release(KCDATA_OBJECT_TYPE_LW_CORPSE);
595 			goto out;
596 		}
597 
598 		kr = kcdata_create_object(desc, KCDATA_OBJECT_TYPE_LW_CORPSE, BTINFO_ALLOCATION_SIZE, &obj);
599 		assert(kr == KERN_SUCCESS);
600 		/* desc ref and throttle slot captured in obj ref */
601 
602 		thread_backtrace_enqueue(obj, exc_ports, etype);
603 		printf("Lightweight corpse enqueued for task %p.\n", task);
604 		/* obj ref and exc_ports send rights consumed */
605 		lw_corpse_enqueued = true;
606 
607 out:
608 		if (!lw_corpse_enqueued) {
609 			for (unsigned int i = 0; i < BT_EXC_PORTS_COUNT; i++) {
610 				ipc_port_release_send(exc_ports[i]);
611 			}
612 		}
613 	} else {
614 		task_t corpse = TASK_NULL;
615 		thread_t thread = THREAD_NULL;
616 
617 		/* Generate a corpse for the given task, will return with a ref on corpse task */
618 		kr = task_generate_corpse_internal(task, &corpse, &thread, etype,
619 		    code[0], code[1], reason);
620 		if (kr == KERN_SUCCESS) {
621 			if (thread == THREAD_NULL) {
622 				return KERN_FAILURE;
623 			}
624 			assert(corpse != TASK_NULL);
625 			assert(etype == EXC_RESOURCE || etype == EXC_GUARD);
626 			thread_exception_enqueue(corpse, thread, etype);
627 			printf("Full corpse %p enqueued for task %p.\n", corpse, task);
628 		}
629 	}
630 
631 	return kr;
632 }
633 
634 /*
635  * Routine: task_generate_corpse_internal
636  * params: task - task to fork a corpse
637  *         corpse_task - task of the generated corpse
638  *         exc_thread - equivalent thread in corpse enqueuing exception
639  *         etype - EXC_RESOURCE or EXC_GUARD or 0
640  *         code - mach exception code to be passed in corpse blob
641  *         subcode - mach exception subcode to be passed in corpse blob
642  * returns: KERN_SUCCESS on Success.
643  *          KERN_FAILURE on Failure.
644  *          KERN_NOT_SUPPORTED on corpse disabled.
645  *          KERN_RESOURCE_SHORTAGE on memory alloc failure or reaching max corpse.
646  */
647 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)648 task_generate_corpse_internal(
649 	task_t task,
650 	task_t *corpse_task,
651 	thread_t *exc_thread,
652 	exception_type_t etype,
653 	mach_exception_data_type_t code,
654 	mach_exception_data_type_t subcode,
655 	void *reason)
656 {
657 	task_t new_task = TASK_NULL;
658 	thread_t thread = THREAD_NULL;
659 	thread_t thread_next = THREAD_NULL;
660 	kern_return_t kr;
661 	struct proc *p = NULL;
662 	int is_64bit_addr;
663 	int is_64bit_data;
664 	int t_flags;
665 	uint64_t *udata_buffer = NULL;
666 	int size = 0;
667 	int num_udata = 0;
668 	corpse_flags_t kc_u_flags = CORPSE_CRASHINFO_HAS_REF;
669 	void *corpse_proc = NULL;
670 
671 #if CONFIG_MACF
672 	struct label *label = NULL;
673 #endif
674 
675 	if (!corpses_enabled()) {
676 		return KERN_NOT_SUPPORTED;
677 	}
678 
679 	if (task_corpse_forking_disabled(task)) {
680 		os_log(OS_LOG_DEFAULT, "corpse for pid %d disabled via SPI\n", task_pid(task));
681 		return KERN_FAILURE;
682 	}
683 
684 	if (etype == EXC_GUARD && EXC_GUARD_DECODE_GUARD_TYPE(code) == GUARD_TYPE_USER) {
685 		kc_u_flags |= CORPSE_CRASHINFO_USER_FAULT;
686 	}
687 
688 	kr = task_crashinfo_get_ref(kc_u_flags);
689 	if (kr != KERN_SUCCESS) {
690 		return kr;
691 	}
692 
693 	/* Having a task reference does not guarantee a proc reference */
694 	p = proc_find(task_pid(task));
695 	if (p == NULL) {
696 		kr = KERN_INVALID_TASK;
697 		goto error_task_generate_corpse;
698 	}
699 
700 	is_64bit_addr = IS_64BIT_PROCESS(p);
701 	is_64bit_data = (task == TASK_NULL) ? is_64bit_addr : task_get_64bit_data(task);
702 	t_flags = TF_CORPSE_FORK |
703 	    TF_PENDING_CORPSE |
704 	    TF_CORPSE |
705 	    (is_64bit_addr ? TF_64B_ADDR : TF_NONE) |
706 	    (is_64bit_data ? TF_64B_DATA : TF_NONE);
707 
708 #if CONFIG_MACF
709 	/* Create the corpse label credentials from the process. */
710 	label = mac_exc_create_label_for_proc(p);
711 #endif
712 
713 	corpse_proc = zalloc_flags(proc_task_zone, Z_WAITOK | Z_ZERO);
714 	new_task = proc_get_task_raw(corpse_proc);
715 
716 	/* Create a task for corpse */
717 	kr = task_create_internal(task,
718 	    NULL,
719 	    NULL,
720 	    TRUE,
721 	    is_64bit_addr,
722 	    is_64bit_data,
723 	    t_flags,
724 	    TPF_NONE,
725 	    TWF_NONE,
726 	    new_task);
727 	if (kr != KERN_SUCCESS) {
728 		goto error_task_generate_corpse;
729 	}
730 
731 	/* Enable IPC access to the corpse task */
732 	ipc_task_enable(new_task);
733 
734 	/* new task is now referenced, do not free the struct in error case */
735 	corpse_proc = NULL;
736 
737 	/* Create and copy threads from task, returns a ref to thread */
738 	kr = task_duplicate_map_and_threads(task, p, new_task, &thread,
739 	    &udata_buffer, &size, &num_udata, (etype != 0));
740 	if (kr != KERN_SUCCESS) {
741 		goto error_task_generate_corpse;
742 	}
743 
744 	kr = task_collect_crash_info(new_task,
745 #if CONFIG_MACF
746 	    label,
747 #endif
748 	    TRUE);
749 	if (kr != KERN_SUCCESS) {
750 		goto error_task_generate_corpse;
751 	}
752 
753 	/* transfer our references to the corpse info */
754 	assert(new_task->corpse_info->kcd_user_flags == 0);
755 	new_task->corpse_info->kcd_user_flags = kc_u_flags;
756 	kc_u_flags = 0;
757 
758 	kr = task_start_halt(new_task);
759 	if (kr != KERN_SUCCESS) {
760 		goto error_task_generate_corpse;
761 	}
762 
763 	/* terminate the ipc space */
764 	ipc_space_terminate(new_task->itk_space);
765 
766 	/* Populate the corpse blob, use the proc struct of task instead of corpse task */
767 	gather_populate_corpse_crashinfo(p, new_task,
768 	    code, subcode, udata_buffer, num_udata, reason, etype);
769 
770 	/* Add it to global corpse task list */
771 	task_add_to_corpse_task_list(new_task);
772 
773 	*corpse_task = new_task;
774 	*exc_thread = thread;
775 
776 error_task_generate_corpse:
777 #if CONFIG_MACF
778 	if (label) {
779 		mac_exc_free_label(label);
780 	}
781 #endif
782 
783 	/* Release the proc reference */
784 	if (p != NULL) {
785 		proc_rele(p);
786 	}
787 
788 	if (corpse_proc != NULL) {
789 		zfree(proc_task_zone, corpse_proc);
790 	}
791 
792 	if (kr != KERN_SUCCESS) {
793 		if (thread != THREAD_NULL) {
794 			thread_deallocate(thread);
795 		}
796 		if (new_task != TASK_NULL) {
797 			task_lock(new_task);
798 			/* Terminate all the other threads in the task. */
799 			queue_iterate(&new_task->threads, thread_next, thread_t, task_threads)
800 			{
801 				thread_terminate_internal(thread_next);
802 			}
803 			/* wait for all the threads in the task to terminate */
804 			task_wait_till_threads_terminate_locked(new_task);
805 			task_unlock(new_task);
806 
807 			task_clear_corpse(new_task);
808 			task_terminate_internal(new_task);
809 			task_deallocate(new_task);
810 		}
811 		if (kc_u_flags) {
812 			task_crashinfo_release_ref(kc_u_flags);
813 		}
814 	}
815 	/* Free the udata buffer allocated in task_duplicate_map_and_threads */
816 	kfree_data(udata_buffer, size);
817 
818 	return kr;
819 }
820 
821 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)822 task_map_kcdata_64(
823 	task_t task,
824 	void *kcdata_addr,
825 	mach_vm_address_t *uaddr,
826 	mach_vm_size_t kcd_size,
827 	vm_tag_t tag)
828 {
829 	kern_return_t kr;
830 	mach_vm_offset_t udata_ptr;
831 
832 	assert(!task_is_a_corpse(task));
833 
834 	kr = mach_vm_allocate_kernel(task->map, &udata_ptr, (size_t)kcd_size,
835 	    VM_FLAGS_ANYWHERE, tag);
836 	if (kr != KERN_SUCCESS) {
837 		return kr;
838 	}
839 	copyout(kcdata_addr, (user_addr_t)udata_ptr, (size_t)kcd_size);
840 	*uaddr = udata_ptr;
841 
842 	return KERN_SUCCESS;
843 }
844 
845 /*
846  * Routine: task_map_corpse_info
847  * params: task - Map the corpse info in task's address space
848  *         corpse_task - task port of the corpse
849  *         kcd_addr_begin - address of the mapped corpse info
850  *         kcd_addr_begin - size of the mapped corpse info
851  * returns: KERN_SUCCESS on Success.
852  *          KERN_FAILURE on Failure.
853  *          KERN_INVALID_ARGUMENT on invalid arguments.
854  * Note: Temporary function, will be deleted soon.
855  */
856 kern_return_t
task_map_corpse_info(task_t task,task_t corpse_task,vm_address_t * kcd_addr_begin,uint32_t * kcd_size)857 task_map_corpse_info(
858 	task_t task,
859 	task_t corpse_task,
860 	vm_address_t *kcd_addr_begin,
861 	uint32_t *kcd_size)
862 {
863 	kern_return_t kr;
864 	mach_vm_address_t kcd_addr_begin_64;
865 	mach_vm_size_t size_64;
866 
867 	kr = task_map_corpse_info_64(task, corpse_task, &kcd_addr_begin_64, &size_64);
868 	if (kr != KERN_SUCCESS) {
869 		return kr;
870 	}
871 
872 	*kcd_addr_begin = (vm_address_t)kcd_addr_begin_64;
873 	*kcd_size = (uint32_t) size_64;
874 	return KERN_SUCCESS;
875 }
876 
877 /*
878  * Routine: task_map_corpse_info_64
879  * params: task - Map the corpse info in task's address space
880  *         corpse_task - task port of the corpse
881  *         kcd_addr_begin - address of the mapped corpse info (takes mach_vm_addess_t *)
882  *         kcd_size - size of the mapped corpse info (takes mach_vm_size_t *)
883  * returns: KERN_SUCCESS on Success.
884  *          KERN_FAILURE on Failure.
885  *          KERN_INVALID_ARGUMENT on invalid arguments.
886  */
887 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)888 task_map_corpse_info_64(
889 	task_t task,
890 	task_t corpse_task,
891 	mach_vm_address_t *kcd_addr_begin,
892 	mach_vm_size_t *kcd_size)
893 {
894 	kern_return_t kr;
895 	mach_vm_offset_t crash_data_ptr = 0;
896 	const mach_vm_size_t size = CORPSEINFO_ALLOCATION_SIZE;
897 	void *corpse_info_kernel = NULL;
898 
899 	if (task == TASK_NULL || task_is_a_corpse(task) ||
900 	    corpse_task == TASK_NULL || !task_is_a_corpse(corpse_task)) {
901 		return KERN_INVALID_ARGUMENT;
902 	}
903 
904 	corpse_info_kernel = kcdata_memory_get_begin_addr(corpse_task->corpse_info);
905 	if (corpse_info_kernel == NULL) {
906 		return KERN_INVALID_ARGUMENT;
907 	}
908 
909 	kr = task_map_kcdata_64(task, corpse_info_kernel, &crash_data_ptr, size,
910 	    VM_MEMORY_CORPSEINFO);
911 
912 	if (kr == KERN_SUCCESS) {
913 		*kcd_addr_begin = crash_data_ptr;
914 		*kcd_size = size;
915 	}
916 
917 	return kr;
918 }
919 
920 /*
921  * Routine: task_map_kcdata_object_64
922  * params: task - Map the underlying kcdata in task's address space
923  *         kcdata_obj - Object representing the data
924  *         kcd_addr_begin - Address of the mapped kcdata
925  *         kcd_size - Size of the mapped kcdata
926  * returns: KERN_SUCCESS on Success.
927  *          KERN_FAILURE on Failure.
928  *          KERN_INVALID_ARGUMENT on invalid arguments.
929  */
930 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)931 task_map_kcdata_object_64(
932 	task_t task,
933 	kcdata_object_t kcdata_obj,
934 	mach_vm_address_t *kcd_addr_begin,
935 	mach_vm_size_t *kcd_size)
936 {
937 	kern_return_t kr;
938 	mach_vm_offset_t bt_data_ptr = 0;
939 	const mach_vm_size_t size = BTINFO_ALLOCATION_SIZE;
940 	void *bt_info_kernel = NULL;
941 
942 	if (task == TASK_NULL || task_is_a_corpse(task) ||
943 	    kcdata_obj == KCDATA_OBJECT_NULL) {
944 		return KERN_INVALID_ARGUMENT;
945 	}
946 
947 	bt_info_kernel = kcdata_memory_get_begin_addr(kcdata_obj->ko_data);
948 	if (bt_info_kernel == NULL) {
949 		return KERN_INVALID_ARGUMENT;
950 	}
951 
952 	kr = task_map_kcdata_64(task, bt_info_kernel, &bt_data_ptr, size,
953 	    VM_MEMORY_BTINFO);
954 
955 	if (kr == KERN_SUCCESS) {
956 		*kcd_addr_begin = bt_data_ptr;
957 		*kcd_size = size;
958 	}
959 
960 	return kr;
961 }
962 
963 uint64_t
task_corpse_get_crashed_thread_id(task_t corpse_task)964 task_corpse_get_crashed_thread_id(task_t corpse_task)
965 {
966 	return corpse_task->crashed_thread_id;
967 }
968