2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989 Carnegie Mellon University
34 * All Rights Reserved.
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.
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.
46 * Carnegie Mellon requests users of this software to return to
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
57 #include <mach_assert.h>
60 #include <kdp/kdp_core.h>
61 #include <kdp/kdp_internal.h>
62 #include <kdp/kdp_callout.h>
63 #include <kern/cpu_number.h>
64 #include <kern/kalloc.h>
66 #include <kern/thread.h>
67 #include <kern/assert.h>
68 #include <kern/sched_prim.h>
69 #include <kern/misc_protos.h>
70 #include <kern/clock.h>
71 #include <kern/telemetry.h>
73 #include <kern/kern_cdata.h>
74 #include <kern/zalloc.h>
75 #include <vm/vm_kern.h>
78 #include <stdatomic.h>
80 #include <console/serial_protos.h>
82 #if !(MACH_KDP && CONFIG_KDP_INTERACTIVE_DEBUGGING)
83 #include <kdp/kdp_udp.h>
85 #include <kern/processor.h>
87 #if defined(__i386__) || defined(__x86_64__)
88 #include <i386/cpu_threads.h>
89 #include <i386/pmCPU.h>
92 #include <IOKit/IOPlatformExpert.h>
93 #include <machine/pal_routines.h>
95 #include <sys/kdebug.h>
96 #include <libkern/OSKextLibPrivate.h>
97 #include <libkern/OSAtomic.h>
98 #include <libkern/kernel_mach_header.h>
99 #include <uuid/uuid.h>
100 #include <mach_debug/zone_info.h>
102 #include <os/log_private.h>
105 #include <pexpert/pexpert.h> /* For gPanicBase */
106 #include <arm/caches_internal.h>
107 #include <arm/misc_protos.h>
108 extern volatile struct xnu_hw_shmem_dbg_command_info
*hwsd_info
;
112 unsigned int halt_in_debugger
= 0;
113 unsigned int current_debugger
= 0;
114 unsigned int active_debugger
= 0;
115 unsigned int panicDebugging
= FALSE
;
116 unsigned int kdebug_serial
= FALSE
;
117 unsigned int kernel_debugger_entry_count
= 0;
121 #define TRAP_DEBUGGER __asm__ volatile("trap")
122 #elif defined(__arm64__)
124 * Magic number; this should be identical to the __arm__ encoding for trap.
126 #define TRAP_DEBUGGER __asm__ volatile(".long 0xe7ffdeff")
127 #elif defined (__x86_64__)
128 #define TRAP_DEBUGGER __asm__("int3")
130 #error No TRAP_DEBUGGER for this architecture
133 #if defined(__i386__) || defined(__x86_64__)
134 #define panic_stop() pmCPUHalt(PM_HALT_PANIC)
136 #define panic_stop() panic_spin_forever()
139 #define CPUDEBUGGEROP PROCESSOR_DATA(current_processor(), debugger_state).db_current_op
140 #define CPUDEBUGGERMSG PROCESSOR_DATA(current_processor(), debugger_state).db_message
141 #define CPUPANICSTR PROCESSOR_DATA(current_processor(), debugger_state).db_panic_str
142 #define CPUPANICARGS PROCESSOR_DATA(current_processor(), debugger_state).db_panic_args
143 #define CPUPANICOPTS PROCESSOR_DATA(current_processor(), debugger_state).db_panic_options
144 #define CPUDEBUGGERSYNC PROCESSOR_DATA(current_processor(), debugger_state).db_proceed_on_sync_failure
145 #define CPUDEBUGGERCOUNT PROCESSOR_DATA(current_processor(), debugger_state).db_entry_count
146 #define CPUDEBUGGERRET PROCESSOR_DATA(current_processor(), debugger_state).db_op_return
147 #define CPUPANICCALLER PROCESSOR_DATA(current_processor(), debugger_state).db_panic_caller
149 #if DEVELOPMENT || DEBUG
150 #define DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED(requested) \
153 volatile int *badpointer = (int *)4; \
157 #endif /* DEVELOPMENT || DEBUG */
159 debugger_op debugger_current_op
= DBOP_NONE
;
160 const char *debugger_panic_str
= NULL
;
161 va_list *debugger_panic_args
= NULL
;
162 uint64_t debugger_panic_options
= 0;
163 const char *debugger_message
= NULL
;
164 unsigned long debugger_panic_caller
= 0;
166 void panic_trap_to_debugger(const char *panic_format_str
, va_list *panic_args
, unsigned int reason
, void *ctx
, uint64_t panic_options_mask
, unsigned long panic_caller
);
167 static void kdp_machine_reboot_type(unsigned int type
);
168 __attribute__((noreturn
)) void panic_spin_forever(void);
169 extern kern_return_t
do_stackshot(void);
173 #define NESTEDDEBUGGERENTRYMAX 5
176 #define DEBUG_BUF_SIZE (4096)
177 #define KDBG_TRACE_PANIC_FILENAME "/var/log/panic.trace"
180 * DEBUG_BUF_SIZE can't grow without updates to SMC and iBoot to store larger panic logs on co-processor systems */
181 #define DEBUG_BUF_SIZE ((3 * PAGE_SIZE) + offsetof(struct macos_panic_header, mph_data))
182 #define KDBG_TRACE_PANIC_FILENAME "/var/tmp/panic.trace"
185 /* debug_buf is directly linked with iBoot panic region for embedded targets */
187 char *debug_buf_base
= NULL
;
188 char *debug_buf_ptr
= NULL
;
189 unsigned int debug_buf_size
= 0;
191 char debug_buf
[DEBUG_BUF_SIZE
];
192 struct macos_panic_header
*panic_info
= (struct macos_panic_header
*)debug_buf
;
193 char *debug_buf_base
= (debug_buf
+ offsetof(struct macos_panic_header
, mph_data
));
194 char *debug_buf_ptr
= (debug_buf
+ offsetof(struct macos_panic_header
, mph_data
));
197 * We don't include the size of the panic header in the length of the data we actually write.
198 * On co-processor platforms, we lose sizeof(struct macos_panic_header) bytes from the end of
199 * the end of the log because we only support writing (3*PAGESIZE) bytes.
201 const unsigned int debug_buf_size
= (DEBUG_BUF_SIZE
- offsetof(struct macos_panic_header
, mph_data
));
205 atomic_int debugger_cpu
= ATOMIC_VAR_INIT(DEBUGGER_NO_CPU
);
206 boolean_t debugger_allcpus_halted
= FALSE
;
207 boolean_t debugger_safe_to_return
= TRUE
;
208 unsigned int debugger_context
= 0;
210 static char model_name
[64];
211 unsigned char *kernel_uuid
;
214 * By default we treat Debugger() the same as calls to panic(), unless
215 * we have debug boot-args present and the DB_KERN_DUMP_ON_NMI *NOT* set.
216 * If DB_KERN_DUMP_ON_NMI is *NOT* set, return from Debugger() is supported.
218 * Return from Debugger() is currently only implemented on x86
220 static boolean_t debugger_is_panic
= TRUE
;
223 char kernel_uuid_string
[37]; /* uuid_string_t */
224 char panic_disk_error_description
[512];
225 size_t panic_disk_error_description_size
= sizeof(panic_disk_error_description
);
227 extern unsigned int write_trace_on_panic
;
229 int kext_assertions_enable
=
230 #if DEBUG || DEVELOPMENT
239 unsigned long uuidlen
= 0;
242 uuid
= getuuidfromheader(&_mh_execute_header
, &uuidlen
);
243 if ((uuid
!= NULL
) && (uuidlen
== sizeof(uuid_t
))) {
245 uuid_unparse_upper(*(uuid_t
*)uuid
, kernel_uuid_string
);
248 if (!PE_parse_boot_argn("assertions", &mach_assert
, sizeof(mach_assert
))) {
253 uint32_t debug_flags
= 0;
255 if (PE_i_can_has_debugger(&debug_flags
) && !(debug_flags
& DB_KERN_DUMP_ON_NMI
)) {
256 debugger_is_panic
= FALSE
;
267 printf("debug_log_init: Error!! gPanicBase is still not initialized\n");
270 /* Shift debug buf start location and size by the length of the panic header */
271 debug_buf_base
= (char *)gPanicBase
+ sizeof(struct embedded_panic_header
);
272 debug_buf_ptr
= debug_buf_base
;
273 debug_buf_size
= gPanicSize
- sizeof(struct embedded_panic_header
);
275 assert(debug_buf_base
!= NULL
);
276 assert(debug_buf_ptr
!= NULL
);
277 assert(debug_buf_size
!= 0);
278 bzero(debug_buf
, sizeof(debug_buf
));
285 int my_cpu
= cpu_number();
286 int debugger_exp_cpu
= DEBUGGER_NO_CPU
;
287 assert(ml_get_interrupts_enabled() == FALSE
);
289 if (debugger_cpu
== my_cpu
) {
293 while(!atomic_compare_exchange_strong(&debugger_cpu
, &debugger_exp_cpu
, my_cpu
)) {
294 debugger_exp_cpu
= DEBUGGER_NO_CPU
;
303 assert(debugger_cpu
== cpu_number());
306 * We don't do an atomic exchange here in case
307 * there's another CPU spinning to acquire the debugger_lock
308 * and we never get a chance to update it. We already have the
309 * lock so we can simply store DEBUGGER_NO_CPU and follow with
312 debugger_cpu
= DEBUGGER_NO_CPU
;
319 DebuggerHaltOtherCores(boolean_t proceed_on_failure
)
322 return DebuggerXCallEnter(proceed_on_failure
);
323 #else /* CONFIG_EMBEDDED */
324 #pragma unused(proceed_on_failure)
325 mp_kdp_enter(proceed_on_failure
);
331 DebuggerResumeOtherCores()
334 DebuggerXCallReturn();
335 #else /* CONFIG_EMBEDDED */
341 DebuggerSaveState(debugger_op db_op
, const char *db_message
, const char *db_panic_str
,
342 va_list *db_panic_args
, uint64_t db_panic_options
,
343 boolean_t db_proceed_on_sync_failure
, unsigned long db_panic_caller
)
345 CPUDEBUGGEROP
= db_op
;
347 /* Preserve the original panic message */
348 if (CPUDEBUGGERCOUNT
== 1 || CPUPANICSTR
== NULL
) {
349 CPUDEBUGGERMSG
= db_message
;
350 CPUPANICSTR
= db_panic_str
;
351 CPUPANICARGS
= db_panic_args
;
352 CPUPANICCALLER
= db_panic_caller
;
353 } else if (CPUDEBUGGERCOUNT
> 1 && db_panic_str
!= NULL
) {
354 kprintf("Nested panic detected: %s", db_panic_str
);
357 CPUDEBUGGERSYNC
= db_proceed_on_sync_failure
;
358 CPUDEBUGGERRET
= KERN_SUCCESS
;
360 /* Reset these on any nested panics */
361 CPUPANICOPTS
= db_panic_options
;
367 * Save the requested debugger state/action into the current processor's processor_data
368 * and trap to the debugger.
371 DebuggerTrapWithState(debugger_op db_op
, const char *db_message
, const char *db_panic_str
,
372 va_list *db_panic_args
, uint64_t db_panic_options
,
373 boolean_t db_proceed_on_sync_failure
, unsigned long db_panic_caller
)
377 assert(ml_get_interrupts_enabled() == FALSE
);
378 DebuggerSaveState(db_op
, db_message
, db_panic_str
,
379 db_panic_args
, db_panic_options
, db_proceed_on_sync_failure
,
384 ret
= CPUDEBUGGERRET
;
386 DebuggerSaveState(DBOP_NONE
, NULL
, NULL
, NULL
, 0, FALSE
, 0);
391 void __attribute__((noinline
))
395 const char *expression
399 kprintf("%s:%d non-fatal Assertion: %s", file
, line
, expression
);
403 panic_plain("%s:%d Assertion failed: %s", file
, line
, expression
);
408 Debugger(const char *message
)
410 DebuggerWithContext(0, NULL
, message
, DEBUGGER_OPTION_NONE
);
414 DebuggerWithContext(unsigned int reason
, void *ctx
, const char *message
,
415 uint64_t debugger_options_mask
)
417 spl_t previous_interrupts_state
;
418 boolean_t old_doprnt_hide_pointers
= doprnt_hide_pointers
;
420 previous_interrupts_state
= ml_set_interrupts_enabled(FALSE
);
421 disable_preemption();
425 if (CPUDEBUGGERCOUNT
> NESTEDDEBUGGERENTRYMAX
) {
426 static boolean_t in_panic_kprintf
= FALSE
;
428 /* Notify any listeners that we've started a panic */
429 PEHaltRestart(kPEPanicBegin
);
431 if (!in_panic_kprintf
) {
432 in_panic_kprintf
= TRUE
;
433 kprintf("Detected nested debugger entry count exceeding %d\n",
434 NESTEDDEBUGGERENTRYMAX
);
435 in_panic_kprintf
= FALSE
;
438 if (!panicDebugging
) {
439 kdp_machine_reboot_type(kPEPanicRestartCPU
);
442 panic_spin_forever();
445 #if DEVELOPMENT || DEBUG
446 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_options_mask
& DEBUGGER_OPTION_RECURPANIC_ENTRY
));
449 doprnt_hide_pointers
= FALSE
;
452 DebuggerSaveState(DBOP_DEBUGGER
, message
,
453 NULL
, NULL
, debugger_options_mask
, TRUE
, 0);
454 handle_debugger_trap(reason
, 0, 0, ctx
);
455 DebuggerSaveState(DBOP_NONE
, NULL
, NULL
,
458 DebuggerTrapWithState(DBOP_DEBUGGER
, message
,
459 NULL
, NULL
, debugger_options_mask
, TRUE
, 0);
463 doprnt_hide_pointers
= old_doprnt_hide_pointers
;
465 ml_set_interrupts_enabled(previous_interrupts_state
);
468 static struct kdp_callout
{
469 struct kdp_callout
* callout_next
;
470 kdp_callout_fn_t callout_fn
;
471 boolean_t callout_in_progress
;
473 } * kdp_callout_list
= NULL
;
476 * Called from kernel context to register a kdp event callout.
479 kdp_register_callout(kdp_callout_fn_t fn
, void * arg
)
481 struct kdp_callout
* kcp
;
482 struct kdp_callout
* list_head
;
484 kcp
= kalloc(sizeof(*kcp
));
486 panic("kdp_register_callout() kalloc failed");
488 kcp
->callout_fn
= fn
;
489 kcp
->callout_arg
= arg
;
490 kcp
->callout_in_progress
= FALSE
;
492 /* Lock-less list insertion using compare and exchange. */
494 list_head
= kdp_callout_list
;
495 kcp
->callout_next
= list_head
;
496 } while (!OSCompareAndSwapPtr(list_head
, kcp
, &kdp_callout_list
));
500 kdp_callouts(kdp_event_t event
)
502 struct kdp_callout
*kcp
= kdp_callout_list
;
505 if (!kcp
->callout_in_progress
) {
506 kcp
->callout_in_progress
= TRUE
;
507 kcp
->callout_fn(kcp
->callout_arg
, event
);
508 kcp
->callout_in_progress
= FALSE
;
510 kcp
= kcp
->callout_next
;
515 * An overview of the xnu panic path:
517 * Several panic wrappers (panic(), panic_with_options(), etc.) all funnel into panic_trap_to_debugger().
518 * panic_trap_to_debugger() sets the panic state in the current processor's processor_data_t prior
519 * to trapping into the debugger. Once we trap to the debugger, we end up in handle_debugger_trap()
520 * which tries to acquire the panic lock by atomically swapping the current CPU number into debugger_cpu.
521 * debugger_cpu acts as a synchronization point, from which the winning CPU can halt the other cores and
522 * continue to debugger_collect_diagnostics() where we write the paniclog, corefile (if appropriate) and proceed
523 * according to the device's boot-args.
527 panic(const char *str
, ...)
529 va_list panic_str_args
;
531 va_start(panic_str_args
, str
);
532 panic_trap_to_debugger(str
, &panic_str_args
, 0, NULL
, 0, (unsigned long)(char *)__builtin_return_address(0));
533 va_end(panic_str_args
);
537 panic_with_options(unsigned int reason
, void *ctx
, uint64_t debugger_options_mask
, const char *str
, ...)
539 va_list panic_str_args
;
541 va_start(panic_str_args
, str
);
542 panic_trap_to_debugger(str
, &panic_str_args
, reason
, ctx
, debugger_options_mask
, (unsigned long)(char *)__builtin_return_address(0));
543 va_end(panic_str_args
);
547 panic_context(unsigned int reason
, void *ctx
, const char *str
, ...)
549 va_list panic_str_args
;
551 va_start(panic_str_args
, str
);
552 panic_trap_to_debugger(str
, &panic_str_args
, reason
, ctx
, 0, (unsigned long)(char *)__builtin_return_address(0));
553 va_end(panic_str_args
);
556 #pragma clang diagnostic push
557 #pragma clang diagnostic ignored "-Wmissing-noreturn"
559 panic_trap_to_debugger(const char *panic_format_str
, va_list *panic_args
, unsigned int reason
, void
560 *ctx
, uint64_t panic_options_mask
, unsigned long panic_caller
)
562 #pragma clang diagnostic pop
564 if (ml_wants_panic_trap_to_debugger()) {
565 ml_panic_trap_to_debugger(panic_format_str
, panic_args
, reason
, ctx
, panic_options_mask
, panic_caller
);
568 * This should not return, but we return here for the tail call
569 * as it simplifies the backtrace.
576 if (CPUDEBUGGERCOUNT
> NESTEDDEBUGGERENTRYMAX
) {
577 static boolean_t in_panic_kprintf
= FALSE
;
579 /* Notify any listeners that we've started a panic */
580 PEHaltRestart(kPEPanicBegin
);
582 if (!in_panic_kprintf
) {
583 in_panic_kprintf
= TRUE
;
584 kprintf("Detected nested debugger entry count exceeding %d\n",
585 NESTEDDEBUGGERENTRYMAX
);
586 in_panic_kprintf
= FALSE
;
589 if (!panicDebugging
) {
590 kdp_machine_reboot_type(kPEPanicRestartCPU
);
593 panic_spin_forever();
596 #if DEVELOPMENT || DEBUG
597 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((panic_options_mask
& DEBUGGER_OPTION_RECURPANIC_ENTRY
));
601 if (PE_arm_debug_panic_hook
)
602 PE_arm_debug_panic_hook(panic_format_str
);
605 #if defined (__x86_64__)
609 if (write_trace_on_panic
&& kdebug_enable
) {
610 if (get_preemption_level() == 0 && !ml_at_interrupt_context()) {
611 ml_set_interrupts_enabled(TRUE
);
613 kdbg_dump_trace_to_file(KDBG_TRACE_PANIC_FILENAME
);
617 ml_set_interrupts_enabled(FALSE
);
618 disable_preemption();
620 #if defined (__x86_64__)
621 pmSafeMode(x86_lcpu(), PM_SAFE_FL_SAFE
);
622 #endif /* defined (__x86_64__) */
624 /* Never hide pointers from panic logs. */
625 doprnt_hide_pointers
= FALSE
;
629 * We called into panic from a trap, no need to trap again. Set the
630 * state on the current CPU and then jump to handle_debugger_trap.
632 DebuggerSaveState(DBOP_PANIC
, "panic",
633 panic_format_str
, panic_args
,
634 panic_options_mask
, TRUE
, panic_caller
);
635 handle_debugger_trap(reason
, 0, 0, ctx
);
638 #if defined(__arm64__)
640 * Signal to fastsim that it should open debug ports (nop on hardware)
642 __asm__
volatile("HINT 0x45");
643 #endif /* defined(__arm64__) */
645 DebuggerTrapWithState(DBOP_PANIC
, "panic", panic_format_str
,
646 panic_args
, panic_options_mask
, TRUE
, panic_caller
);
654 __attribute__((noreturn
))
658 paniclog_append_noflush("\nPlease go to https://panic.apple.com to report this panic\n");
664 kdp_machine_reboot_type(unsigned int type
)
666 printf("Attempting system restart...");
672 kdp_machine_reboot(void)
674 kdp_machine_reboot_type(kPEPanicRestartCPU
);
678 * Gather and save diagnostic information about a panic (or Debugger call).
680 * On embedded, Debugger and Panic are treated very similarly -- WDT uses Debugger so we can
681 * theoretically return from it. On desktop, Debugger is treated as a conventional debugger -- i.e no
682 * paniclog is written and no core is written unless we request a core on NMI.
684 * This routine handles kicking off local coredumps, paniclogs, calling into the Debugger/KDP (if it's configured),
685 * and calling out to any other functions we have for collecting diagnostic info.
688 debugger_collect_diagnostics(unsigned int exception
, unsigned int code
, unsigned int subcode
, void *state
)
690 #if DEVELOPMENT || DEBUG
691 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_panic_options
& DEBUGGER_OPTION_RECURPANIC_PRELOG
));
694 #if defined(__x86_64__)
695 kprintf("Debugger called: <%s>\n", debugger_message
);
698 * DB_HALT (halt_in_debugger) can be requested on startup, we shouldn't generate
699 * a coredump/paniclog for this type of debugger entry. If KDP isn't configured,
700 * we'll just spin in kdp_raise_exception.
702 if (debugger_current_op
== DBOP_DEBUGGER
&& halt_in_debugger
) {
703 kdp_raise_exception(exception
, code
, subcode
, state
);
704 if (debugger_safe_to_return
&& !debugger_is_panic
) {
709 if ((debugger_current_op
== DBOP_PANIC
) ||
710 (debugger_current_op
== DBOP_DEBUGGER
&& debugger_is_panic
)) {
712 * Attempt to notify listeners once and only once that we've started
713 * panicking. Only do this for Debugger() calls if we're treating
714 * Debugger() calls like panic().
716 PEHaltRestart(kPEPanicBegin
);
719 * Set the begin pointer in the panic log structure. We key off of this
720 * static variable rather than contents from the panic header itself in case someone
721 * has stomped over the panic_info structure. Also initializes the header magic.
723 static boolean_t began_writing_paniclog
= FALSE
;
724 if (!began_writing_paniclog
) {
725 PE_init_panicheader();
726 began_writing_paniclog
= TRUE
;
729 * If we reached here, update the panic header to keep it as consistent
730 * as possible during a nested panic
732 PE_update_panicheader_nestedpanic();
737 * Write panic string if this was a panic.
739 * TODO: Consider moving to SavePanicInfo as this is part of the panic log.
741 if (debugger_current_op
== DBOP_PANIC
) {
742 paniclog_append_noflush("panic(cpu %d caller 0x%lx): ", (unsigned) cpu_number(), debugger_panic_caller
);
743 if (debugger_panic_str
) {
744 _doprnt(debugger_panic_str
, debugger_panic_args
, consdebug_putc
, 0);
746 paniclog_append_noflush("\n");
750 * Debugger() is treated like panic() on embedded -- for example we use it for WDT
751 * panics (so we need to write a paniclog). On desktop Debugger() is used in the
752 * conventional sense.
754 #if defined(__x86_64__)
755 if (debugger_current_op
== DBOP_PANIC
)
758 kdp_callouts(KDP_EVENT_PANICLOG
);
761 * Write paniclog and panic stackshot (if supported)
762 * TODO: Need to clear panic log when return from debugger
763 * hooked up for embedded
765 SavePanicInfo(debugger_message
, debugger_panic_options
);
767 #if DEVELOPMENT || DEBUG
768 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_panic_options
& DEBUGGER_OPTION_RECURPANIC_POSTLOG
));
771 /* DEBUGGER_OPTION_PANICLOGANDREBOOT is used for two finger resets on embedded so we get a paniclog */
772 if (debugger_panic_options
& DEBUGGER_OPTION_PANICLOGANDREBOOT
)
773 PEHaltRestart(kPEPanicRestartCPU
);
776 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
777 uint32_t debug_flags
= 0;
778 PE_i_can_has_debugger(&debug_flags
);
781 * If reboot on panic is enabled and the caller of panic indicated that we should skip
782 * local coredumps, don't try to write these and instead go straight to reboot. This
783 * allows us to persist any data that's stored in the panic log.
785 if ((debugger_panic_options
& DEBUGGER_OPTION_SKIP_LOCAL_COREDUMP
) &&
786 (debug_flags
& DB_REBOOT_POST_CORE
)) {
787 kdp_machine_reboot_type(kPEPanicRestartCPU
);
791 * Consider generating a local corefile if the infrastructure is configured
792 * and we haven't disabled on-device coredumps.
794 if (kdp_has_polled_corefile() && !(debug_flags
& DB_DISABLE_LOCAL_CORE
)) {
797 #if defined (__x86_64__)
798 /* On x86 we don't do a coredump on Debugger unless the DB_KERN_DUMP_ON_NMI boot-arg is specified. */
799 if (debugger_current_op
!= DBOP_DEBUGGER
|| (debug_flags
& DB_KERN_DUMP_ON_NMI
))
803 * Doing an on-device coredump leaves the disk driver in a state
804 * that can not be resumed.
806 debugger_safe_to_return
= FALSE
;
807 begin_panic_transfer();
808 ret
= kern_dump(KERN_DUMP_DISK
);
809 abort_panic_transfer();
811 #if DEVELOPMENT || DEBUG
812 DEBUGGER_DEBUGGING_NESTED_PANIC_IF_REQUESTED((debugger_panic_options
& DEBUGGER_OPTION_RECURPANIC_POSTCORE
));
816 /* If we wrote a corefile and DB_REBOOT_POST_CORE is set, reboot */
817 if (ret
== 0 && (debug_flags
& DB_REBOOT_POST_CORE
))
818 kdp_machine_reboot_type(kPEPanicRestartCPU
);
821 /* If KDP is configured, try to trap to the debugger */
822 if (current_debugger
!= NO_CUR_DB
) {
823 kdp_raise_exception(exception
, code
, subcode
, state
);
825 * Only return if we entered via Debugger and it's safe to return
826 * (we halted the other cores successfully, this isn't a nested panic, etc)
828 if (debugger_current_op
== DBOP_DEBUGGER
&&
829 debugger_safe_to_return
&&
830 kernel_debugger_entry_count
== 1 &&
831 !debugger_is_panic
) {
837 if (panicDebugging
) {
838 /* If panic debugging is configured, spin for astris to connect */
841 #endif /* CONFIG_EMBEDDED */
842 #endif /* CONFIG_KDP_INTERACTIVE_DEBUGGING */
844 if (!panicDebugging
) {
845 kdp_machine_reboot_type(kPEPanicRestartCPU
);
848 panic_spin_forever();
851 #if INTERRUPT_MASKED_DEBUG
852 uint64_t debugger_trap_timestamps
[9];
853 # define DEBUGGER_TRAP_TIMESTAMP(i) debugger_trap_timestamps[i] = mach_absolute_time();
855 # define DEBUGGER_TRAP_TIMESTAMP(i)
859 handle_debugger_trap(unsigned int exception
, unsigned int code
, unsigned int subcode
, void *state
)
861 unsigned int initial_not_in_kdp
= not_in_kdp
;
863 debugger_op db_prev_op
= debugger_current_op
;
865 DEBUGGER_TRAP_TIMESTAMP(0);
868 ret
= DebuggerHaltOtherCores(CPUDEBUGGERSYNC
);
870 DEBUGGER_TRAP_TIMESTAMP(1);
872 #if INTERRUPT_MASKED_DEBUG
873 if (serialmode
& SERIALMODE_OUTPUT
) {
874 ml_spin_debug_reset(current_thread());
877 if (ret
!= KERN_SUCCESS
) {
878 CPUDEBUGGERRET
= ret
;
883 /* Update the global panic/debugger nested entry level */
884 kernel_debugger_entry_count
= CPUDEBUGGERCOUNT
;
887 * TODO: Should we do anything special for nested panics here? i.e. if we've trapped more than twice
888 * should we call into the debugger if it's configured and then reboot if the panic log has been written?
891 if (CPUDEBUGGEROP
== DBOP_NONE
) {
892 /* If there was no debugger context setup, we trapped due to a software breakpoint */
893 debugger_current_op
= DBOP_BREAKPOINT
;
895 /* Not safe to return from a nested panic/debugger call */
896 if (debugger_current_op
== DBOP_PANIC
||
897 debugger_current_op
== DBOP_DEBUGGER
) {
898 debugger_safe_to_return
= FALSE
;
901 debugger_current_op
= CPUDEBUGGEROP
;
903 /* Only overwrite the panic message if there is none already - save the data from the first call */
904 if (debugger_panic_str
== NULL
) {
905 debugger_panic_str
= CPUPANICSTR
;
906 debugger_panic_args
= CPUPANICARGS
;
907 debugger_message
= CPUDEBUGGERMSG
;
908 debugger_panic_caller
= CPUPANICCALLER
;
911 debugger_panic_options
= CPUPANICOPTS
;
915 * Clear the op from the processor debugger context so we can handle
916 * breakpoints in the debugger
918 CPUDEBUGGEROP
= DBOP_NONE
;
920 DEBUGGER_TRAP_TIMESTAMP(2);
922 kdp_callouts(KDP_EVENT_ENTER
);
925 DEBUGGER_TRAP_TIMESTAMP(3);
927 if (debugger_current_op
== DBOP_BREAKPOINT
) {
928 kdp_raise_exception(exception
, code
, subcode
, state
);
929 } else if (debugger_current_op
== DBOP_STACKSHOT
) {
930 CPUDEBUGGERRET
= do_stackshot();
932 } else if (debugger_current_op
== DBOP_RESET_PGO_COUNTERS
) {
933 CPUDEBUGGERRET
= do_pgo_reset_counters();
936 debugger_collect_diagnostics(exception
, code
, subcode
, state
);
939 DEBUGGER_TRAP_TIMESTAMP(4);
941 not_in_kdp
= initial_not_in_kdp
;
942 kdp_callouts(KDP_EVENT_EXIT
);
944 DEBUGGER_TRAP_TIMESTAMP(5);
946 if (debugger_current_op
!= DBOP_BREAKPOINT
) {
947 debugger_panic_str
= NULL
;
948 debugger_panic_args
= NULL
;
949 debugger_panic_options
= 0;
950 debugger_message
= NULL
;
953 /* Restore the previous debugger state */
954 debugger_current_op
= db_prev_op
;
956 DEBUGGER_TRAP_TIMESTAMP(6);
958 DebuggerResumeOtherCores();
960 DEBUGGER_TRAP_TIMESTAMP(7);
964 DEBUGGER_TRAP_TIMESTAMP(8);
969 __attribute__((noinline
,not_tail_called
))
970 void log(__unused
int level
, char *fmt
, ...)
972 void *caller
= __builtin_return_address(0);
981 va_start(listp
, fmt
);
982 va_copy(listp2
, listp
);
984 disable_preemption();
985 _doprnt(fmt
, &listp
, cons_putc_locked
, 0);
990 os_log_with_args(OS_LOG_DEFAULT
, OS_LOG_TYPE_DEFAULT
, fmt
, listp2
, caller
);
996 * Per <rdar://problem/24974766>, skip appending log messages to
997 * the new logging infrastructure in contexts where safety is
998 * uncertain. These contexts include:
999 * - When we're in the debugger
1000 * - We're in a panic
1001 * - Interrupts are disabled
1002 * - Or Pre-emption is disabled
1003 * In all the above cases, it is potentially unsafe to log messages.
1007 oslog_is_safe(void) {
1008 return (kernel_debugger_entry_count
== 0 &&
1010 get_preemption_level() == 0 &&
1011 ml_get_interrupts_enabled() == TRUE
);
1015 debug_mode_active(void)
1017 return ((0 != kernel_debugger_entry_count
!= 0) || (0 == not_in_kdp
));
1023 if ((debug_buf_size
!= 0) &&
1024 ((debug_buf_ptr
- debug_buf_base
) < (int)debug_buf_size
)) {
1030 #if defined (__x86_64__)
1040 } __attribute__((packed
));
1042 typedef struct pasc pasc_t
;
1045 * In-place packing routines -- inefficient, but they're called at most once.
1046 * Assumes "buflen" is a multiple of 8. Used for compressing paniclogs on x86.
1049 packA(char *inbuf
, uint32_t length
, uint32_t buflen
)
1051 unsigned int i
, j
= 0;
1054 length
= MIN(((length
+ 7) & ~7), buflen
);
1056 for (i
= 0; i
< length
; i
+=8)
1059 pack
.b
= inbuf
[i
+1];
1060 pack
.c
= inbuf
[i
+2];
1061 pack
.d
= inbuf
[i
+3];
1062 pack
.e
= inbuf
[i
+4];
1063 pack
.f
= inbuf
[i
+5];
1064 pack
.g
= inbuf
[i
+6];
1065 pack
.h
= inbuf
[i
+7];
1066 bcopy ((char *) &pack
, inbuf
+ j
, 7);
1073 unpackA(char *inbuf
, uint32_t length
)
1077 length
= (length
* 8)/7;
1079 while (i
< length
) {
1080 packs
= *(pasc_t
*)&inbuf
[i
];
1081 bcopy(&inbuf
[i
+7], &inbuf
[i
+8], MAX(0, (int) (length
- i
- 8)));
1082 inbuf
[i
++] = packs
.a
;
1083 inbuf
[i
++] = packs
.b
;
1084 inbuf
[i
++] = packs
.c
;
1085 inbuf
[i
++] = packs
.d
;
1086 inbuf
[i
++] = packs
.e
;
1087 inbuf
[i
++] = packs
.f
;
1088 inbuf
[i
++] = packs
.g
;
1089 inbuf
[i
++] = packs
.h
;
1092 #endif /* defined (__x86_64__) */
1094 extern void *proc_name_address(void *p
);
1097 panic_display_process_name(void) {
1098 /* because of scoping issues len(p_comm) from proc_t is hard coded here */
1099 char proc_name
[17] = "Unknown";
1101 void *cbsd_info
= 0;
1103 if (ml_nofault_copy((vm_offset_t
)¤t_thread()->task
, (vm_offset_t
) &ctask
, sizeof(task_t
)) == sizeof(task_t
))
1104 if(ml_nofault_copy((vm_offset_t
)&ctask
->bsd_info
, (vm_offset_t
)&cbsd_info
, sizeof(cbsd_info
)) == sizeof(cbsd_info
))
1105 if (cbsd_info
&& (ml_nofault_copy((vm_offset_t
) proc_name_address(cbsd_info
), (vm_offset_t
) &proc_name
, sizeof(proc_name
)) > 0))
1106 proc_name
[sizeof(proc_name
) - 1] = '\0';
1107 paniclog_append_noflush("\nBSD process name corresponding to current thread: %s\n", proc_name
);
1111 panic_active(void) {
1112 return ((debugger_panic_str
!= (char *) 0));
1116 populate_model_name(char *model_string
) {
1117 strlcpy(model_name
, model_string
, sizeof(model_name
));
1121 panic_display_model_name(void) {
1122 char tmp_model_name
[sizeof(model_name
)];
1124 if (ml_nofault_copy((vm_offset_t
) &model_name
, (vm_offset_t
) &tmp_model_name
, sizeof(model_name
)) != sizeof(model_name
))
1127 tmp_model_name
[sizeof(tmp_model_name
) - 1] = '\0';
1129 if (tmp_model_name
[0] != 0)
1130 paniclog_append_noflush("System model name: %s\n", tmp_model_name
);
1134 panic_display_kernel_uuid(void) {
1135 char tmp_kernel_uuid
[sizeof(kernel_uuid_string
)];
1137 if (ml_nofault_copy((vm_offset_t
) &kernel_uuid_string
, (vm_offset_t
) &tmp_kernel_uuid
, sizeof(kernel_uuid_string
)) != sizeof(kernel_uuid_string
))
1140 if (tmp_kernel_uuid
[0] != '\0')
1141 paniclog_append_noflush("Kernel UUID: %s\n", tmp_kernel_uuid
);
1145 panic_display_kernel_aslr(void) {
1146 if (vm_kernel_slide
) {
1147 paniclog_append_noflush("Kernel slide: 0x%016lx\n", (unsigned long) vm_kernel_slide
);
1148 paniclog_append_noflush("Kernel text base: %p\n", (void *) vm_kernel_stext
);
1153 panic_display_hibb(void) {
1154 #if defined(__i386__) || defined (__x86_64__)
1155 paniclog_append_noflush("__HIB text base: %p\n", (void *) vm_hib_base
);
1160 panic_display_uptime(void) {
1162 absolutetime_to_nanoseconds(mach_absolute_time(), &uptime
);
1164 paniclog_append_noflush("\nSystem uptime in nanoseconds: %llu\n", uptime
);
1168 panic_display_disk_errors(void) {
1170 if (panic_disk_error_description
[0]) {
1171 panic_disk_error_description
[sizeof(panic_disk_error_description
) - 1] = '\0';
1172 paniclog_append_noflush("Root disk errors: \"%s\"\n", panic_disk_error_description
);
1176 extern const char version
[];
1177 extern char osversion
[];
1179 static volatile uint32_t config_displayed
= 0;
1181 __private_extern__
void
1182 panic_display_system_configuration(boolean_t launchd_exit
) {
1184 if (!launchd_exit
) panic_display_process_name();
1185 if (OSCompareAndSwap(0, 1, &config_displayed
)) {
1187 if (!launchd_exit
&& strlcpy(buf
, PE_boot_args(), sizeof(buf
)))
1188 paniclog_append_noflush("Boot args: %s\n", buf
);
1189 paniclog_append_noflush("\nMac OS version:\n%s\n",
1190 (osversion
[0] != 0) ? osversion
: "Not yet set");
1191 paniclog_append_noflush("\nKernel version:\n%s\n",version
);
1192 panic_display_kernel_uuid();
1193 if (!launchd_exit
) {
1194 panic_display_kernel_aslr();
1195 panic_display_hibb();
1196 panic_display_pal_info();
1198 panic_display_model_name();
1199 panic_display_disk_errors();
1200 if (!launchd_exit
) {
1201 panic_display_uptime();
1202 panic_display_zprint();
1204 panic_display_ztrace();
1205 #endif /* CONFIG_ZLEAKS */
1206 kext_dump_panic_lists(&paniclog_append_noflush
);
1211 extern unsigned int stack_total
;
1212 extern unsigned long long stack_allocs
;
1214 #if defined (__x86_64__)
1215 extern unsigned int inuse_ptepages_count
;
1216 extern long long alloc_ptepages_count
;
1219 extern boolean_t panic_include_zprint
;
1220 extern mach_memory_info_t
*panic_kext_memory_info
;
1221 extern vm_size_t panic_kext_memory_size
;
1223 __private_extern__
void
1224 panic_display_zprint()
1226 if(panic_include_zprint
== TRUE
) {
1229 struct zone zone_copy
;
1231 paniclog_append_noflush("%-20s %10s %10s\n", "Zone Name", "Cur Size", "Free Size");
1232 for (i
= 0; i
< num_zones
; i
++) {
1233 if(ml_nofault_copy((vm_offset_t
)(&zone_array
[i
]), (vm_offset_t
)&zone_copy
, sizeof(struct zone
)) == sizeof(struct zone
)) {
1234 if(zone_copy
.cur_size
> (1024*1024)) {
1235 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
));
1240 paniclog_append_noflush("%-20s %10lu\n", "Kernel Stacks", (uintptr_t)(kernel_stack_size
* stack_total
));
1242 #if defined (__x86_64__)
1243 paniclog_append_noflush("%-20s %10lu\n", "PageTables",(uintptr_t)(PAGE_SIZE
* inuse_ptepages_count
));
1246 paniclog_append_noflush("%-20s %10lu\n", "Kalloc.Large", (uintptr_t)kalloc_large_total
);
1247 if (panic_kext_memory_info
) {
1248 mach_memory_info_t
*mem_info
= panic_kext_memory_info
;
1249 paniclog_append_noflush("\n%-5s %10s\n", "Kmod", "Size");
1250 for (i
= 0; i
< (panic_kext_memory_size
/ sizeof(mach_zone_info_t
)); i
++) {
1251 if (((mem_info
[i
].flags
& VM_KERN_SITE_TYPE
) == VM_KERN_SITE_KMOD
) && (mem_info
[i
].size
> (1024 * 1024))) {
1252 paniclog_append_noflush("%-5lld %10lld\n", mem_info
[i
].site
, mem_info
[i
].size
);
1259 #if CONFIG_ECC_LOGGING
1260 __private_extern__
void
1261 panic_display_ecc_errors()
1263 uint32_t count
= ecc_log_get_correction_count();
1266 paniclog_append_noflush("ECC Corrections:%u\n", count
);
1269 #endif /* CONFIG_ECC_LOGGING */
1272 extern boolean_t panic_include_ztrace
;
1273 extern struct ztrace
* top_ztrace
;
1274 void panic_print_symbol_name(vm_address_t search
);
1277 * Prints the backtrace most suspected of being a leaker, if we paniced in the zone allocator.
1278 * top_ztrace and panic_include_ztrace comes from osfmk/kern/zalloc.c
1280 __private_extern__
void
1281 panic_display_ztrace(void)
1283 if(panic_include_ztrace
== TRUE
) {
1285 boolean_t keepsyms
= FALSE
;
1287 PE_parse_boot_argn("keepsyms", &keepsyms
, sizeof (keepsyms
));
1288 struct ztrace top_ztrace_copy
;
1290 /* Make sure not to trip another panic if there's something wrong with memory */
1291 if(ml_nofault_copy((vm_offset_t
)top_ztrace
, (vm_offset_t
)&top_ztrace_copy
, sizeof(struct ztrace
)) == sizeof(struct ztrace
)) {
1292 paniclog_append_noflush("\nBacktrace suspected of leaking: (outstanding bytes: %lu)\n", (uintptr_t)top_ztrace_copy
.zt_size
);
1293 /* Print the backtrace addresses */
1294 for (i
= 0; (i
< top_ztrace_copy
.zt_depth
&& i
< MAX_ZTRACE_DEPTH
) ; i
++) {
1295 paniclog_append_noflush("%p ", top_ztrace_copy
.zt_stack
[i
]);
1297 panic_print_symbol_name((vm_address_t
)top_ztrace_copy
.zt_stack
[i
]);
1299 paniclog_append_noflush("\n");
1301 /* Print any kexts in that backtrace, along with their link addresses so we can properly blame them */
1302 kmod_panic_dump((vm_offset_t
*)&top_ztrace_copy
.zt_stack
[0], top_ztrace_copy
.zt_depth
);
1305 paniclog_append_noflush("\nCan't access top_ztrace...\n");
1307 paniclog_append_noflush("\n");
1310 #endif /* CONFIG_ZLEAKS */
1312 #if !CONFIG_TELEMETRY
1314 telemetry_gather(user_addr_t buffer __unused
, uint32_t *length __unused
, boolean_t mark __unused
)
1316 return KERN_NOT_SUPPORTED
;
1320 #include <machine/machine_cpu.h>
1322 uint32_t kern_feature_overrides
= 0;
1324 boolean_t
kern_feature_override(uint32_t fmask
) {
1325 if (kern_feature_overrides
== 0) {
1326 uint32_t fdisables
= 0;
1327 /* Expected to be first invoked early, in a single-threaded
1330 if (PE_parse_boot_argn("validation_disables", &fdisables
, sizeof(fdisables
))) {
1331 fdisables
|= KF_INITIALIZED
;
1332 kern_feature_overrides
= fdisables
;
1334 kern_feature_overrides
|= KF_INITIALIZED
;
1337 return ((kern_feature_overrides
& fmask
) == fmask
);