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