]> git.saurik.com Git - apple/xnu.git/blame - osfmk/kern/debug.c
xnu-4903.241.1.tar.gz
[apple/xnu.git] / osfmk / kern / debug.c
CommitLineData
1c79356b 1/*
39037602 2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
1c79356b 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/*
29 * @OSF_COPYRIGHT@
30 */
31/*
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56
57#include <mach_assert.h>
1c79356b 58#include <mach_kdp.h>
5ba3f43e
A
59#include <kdp/kdp.h>
60#include <kdp/kdp_core.h>
61#include <kdp/kdp_internal.h>
62#include <kdp/kdp_callout.h>
1c79356b 63#include <kern/cpu_number.h>
b0d623f7 64#include <kern/kalloc.h>
1c79356b
A
65#include <kern/spl.h>
66#include <kern/thread.h>
67#include <kern/assert.h>
68#include <kern/sched_prim.h>
69#include <kern/misc_protos.h>
c910b4d9 70#include <kern/clock.h>
39236c6e 71#include <kern/telemetry.h>
fe8ab488 72#include <kern/ecc.h>
3e170ce0 73#include <kern/kern_cdata.h>
39037602 74#include <kern/zalloc.h>
9bccf70c 75#include <vm/vm_kern.h>
91447636 76#include <vm/pmap.h>
1c79356b 77#include <stdarg.h>
5ba3f43e
A
78#include <stdatomic.h>
79#include <sys/pgo.h>
80#include <console/serial_protos.h>
81
fe8ab488 82#if !(MACH_KDP && CONFIG_KDP_INTERACTIVE_DEBUGGING)
2d21ac55
A
83#include <kdp/kdp_udp.h>
84#endif
5ba3f43e 85#include <kern/processor.h>
1c79356b 86
b0d623f7 87#if defined(__i386__) || defined(__x86_64__)
2d21ac55
A
88#include <i386/cpu_threads.h>
89#include <i386/pmCPU.h>
90#endif
91
92#include <IOKit/IOPlatformExpert.h>
6d2010ae 93#include <machine/pal_routines.h>
2d21ac55 94
b0d623f7
A
95#include <sys/kdebug.h>
96#include <libkern/OSKextLibPrivate.h>
6d2010ae
A
97#include <libkern/OSAtomic.h>
98#include <libkern/kernel_mach_header.h>
cc8bc92a 99#include <libkern/section_keywords.h>
6d2010ae 100#include <uuid/uuid.h>
3e170ce0 101#include <mach_debug/zone_info.h>
b0d623f7 102
39037602
A
103#include <os/log_private.h>
104
5ba3f43e 105#if CONFIG_EMBEDDED
fe8ab488 106#include <pexpert/pexpert.h> /* For gPanicBase */
5ba3f43e
A
107#include <arm/caches_internal.h>
108#include <arm/misc_protos.h>
109extern volatile struct xnu_hw_shmem_dbg_command_info *hwsd_info;
fe8ab488
A
110#endif
111
d9a64523
A
112#if CONFIG_XNUPOST
113#include <tests/xnupost.h>
114extern int vsnprintf(char *, size_t, const char *, va_list);
115#endif
39037602 116
1c79356b 117unsigned int halt_in_debugger = 0;
1c79356b
A
118unsigned int current_debugger = 0;
119unsigned int active_debugger = 0;
91447636 120unsigned int panicDebugging = FALSE;
04b8595b 121unsigned int kdebug_serial = FALSE;
5ba3f43e
A
122unsigned int kernel_debugger_entry_count = 0;
123
124
125#if defined(__arm__)
126#define TRAP_DEBUGGER __asm__ volatile("trap")
127#elif defined(__arm64__)
128/*
129 * Magic number; this should be identical to the __arm__ encoding for trap.
130 */
131#define TRAP_DEBUGGER __asm__ volatile(".long 0xe7ffdeff")
132#elif defined (__x86_64__)
133#define TRAP_DEBUGGER __asm__("int3")
134#else
135#error No TRAP_DEBUGGER for this architecture
136#endif
137
138#if defined(__i386__) || defined(__x86_64__)
139#define panic_stop() pmCPUHalt(PM_HALT_PANIC)
140#else
141#define panic_stop() panic_spin_forever()
142#endif
143
144#define CPUDEBUGGEROP PROCESSOR_DATA(current_processor(), debugger_state).db_current_op
145#define CPUDEBUGGERMSG PROCESSOR_DATA(current_processor(), debugger_state).db_message
146#define CPUPANICSTR PROCESSOR_DATA(current_processor(), debugger_state).db_panic_str
147#define CPUPANICARGS PROCESSOR_DATA(current_processor(), debugger_state).db_panic_args
148#define CPUPANICOPTS PROCESSOR_DATA(current_processor(), debugger_state).db_panic_options
d9a64523 149#define CPUPANICDATAPTR PROCESSOR_DATA(current_processor(), debugger_state).db_panic_data_ptr
5ba3f43e
A
150#define CPUDEBUGGERSYNC PROCESSOR_DATA(current_processor(), debugger_state).db_proceed_on_sync_failure
151#define CPUDEBUGGERCOUNT PROCESSOR_DATA(current_processor(), debugger_state).db_entry_count
152#define CPUDEBUGGERRET PROCESSOR_DATA(current_processor(), debugger_state).db_op_return
153#define CPUPANICCALLER PROCESSOR_DATA(current_processor(), debugger_state).db_panic_caller
154
155#if DEVELOPMENT || DEBUG
156#define DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED(requested) \
157MACRO_BEGIN \
158 if (requested) { \
159 volatile int *badpointer = (int *)4; \
160 *badpointer = 0; \
161 } \
162MACRO_END
163#endif /* DEVELOPMENT || DEBUG */
164
165debugger_op debugger_current_op = DBOP_NONE;
166const char *debugger_panic_str = NULL;
167va_list *debugger_panic_args = NULL;
d9a64523 168void *debugger_panic_data = NULL;
5ba3f43e
A
169uint64_t debugger_panic_options = 0;
170const char *debugger_message = NULL;
171unsigned long debugger_panic_caller = 0;
172
d9a64523
A
173void panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsigned int reason, void *ctx,
174 uint64_t panic_options_mask, void *panic_data, unsigned long panic_caller);
5ba3f43e
A
175static void kdp_machine_reboot_type(unsigned int type);
176__attribute__((noreturn)) void panic_spin_forever(void);
177extern kern_return_t do_stackshot(void);
1c79356b
A
178
179int mach_assert = 1;
180
5ba3f43e 181#define NESTEDDEBUGGERENTRYMAX 5
1c79356b 182
5ba3f43e
A
183#if CONFIG_EMBEDDED
184#define DEBUG_BUF_SIZE (4096)
185#define KDBG_TRACE_PANIC_FILENAME "/var/log/panic.trace"
186#else
187/*
cc8bc92a 188 * EXTENDED_/DEBUG_BUF_SIZE can't grow without updates to SMC and iBoot to store larger panic logs on co-processor systems */
5ba3f43e 189#define DEBUG_BUF_SIZE ((3 * PAGE_SIZE) + offsetof(struct macos_panic_header, mph_data))
cc8bc92a 190#define EXTENDED_DEBUG_BUF_SIZE 0x0013ff80
5c9f4661 191static_assert(((EXTENDED_DEBUG_BUF_SIZE % PANIC_FLUSH_BOUNDARY) == 0), "Extended debug buf size must match SMC alignment requirements");
5ba3f43e
A
192#define KDBG_TRACE_PANIC_FILENAME "/var/tmp/panic.trace"
193#endif
c910b4d9 194
5ba3f43e
A
195/* debug_buf is directly linked with iBoot panic region for embedded targets */
196#if CONFIG_EMBEDDED
197char *debug_buf_base = NULL;
fe8ab488
A
198char *debug_buf_ptr = NULL;
199unsigned int debug_buf_size = 0;
200#else
c910b4d9 201char debug_buf[DEBUG_BUF_SIZE];
5ba3f43e
A
202struct macos_panic_header *panic_info = (struct macos_panic_header *)debug_buf;
203char *debug_buf_base = (debug_buf + offsetof(struct macos_panic_header, mph_data));
204char *debug_buf_ptr = (debug_buf + offsetof(struct macos_panic_header, mph_data));
205
206/*
207 * We don't include the size of the panic header in the length of the data we actually write.
208 * On co-processor platforms, we lose sizeof(struct macos_panic_header) bytes from the end of
209 * the end of the log because we only support writing (3*PAGESIZE) bytes.
210 */
cc8bc92a
A
211unsigned int debug_buf_size = (DEBUG_BUF_SIZE - offsetof(struct macos_panic_header, mph_data));
212
213boolean_t extended_debug_log_enabled = FALSE;
fe8ab488 214#endif
2d21ac55 215
5ba3f43e
A
216/* Debugger state */
217atomic_int debugger_cpu = ATOMIC_VAR_INIT(DEBUGGER_NO_CPU);
218boolean_t debugger_allcpus_halted = FALSE;
219boolean_t debugger_safe_to_return = TRUE;
220unsigned int debugger_context = 0;
39037602 221
2d21ac55 222static char model_name[64];
39236c6e 223unsigned char *kernel_uuid;
2d21ac55 224
d9a64523
A
225boolean_t kernelcache_uuid_valid = FALSE;
226uuid_t kernelcache_uuid;
227uuid_string_t kernelcache_uuid_string;
228
5ba3f43e
A
229/*
230 * By default we treat Debugger() the same as calls to panic(), unless
231 * we have debug boot-args present and the DB_KERN_DUMP_ON_NMI *NOT* set.
232 * If DB_KERN_DUMP_ON_NMI is *NOT* set, return from Debugger() is supported.
233 *
234 * Return from Debugger() is currently only implemented on x86
235 */
236static boolean_t debugger_is_panic = TRUE;
316670eb 237
cc8bc92a
A
238#if DEVELOPMENT || DEBUG
239boolean_t debug_boot_arg_inited = FALSE;
240#endif
241
242SECURITY_READ_ONLY_LATE(unsigned int) debug_boot_arg;
2d21ac55 243
5ba3f43e 244char kernel_uuid_string[37]; /* uuid_string_t */
d9a64523 245char kernelcache_uuid_string[37]; /* uuid_string_t */
5ba3f43e
A
246char panic_disk_error_description[512];
247size_t panic_disk_error_description_size = sizeof(panic_disk_error_description);
9bccf70c 248
5ba3f43e 249extern unsigned int write_trace_on_panic;
39037602
A
250int kext_assertions_enable =
251#if DEBUG || DEVELOPMENT
252 TRUE;
253#else
254 FALSE;
255#endif
256
1c79356b
A
257void
258panic_init(void)
259{
6d2010ae
A
260 unsigned long uuidlen = 0;
261 void *uuid;
262
263 uuid = getuuidfromheader(&_mh_execute_header, &uuidlen);
264 if ((uuid != NULL) && (uuidlen == sizeof(uuid_t))) {
39236c6e
A
265 kernel_uuid = uuid;
266 uuid_unparse_upper(*(uuid_t *)uuid, kernel_uuid_string);
6d2010ae
A
267 }
268
3e170ce0
A
269 if (!PE_parse_boot_argn("assertions", &mach_assert, sizeof(mach_assert))) {
270 mach_assert = 1;
271 }
5ba3f43e 272
cc8bc92a
A
273 /*
274 * Initialize the value of the debug boot-arg
275 */
276 debug_boot_arg = 0;
277#if ((CONFIG_EMBEDDED && MACH_KDP) || defined(__x86_64__))
278 if (PE_parse_boot_argn("debug", &debug_boot_arg, sizeof (debug_boot_arg))) {
279#if DEVELOPMENT || DEBUG
280 if (debug_boot_arg & DB_HALT) {
281 halt_in_debugger=1;
282 }
283#endif
5ba3f43e 284
cc8bc92a
A
285#if CONFIG_EMBEDDED
286 if (debug_boot_arg & DB_NMI) {
287 panicDebugging = TRUE;
288 }
289#else
290 panicDebugging = TRUE;
291#if KDEBUG_MOJO_TRACE
292 if (debug_boot_arg & DB_PRT_KDEBUG) {
293 kdebug_serial = TRUE;
294 }
295#endif
296#endif /* CONFIG_EMBEDDED */
297 }
298#endif /* ((CONFIG_EMBEDDED && MACH_KDP) || defined(__x86_64__)) */
299
300#if DEVELOPMENT || DEBUG
301 debug_boot_arg_inited = TRUE;
302#endif
303
304#if !CONFIG_EMBEDDED
305 /*
306 * By default we treat Debugger() the same as calls to panic(), unless
307 * we have debug boot-args present and the DB_KERN_DUMP_ON_NMI *NOT* set.
308 * If DB_KERN_DUMP_ON_NMI is *NOT* set, return from Debugger() is supported.
309 * This is because writing an on-device corefile is a destructive operation.
310 *
311 * Return from Debugger() is currently only implemented on x86
312 */
313 if (PE_i_can_has_debugger(NULL) && !(debug_boot_arg & DB_KERN_DUMP_ON_NMI)) {
5ba3f43e
A
314 debugger_is_panic = FALSE;
315 }
316#endif
317
1c79356b
A
318}
319
cc8bc92a
A
320#if defined (__x86_64__)
321void
322extended_debug_log_init(void)
323{
324 assert(coprocessor_paniclog_flush);
325 /*
326 * Allocate an extended panic log buffer that has space for the panic
327 * stackshot at the end. Update the debug buf pointers appropriately
328 * to point at this new buffer.
329 */
330 char *new_debug_buf = kalloc(EXTENDED_DEBUG_BUF_SIZE);
5c9f4661
A
331 /*
332 * iBoot pre-initializes the panic region with the NULL character. We set this here
333 * so we can accurately calculate the CRC for the region without needing to flush the
334 * full region over SMC.
335 */
336 memset(new_debug_buf, '\0', EXTENDED_DEBUG_BUF_SIZE);
cc8bc92a
A
337
338 panic_info = (struct macos_panic_header *)new_debug_buf;
339 debug_buf_ptr = debug_buf_base = (new_debug_buf + offsetof(struct macos_panic_header, mph_data));
340 debug_buf_size = (EXTENDED_DEBUG_BUF_SIZE - offsetof(struct macos_panic_header, mph_data));
341
342 extended_debug_log_enabled = TRUE;
343}
344#endif /* defined (__x86_64__) */
345
2d21ac55
A
346void
347debug_log_init(void)
348{
5ba3f43e 349#if CONFIG_EMBEDDED
fe8ab488
A
350 if (!gPanicBase) {
351 printf("debug_log_init: Error!! gPanicBase is still not initialized\n");
352 return;
353 }
5ba3f43e
A
354 /* Shift debug buf start location and size by the length of the panic header */
355 debug_buf_base = (char *)gPanicBase + sizeof(struct embedded_panic_header);
356 debug_buf_ptr = debug_buf_base;
357 debug_buf_size = gPanicSize - sizeof(struct embedded_panic_header);
fe8ab488 358#else
cc8bc92a
A
359 bzero(panic_info, DEBUG_BUF_SIZE);
360
5ba3f43e
A
361 assert(debug_buf_base != NULL);
362 assert(debug_buf_ptr != NULL);
363 assert(debug_buf_size != 0);
fe8ab488 364#endif
2d21ac55
A
365}
366
5ba3f43e
A
367static void
368DebuggerLock()
369{
370 int my_cpu = cpu_number();
371 int debugger_exp_cpu = DEBUGGER_NO_CPU;
372 assert(ml_get_interrupts_enabled() == FALSE);
373
374 if (debugger_cpu == my_cpu) {
375 return;
376 }
377
378 while(!atomic_compare_exchange_strong(&debugger_cpu, &debugger_exp_cpu, my_cpu)) {
379 debugger_exp_cpu = DEBUGGER_NO_CPU;
380 }
381
382 return;
383}
384
385static void
386DebuggerUnlock()
387{
388 assert(debugger_cpu == cpu_number());
389
390 /*
391 * We don't do an atomic exchange here in case
392 * there's another CPU spinning to acquire the debugger_lock
393 * and we never get a chance to update it. We already have the
394 * lock so we can simply store DEBUGGER_NO_CPU and follow with
395 * a barrier.
396 */
397 debugger_cpu = DEBUGGER_NO_CPU;
398 OSMemoryBarrier();
399
400 return;
401}
402
403static kern_return_t
404DebuggerHaltOtherCores(boolean_t proceed_on_failure)
405{
406#if CONFIG_EMBEDDED
407 return DebuggerXCallEnter(proceed_on_failure);
408#else /* CONFIG_EMBEDDED */
409#pragma unused(proceed_on_failure)
410 mp_kdp_enter(proceed_on_failure);
411 return KERN_SUCCESS;
2d21ac55 412#endif
5ba3f43e
A
413}
414
415static void
416DebuggerResumeOtherCores()
417{
418#if CONFIG_EMBEDDED
419 DebuggerXCallReturn();
420#else /* CONFIG_EMBEDDED */
421 mp_kdp_exit();
422#endif
423}
424
425static void
426DebuggerSaveState(debugger_op db_op, const char *db_message, const char *db_panic_str,
d9a64523 427 va_list *db_panic_args, uint64_t db_panic_options, void *db_panic_data_ptr,
5ba3f43e
A
428 boolean_t db_proceed_on_sync_failure, unsigned long db_panic_caller)
429{
430 CPUDEBUGGEROP = db_op;
431
432 /* Preserve the original panic message */
433 if (CPUDEBUGGERCOUNT == 1 || CPUPANICSTR == NULL) {
434 CPUDEBUGGERMSG = db_message;
435 CPUPANICSTR = db_panic_str;
436 CPUPANICARGS = db_panic_args;
d9a64523 437 CPUPANICDATAPTR = db_panic_data_ptr;
5ba3f43e
A
438 CPUPANICCALLER = db_panic_caller;
439 } else if (CPUDEBUGGERCOUNT > 1 && db_panic_str != NULL) {
cc8bc92a
A
440 kprintf("Nested panic detected:");
441 if (db_panic_str != NULL)
442 _doprnt(db_panic_str, db_panic_args, PE_kputc, 0);
5ba3f43e
A
443 }
444
445 CPUDEBUGGERSYNC = db_proceed_on_sync_failure;
446 CPUDEBUGGERRET = KERN_SUCCESS;
447
448 /* Reset these on any nested panics */
449 CPUPANICOPTS = db_panic_options;
450
451 return;
452}
2d21ac55 453
b0d623f7 454/*
5ba3f43e
A
455 * Save the requested debugger state/action into the current processor's processor_data
456 * and trap to the debugger.
b0d623f7 457 */
5ba3f43e
A
458kern_return_t
459DebuggerTrapWithState(debugger_op db_op, const char *db_message, const char *db_panic_str,
d9a64523 460 va_list *db_panic_args, uint64_t db_panic_options, void *db_panic_data_ptr,
5ba3f43e
A
461 boolean_t db_proceed_on_sync_failure, unsigned long db_panic_caller)
462{
463 kern_return_t ret;
464
465 assert(ml_get_interrupts_enabled() == FALSE);
d9a64523
A
466 DebuggerSaveState(db_op, db_message, db_panic_str, db_panic_args,
467 db_panic_options, db_panic_data_ptr,
468 db_proceed_on_sync_failure, db_panic_caller);
5ba3f43e
A
469
470 TRAP_DEBUGGER;
471
472 ret = CPUDEBUGGERRET;
b0d623f7 473
d9a64523 474 DebuggerSaveState(DBOP_NONE, NULL, NULL, NULL, 0, NULL, FALSE, 0);
5ba3f43e
A
475
476 return ret;
477}
478
479void __attribute__((noinline))
480Assert(
481 const char *file,
482 int line,
483 const char *expression
484 )
b0d623f7 485{
5ba3f43e
A
486 if (!mach_assert) {
487 kprintf("%s:%d non-fatal Assertion: %s", file, line, expression);
488 return;
489 }
490
491 panic_plain("%s:%d Assertion failed: %s", file, line, expression);
b0d623f7
A
492}
493
fe8ab488 494
5ba3f43e
A
495void
496Debugger(const char *message)
1c79356b 497{
5ba3f43e
A
498 DebuggerWithContext(0, NULL, message, DEBUGGER_OPTION_NONE);
499}
1c79356b 500
5ba3f43e
A
501void
502DebuggerWithContext(unsigned int reason, void *ctx, const char *message,
503 uint64_t debugger_options_mask)
504{
505 spl_t previous_interrupts_state;
506 boolean_t old_doprnt_hide_pointers = doprnt_hide_pointers;
7ddcb079 507
5ba3f43e 508 previous_interrupts_state = ml_set_interrupts_enabled(FALSE);
7ddcb079
A
509 disable_preemption();
510
5ba3f43e 511 CPUDEBUGGERCOUNT++;
b0d623f7 512
5ba3f43e
A
513 if (CPUDEBUGGERCOUNT > NESTEDDEBUGGERENTRYMAX) {
514 static boolean_t in_panic_kprintf = FALSE;
2d21ac55 515
5ba3f43e
A
516 /* Notify any listeners that we've started a panic */
517 PEHaltRestart(kPEPanicBegin);
91447636 518
5ba3f43e
A
519 if (!in_panic_kprintf) {
520 in_panic_kprintf = TRUE;
521 kprintf("Detected nested debugger entry count exceeding %d\n",
522 NESTEDDEBUGGERENTRYMAX);
523 in_panic_kprintf = FALSE;
524 }
316670eb 525
5ba3f43e
A
526 if (!panicDebugging) {
527 kdp_machine_reboot_type(kPEPanicRestartCPU);
1c79356b 528 }
5ba3f43e
A
529
530 panic_spin_forever();
1c79356b 531 }
1c79356b 532
5ba3f43e
A
533#if DEVELOPMENT || DEBUG
534 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_options_mask & DEBUGGER_OPTION_RECURPANIC_ENTRY));
535#endif
536
537 doprnt_hide_pointers = FALSE;
538
539 if (ctx != NULL) {
540 DebuggerSaveState(DBOP_DEBUGGER, message,
d9a64523 541 NULL, NULL, debugger_options_mask, NULL, TRUE, 0);
5ba3f43e
A
542 handle_debugger_trap(reason, 0, 0, ctx);
543 DebuggerSaveState(DBOP_NONE, NULL, NULL,
d9a64523 544 NULL, 0, NULL, FALSE, 0);
5ba3f43e
A
545 } else {
546 DebuggerTrapWithState(DBOP_DEBUGGER, message,
d9a64523 547 NULL, NULL, debugger_options_mask, NULL, TRUE, 0);
5ba3f43e 548 }
39037602 549
5ba3f43e
A
550 CPUDEBUGGERCOUNT--;
551 doprnt_hide_pointers = old_doprnt_hide_pointers;
552 enable_preemption();
553 ml_set_interrupts_enabled(previous_interrupts_state);
554}
555
556static struct kdp_callout {
557 struct kdp_callout * callout_next;
558 kdp_callout_fn_t callout_fn;
559 boolean_t callout_in_progress;
560 void * callout_arg;
561} * kdp_callout_list = NULL;
562
563/*
564 * Called from kernel context to register a kdp event callout.
565 */
566void
567kdp_register_callout(kdp_callout_fn_t fn, void * arg)
568{
569 struct kdp_callout * kcp;
570 struct kdp_callout * list_head;
571
572 kcp = kalloc(sizeof(*kcp));
573 if (kcp == NULL)
574 panic("kdp_register_callout() kalloc failed");
575
576 kcp->callout_fn = fn;
577 kcp->callout_arg = arg;
578 kcp->callout_in_progress = FALSE;
579
580 /* Lock-less list insertion using compare and exchange. */
581 do {
582 list_head = kdp_callout_list;
583 kcp->callout_next = list_head;
584 } while (!OSCompareAndSwapPtr(list_head, kcp, &kdp_callout_list));
316670eb 585}
1c79356b 586
39037602 587static void
5ba3f43e 588kdp_callouts(kdp_event_t event)
316670eb 589{
5ba3f43e 590 struct kdp_callout *kcp = kdp_callout_list;
2d21ac55 591
5ba3f43e
A
592 while (kcp) {
593 if (!kcp->callout_in_progress) {
594 kcp->callout_in_progress = TRUE;
595 kcp->callout_fn(kcp->callout_arg, event);
596 kcp->callout_in_progress = FALSE;
597 }
598 kcp = kcp->callout_next;
55e303ae 599 }
1c79356b
A
600}
601
5ba3f43e
A
602/*
603 * An overview of the xnu panic path:
604 *
605 * Several panic wrappers (panic(), panic_with_options(), etc.) all funnel into panic_trap_to_debugger().
606 * panic_trap_to_debugger() sets the panic state in the current processor's processor_data_t prior
607 * to trapping into the debugger. Once we trap to the debugger, we end up in handle_debugger_trap()
608 * which tries to acquire the panic lock by atomically swapping the current CPU number into debugger_cpu.
609 * debugger_cpu acts as a synchronization point, from which the winning CPU can halt the other cores and
610 * continue to debugger_collect_diagnostics() where we write the paniclog, corefile (if appropriate) and proceed
611 * according to the device's boot-args.
612 */
613#undef panic
316670eb
A
614void
615panic(const char *str, ...)
616{
5ba3f43e
A
617 va_list panic_str_args;
618
619 va_start(panic_str_args, str);
d9a64523 620 panic_trap_to_debugger(str, &panic_str_args, 0, NULL, 0, NULL, (unsigned long)(char *)__builtin_return_address(0));
5ba3f43e
A
621 va_end(panic_str_args);
622}
623
624void
625panic_with_options(unsigned int reason, void *ctx, uint64_t debugger_options_mask, const char *str, ...)
626{
627 va_list panic_str_args;
628
629 va_start(panic_str_args, str);
d9a64523
A
630 panic_trap_to_debugger(str, &panic_str_args, reason, ctx, (debugger_options_mask & ~DEBUGGER_INTERNAL_OPTIONS_MASK),
631 NULL, (unsigned long)(char *)__builtin_return_address(0));
5ba3f43e
A
632 va_end(panic_str_args);
633}
634
d9a64523
A
635#if defined (__x86_64__)
636/*
637 * panic_with_thread_context() is used on x86 platforms to specify a different thread that should be backtraced in the paniclog.
638 * We don't generally need this functionality on embedded platforms because embedded platforms include a panic time stackshot
639 * from customer devices. We plumb the thread pointer via the debugger trap mechanism and backtrace the kernel stack from the
640 * thread when writing the panic log.
641 *
642 * NOTE: panic_with_thread_context() should be called with an explicit thread reference held on the passed thread.
643 */
5ba3f43e 644void
d9a64523 645panic_with_thread_context(unsigned int reason, void *ctx, uint64_t debugger_options_mask, thread_t thread, const char *str, ...)
5ba3f43e
A
646{
647 va_list panic_str_args;
d9a64523
A
648
649 assert_thread_magic(thread);
d9a64523
A
650
651 /* Take a reference on the thread so it doesn't disappear by the time we try to backtrace it */
652 thread_reference(thread);
5ba3f43e
A
653
654 va_start(panic_str_args, str);
d9a64523
A
655 panic_trap_to_debugger(str, &panic_str_args, reason, ctx, ((debugger_options_mask & ~DEBUGGER_INTERNAL_OPTIONS_MASK) | DEBUGGER_INTERNAL_OPTION_THREAD_BACKTRACE),
656 thread, (unsigned long)(char *)__builtin_return_address(0));
657
5ba3f43e 658 va_end(panic_str_args);
d9a64523 659
5ba3f43e 660}
d9a64523 661#endif /* defined (__x86_64__) */
5ba3f43e
A
662
663#pragma clang diagnostic push
664#pragma clang diagnostic ignored "-Wmissing-noreturn"
665void
d9a64523
A
666panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsigned int reason, void *ctx,
667 uint64_t panic_options_mask, void *panic_data_ptr, unsigned long panic_caller)
5ba3f43e
A
668{
669#pragma clang diagnostic pop
670
671 if (ml_wants_panic_trap_to_debugger()) {
672 ml_panic_trap_to_debugger(panic_format_str, panic_args, reason, ctx, panic_options_mask, panic_caller);
673
674 /*
675 * This should not return, but we return here for the tail call
676 * as it simplifies the backtrace.
677 */
678 return;
679 }
680
681 CPUDEBUGGERCOUNT++;
682
683 if (CPUDEBUGGERCOUNT > NESTEDDEBUGGERENTRYMAX) {
684 static boolean_t in_panic_kprintf = FALSE;
685
686 /* Notify any listeners that we've started a panic */
687 PEHaltRestart(kPEPanicBegin);
688
689 if (!in_panic_kprintf) {
690 in_panic_kprintf = TRUE;
691 kprintf("Detected nested debugger entry count exceeding %d\n",
692 NESTEDDEBUGGERENTRYMAX);
693 in_panic_kprintf = FALSE;
694 }
695
696 if (!panicDebugging) {
697 kdp_machine_reboot_type(kPEPanicRestartCPU);
698 }
699
700 panic_spin_forever();
701 }
702
703#if DEVELOPMENT || DEBUG
704 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((panic_options_mask & DEBUGGER_OPTION_RECURPANIC_ENTRY));
705#endif
706
707#if CONFIG_EMBEDDED
708 if (PE_arm_debug_panic_hook)
709 PE_arm_debug_panic_hook(panic_format_str);
710#endif
316670eb 711
39037602
A
712#if defined (__x86_64__)
713 plctrace_disable();
714#endif
39037602 715
5ba3f43e
A
716 if (write_trace_on_panic && kdebug_enable) {
717 if (get_preemption_level() == 0 && !ml_at_interrupt_context()) {
718 ml_set_interrupts_enabled(TRUE);
a39ff7e2 719 KDBG_RELEASE(TRACE_PANIC);
5ba3f43e
A
720 kdbg_dump_trace_to_file(KDBG_TRACE_PANIC_FILENAME);
721 }
722 }
723
724 ml_set_interrupts_enabled(FALSE);
725 disable_preemption();
39037602 726
5ba3f43e
A
727#if defined (__x86_64__)
728 pmSafeMode(x86_lcpu(), PM_SAFE_FL_SAFE);
729#endif /* defined (__x86_64__) */
3e170ce0
A
730
731 /* Never hide pointers from panic logs. */
732 doprnt_hide_pointers = FALSE;
733
5ba3f43e
A
734 if (ctx != NULL) {
735 /*
736 * We called into panic from a trap, no need to trap again. Set the
737 * state on the current CPU and then jump to handle_debugger_trap.
738 */
739 DebuggerSaveState(DBOP_PANIC, "panic",
740 panic_format_str, panic_args,
d9a64523 741 panic_options_mask, panic_data_ptr, TRUE, panic_caller);
5ba3f43e 742 handle_debugger_trap(reason, 0, 0, ctx);
316670eb 743 }
316670eb 744
5ba3f43e 745#if defined(__arm64__)
316670eb 746 /*
5ba3f43e 747 * Signal to fastsim that it should open debug ports (nop on hardware)
316670eb 748 */
5ba3f43e
A
749 __asm__ volatile("HINT 0x45");
750#endif /* defined(__arm64__) */
3e170ce0 751
5ba3f43e 752 DebuggerTrapWithState(DBOP_PANIC, "panic", panic_format_str,
d9a64523 753 panic_args, panic_options_mask, panic_data_ptr, TRUE, panic_caller);
3e170ce0 754
5ba3f43e
A
755 /*
756 * Not reached.
757 */
758 panic_stop();
316670eb
A
759}
760
39037602 761__attribute__((noreturn))
39037602 762void
5ba3f43e 763panic_spin_forever()
39037602 764{
5ba3f43e
A
765 paniclog_append_noflush("\nPlease go to https://panic.apple.com to report this panic\n");
766
767 for (;;) { }
768}
769
770static void
771kdp_machine_reboot_type(unsigned int type)
772{
773 printf("Attempting system restart...");
774 PEHaltRestart(type);
775 halt_all_cpus(TRUE);
776}
777
778void
779kdp_machine_reboot(void)
780{
781 kdp_machine_reboot_type(kPEPanicRestartCPU);
782}
783
784/*
785 * Gather and save diagnostic information about a panic (or Debugger call).
786 *
787 * On embedded, Debugger and Panic are treated very similarly -- WDT uses Debugger so we can
788 * theoretically return from it. On desktop, Debugger is treated as a conventional debugger -- i.e no
789 * paniclog is written and no core is written unless we request a core on NMI.
790 *
791 * This routine handles kicking off local coredumps, paniclogs, calling into the Debugger/KDP (if it's configured),
792 * and calling out to any other functions we have for collecting diagnostic info.
793 */
794static void
795debugger_collect_diagnostics(unsigned int exception, unsigned int code, unsigned int subcode, void *state)
796{
797#if DEVELOPMENT || DEBUG
798 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_panic_options & DEBUGGER_OPTION_RECURPANIC_PRELOG));
799#endif
800
801#if defined(__x86_64__)
cc8bc92a 802 kprintf("Debugger called: <%s>\n", debugger_message ? debugger_message : "");
5ba3f43e
A
803#endif
804 /*
805 * DB_HALT (halt_in_debugger) can be requested on startup, we shouldn't generate
806 * a coredump/paniclog for this type of debugger entry. If KDP isn't configured,
807 * we'll just spin in kdp_raise_exception.
808 */
809 if (debugger_current_op == DBOP_DEBUGGER && halt_in_debugger) {
810 kdp_raise_exception(exception, code, subcode, state);
811 if (debugger_safe_to_return && !debugger_is_panic) {
812 return;
813 }
814 }
815
816 if ((debugger_current_op == DBOP_PANIC) ||
cc8bc92a 817 ((debugger_current_op == DBOP_DEBUGGER) && debugger_is_panic)) {
5ba3f43e
A
818 /*
819 * Attempt to notify listeners once and only once that we've started
820 * panicking. Only do this for Debugger() calls if we're treating
821 * Debugger() calls like panic().
822 */
823 PEHaltRestart(kPEPanicBegin);
824
825 /*
826 * Set the begin pointer in the panic log structure. We key off of this
827 * static variable rather than contents from the panic header itself in case someone
828 * has stomped over the panic_info structure. Also initializes the header magic.
829 */
830 static boolean_t began_writing_paniclog = FALSE;
831 if (!began_writing_paniclog) {
832 PE_init_panicheader();
833 began_writing_paniclog = TRUE;
834 } else {
835 /*
836 * If we reached here, update the panic header to keep it as consistent
837 * as possible during a nested panic
838 */
839 PE_update_panicheader_nestedpanic();
840 }
841 }
842
843 /*
844 * Write panic string if this was a panic.
845 *
846 * TODO: Consider moving to SavePanicInfo as this is part of the panic log.
847 */
848 if (debugger_current_op == DBOP_PANIC) {
849 paniclog_append_noflush("panic(cpu %d caller 0x%lx): ", (unsigned) cpu_number(), debugger_panic_caller);
850 if (debugger_panic_str) {
851 _doprnt(debugger_panic_str, debugger_panic_args, consdebug_putc, 0);
852 }
853 paniclog_append_noflush("\n");
854 }
cc8bc92a
A
855#if defined(__x86_64__)
856 else if (((debugger_current_op == DBOP_DEBUGGER) && debugger_is_panic)) {
857 paniclog_append_noflush("Debugger called: <%s>\n", debugger_message ? debugger_message : "");
858 }
5ba3f43e
A
859
860 /*
861 * Debugger() is treated like panic() on embedded -- for example we use it for WDT
862 * panics (so we need to write a paniclog). On desktop Debugger() is used in the
863 * conventional sense.
864 */
cc8bc92a 865 if (debugger_current_op == DBOP_PANIC || ((debugger_current_op == DBOP_DEBUGGER) && debugger_is_panic))
5ba3f43e
A
866#endif
867 {
868 kdp_callouts(KDP_EVENT_PANICLOG);
39037602 869
5ba3f43e
A
870 /*
871 * Write paniclog and panic stackshot (if supported)
872 * TODO: Need to clear panic log when return from debugger
873 * hooked up for embedded
874 */
d9a64523 875 SavePanicInfo(debugger_message, debugger_panic_data, debugger_panic_options);
39037602 876
5ba3f43e
A
877#if DEVELOPMENT || DEBUG
878 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_panic_options & DEBUGGER_OPTION_RECURPANIC_POSTLOG));
879#endif
39037602 880
5ba3f43e
A
881 /* DEBUGGER_OPTION_PANICLOGANDREBOOT is used for two finger resets on embedded so we get a paniclog */
882 if (debugger_panic_options & DEBUGGER_OPTION_PANICLOGANDREBOOT)
883 PEHaltRestart(kPEPanicRestartCPU);
39037602 884 }
5ba3f43e
A
885
886#if CONFIG_KDP_INTERACTIVE_DEBUGGING
39037602 887 /*
5ba3f43e
A
888 * If reboot on panic is enabled and the caller of panic indicated that we should skip
889 * local coredumps, don't try to write these and instead go straight to reboot. This
890 * allows us to persist any data that's stored in the panic log.
39037602 891 */
5ba3f43e 892 if ((debugger_panic_options & DEBUGGER_OPTION_SKIP_LOCAL_COREDUMP) &&
cc8bc92a 893 (debug_boot_arg & DB_REBOOT_POST_CORE)) {
5ba3f43e
A
894 kdp_machine_reboot_type(kPEPanicRestartCPU);
895 }
896
897 /*
898 * Consider generating a local corefile if the infrastructure is configured
899 * and we haven't disabled on-device coredumps.
900 */
d9a64523
A
901 if (!(debug_boot_arg & DB_DISABLE_LOCAL_CORE)) {
902 if (!kdp_has_polled_corefile()) {
903 if (debug_boot_arg & (DB_KERN_DUMP_ON_PANIC | DB_KERN_DUMP_ON_NMI)) {
904 paniclog_append_noflush("skipping local kernel core because core file could not be opened prior to panic (error : 0x%x)",
905 kdp_polled_corefile_error());
906#if CONFIG_EMBEDDED
907 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_COREDUMP_FAILED;
908 paniclog_flush();
909#else /* CONFIG_EMBEDDED */
910 if (panic_info->mph_panic_log_offset != 0) {
911 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_COREDUMP_FAILED;
912 paniclog_flush();
913 }
914#endif /* CONFIG_EMBEDDED */
915 }
916 } else {
917 int ret = -1;
5ba3f43e
A
918
919#if defined (__x86_64__)
d9a64523
A
920 /* On x86 we don't do a coredump on Debugger unless the DB_KERN_DUMP_ON_NMI boot-arg is specified. */
921 if (debugger_current_op != DBOP_DEBUGGER || (debug_boot_arg & DB_KERN_DUMP_ON_NMI))
5ba3f43e 922#endif
d9a64523
A
923 {
924 /*
925 * Doing an on-device coredump leaves the disk driver in a state
926 * that can not be resumed.
927 */
928 debugger_safe_to_return = FALSE;
929 begin_panic_transfer();
930 ret = kern_dump(KERN_DUMP_DISK);
931 abort_panic_transfer();
5ba3f43e
A
932
933#if DEVELOPMENT || DEBUG
d9a64523 934 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_panic_options & DEBUGGER_OPTION_RECURPANIC_POSTCORE));
5ba3f43e 935#endif
d9a64523 936 }
5ba3f43e 937
d9a64523
A
938 /*
939 * If DB_REBOOT_POST_CORE is set, then reboot if coredump is sucessfully saved
940 * or if option to ignore failures is set.
941 */
942 if ((debug_boot_arg & DB_REBOOT_POST_CORE) &&
943 ((ret == 0) || (debugger_panic_options & DEBUGGER_OPTION_ATTEMPTCOREDUMPANDREBOOT))) {
944 kdp_machine_reboot_type(kPEPanicRestartCPU);
945 }
cc8bc92a 946 }
5ba3f43e
A
947 }
948
5c9f4661
A
949 if (debug_boot_arg & DB_REBOOT_ALWAYS) {
950 kdp_machine_reboot_type(kPEPanicRestartCPU);
951 }
952
5ba3f43e
A
953 /* If KDP is configured, try to trap to the debugger */
954 if (current_debugger != NO_CUR_DB) {
955 kdp_raise_exception(exception, code, subcode, state);
956 /*
957 * Only return if we entered via Debugger and it's safe to return
958 * (we halted the other cores successfully, this isn't a nested panic, etc)
959 */
960 if (debugger_current_op == DBOP_DEBUGGER &&
961 debugger_safe_to_return &&
962 kernel_debugger_entry_count == 1 &&
963 !debugger_is_panic) {
964 return;
965 }
966 }
967
968#if CONFIG_EMBEDDED
969 if (panicDebugging) {
970 /* If panic debugging is configured, spin for astris to connect */
971 panic_spin_shmcon();
972 }
973#endif /* CONFIG_EMBEDDED */
974#endif /* CONFIG_KDP_INTERACTIVE_DEBUGGING */
975
976 if (!panicDebugging) {
977 kdp_machine_reboot_type(kPEPanicRestartCPU);
978 }
979
980 panic_spin_forever();
39037602
A
981}
982
5ba3f43e
A
983#if INTERRUPT_MASKED_DEBUG
984uint64_t debugger_trap_timestamps[9];
985# define DEBUGGER_TRAP_TIMESTAMP(i) debugger_trap_timestamps[i] = mach_absolute_time();
986#else
987# define DEBUGGER_TRAP_TIMESTAMP(i)
39037602 988#endif
5ba3f43e 989
316670eb 990void
5ba3f43e 991handle_debugger_trap(unsigned int exception, unsigned int code, unsigned int subcode, void *state)
316670eb 992{
5ba3f43e
A
993 unsigned int initial_not_in_kdp = not_in_kdp;
994 kern_return_t ret;
995 debugger_op db_prev_op = debugger_current_op;
996
997 DEBUGGER_TRAP_TIMESTAMP(0);
998
999 DebuggerLock();
1000 ret = DebuggerHaltOtherCores(CPUDEBUGGERSYNC);
316670eb 1001
5ba3f43e 1002 DEBUGGER_TRAP_TIMESTAMP(1);
39236c6e 1003
5ba3f43e
A
1004#if INTERRUPT_MASKED_DEBUG
1005 if (serialmode & SERIALMODE_OUTPUT) {
1006 ml_spin_debug_reset(current_thread());
1007 }
1008#endif
1009 if (ret != KERN_SUCCESS) {
1010 CPUDEBUGGERRET = ret;
1011 DebuggerUnlock();
1012 return;
1013 }
1014
1015 /* Update the global panic/debugger nested entry level */
1016 kernel_debugger_entry_count = CPUDEBUGGERCOUNT;
1017
1018 /*
1019 * TODO: Should we do anything special for nested panics here? i.e. if we've trapped more than twice
1020 * should we call into the debugger if it's configured and then reboot if the panic log has been written?
1021 */
1022
1023 if (CPUDEBUGGEROP == DBOP_NONE) {
1024 /* If there was no debugger context setup, we trapped due to a software breakpoint */
1025 debugger_current_op = DBOP_BREAKPOINT;
1026 } else {
1027 /* Not safe to return from a nested panic/debugger call */
1028 if (debugger_current_op == DBOP_PANIC ||
1029 debugger_current_op == DBOP_DEBUGGER) {
1030 debugger_safe_to_return = FALSE;
1031 }
1032
1033 debugger_current_op = CPUDEBUGGEROP;
1034
1035 /* Only overwrite the panic message if there is none already - save the data from the first call */
1036 if (debugger_panic_str == NULL) {
1037 debugger_panic_str = CPUPANICSTR;
1038 debugger_panic_args = CPUPANICARGS;
d9a64523 1039 debugger_panic_data = CPUPANICDATAPTR;
5ba3f43e
A
1040 debugger_message = CPUDEBUGGERMSG;
1041 debugger_panic_caller = CPUPANICCALLER;
1042 }
1043
1044 debugger_panic_options = CPUPANICOPTS;
316670eb 1045 }
316670eb
A
1046
1047 /*
5ba3f43e
A
1048 * Clear the op from the processor debugger context so we can handle
1049 * breakpoints in the debugger
316670eb 1050 */
5ba3f43e
A
1051 CPUDEBUGGEROP = DBOP_NONE;
1052
1053 DEBUGGER_TRAP_TIMESTAMP(2);
1054
1055 kdp_callouts(KDP_EVENT_ENTER);
1056 not_in_kdp = 0;
1057
1058 DEBUGGER_TRAP_TIMESTAMP(3);
1059
1060 if (debugger_current_op == DBOP_BREAKPOINT) {
1061 kdp_raise_exception(exception, code, subcode, state);
1062 } else if (debugger_current_op == DBOP_STACKSHOT) {
1063 CPUDEBUGGERRET = do_stackshot();
1064#if PGO
1065 } else if (debugger_current_op == DBOP_RESET_PGO_COUNTERS) {
1066 CPUDEBUGGERRET = do_pgo_reset_counters();
1067#endif
1068 } else {
1069 debugger_collect_diagnostics(exception, code, subcode, state);
1070 }
1071
1072 DEBUGGER_TRAP_TIMESTAMP(4);
1073
1074 not_in_kdp = initial_not_in_kdp;
1075 kdp_callouts(KDP_EVENT_EXIT);
1076
1077 DEBUGGER_TRAP_TIMESTAMP(5);
1078
1079 if (debugger_current_op != DBOP_BREAKPOINT) {
1080 debugger_panic_str = NULL;
1081 debugger_panic_args = NULL;
d9a64523 1082 debugger_panic_data = NULL;
5ba3f43e
A
1083 debugger_panic_options = 0;
1084 debugger_message = NULL;
1085 }
1086
1087 /* Restore the previous debugger state */
1088 debugger_current_op = db_prev_op;
1089
1090 DEBUGGER_TRAP_TIMESTAMP(6);
1091
1092 DebuggerResumeOtherCores();
1093
1094 DEBUGGER_TRAP_TIMESTAMP(7);
1095
1096 DebuggerUnlock();
1097
1098 DEBUGGER_TRAP_TIMESTAMP(8);
1099
1100 return;
316670eb
A
1101}
1102
39037602
A
1103__attribute__((noinline,not_tail_called))
1104void log(__unused int level, char *fmt, ...)
1c79356b 1105{
39037602 1106 void *caller = __builtin_return_address(0);
1c79356b 1107 va_list listp;
39037602
A
1108 va_list listp2;
1109
1c79356b
A
1110
1111#ifdef lint
1112 level++;
1113#endif /* lint */
1114#ifdef MACH_BSD
1c79356b 1115 va_start(listp, fmt);
39037602
A
1116 va_copy(listp2, listp);
1117
1118 disable_preemption();
1119 _doprnt(fmt, &listp, cons_putc_locked, 0);
1c79356b 1120 enable_preemption();
39037602
A
1121
1122 va_end(listp);
1123
1124 os_log_with_args(OS_LOG_DEFAULT, OS_LOG_TYPE_DEFAULT, fmt, listp2, caller);
1125 va_end(listp2);
1c79356b
A
1126#endif
1127}
9bccf70c 1128
39037602 1129/*
5ba3f43e
A
1130 * Per <rdar://problem/24974766>, skip appending log messages to
1131 * the new logging infrastructure in contexts where safety is
1132 * uncertain. These contexts include:
39037602
A
1133 * - When we're in the debugger
1134 * - We're in a panic
1135 * - Interrupts are disabled
1136 * - Or Pre-emption is disabled
1137 * In all the above cases, it is potentially unsafe to log messages.
1138 */
1139
5ba3f43e
A
1140boolean_t
1141oslog_is_safe(void) {
1142 return (kernel_debugger_entry_count == 0 &&
39037602
A
1143 not_in_kdp == 1 &&
1144 get_preemption_level() == 0 &&
1145 ml_get_interrupts_enabled() == TRUE);
1146}
1147
5ba3f43e
A
1148boolean_t
1149debug_mode_active(void)
1150{
1151 return ((0 != kernel_debugger_entry_count != 0) || (0 == not_in_kdp));
1152}
1153
9bccf70c
A
1154void
1155debug_putc(char c)
1156{
2d21ac55 1157 if ((debug_buf_size != 0) &&
5ba3f43e 1158 ((debug_buf_ptr - debug_buf_base) < (int)debug_buf_size)) {
9bccf70c
A
1159 *debug_buf_ptr=c;
1160 debug_buf_ptr++;
1161 }
1162}
2d21ac55 1163
5ba3f43e
A
1164#if defined (__x86_64__)
1165struct pasc {
1166 unsigned a: 7;
1167 unsigned b: 7;
1168 unsigned c: 7;
1169 unsigned d: 7;
1170 unsigned e: 7;
1171 unsigned f: 7;
1172 unsigned g: 7;
1173 unsigned h: 7;
1174} __attribute__((packed));
2d21ac55 1175
5ba3f43e
A
1176typedef struct pasc pasc_t;
1177
1178/*
1179 * In-place packing routines -- inefficient, but they're called at most once.
1180 * Assumes "buflen" is a multiple of 8. Used for compressing paniclogs on x86.
1181 */
1182int
1183packA(char *inbuf, uint32_t length, uint32_t buflen)
2d21ac55
A
1184{
1185 unsigned int i, j = 0;
1186 pasc_t pack;
1187
6d2010ae 1188 length = MIN(((length + 7) & ~7), buflen);
2d21ac55
A
1189
1190 for (i = 0; i < length; i+=8)
1191 {
1192 pack.a = inbuf[i];
1193 pack.b = inbuf[i+1];
1194 pack.c = inbuf[i+2];
1195 pack.d = inbuf[i+3];
1196 pack.e = inbuf[i+4];
1197 pack.f = inbuf[i+5];
1198 pack.g = inbuf[i+6];
1199 pack.h = inbuf[i+7];
1200 bcopy ((char *) &pack, inbuf + j, 7);
1201 j += 7;
1202 }
6d2010ae 1203 return j;
2d21ac55
A
1204}
1205
5ba3f43e
A
1206void
1207unpackA(char *inbuf, uint32_t length)
2d21ac55
A
1208{
1209 pasc_t packs;
1210 unsigned i = 0;
1211 length = (length * 8)/7;
1212
1213 while (i < length) {
1214 packs = *(pasc_t *)&inbuf[i];
1215 bcopy(&inbuf[i+7], &inbuf[i+8], MAX(0, (int) (length - i - 8)));
1216 inbuf[i++] = packs.a;
1217 inbuf[i++] = packs.b;
1218 inbuf[i++] = packs.c;
1219 inbuf[i++] = packs.d;
1220 inbuf[i++] = packs.e;
1221 inbuf[i++] = packs.f;
1222 inbuf[i++] = packs.g;
1223 inbuf[i++] = packs.h;
1224 }
1225}
5ba3f43e 1226#endif /* defined (__x86_64__) */
2d21ac55
A
1227
1228extern void *proc_name_address(void *p);
1229
1230static void
1231panic_display_process_name(void) {
3e170ce0
A
1232 /* because of scoping issues len(p_comm) from proc_t is hard coded here */
1233 char proc_name[17] = "Unknown";
2d21ac55
A
1234 task_t ctask = 0;
1235 void *cbsd_info = 0;
1236
1237 if (ml_nofault_copy((vm_offset_t)&current_thread()->task, (vm_offset_t) &ctask, sizeof(task_t)) == sizeof(task_t))
3e170ce0 1238 if(ml_nofault_copy((vm_offset_t)&ctask->bsd_info, (vm_offset_t)&cbsd_info, sizeof(cbsd_info)) == sizeof(cbsd_info))
2d21ac55
A
1239 if (cbsd_info && (ml_nofault_copy((vm_offset_t) proc_name_address(cbsd_info), (vm_offset_t) &proc_name, sizeof(proc_name)) > 0))
1240 proc_name[sizeof(proc_name) - 1] = '\0';
5ba3f43e 1241 paniclog_append_noflush("\nBSD process name corresponding to current thread: %s\n", proc_name);
2d21ac55
A
1242}
1243
5ba3f43e
A
1244unsigned
1245panic_active(void) {
1246 return ((debugger_panic_str != (char *) 0));
2d21ac55
A
1247}
1248
5ba3f43e
A
1249void
1250populate_model_name(char *model_string) {
2d21ac55
A
1251 strlcpy(model_name, model_string, sizeof(model_name));
1252}
1253
5ba3f43e
A
1254void
1255panic_display_model_name(void) {
2d21ac55
A
1256 char tmp_model_name[sizeof(model_name)];
1257
1258 if (ml_nofault_copy((vm_offset_t) &model_name, (vm_offset_t) &tmp_model_name, sizeof(model_name)) != sizeof(model_name))
1259 return;
1260
6d2010ae
A
1261 tmp_model_name[sizeof(tmp_model_name) - 1] = '\0';
1262
1263 if (tmp_model_name[0] != 0)
5ba3f43e 1264 paniclog_append_noflush("System model name: %s\n", tmp_model_name);
6d2010ae
A
1265}
1266
5ba3f43e
A
1267void
1268panic_display_kernel_uuid(void) {
39236c6e 1269 char tmp_kernel_uuid[sizeof(kernel_uuid_string)];
6d2010ae 1270
39236c6e 1271 if (ml_nofault_copy((vm_offset_t) &kernel_uuid_string, (vm_offset_t) &tmp_kernel_uuid, sizeof(kernel_uuid_string)) != sizeof(kernel_uuid_string))
6d2010ae 1272 return;
2d21ac55 1273
6d2010ae 1274 if (tmp_kernel_uuid[0] != '\0')
5ba3f43e 1275 paniclog_append_noflush("Kernel UUID: %s\n", tmp_kernel_uuid);
2d21ac55
A
1276}
1277
5ba3f43e
A
1278void
1279panic_display_kernel_aslr(void) {
316670eb 1280 if (vm_kernel_slide) {
5ba3f43e
A
1281 paniclog_append_noflush("Kernel slide: 0x%016lx\n", (unsigned long) vm_kernel_slide);
1282 paniclog_append_noflush("Kernel text base: %p\n", (void *) vm_kernel_stext);
316670eb 1283 }
316670eb
A
1284}
1285
5ba3f43e
A
1286void
1287panic_display_hibb(void) {
fe8ab488 1288#if defined(__i386__) || defined (__x86_64__)
5ba3f43e 1289 paniclog_append_noflush("__HIB text base: %p\n", (void *) vm_hib_base);
fe8ab488
A
1290#endif
1291}
1292
5ba3f43e
A
1293static void
1294panic_display_uptime(void) {
c910b4d9
A
1295 uint64_t uptime;
1296 absolutetime_to_nanoseconds(mach_absolute_time(), &uptime);
1297
5ba3f43e 1298 paniclog_append_noflush("\nSystem uptime in nanoseconds: %llu\n", uptime);
c910b4d9
A
1299}
1300
5ba3f43e
A
1301static void
1302panic_display_disk_errors(void) {
d190cdc3
A
1303
1304 if (panic_disk_error_description[0]) {
1305 panic_disk_error_description[sizeof(panic_disk_error_description) - 1] = '\0';
5ba3f43e 1306 paniclog_append_noflush("Root disk errors: \"%s\"\n", panic_disk_error_description);
d190cdc3
A
1307 }
1308};
1309
2d21ac55
A
1310extern const char version[];
1311extern char osversion[];
1312
6d2010ae
A
1313static volatile uint32_t config_displayed = 0;
1314
5ba3f43e
A
1315__private_extern__ void
1316panic_display_system_configuration(boolean_t launchd_exit) {
2d21ac55 1317
d190cdc3 1318 if (!launchd_exit) panic_display_process_name();
6d2010ae
A
1319 if (OSCompareAndSwap(0, 1, &config_displayed)) {
1320 char buf[256];
d190cdc3 1321 if (!launchd_exit && strlcpy(buf, PE_boot_args(), sizeof(buf)))
5ba3f43e
A
1322 paniclog_append_noflush("Boot args: %s\n", buf);
1323 paniclog_append_noflush("\nMac OS version:\n%s\n",
2d21ac55 1324 (osversion[0] != 0) ? osversion : "Not yet set");
5ba3f43e 1325 paniclog_append_noflush("\nKernel version:\n%s\n",version);
6d2010ae 1326 panic_display_kernel_uuid();
d190cdc3
A
1327 if (!launchd_exit) {
1328 panic_display_kernel_aslr();
1329 panic_display_hibb();
1330 panic_display_pal_info();
1331 }
2d21ac55 1332 panic_display_model_name();
d190cdc3
A
1333 panic_display_disk_errors();
1334 if (!launchd_exit) {
1335 panic_display_uptime();
1336 panic_display_zprint();
6d2010ae 1337#if CONFIG_ZLEAKS
d190cdc3 1338 panic_display_ztrace();
6d2010ae 1339#endif /* CONFIG_ZLEAKS */
5ba3f43e 1340 kext_dump_panic_lists(&paniclog_append_noflush);
d190cdc3 1341 }
2d21ac55
A
1342 }
1343}
1344
39037602 1345extern unsigned int stack_total;
6d2010ae 1346extern unsigned long long stack_allocs;
c910b4d9 1347
5ba3f43e 1348#if defined (__x86_64__)
c910b4d9 1349extern unsigned int inuse_ptepages_count;
6d2010ae 1350extern long long alloc_ptepages_count;
c910b4d9
A
1351#endif
1352
5ba3f43e
A
1353extern boolean_t panic_include_zprint;
1354extern mach_memory_info_t *panic_kext_memory_info;
1355extern vm_size_t panic_kext_memory_size;
c910b4d9 1356
5ba3f43e
A
1357__private_extern__ void
1358panic_display_zprint()
c910b4d9
A
1359{
1360 if(panic_include_zprint == TRUE) {
1361
1362 unsigned int i;
1363 struct zone zone_copy;
1364
5ba3f43e 1365 paniclog_append_noflush("%-20s %10s %10s\n", "Zone Name", "Cur Size", "Free Size");
39037602
A
1366 for (i = 0; i < num_zones; i++) {
1367 if(ml_nofault_copy((vm_offset_t)(&zone_array[i]), (vm_offset_t)&zone_copy, sizeof(struct zone)) == sizeof(struct zone)) {
1368 if(zone_copy.cur_size > (1024*1024)) {
5ba3f43e 1369 paniclog_append_noflush("%-20s %10lu %10lu\n",zone_copy.zone_name, (uintptr_t)zone_copy.cur_size,(uintptr_t)(zone_copy.countfree * zone_copy.elem_size));
c910b4d9 1370 }
39037602 1371 }
c910b4d9
A
1372 }
1373
5ba3f43e 1374 paniclog_append_noflush("%-20s %10lu\n", "Kernel Stacks", (uintptr_t)(kernel_stack_size * stack_total));
b0d623f7 1375
5ba3f43e
A
1376#if defined (__x86_64__)
1377 paniclog_append_noflush("%-20s %10lu\n", "PageTables",(uintptr_t)(PAGE_SIZE * inuse_ptepages_count));
c910b4d9 1378#endif
b0d623f7 1379
5ba3f43e 1380 paniclog_append_noflush("%-20s %10lu\n", "Kalloc.Large", (uintptr_t)kalloc_large_total);
3e170ce0 1381 if (panic_kext_memory_info) {
5ba3f43e
A
1382 mach_memory_info_t *mem_info = panic_kext_memory_info;
1383 paniclog_append_noflush("\n%-5s %10s\n", "Kmod", "Size");
1384 for (i = 0; i < (panic_kext_memory_size / sizeof(mach_zone_info_t)); i++) {
3e170ce0 1385 if (((mem_info[i].flags & VM_KERN_SITE_TYPE) == VM_KERN_SITE_KMOD) && (mem_info[i].size > (1024 * 1024))) {
5ba3f43e 1386 paniclog_append_noflush("%-5lld %10lld\n", mem_info[i].site, mem_info[i].size);
3e170ce0
A
1387 }
1388 }
1389 }
c910b4d9
A
1390 }
1391}
1392
fe8ab488 1393#if CONFIG_ECC_LOGGING
5ba3f43e
A
1394__private_extern__ void
1395panic_display_ecc_errors()
fe8ab488
A
1396{
1397 uint32_t count = ecc_log_get_correction_count();
1398
1399 if (count > 0) {
5ba3f43e 1400 paniclog_append_noflush("ECC Corrections:%u\n", count);
fe8ab488
A
1401 }
1402}
1403#endif /* CONFIG_ECC_LOGGING */
1404
6d2010ae
A
1405#if CONFIG_ZLEAKS
1406extern boolean_t panic_include_ztrace;
1407extern struct ztrace* top_ztrace;
04b8595b
A
1408void panic_print_symbol_name(vm_address_t search);
1409
6d2010ae
A
1410/*
1411 * Prints the backtrace most suspected of being a leaker, if we paniced in the zone allocator.
1412 * top_ztrace and panic_include_ztrace comes from osfmk/kern/zalloc.c
1413 */
5ba3f43e
A
1414__private_extern__ void
1415panic_display_ztrace(void)
6d2010ae
A
1416{
1417 if(panic_include_ztrace == TRUE) {
1418 unsigned int i = 0;
04b8595b
A
1419 boolean_t keepsyms = FALSE;
1420
1421 PE_parse_boot_argn("keepsyms", &keepsyms, sizeof (keepsyms));
6d2010ae
A
1422 struct ztrace top_ztrace_copy;
1423
1424 /* Make sure not to trip another panic if there's something wrong with memory */
1425 if(ml_nofault_copy((vm_offset_t)top_ztrace, (vm_offset_t)&top_ztrace_copy, sizeof(struct ztrace)) == sizeof(struct ztrace)) {
5ba3f43e 1426 paniclog_append_noflush("\nBacktrace suspected of leaking: (outstanding bytes: %lu)\n", (uintptr_t)top_ztrace_copy.zt_size);
6d2010ae
A
1427 /* Print the backtrace addresses */
1428 for (i = 0; (i < top_ztrace_copy.zt_depth && i < MAX_ZTRACE_DEPTH) ; i++) {
5ba3f43e 1429 paniclog_append_noflush("%p ", top_ztrace_copy.zt_stack[i]);
04b8595b
A
1430 if (keepsyms) {
1431 panic_print_symbol_name((vm_address_t)top_ztrace_copy.zt_stack[i]);
1432 }
5ba3f43e 1433 paniclog_append_noflush("\n");
6d2010ae
A
1434 }
1435 /* Print any kexts in that backtrace, along with their link addresses so we can properly blame them */
1436 kmod_panic_dump((vm_offset_t *)&top_ztrace_copy.zt_stack[0], top_ztrace_copy.zt_depth);
1437 }
1438 else {
5ba3f43e 1439 paniclog_append_noflush("\nCan't access top_ztrace...\n");
6d2010ae 1440 }
5ba3f43e 1441 paniclog_append_noflush("\n");
6d2010ae
A
1442 }
1443}
1444#endif /* CONFIG_ZLEAKS */
1445
39236c6e 1446#if !CONFIG_TELEMETRY
5ba3f43e
A
1447int
1448telemetry_gather(user_addr_t buffer __unused, uint32_t *length __unused, boolean_t mark __unused)
39236c6e
A
1449{
1450 return KERN_NOT_SUPPORTED;
1451}
1452#endif
5ba3f43e
A
1453
1454#include <machine/machine_cpu.h>
1455
1456uint32_t kern_feature_overrides = 0;
1457
1458boolean_t kern_feature_override(uint32_t fmask) {
1459 if (kern_feature_overrides == 0) {
1460 uint32_t fdisables = 0;
1461 /* Expected to be first invoked early, in a single-threaded
1462 * environment
1463 */
1464 if (PE_parse_boot_argn("validation_disables", &fdisables, sizeof(fdisables))) {
1465 fdisables |= KF_INITIALIZED;
1466 kern_feature_overrides = fdisables;
1467 } else {
1468 kern_feature_overrides |= KF_INITIALIZED;
1469 }
1470 }
1471 return ((kern_feature_overrides & fmask) == fmask);
1472}