1 /*
2 * Copyright (c) 2000-2019 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, 1988 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 [email protected]
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 /*
58 */
59
60 /*
61 * File: model_dep.c
62 * Author: Avadis Tevanian, Jr., Michael Wayne Young
63 *
64 * Copyright (C) 1986, Avadis Tevanian, Jr., Michael Wayne Young
65 *
66 * Basic initialization for I386 - ISA bus machines.
67 */
68
69
70 #define __APPLE_API_PRIVATE 1
71 #define __APPLE_API_UNSTABLE 1
72 #include <kern/debug.h>
73
74 #include <mach/i386/vm_param.h>
75
76 #include <string.h>
77 #include <mach/vm_param.h>
78 #include <mach/vm_prot.h>
79 #include <mach/machine.h>
80 #include <mach/time_value.h>
81 #include <sys/kdebug.h>
82 #include <sys/time.h>
83 #include <kern/spl.h>
84 #include <kern/assert.h>
85 #include <kern/lock_group.h>
86 #include <kern/misc_protos.h>
87 #include <kern/startup.h>
88 #include <kern/clock.h>
89 #include <kern/cpu_data.h>
90 #include <kern/machine.h>
91 #include <i386/postcode.h>
92 #include <i386/mp_desc.h>
93 #include <i386/misc_protos.h>
94 #include <i386/panic_notify.h>
95 #include <i386/thread.h>
96 #include <i386/trap.h>
97 #include <i386/machine_routines.h>
98 #include <i386/mp.h>
99 #include <i386/cpuid.h>
100 #include <i386/fpu.h>
101 #include <i386/machine_cpu.h>
102 #include <i386/pmap.h>
103 #if CONFIG_MTRR
104 #include <i386/mtrr.h>
105 #endif
106 #include <i386/ucode.h>
107 #include <i386/pmCPU.h>
108 #include <i386/panic_hooks.h>
109 #include <i386/lbr.h>
110
111 #include <architecture/i386/pio.h> /* inb() */
112 #include <pexpert/i386/boot.h>
113
114 #include <kdp/kdp_dyld.h>
115 #include <kdp/kdp_core.h>
116 #include <vm/pmap.h>
117 #include <vm/vm_map.h>
118 #include <vm/vm_kern.h>
119
120 #include <IOKit/IOBSD.h>
121 #include <IOKit/IOPlatformExpert.h>
122 #include <IOKit/IOHibernatePrivate.h>
123
124 #include <pexpert/i386/efi.h>
125
126 #include <kern/thread.h>
127 #include <kern/sched.h>
128 #include <mach-o/loader.h>
129 #include <mach-o/nlist.h>
130
131 #include <libkern/kernel_mach_header.h>
132 #include <libkern/OSKextLibPrivate.h>
133 #include <libkern/crc.h>
134
135 #if DEBUG || DEVELOPMENT
136 #define DPRINTF(x ...) kprintf(x)
137 #else
138 #define DPRINTF(x ...)
139 #endif
140
141 #ifndef ROUNDUP
142 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
143 #endif
144
145 #ifndef ROUNDDOWN
146 #define ROUNDDOWN(x, y) (((x)/(y))*(y))
147 #endif
148
149 static void machine_conf(void);
150 void panic_print_symbol_name(vm_address_t search);
151 void RecordPanicStackshot(void);
152
153 typedef enum paniclog_flush_type {
154 kPaniclogFlushBase = 1,/* Flush the initial log and paniclog header */
155 kPaniclogFlushStackshot = 2,/* Flush only the stackshot data, then flush the header */
156 kPaniclogFlushOtherLog = 3/* Flush the other log, then flush the header */
157 } paniclog_flush_type_t;
158
159 void paniclog_flush_internal(paniclog_flush_type_t variant);
160
161 extern const char version[];
162 extern char osversion[];
163 extern int max_poll_quanta;
164 extern unsigned int panic_is_inited;
165
166 /* #include <sys/proc.h> */
167 #define MAXCOMLEN 16
168 struct proc;
169 extern int proc_pid(struct proc *p);
170 extern void proc_name_kdp(struct proc *p, char * buf, int size);
171
172
173 /* Definitions for frame pointers */
174 #define FP_ALIGNMENT_MASK ((uint32_t)(0x3))
175 #define FP_LR_OFFSET ((uint32_t)4)
176 #define FP_LR_OFFSET64 ((uint32_t)8)
177 #define FP_MAX_NUM_TO_EVALUATE (50)
178
179 volatile int pbtcpu = -1;
180 hw_lock_data_t pbtlock; /* backtrace print lock */
181 uint32_t pbtcnt = 0;
182
183 volatile int panic_double_fault_cpu = -1;
184
185 #define PRINT_ARGS_FROM_STACK_FRAME 0
186
187 typedef struct _cframe_t {
188 struct _cframe_t *prev;
189 uintptr_t caller;
190 #if PRINT_ARGS_FROM_STACK_FRAME
191 unsigned args[0];
192 #endif
193 } cframe_t;
194
195 static unsigned commit_paniclog_to_nvram;
196 boolean_t coprocessor_paniclog_flush = FALSE;
197
198 struct kcdata_descriptor kc_panic_data;
199 static boolean_t begun_panic_stackshot = FALSE;
200 extern kern_return_t do_stackshot(void *);
201
202 extern void kdp_snapshot_preflight(int pid, void * tracebuf,
203 uint32_t tracebuf_size, uint64_t flags,
204 kcdata_descriptor_t data_p,
205 uint64_t since_timestamp, uint32_t pagetable_mask);
206 extern int kdp_stack_snapshot_bytes_traced(void);
207 extern int kdp_stack_snapshot_bytes_uncompressed(void);
208
209 extern void stackshot_memcpy(void *dst, const void *src, size_t len);
210 vm_offset_t panic_stackshot_buf = 0;
211 size_t panic_stackshot_buf_len = 0;
212
213 size_t panic_stackshot_len = 0;
214
215 boolean_t is_clock_configured = FALSE;
216
217 static struct lbr_data lbrs[MAX_CPUS];
218 static uint32_t lbr_stack_size;
219
220 /*
221 * Backtrace a single frame.
222 */
223 void
print_one_backtrace(pmap_t pmap,vm_offset_t topfp,const char * cur_marker,boolean_t is_64_bit)224 print_one_backtrace(pmap_t pmap, vm_offset_t topfp, const char *cur_marker,
225 boolean_t is_64_bit)
226 {
227 unsigned int i = 0;
228 addr64_t lr = 0;
229 addr64_t fp = topfp;
230 addr64_t fp_for_ppn = 0;
231 ppnum_t ppn = (ppnum_t)NULL;
232 bool dump_kernel_stack = (fp >= VM_MIN_KERNEL_ADDRESS);
233
234 do {
235 if ((fp == 0) || ((fp & FP_ALIGNMENT_MASK) != 0)) {
236 break;
237 }
238 if (dump_kernel_stack && ((fp < VM_MIN_KERNEL_ADDRESS) || (fp > VM_MAX_KERNEL_ADDRESS))) {
239 break;
240 }
241 if ((!dump_kernel_stack) && (fp >= VM_MIN_KERNEL_ADDRESS)) {
242 break;
243 }
244
245 /* Check to see if current address will result in a different
246 * ppn than previously computed (to avoid recomputation) via
247 * (addr) ^ fp_for_ppn) >> PAGE_SHIFT) */
248
249 if ((((fp + FP_LR_OFFSET) ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
250 ppn = pmap_find_phys(pmap, fp + FP_LR_OFFSET);
251 fp_for_ppn = fp + (is_64_bit ? FP_LR_OFFSET64 : FP_LR_OFFSET);
252 }
253 if (ppn != (ppnum_t)NULL) {
254 if (is_64_bit) {
255 lr = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET64) & PAGE_MASK));
256 } else {
257 lr = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET) & PAGE_MASK));
258 }
259 } else {
260 if (is_64_bit) {
261 paniclog_append_noflush("%s\t Could not read LR from frame at 0x%016llx\n", cur_marker, fp + FP_LR_OFFSET64);
262 } else {
263 paniclog_append_noflush("%s\t Could not read LR from frame at 0x%08x\n", cur_marker, (uint32_t)(fp + FP_LR_OFFSET));
264 }
265 break;
266 }
267 if (((fp ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
268 ppn = pmap_find_phys(pmap, fp);
269 fp_for_ppn = fp;
270 }
271 if (ppn != (ppnum_t)NULL) {
272 if (is_64_bit) {
273 fp = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
274 } else {
275 fp = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
276 }
277 } else {
278 if (is_64_bit) {
279 paniclog_append_noflush("%s\t Could not read FP from frame at 0x%016llx\n", cur_marker, fp);
280 } else {
281 paniclog_append_noflush("%s\t Could not read FP from frame at 0x%08x\n", cur_marker, (uint32_t)fp);
282 }
283 break;
284 }
285 /*
286 * Counter 'i' may == FP_MAX_NUM_TO_EVALUATE when running one
287 * extra round to check whether we have all frames in order to
288 * indicate (in)complete backtrace below. This happens in a case
289 * where total frame count and FP_MAX_NUM_TO_EVALUATE are equal.
290 * Do not capture anything.
291 */
292 if (i < FP_MAX_NUM_TO_EVALUATE && lr) {
293 if (is_64_bit) {
294 paniclog_append_noflush("%s\t0x%016llx\n", cur_marker, lr);
295 } else {
296 paniclog_append_noflush("%s\t0x%08x\n", cur_marker, (uint32_t)lr);
297 }
298 }
299 } while ((++i <= FP_MAX_NUM_TO_EVALUATE) && (fp != topfp));
300
301 if (i > FP_MAX_NUM_TO_EVALUATE && fp != 0) {
302 paniclog_append_noflush("Backtrace continues...\n");
303 }
304 }
305 void
machine_startup(void)306 machine_startup(void)
307 {
308 int boot_arg;
309
310 #if 0
311 if (PE_get_hotkey( kPEControlKey )) {
312 halt_in_debugger = halt_in_debugger ? 0 : 1;
313 }
314 #endif
315
316 if (!PE_parse_boot_argn("nvram_paniclog", &commit_paniclog_to_nvram, sizeof(commit_paniclog_to_nvram))) {
317 commit_paniclog_to_nvram = 1;
318 }
319
320 /*
321 * Entering the debugger will put the CPUs into a "safe"
322 * power mode.
323 */
324 if (PE_parse_boot_argn("pmsafe_debug", &boot_arg, sizeof(boot_arg))) {
325 pmsafe_debug = boot_arg;
326 }
327
328 hw_lock_init(&pbtlock); /* initialize print backtrace lock */
329
330 if (PE_parse_boot_argn("yield", &boot_arg, sizeof(boot_arg))) {
331 sched_poll_yield_shift = boot_arg;
332 }
333
334 panic_notify_init();
335
336 machine_conf();
337
338 panic_hooks_init();
339
340 /*
341 * Start the system.
342 */
343 kernel_bootstrap();
344 /*NOTREACHED*/
345 }
346
347
348 static void
machine_conf(void)349 machine_conf(void)
350 {
351 machine_info.memory_size = (typeof(machine_info.memory_size))mem_size;
352 }
353
354 extern void *gPEEFIRuntimeServices;
355 extern void *gPEEFISystemTable;
356
357 static void
efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table)358 efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table)
359 {
360 EFI_RUNTIME_SERVICES_64 *runtime;
361 uint32_t hdr_cksum;
362 uint32_t cksum;
363
364 DPRINTF("Processing 64-bit EFI tables at %p\n", system_table);
365 do {
366 DPRINTF("Header:\n");
367 DPRINTF(" Signature: 0x%016llx\n", system_table->Hdr.Signature);
368 DPRINTF(" Revision: 0x%08x\n", system_table->Hdr.Revision);
369 DPRINTF(" HeaderSize: 0x%08x\n", system_table->Hdr.HeaderSize);
370 DPRINTF(" CRC32: 0x%08x\n", system_table->Hdr.CRC32);
371 DPRINTF("RuntimeServices: 0x%016llx\n", system_table->RuntimeServices);
372 if (system_table->Hdr.Signature != EFI_SYSTEM_TABLE_SIGNATURE) {
373 kprintf("Bad EFI system table signature\n");
374 break;
375 }
376 // Verify signature of the system table
377 hdr_cksum = system_table->Hdr.CRC32;
378 system_table->Hdr.CRC32 = 0;
379 cksum = crc32(0L, system_table, system_table->Hdr.HeaderSize);
380
381 DPRINTF("System table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
382 system_table->Hdr.CRC32 = hdr_cksum;
383 if (cksum != hdr_cksum) {
384 kprintf("Bad EFI system table checksum\n");
385 break;
386 }
387
388 gPEEFISystemTable = system_table;
389
390 if (system_table->RuntimeServices == 0) {
391 kprintf("No runtime table present\n");
392 break;
393 }
394 DPRINTF("RuntimeServices table at 0x%qx\n", system_table->RuntimeServices);
395 // 64-bit virtual address is OK for 64-bit EFI and 64/32-bit kernel.
396 runtime = (EFI_RUNTIME_SERVICES_64 *) (uintptr_t)system_table->RuntimeServices;
397 DPRINTF("Checking runtime services table %p\n", runtime);
398 if (runtime->Hdr.Signature != EFI_RUNTIME_SERVICES_SIGNATURE) {
399 kprintf("Bad EFI runtime table signature\n");
400 break;
401 }
402
403 // Verify signature of runtime services table
404 hdr_cksum = runtime->Hdr.CRC32;
405 runtime->Hdr.CRC32 = 0;
406 cksum = crc32(0L, runtime, runtime->Hdr.HeaderSize);
407
408 DPRINTF("Runtime table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
409 runtime->Hdr.CRC32 = hdr_cksum;
410 if (cksum != hdr_cksum) {
411 kprintf("Bad EFI runtime table checksum\n");
412 break;
413 }
414
415 gPEEFIRuntimeServices = runtime;
416 } while (FALSE);
417 }
418
419 /* Map in EFI runtime areas. */
420 static void
efi_init(void)421 efi_init(void)
422 {
423 boot_args *args = (boot_args *)PE_state.bootArgs;
424
425 kprintf("Initializing EFI runtime services\n");
426
427 do {
428 vm_offset_t vm_size, vm_addr;
429 vm_map_offset_t phys_addr;
430 EfiMemoryRange *mptr;
431 unsigned int msize, mcount;
432 unsigned int i;
433
434 msize = args->MemoryMapDescriptorSize;
435 mcount = args->MemoryMapSize / msize;
436
437 DPRINTF("efi_init() kernel base: 0x%x size: 0x%x\n",
438 args->kaddr, args->ksize);
439 DPRINTF(" efiSystemTable physical: 0x%x virtual: %p\n",
440 args->efiSystemTable,
441 (void *) ml_static_ptovirt(args->efiSystemTable));
442 DPRINTF(" efiRuntimeServicesPageStart: 0x%x\n",
443 args->efiRuntimeServicesPageStart);
444 DPRINTF(" efiRuntimeServicesPageCount: 0x%x\n",
445 args->efiRuntimeServicesPageCount);
446 DPRINTF(" efiRuntimeServicesVirtualPageStart: 0x%016llx\n",
447 args->efiRuntimeServicesVirtualPageStart);
448 mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap);
449 for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
450 if (((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME)) {
451 vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
452 vm_addr = (vm_offset_t) mptr->VirtualStart;
453 /* For K64 on EFI32, shadow-map into high KVA */
454 if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
455 vm_addr |= VM_MIN_KERNEL_ADDRESS;
456 }
457 phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
458 DPRINTF(" Type: %x phys: %p EFIv: %p kv: %p size: %p\n",
459 mptr->Type,
460 (void *) (uintptr_t) phys_addr,
461 (void *) (uintptr_t) mptr->VirtualStart,
462 (void *) vm_addr,
463 (void *) vm_size);
464 pmap_map_bd(vm_addr, phys_addr, phys_addr + round_page(vm_size),
465 (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ | VM_PROT_WRITE,
466 (mptr->Type == EfiMemoryMappedIO) ? VM_WIMG_IO : VM_WIMG_USE_DEFAULT);
467 }
468 }
469
470 if (args->Version != kBootArgsVersion2) {
471 panic("Incompatible boot args version %d revision %d", args->Version, args->Revision);
472 }
473
474 DPRINTF("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode);
475 if (args->efiMode == kBootArgsEfiMode64) {
476 efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable));
477 } else {
478 panic("Unsupported 32-bit EFI system table!");
479 }
480 } while (FALSE);
481
482 return;
483 }
484
485 /* Returns TRUE if a page belongs to the EFI Runtime Services (code or data) */
486 boolean_t
bootloader_valid_page(ppnum_t ppn)487 bootloader_valid_page(ppnum_t ppn)
488 {
489 boot_args *args = (boot_args *)PE_state.bootArgs;
490 ppnum_t pstart = args->efiRuntimeServicesPageStart;
491 ppnum_t pend = pstart + args->efiRuntimeServicesPageCount;
492
493 return pstart <= ppn && ppn < pend;
494 }
495
496 /* Remap EFI runtime areas. */
497 void
hibernate_newruntime_map(void * map,vm_size_t map_size,uint32_t system_table_offset)498 hibernate_newruntime_map(void * map, vm_size_t map_size, uint32_t system_table_offset)
499 {
500 boot_args *args = (boot_args *)PE_state.bootArgs;
501
502 kprintf("Reinitializing EFI runtime services\n");
503
504 do {
505 vm_offset_t vm_size, vm_addr;
506 vm_map_offset_t phys_addr;
507 EfiMemoryRange *mptr;
508 unsigned int msize, mcount;
509 unsigned int i;
510
511 gPEEFISystemTable = 0;
512 gPEEFIRuntimeServices = 0;
513
514 system_table_offset += ptoa_32(args->efiRuntimeServicesPageStart);
515
516 kprintf("Old system table 0x%x, new 0x%x\n",
517 (uint32_t)args->efiSystemTable, system_table_offset);
518
519 args->efiSystemTable = system_table_offset;
520
521 kprintf("Old map:\n");
522 msize = args->MemoryMapDescriptorSize;
523 mcount = args->MemoryMapSize / msize;
524 mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap);
525 for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
526 if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {
527 vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
528 vm_addr = (vm_offset_t) mptr->VirtualStart;
529 /* K64 on EFI32 */
530 if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
531 vm_addr |= VM_MIN_KERNEL_ADDRESS;
532 }
533 phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
534
535 kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages);
536 }
537 }
538
539 pmap_remove(kernel_pmap, i386_ptob(args->efiRuntimeServicesPageStart),
540 i386_ptob(args->efiRuntimeServicesPageStart + args->efiRuntimeServicesPageCount));
541
542 kprintf("New map:\n");
543 msize = args->MemoryMapDescriptorSize;
544 mcount = (unsigned int)(map_size / msize);
545 mptr = map;
546 for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
547 if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {
548 vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
549 vm_addr = (vm_offset_t) mptr->VirtualStart;
550 if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
551 vm_addr |= VM_MIN_KERNEL_ADDRESS;
552 }
553 phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
554
555 kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages);
556
557 pmap_map(vm_addr, phys_addr, phys_addr + round_page(vm_size),
558 (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ | VM_PROT_WRITE,
559 (mptr->Type == EfiMemoryMappedIO) ? VM_WIMG_IO : VM_WIMG_USE_DEFAULT);
560 }
561 }
562
563 if (args->Version != kBootArgsVersion2) {
564 panic("Incompatible boot args version %d revision %d", args->Version, args->Revision);
565 }
566
567 kprintf("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode);
568 if (args->efiMode == kBootArgsEfiMode64) {
569 efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable));
570 } else {
571 panic("Unsupported 32-bit EFI system table!");
572 }
573 } while (FALSE);
574
575 kprintf("Done reinitializing EFI runtime services\n");
576
577 return;
578 }
579
580 /*
581 * Find devices. The system is alive.
582 */
583 void
machine_init(void)584 machine_init(void)
585 {
586 /* Now with VM up, switch to dynamically allocated cpu data */
587 cpu_data_realloc();
588
589 /* Ensure panic buffer is initialized. */
590 debug_log_init();
591
592 /*
593 * Display CPU identification
594 */
595 cpuid_cpu_display("CPU identification");
596 cpuid_feature_display("CPU features");
597 cpuid_extfeature_display("CPU extended features");
598
599 /*
600 * Initialize EFI runtime services.
601 */
602 efi_init();
603
604 smp_init();
605
606 /*
607 * Set up to use floating point.
608 */
609 init_fpu();
610
611 /*
612 * Configure clock devices.
613 */
614 clock_config();
615 is_clock_configured = TRUE;
616
617 #if CONFIG_MTRR
618 /*
619 * Initialize MTRR from boot processor.
620 */
621 mtrr_init();
622
623 /*
624 * Set up PAT for boot processor.
625 */
626 pat_init();
627 #endif
628
629 /*
630 * Free lowmem pages and complete other setup
631 */
632 pmap_lowmem_finalize();
633 }
634
635 /*
636 * Halt a cpu.
637 */
638 void
halt_cpu(void)639 halt_cpu(void)
640 {
641 halt_all_cpus(FALSE);
642 }
643
644 int reset_mem_on_reboot = 1;
645
646 /*
647 * Halt the system or reboot.
648 */
649 __attribute__((noreturn))
650 void
halt_all_cpus(boolean_t reboot)651 halt_all_cpus(boolean_t reboot)
652 {
653 if (reboot) {
654 printf("MACH Reboot\n");
655 PEHaltRestart( kPERestartCPU );
656 } else {
657 printf("CPU halted\n");
658 PEHaltRestart( kPEHaltCPU );
659 }
660 while (1) {
661 ;
662 }
663 }
664
665 /* For use with the MP rendezvous mechanism
666 */
667
668 uint64_t panic_restart_timeout = ~(0ULL);
669
670 #define PANIC_RESTART_TIMEOUT (3ULL * NSEC_PER_SEC)
671
672 /*
673 * We should always return from this function with the other log offset
674 * set in the panic_info structure.
675 */
676 void
RecordPanicStackshot()677 RecordPanicStackshot()
678 {
679 int err = 0;
680 size_t bytes_traced = 0, bytes_uncompressed = 0, bytes_used = 0, bytes_remaining = 0;
681 char *stackshot_begin_loc = NULL;
682
683 /* Don't re-enter this code if we panic here */
684 if (begun_panic_stackshot) {
685 if (panic_info->mph_other_log_offset == 0) {
686 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
687 }
688 return;
689 }
690 begun_panic_stackshot = TRUE;
691
692 /* The panic log length should have been set before we came to capture a stackshot */
693 if (panic_info->mph_panic_log_len == 0) {
694 kdb_printf("Found zero length panic log, skipping capturing panic stackshot\n");
695 if (panic_info->mph_other_log_offset == 0) {
696 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
697 }
698 return;
699 }
700
701 if (stackshot_active()) {
702 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_NESTED;
703 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
704 kdb_printf("Panicked during stackshot, skipping panic stackshot\n");
705 return;
706 }
707
708 /* Try to capture an in memory panic_stackshot */
709 if (extended_debug_log_enabled) {
710 /* On coprocessor systems we write this into the extended debug log */
711 stackshot_begin_loc = debug_buf_ptr;
712 bytes_remaining = debug_buf_size - (unsigned int)((uintptr_t)stackshot_begin_loc - (uintptr_t)debug_buf_base);
713 } else if (panic_stackshot_buf != 0) {
714 /* On other systems we use the panic stackshot_buf */
715 stackshot_begin_loc = (char *) panic_stackshot_buf;
716 bytes_remaining = panic_stackshot_buf_len;
717 } else {
718 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
719 return;
720 }
721
722
723 err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)stackshot_begin_loc,
724 KCDATA_BUFFER_BEGIN_COMPRESSED, (unsigned int) bytes_remaining, KCFLAG_USE_MEMCOPY);
725 if (err != KERN_SUCCESS) {
726 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
727 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
728 kdb_printf("Failed to initialize kcdata buffer for in-memory panic stackshot, skipping ...\n");
729 return;
730 }
731
732 uint64_t stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT |
733 STACKSHOT_ENABLE_BT_FAULTING | STACKSHOT_ENABLE_UUID_FAULTING | STACKSHOT_FROM_PANIC | STACKSHOT_DO_COMPRESS |
734 STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_DISABLE_LATENCY_INFO | STACKSHOT_GET_DQ);
735
736 err = kcdata_init_compress(&kc_panic_data, KCDATA_BUFFER_BEGIN_STACKSHOT, stackshot_memcpy, KCDCT_ZLIB);
737 if (err != KERN_SUCCESS) {
738 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_COMPRESS;
739 stackshot_flags &= ~STACKSHOT_DO_COMPRESS;
740 }
741
742 #if DEVELOPMENT
743 /*
744 * Include the shared cache layout in panic stackshots on DEVELOPMENT kernels so that we can symbolicate
745 * panic stackshots from corefiles.
746 */
747 stackshot_flags |= STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT;
748 #endif
749
750 kdp_snapshot_preflight(-1, (void *) stackshot_begin_loc, (uint32_t) bytes_remaining, stackshot_flags, &kc_panic_data, 0, 0);
751 err = do_stackshot(NULL);
752 bytes_traced = (size_t) kdp_stack_snapshot_bytes_traced();
753 bytes_uncompressed = (size_t) kdp_stack_snapshot_bytes_uncompressed();
754 bytes_used = (size_t) kcdata_memory_get_used_bytes(&kc_panic_data);
755
756 if ((err != KERN_SUCCESS) && (bytes_used > 0)) {
757 /*
758 * We ran out of space while trying to capture a stackshot, try again without user frames.
759 * It's not safe to log from here (in case we're writing in the middle of the debug buffer on coprocessor systems)
760 * but append a flag to the panic flags.
761 */
762 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_KERNEL_ONLY;
763 panic_stackshot_reset_state();
764
765 /* Erase the stackshot data (this region is pre-populated with the NULL character) */
766 memset(stackshot_begin_loc, '\0', bytes_used);
767
768 err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)stackshot_begin_loc,
769 KCDATA_BUFFER_BEGIN_STACKSHOT, (unsigned int) bytes_remaining, KCFLAG_USE_MEMCOPY);
770 if (err != KERN_SUCCESS) {
771 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
772 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
773 kdb_printf("Failed to re-initialize kcdata buffer for kernel only in-memory panic stackshot, skipping ...\n");
774 return;
775 }
776
777 stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_KCDATA_FORMAT | STACKSHOT_FROM_PANIC | STACKSHOT_DISABLE_LATENCY_INFO |
778 STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY | STACKSHOT_GET_DQ);
779 #if DEVELOPMENT
780 /*
781 * Include the shared cache layout in panic stackshots on DEVELOPMENT kernels so that we can symbolicate
782 * panic stackshots from corefiles.
783 */
784 stackshot_flags |= STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT;
785 #endif
786
787 kdp_snapshot_preflight(-1, (void *) stackshot_begin_loc, (uint32_t) bytes_remaining, stackshot_flags, &kc_panic_data, 0, 0);
788 err = do_stackshot(NULL);
789 bytes_traced = (size_t) kdp_stack_snapshot_bytes_traced();
790 bytes_uncompressed = (size_t) kdp_stack_snapshot_bytes_uncompressed();
791 bytes_used = (size_t) kcdata_memory_get_used_bytes(&kc_panic_data);
792 }
793
794 if (err == KERN_SUCCESS) {
795 if (extended_debug_log_enabled) {
796 debug_buf_ptr += bytes_traced;
797 }
798 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_SUCCEEDED;
799
800 /* On other systems this is not in the debug buffer itself, it's in a separate buffer allocated at boot. */
801 if (extended_debug_log_enabled) {
802 panic_info->mph_stackshot_offset = PE_get_offset_into_panic_region(stackshot_begin_loc);
803 panic_info->mph_stackshot_len = (uint32_t) bytes_traced;
804 } else {
805 panic_info->mph_stackshot_offset = panic_info->mph_stackshot_len = 0;
806 }
807
808 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
809 if (stackshot_flags & STACKSHOT_DO_COMPRESS) {
810 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_DATA_COMPRESSED;
811 kdb_printf("\n** In Memory Panic Stackshot Succeeded ** Bytes Traced %zu (Uncompressed %zu) **\n", bytes_traced, bytes_uncompressed);
812 } else {
813 kdb_printf("\n** In Memory Panic Stackshot Succeeded ** Bytes Traced %zu **\n", bytes_traced);
814 }
815
816 /* Used by the code that writes the buffer to disk */
817 panic_stackshot_buf = (vm_offset_t) stackshot_begin_loc;
818 panic_stackshot_len = bytes_traced;
819
820 if (!extended_debug_log_enabled && (gIOPolledCoreFileMode == kIOPolledCoreFileModeStackshot)) {
821 /* System configured to write panic stackshot to disk */
822 kern_dump(KERN_DUMP_STACKSHOT_DISK);
823 }
824 } else {
825 if (bytes_used > 0) {
826 /* Erase the stackshot data (this region is pre-populated with the NULL character) */
827 memset(stackshot_begin_loc, '\0', bytes_used);
828 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_INCOMPLETE;
829
830 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
831 kdb_printf("\n** In Memory Panic Stackshot Incomplete ** Bytes Filled %zu ** Err %d\n", bytes_used, err);
832 } else {
833 bzero(stackshot_begin_loc, bytes_used);
834 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
835
836 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
837 kdb_printf("\n** In Memory Panic Stackshot Failed ** Bytes Traced %zu, err %d\n", bytes_traced, err);
838 }
839 }
840
841 return;
842 }
843
844 void
SavePanicInfo(__unused const char * message,void * panic_data,uint64_t panic_options)845 SavePanicInfo(
846 __unused const char *message, void *panic_data, uint64_t panic_options)
847 {
848 void *stackptr = NULL;
849 thread_t thread_to_trace = (thread_t) panic_data;
850 cframe_t synthetic_stack_frame = { };
851 char *debugger_msg = NULL;
852 int cn = cpu_number();
853
854 /*
855 * Issue an I/O port read if one has been requested - this is an event logic
856 * analyzers can use as a trigger point.
857 */
858 panic_notify();
859
860 /* Obtain frame pointer for stack to trace */
861 if (panic_options & DEBUGGER_INTERNAL_OPTION_THREAD_BACKTRACE) {
862 if (!mp_kdp_all_cpus_halted()) {
863 debugger_msg = "Backtracing panicked thread because failed to halt all CPUs\n";
864 } else if (thread_to_trace == THREAD_NULL) {
865 debugger_msg = "Backtracing panicked thread because no thread pointer provided\n";
866 } else if (kvtophys((vm_offset_t)thread_to_trace) == 0ULL) {
867 debugger_msg = "Backtracing panicked thread because unable to access specified thread\n";
868 } else if (thread_to_trace->kernel_stack == 0) {
869 debugger_msg = "Backtracing panicked thread because kernel_stack is NULL for specified thread\n";
870 } else if (kvtophys(STACK_IKS(thread_to_trace->kernel_stack) == 0ULL)) {
871 debugger_msg = "Backtracing panicked thread because unable to access kernel_stack for specified thread\n";
872 } else {
873 debugger_msg = "Backtracing specified thread\n";
874 /* We construct a synthetic stack frame so we can include the current instruction pointer */
875 synthetic_stack_frame.prev = (cframe_t *)STACK_IKS(thread_to_trace->kernel_stack)->k_rbp;
876 synthetic_stack_frame.caller = (uintptr_t) STACK_IKS(thread_to_trace->kernel_stack)->k_rip;
877 stackptr = (void *) &synthetic_stack_frame;
878 }
879 }
880
881 if (stackptr == NULL) {
882 __asm__ volatile ("movq %%rbp, %0" : "=m" (stackptr));
883 }
884
885 /* Print backtrace - callee is internally synchronized */
886 if (panic_options & DEBUGGER_OPTION_INITPROC_PANIC) {
887 /* Special handling of launchd died panics */
888 print_launchd_info();
889 } else {
890 panic_i386_backtrace(stackptr, ((panic_double_fault_cpu == cn) ? 80 : 48), debugger_msg, FALSE, NULL);
891 }
892
893 if (panic_options & DEBUGGER_OPTION_COPROC_INITIATED_PANIC) {
894 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_COPROC_INITIATED_PANIC;
895 }
896
897 #if MACH_KDP
898 /*
899 * If this panic is due to a PTE corruption event, use the kdp cross-cpu calling machinery to ask
900 * each CPU to dump their backtraces before proceeding. This mechanism was preferred to adding new
901 * synchronization operations in NMIInterruptHandler and the normal panic flow; this mechanism allows
902 * each CPU to add their backtraces after all other primary panic output is complete while not adding
903 * additional complexity to the common panic path.
904 */
905 if (NMI_panic_reason == PTE_CORRUPTION) {
906 for (uint64_t cpu = 0; cpu < real_ncpus; cpu++) {
907 if (cpu == cpu_number() || !cpu_is_running(cpu)) {
908 continue;
909 }
910 (void) kdp_x86_xcpu_invoke(cpu, NMI_pte_corruption_callback, NULL, NULL, NSEC_PER_SEC /* 1 second timeout */);
911 }
912 }
913 #else
914 #error NMI PTE Corruption panic flow requires KDP
915 #endif
916
917 if (PE_get_offset_into_panic_region(debug_buf_ptr) < panic_info->mph_panic_log_offset) {
918 kdb_printf("Invalid panic log offset found (not properly initialized?): debug_buf_ptr : 0x%p, panic_info: 0x%p mph_panic_log_offset: 0x%x\n",
919 debug_buf_ptr, panic_info, panic_info->mph_panic_log_offset);
920 panic_info->mph_panic_log_len = 0;
921 } else {
922 panic_info->mph_panic_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->mph_panic_log_offset;
923 }
924
925 /* Flush the panic log */
926 paniclog_flush_internal(kPaniclogFlushBase);
927
928 /* Try to take a panic stackshot */
929 RecordPanicStackshot();
930
931 /*
932 * Flush the panic log again with the stackshot or any relevant logging
933 * from when we tried to capture it.
934 */
935 paniclog_flush_internal(kPaniclogFlushStackshot);
936 }
937
938 void
paniclog_flush_internal(paniclog_flush_type_t variant)939 paniclog_flush_internal(paniclog_flush_type_t variant)
940 {
941 /* Update the other log offset if we've opened the other log */
942 if (panic_info->mph_other_log_offset != 0) {
943 panic_info->mph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->mph_other_log_offset;
944 }
945
946 /*
947 * If we've detected that we're on a co-processor system, we flush the panic log via the kPEPanicSync
948 * panic callbacks, otherwise we flush via nvram (unless that has been disabled).
949 */
950 if (coprocessor_paniclog_flush) {
951 uint32_t overall_buffer_size = debug_buf_size;
952 uint32_t size_to_flush = 0, offset_to_flush = 0;
953 if (extended_debug_log_enabled) {
954 /*
955 * debug_buf_size for the extended log does not include the length of the header.
956 * There may be some extra data at the end of the 'basic' log that wouldn't get flushed
957 * for the non-extended case (this is a concession we make to not shrink the paniclog data
958 * for non-coprocessor systems that only use the basic log).
959 */
960 overall_buffer_size = debug_buf_size + sizeof(struct macos_panic_header);
961 }
962
963 /* Update the CRC */
964 panic_info->mph_crc = crc32(0L, &panic_info->mph_version, (overall_buffer_size - offsetof(struct macos_panic_header, mph_version)));
965
966 if (variant == kPaniclogFlushBase) {
967 /* Flush the header and base panic log. */
968 kprintf("Flushing base panic log\n");
969 size_to_flush = ROUNDUP((panic_info->mph_panic_log_offset + panic_info->mph_panic_log_len), PANIC_FLUSH_BOUNDARY);
970 offset_to_flush = 0;
971 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
972 } else if ((variant == kPaniclogFlushStackshot) || (variant == kPaniclogFlushOtherLog)) {
973 if (variant == kPaniclogFlushStackshot) {
974 /*
975 * We flush the stackshot before flushing the updated header because the stackshot
976 * can take a while to flush. We want the paniclog header to be as consistent as possible even
977 * if the stackshot isn't flushed completely. Flush starting from the end of the panic log.
978 */
979 kprintf("Flushing panic log stackshot\n");
980 offset_to_flush = ROUNDDOWN((panic_info->mph_panic_log_offset + panic_info->mph_panic_log_len), PANIC_FLUSH_BOUNDARY);
981 size_to_flush = ROUNDUP((panic_info->mph_stackshot_len + (panic_info->mph_stackshot_offset - offset_to_flush)), PANIC_FLUSH_BOUNDARY);
982 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
983 }
984
985 /* Flush the other log -- everything after the stackshot */
986 kprintf("Flushing panic 'other' log\n");
987 offset_to_flush = ROUNDDOWN((panic_info->mph_stackshot_offset + panic_info->mph_stackshot_len), PANIC_FLUSH_BOUNDARY);
988 size_to_flush = ROUNDUP((panic_info->mph_other_log_len + (panic_info->mph_other_log_offset - offset_to_flush)), PANIC_FLUSH_BOUNDARY);
989 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
990
991 /* Flush the header -- everything before the paniclog */
992 kprintf("Flushing panic log header\n");
993 size_to_flush = ROUNDUP(panic_info->mph_panic_log_offset, PANIC_FLUSH_BOUNDARY);
994 offset_to_flush = 0;
995 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
996 }
997 } else if (commit_paniclog_to_nvram) {
998 assert(debug_buf_size != 0);
999 unsigned int bufpos;
1000 unsigned long pi_size = 0;
1001 uintptr_t cr0;
1002
1003 debug_putc(0);
1004
1005 /*
1006 * Now call the compressor
1007 * XXX Consider using the WKdm compressor in the
1008 * future, rather than just packing - would need to
1009 * be co-ordinated with crashreporter, which decodes
1010 * this post-restart. The compressor should be
1011 * capable of in-place compression.
1012 *
1013 * Don't include the macOS panic header (for co-processor systems only)
1014 */
1015 bufpos = packA(debug_buf_base, (unsigned int) (debug_buf_ptr - debug_buf_base),
1016 debug_buf_size);
1017 /*
1018 * If compression was successful, use the compressed length
1019 */
1020 pi_size = bufpos ? bufpos : (unsigned) (debug_buf_ptr - debug_buf_base);
1021
1022 /*
1023 * The following sequence is a workaround for:
1024 * <rdar://problem/5915669> SnowLeopard10A67: AppleEFINVRAM should not invoke
1025 * any routines that use floating point (MMX in this case) when saving panic
1026 * logs to nvram/flash.
1027 */
1028 cr0 = get_cr0();
1029 clear_ts();
1030
1031 /*
1032 * Save panic log to non-volatile store
1033 * Panic info handler must truncate data that is
1034 * too long for this platform.
1035 * This call must save data synchronously,
1036 * since we can subsequently halt the system.
1037 */
1038 kprintf("Attempting to commit panic log to NVRAM\n");
1039 pi_size = PESavePanicInfo((unsigned char *)debug_buf_base,
1040 (uint32_t)pi_size );
1041 set_cr0(cr0);
1042
1043 /*
1044 * Uncompress in-place, to permit examination of
1045 * the panic log by debuggers.
1046 */
1047 if (bufpos) {
1048 unpackA(debug_buf_base, bufpos);
1049 }
1050 }
1051 }
1052
1053 void
paniclog_flush()1054 paniclog_flush()
1055 {
1056 /* Called outside of this file to update logging appended to the "other" log */
1057 paniclog_flush_internal(kPaniclogFlushOtherLog);
1058 return;
1059 }
1060
1061 char *
machine_boot_info(char * buf,__unused vm_size_t size)1062 machine_boot_info(char *buf, __unused vm_size_t size)
1063 {
1064 *buf = '\0';
1065 return buf;
1066 }
1067
1068 /* Routines for address - symbol translation. Not called unless the "keepsyms"
1069 * boot-arg is supplied.
1070 */
1071
1072 static int
panic_print_macho_symbol_name(kernel_mach_header_t * mh,vm_address_t search,const char * module_name)1073 panic_print_macho_symbol_name(kernel_mach_header_t *mh, vm_address_t search, const char *module_name)
1074 {
1075 kernel_nlist_t *sym = NULL;
1076 struct load_command *cmd;
1077 kernel_segment_command_t *orig_ts = NULL, *orig_le = NULL;
1078 struct symtab_command *orig_st = NULL;
1079 unsigned int i;
1080 char *strings, *bestsym = NULL;
1081 vm_address_t bestaddr = 0, diff, curdiff;
1082
1083 /* Assume that if it's loaded and linked into the kernel, it's a valid Mach-O */
1084
1085 cmd = (struct load_command *) &mh[1];
1086 for (i = 0; i < mh->ncmds; i++) {
1087 if (cmd->cmd == LC_SEGMENT_KERNEL) {
1088 kernel_segment_command_t *orig_sg = (kernel_segment_command_t *) cmd;
1089
1090 if (strncmp(SEG_TEXT, orig_sg->segname,
1091 sizeof(orig_sg->segname)) == 0) {
1092 orig_ts = orig_sg;
1093 } else if (strncmp(SEG_LINKEDIT, orig_sg->segname,
1094 sizeof(orig_sg->segname)) == 0) {
1095 orig_le = orig_sg;
1096 } else if (strncmp("", orig_sg->segname,
1097 sizeof(orig_sg->segname)) == 0) {
1098 orig_ts = orig_sg; /* pre-Lion i386 kexts have a single unnamed segment */
1099 }
1100 } else if (cmd->cmd == LC_SYMTAB) {
1101 orig_st = (struct symtab_command *) cmd;
1102 }
1103
1104 cmd = (struct load_command *) ((uintptr_t) cmd + cmd->cmdsize);
1105 }
1106
1107 if ((orig_ts == NULL) || (orig_st == NULL) || (orig_le == NULL)) {
1108 return 0;
1109 }
1110
1111 if ((search < orig_ts->vmaddr) ||
1112 (search >= orig_ts->vmaddr + orig_ts->vmsize)) {
1113 /* search out of range for this mach header */
1114 return 0;
1115 }
1116
1117 sym = (kernel_nlist_t *)(uintptr_t)(orig_le->vmaddr + orig_st->symoff - orig_le->fileoff);
1118 strings = (char *)(uintptr_t)(orig_le->vmaddr + orig_st->stroff - orig_le->fileoff);
1119 diff = search;
1120
1121 for (i = 0; i < orig_st->nsyms; i++) {
1122 if (sym[i].n_type & N_STAB) {
1123 continue;
1124 }
1125
1126 if (sym[i].n_value <= search) {
1127 curdiff = search - (vm_address_t)sym[i].n_value;
1128 if (curdiff < diff) {
1129 diff = curdiff;
1130 bestaddr = sym[i].n_value;
1131 bestsym = strings + sym[i].n_un.n_strx;
1132 }
1133 }
1134 }
1135
1136 if (bestsym != NULL) {
1137 if (diff != 0) {
1138 paniclog_append_noflush("%s : %s + 0x%lx", module_name, bestsym, (unsigned long)diff);
1139 } else {
1140 paniclog_append_noflush("%s : %s", module_name, bestsym);
1141 }
1142 return 1;
1143 }
1144 return 0;
1145 }
1146
1147 static void
panic_display_uptime(void)1148 panic_display_uptime(void)
1149 {
1150 uint64_t uptime;
1151 absolutetime_to_nanoseconds(mach_absolute_time(), &uptime);
1152
1153 paniclog_append_noflush("\nSystem uptime in nanoseconds: %llu\n", uptime);
1154 }
1155
1156 extern uint32_t gIOHibernateCount;
1157
1158 static void
panic_display_hib_count(void)1159 panic_display_hib_count(void)
1160 {
1161 paniclog_append_noflush("Hibernation exit count: %u\n", gIOHibernateCount);
1162 }
1163
1164 extern AbsoluteTime gIOLastSleepAbsTime;
1165 extern AbsoluteTime gIOLastWakeAbsTime;
1166 extern uint64_t gAcpiLastSleepTscBase;
1167 extern uint64_t gAcpiLastSleepNanoBase;
1168 extern uint64_t gAcpiLastWakeTscBase;
1169 extern uint64_t gAcpiLastWakeNanoBase;
1170 extern boolean_t is_clock_configured;
1171
1172 static void
panic_display_times(void)1173 panic_display_times(void)
1174 {
1175 if (!is_clock_configured) {
1176 paniclog_append_noflush("Warning: clock is not configured. Can't get time\n");
1177 return;
1178 }
1179
1180 paniclog_append_noflush("Last Sleep: absolute base_tsc base_nano\n");
1181 paniclog_append_noflush(" Uptime : 0x%016llx\n", mach_absolute_time());
1182 paniclog_append_noflush(" Sleep : 0x%016llx 0x%016llx 0x%016llx\n", gIOLastSleepAbsTime, gAcpiLastSleepTscBase, gAcpiLastSleepNanoBase);
1183 paniclog_append_noflush(" Wake : 0x%016llx 0x%016llx 0x%016llx\n", gIOLastWakeAbsTime, gAcpiLastWakeTscBase, gAcpiLastWakeNanoBase);
1184 }
1185
1186 static void
panic_display_disk_errors(void)1187 panic_display_disk_errors(void)
1188 {
1189 if (panic_disk_error_description[0]) {
1190 panic_disk_error_description[panic_disk_error_description_size - 1] = '\0';
1191 paniclog_append_noflush("Root disk errors: \"%s\"\n", panic_disk_error_description);
1192 }
1193 }
1194
1195 static void
panic_display_shutdown_status(void)1196 panic_display_shutdown_status(void)
1197 {
1198 #if defined(__i386__) || defined(__x86_64__)
1199 paniclog_append_noflush("System shutdown begun: %s\n", IOPMRootDomainGetWillShutdown() ? "YES" : "NO");
1200 if (gIOPolledCoreFileMode == kIOPolledCoreFileModeNotInitialized) {
1201 paniclog_append_noflush("Panic diags file unavailable, panic occurred prior to initialization\n");
1202 } else if (gIOPolledCoreFileMode != kIOPolledCoreFileModeDisabled) {
1203 /*
1204 * If we haven't marked the corefile as explicitly disabled, and we've made it past initialization, then we know the current
1205 * system was configured to use disk based diagnostics at some point.
1206 */
1207 paniclog_append_noflush("Panic diags file available: %s (0x%x)\n", (gIOPolledCoreFileMode != kIOPolledCoreFileModeClosed) ? "YES" : "NO", kdp_polled_corefile_error());
1208 }
1209 #endif
1210 }
1211
1212 extern const char version[];
1213 extern char osversion[];
1214
1215 static volatile uint32_t config_displayed = 0;
1216
1217 static void
panic_display_system_configuration(boolean_t launchd_exit)1218 panic_display_system_configuration(boolean_t launchd_exit)
1219 {
1220 if (!launchd_exit) {
1221 panic_display_process_name();
1222 }
1223 if (OSCompareAndSwap(0, 1, &config_displayed)) {
1224 char buf[256];
1225 if (!launchd_exit && strlcpy(buf, PE_boot_args(), sizeof(buf))) {
1226 paniclog_append_noflush("Boot args: %s\n", buf);
1227 }
1228 paniclog_append_noflush("\nMac OS version:\n%s\n",
1229 (osversion[0] != 0) ? osversion : "Not yet set");
1230 paniclog_append_noflush("\nKernel version:\n%s\n", version);
1231 panic_display_kernel_uuid();
1232 if (!launchd_exit) {
1233 panic_display_kernel_aslr();
1234 panic_display_hibb();
1235 panic_display_pal_info();
1236 }
1237 panic_display_model_name();
1238 panic_display_disk_errors();
1239 panic_display_shutdown_status();
1240 if (!launchd_exit) {
1241 panic_display_hib_count();
1242 panic_display_uptime();
1243 panic_display_times();
1244 panic_display_compressor_stats();
1245 panic_display_zalloc();
1246 kext_dump_panic_lists(&paniclog_append_noflush);
1247 }
1248 }
1249 }
1250
1251 extern kmod_info_t * kmod; /* the list of modules */
1252
1253 static void
panic_print_kmod_symbol_name(vm_address_t search)1254 panic_print_kmod_symbol_name(vm_address_t search)
1255 {
1256 u_int i;
1257
1258 if (gLoadedKextSummaries == NULL) {
1259 return;
1260 }
1261 for (i = 0; i < gLoadedKextSummaries->numSummaries; ++i) {
1262 OSKextLoadedKextSummary *summary = gLoadedKextSummaries->summaries + i;
1263
1264 if ((search >= summary->address) &&
1265 (search < (summary->address + summary->size))) {
1266 kernel_mach_header_t *header = (kernel_mach_header_t *)(uintptr_t) summary->address;
1267 if (panic_print_macho_symbol_name(header, search, summary->name) == 0) {
1268 paniclog_append_noflush("%s + %llu", summary->name, (unsigned long)search - summary->address);
1269 }
1270 break;
1271 }
1272 }
1273 }
1274
1275 static void
read_lbr_empty(void)1276 read_lbr_empty(void)
1277 {
1278 }
1279
1280 void (*read_lbr)(void) = read_lbr_empty;
1281
1282 static void
capture_lbr_state(void)1283 capture_lbr_state(void)
1284 {
1285 thread_t thr_act = current_thread();
1286 int i;
1287 last_branch_state_t thread_lbr_data;
1288 struct lbr_data *lbr = &lbrs[cpu_number()];
1289
1290 if (lbr_stack_size > 0) {
1291 i386_lbr_disable();
1292
1293 if (i386_filtered_lbr_state_to_mach_thread_state(thr_act, &thread_lbr_data, false) == 0) {
1294 for (i = 0; i < thread_lbr_data.lbr_count; i++) {
1295 lbr->from[i] = thread_lbr_data.lbrs[i].from_ip;
1296 lbr->to[i] = thread_lbr_data.lbrs[i].to_ip;
1297 }
1298 }
1299 }
1300
1301 i386_lbr_enable();
1302 }
1303
1304 static void
copy_lbr_data_for_core(void)1305 copy_lbr_data_for_core(void)
1306 {
1307 unsigned int cpu;
1308 struct {
1309 uint32_t id;
1310 uint8_t ncpus;
1311 uint8_t lbr_count;
1312 } metadata;
1313
1314 /* These two buffers are captured in the core file and placed in named segments */
1315 if (phys_carveout && phys_carveout_metadata) {
1316 // The minimum size of phys_carveout is 1MiB but just in case
1317 if (phys_carveout_size >= sizeof(last_branch_state_t) * max_ncpus) {
1318 for (cpu = 0; cpu < real_ncpus; cpu++) {
1319 void *buf = (void *)(phys_carveout + lbr_stack_size * sizeof(uint64_t) * cpu);
1320 memcpy(buf, lbrs[cpu].from, sizeof(uint64_t) * lbr_stack_size);
1321 memcpy((uint64_t *)buf + lbr_stack_size * sizeof(uint64_t), lbrs[cpu].to,
1322 sizeof(uint64_t) * lbr_stack_size);
1323 }
1324 /* Write 'LBRS' identifier, the number of CPUs and the LBR stack size */
1325 metadata.id = LBR_MAGIC; /* 'LBRS' */
1326 metadata.ncpus = real_ncpus;
1327 metadata.lbr_count = lbr_stack_size;
1328 memcpy((void*)phys_carveout_metadata, (void*)&metadata, sizeof(metadata));
1329 }
1330 }
1331 }
1332
1333 void
lbr_for_kmode_init(uint32_t lbr_count)1334 lbr_for_kmode_init(uint32_t lbr_count)
1335 {
1336 uint32_t size;
1337 int i;
1338
1339 lbr_stack_size = lbr_count;
1340
1341 /* Cannot use real_ncpus here as only one CPU is registered yet*/
1342
1343 size = sizeof(uint64_t) * lbr_stack_size;
1344 for (i = 0; i < max_ncpus; i++) {
1345 lbrs[i].from = kalloc_data(size, Z_WAITOK | Z_ZERO);
1346 lbrs[i].to = kalloc_data(size, Z_WAITOK | Z_ZERO);
1347 if (!lbrs[i].from || !lbrs[i].to) {
1348 kprintf("LBR: Kalloc failed for lbrs.from/to\n");
1349 if (lbrs[i].from) {
1350 kfree_data(lbrs[i].from, size);
1351 }
1352 if (lbrs[i].to) {
1353 kfree_data(lbrs[i].to, size);
1354 }
1355 while (--i >= 0) {
1356 kfree_data(lbrs[i].from, size);
1357 kfree_data(lbrs[i].to, size);
1358 }
1359 goto err;
1360 }
1361 }
1362
1363 read_lbr = capture_lbr_state;
1364
1365 return;
1366
1367 err:
1368 last_branch_enabled_modes = LBR_ENABLED_NONE;
1369 return;
1370 }
1371
1372 static void
write_lbr_to_panic_log(void)1373 write_lbr_to_panic_log(void)
1374 {
1375 unsigned int cpu;
1376 int i;
1377
1378 for (cpu = 0; cpu < real_ncpus; cpu++) {
1379 paniclog_append_noflush("LBR Stack (CPU %d):\n", cpu);
1380 for (i = 0; i < lbr_stack_size; i++) {
1381 if (lbrs[cpu].from[i] == 0x0 && lbrs[cpu].to[i] == 0x0) {
1382 continue;
1383 }
1384 paniclog_append_noflush("0x%llx : 0x%llx\n", lbrs[cpu].from[i], lbrs[cpu].to[i]);
1385 }
1386 }
1387 if (debug_can_coredump_phys_carveout()) {
1388 copy_lbr_data_for_core();
1389 }
1390 }
1391
1392 void
panic_print_symbol_name(vm_address_t search)1393 panic_print_symbol_name(vm_address_t search)
1394 {
1395 /* try searching in the kernel */
1396 if (panic_print_macho_symbol_name(&_mh_execute_header, search, "mach_kernel") == 0) {
1397 /* that failed, now try to search for the right kext */
1398 panic_print_kmod_symbol_name(search);
1399 }
1400 }
1401
1402 /* Generate a backtrace, given a frame pointer - this routine
1403 * should walk the stack safely. The trace is appended to the panic log
1404 * and conditionally, to the console. If the trace contains kernel module
1405 * addresses, display the module name, load address and dependencies.
1406 */
1407
1408 static hw_lock_timeout_status_t
panic_btlock_handler_spin(void * _lock,uint64_t timeout,uint64_t start,uint64_t now,uint64_t interrupt_time)1409 panic_btlock_handler_spin(void *_lock, uint64_t timeout, uint64_t start, uint64_t now, uint64_t interrupt_time)
1410 {
1411 #pragma unused(_lock, timeout, start, now, interrupt_time)
1412 return HW_LOCK_TIMEOUT_RETURN;
1413 }
1414
1415
1416 #define DUMPFRAMES 32
1417 #define PBT_TIMEOUT_CYCLES (5 * 1000 * 1000 * 1000ULL)
1418 void
panic_i386_backtrace(void * _frame,int nframes,const char * msg,boolean_t regdump,x86_saved_state_t * regs)1419 panic_i386_backtrace(void *_frame, int nframes, const char *msg, boolean_t regdump, x86_saved_state_t *regs)
1420 {
1421 cframe_t *frame = (cframe_t *)_frame;
1422 vm_offset_t raddrs[DUMPFRAMES];
1423 vm_offset_t PC = 0;
1424 int frame_index;
1425 volatile uint32_t *ppbtcnt = &pbtcnt;
1426 uint64_t bt_tsc_timeout;
1427 boolean_t keepsyms = FALSE;
1428 int cn = cpu_number();
1429 boolean_t old_doprnt_hide_pointers = doprnt_hide_pointers;
1430 thread_t cur_thread = current_thread();
1431 task_t task;
1432 struct proc *proc;
1433
1434 #if DEVELOPMENT || DEBUG
1435 /* Turn off I/O tracing now that we're panicking */
1436 mmiotrace_enabled = 0;
1437 #endif
1438
1439 if (pbtcpu != cn) {
1440 os_atomic_inc(&pbtcnt, relaxed);
1441 /* Spin on print backtrace lock, which serializes output
1442 * Continue anyway if a timeout occurs.
1443 */
1444 (void)hw_lock_to(&pbtlock, LockTimeOutTSC * 4, panic_btlock_handler_spin, LCK_GRP_NULL);
1445 pbtcpu = cn;
1446 }
1447
1448 if (__improbable(doprnt_hide_pointers == TRUE)) {
1449 /* If we're called directly, the Debugger() function will not be called,
1450 * so we need to reset the value in here. */
1451 doprnt_hide_pointers = FALSE;
1452 }
1453
1454 panic_check_hook();
1455
1456 PE_parse_boot_argn("keepsyms", &keepsyms, sizeof(keepsyms));
1457
1458 if (msg != NULL) {
1459 paniclog_append_noflush("%s", msg);
1460 }
1461
1462 if ((regdump == TRUE) && (regs != NULL)) {
1463 x86_saved_state64_t *ss64p = saved_state64(regs);
1464 paniclog_append_noflush(
1465 "RAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
1466 "RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
1467 "R8: 0x%016llx, R9: 0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
1468 "R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
1469 "RFL: 0x%016llx, RIP: 0x%016llx, CS: 0x%016llx, SS: 0x%016llx\n",
1470 ss64p->rax, ss64p->rbx, ss64p->rcx, ss64p->rdx,
1471 ss64p->isf.rsp, ss64p->rbp, ss64p->rsi, ss64p->rdi,
1472 ss64p->r8, ss64p->r9, ss64p->r10, ss64p->r11,
1473 ss64p->r12, ss64p->r13, ss64p->r14, ss64p->r15,
1474 ss64p->isf.rflags, ss64p->isf.rip, ss64p->isf.cs,
1475 ss64p->isf.ss);
1476 PC = ss64p->isf.rip;
1477 }
1478
1479 // print current task info
1480 if (panic_get_thread_proc_task(cur_thread, &task, &proc)) {
1481 paniclog_append_noflush("Panicked task %p: %d threads: ",
1482 task, task->thread_count);
1483 if (proc) {
1484 char name[MAXCOMLEN + 1];
1485 proc_name_kdp(proc, name, sizeof(name));
1486 paniclog_append_noflush("pid %d: %s", proc_pid(proc), name);
1487 } else {
1488 paniclog_append_noflush("unknown task");
1489 }
1490
1491 paniclog_append_noflush("\n");
1492 }
1493
1494 paniclog_append_noflush("Backtrace (CPU %d), panicked thread: %p, "
1495 #if PRINT_ARGS_FROM_STACK_FRAME
1496 "Frame : Return Address (4 potential args on stack)\n",
1497 #else
1498 "Frame : Return Address\n",
1499 #endif
1500 cn, cur_thread);
1501
1502 for (frame_index = 0; frame_index < nframes; frame_index++) {
1503 vm_offset_t curframep = (vm_offset_t) frame;
1504
1505 if (!curframep) {
1506 break;
1507 }
1508
1509 if (curframep & 0x3) {
1510 paniclog_append_noflush("Unaligned frame\n");
1511 goto invalid;
1512 }
1513
1514 if (!kvtophys(curframep) ||
1515 !kvtophys(curframep + sizeof(cframe_t) - 1)) {
1516 paniclog_append_noflush("No mapping exists for frame pointer\n");
1517 goto invalid;
1518 }
1519
1520 paniclog_append_noflush("%p : 0x%lx ", frame, frame->caller);
1521 if (frame_index < DUMPFRAMES) {
1522 raddrs[frame_index] = frame->caller;
1523 }
1524
1525 #if PRINT_ARGS_FROM_STACK_FRAME
1526 if (kvtophys((vm_offset_t)&(frame->args[3]))) {
1527 paniclog_append_noflush("(0x%x 0x%x 0x%x 0x%x) ",
1528 frame->args[0], frame->args[1],
1529 frame->args[2], frame->args[3]);
1530 }
1531 #endif
1532
1533 /* Display address-symbol translation only if the "keepsyms"
1534 * boot-arg is suppplied, since we unload LINKEDIT otherwise.
1535 * This routine is potentially unsafe; also, function
1536 * boundary identification is unreliable after a strip -x.
1537 */
1538 if (keepsyms) {
1539 panic_print_symbol_name((vm_address_t)frame->caller);
1540 }
1541
1542 paniclog_append_noflush("\n");
1543
1544 frame = frame->prev;
1545 }
1546
1547 if (frame_index >= nframes && (vm_offset_t)frame != 0) {
1548 paniclog_append_noflush("\tBacktrace continues...\n");
1549 }
1550
1551 goto out;
1552
1553 invalid:
1554 paniclog_append_noflush("Backtrace terminated-invalid frame pointer %p\n", frame);
1555 out:
1556
1557 /* Identify kernel modules in the backtrace and display their
1558 * load addresses and dependencies. This routine should walk
1559 * the kmod list safely.
1560 */
1561 if (frame_index) {
1562 kmod_panic_dump((vm_offset_t *)&raddrs[0], frame_index);
1563 }
1564
1565 if (PC != 0) {
1566 kmod_panic_dump(&PC, 1);
1567 }
1568
1569 if (last_branch_enabled_modes == LBR_ENABLED_KERNELMODE) {
1570 write_lbr_to_panic_log();
1571 }
1572
1573 panic_display_system_configuration(FALSE);
1574
1575 doprnt_hide_pointers = old_doprnt_hide_pointers;
1576
1577 /* Release print backtrace lock, to permit other callers in the
1578 * event of panics on multiple processors.
1579 */
1580 hw_lock_unlock(&pbtlock);
1581 os_atomic_dec(&pbtcnt, relaxed);
1582 /* Wait for other processors to complete output
1583 * Timeout and continue after PBT_TIMEOUT_CYCLES.
1584 */
1585 bt_tsc_timeout = rdtsc64() + PBT_TIMEOUT_CYCLES;
1586 while (*ppbtcnt && (rdtsc64() < bt_tsc_timeout)) {
1587 ;
1588 }
1589 }
1590
1591 static boolean_t
debug_copyin(pmap_t p,uint64_t uaddr,void * dest,size_t size)1592 debug_copyin(pmap_t p, uint64_t uaddr, void *dest, size_t size)
1593 {
1594 size_t rem = size;
1595 char *kvaddr = dest;
1596
1597 while (rem) {
1598 ppnum_t upn = pmap_find_phys(p, uaddr);
1599 uint64_t phys_src = ptoa_64(upn) | (uaddr & PAGE_MASK);
1600 uint64_t phys_dest = kvtophys((vm_offset_t)kvaddr);
1601 uint64_t src_rem = PAGE_SIZE - (phys_src & PAGE_MASK);
1602 uint64_t dst_rem = PAGE_SIZE - (phys_dest & PAGE_MASK);
1603 size_t cur_size = (uint32_t) MIN(src_rem, dst_rem);
1604 cur_size = MIN(cur_size, rem);
1605
1606 if (upn && pmap_valid_page(upn) && phys_dest) {
1607 bcopy_phys(phys_src, phys_dest, cur_size);
1608 } else {
1609 break;
1610 }
1611 uaddr += cur_size;
1612 kvaddr += cur_size;
1613 rem -= cur_size;
1614 }
1615 return rem == 0;
1616 }
1617
1618 void
print_threads_registers(thread_t thread)1619 print_threads_registers(thread_t thread)
1620 {
1621 x86_saved_state_t *savestate;
1622
1623 savestate = get_user_regs(thread);
1624 paniclog_append_noflush(
1625 "\nRAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
1626 "RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
1627 "R8: 0x%016llx, R9: 0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
1628 "R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
1629 "RFL: 0x%016llx, RIP: 0x%016llx, CS: 0x%016llx, SS: 0x%016llx\n\n",
1630 savestate->ss_64.rax, savestate->ss_64.rbx, savestate->ss_64.rcx, savestate->ss_64.rdx,
1631 savestate->ss_64.isf.rsp, savestate->ss_64.rbp, savestate->ss_64.rsi, savestate->ss_64.rdi,
1632 savestate->ss_64.r8, savestate->ss_64.r9, savestate->ss_64.r10, savestate->ss_64.r11,
1633 savestate->ss_64.r12, savestate->ss_64.r13, savestate->ss_64.r14, savestate->ss_64.r15,
1634 savestate->ss_64.isf.rflags, savestate->ss_64.isf.rip, savestate->ss_64.isf.cs,
1635 savestate->ss_64.isf.ss);
1636 }
1637
1638 void
print_tasks_user_threads(task_t task)1639 print_tasks_user_threads(task_t task)
1640 {
1641 thread_t thread = current_thread();
1642 x86_saved_state_t *savestate;
1643 pmap_t pmap = 0;
1644 uint64_t rbp;
1645 const char *cur_marker = 0;
1646 int j;
1647
1648 for (j = 0, thread = (thread_t) queue_first(&task->threads); j < task->thread_count;
1649 ++j, thread = (thread_t) queue_next(&thread->task_threads)) {
1650 paniclog_append_noflush("Thread %d: %p\n", j, thread);
1651 pmap = get_task_pmap(task);
1652 savestate = get_user_regs(thread);
1653 rbp = savestate->ss_64.rbp;
1654 paniclog_append_noflush("\t0x%016llx\n", savestate->ss_64.isf.rip);
1655 print_one_backtrace(pmap, (vm_offset_t)rbp, cur_marker, TRUE);
1656 paniclog_append_noflush("\n");
1657 }
1658 }
1659
1660 void
print_thread_num_that_crashed(task_t task)1661 print_thread_num_that_crashed(task_t task)
1662 {
1663 thread_t c_thread = current_thread();
1664 thread_t thread;
1665 int j;
1666
1667 for (j = 0, thread = (thread_t) queue_first(&task->threads); j < task->thread_count;
1668 ++j, thread = (thread_t) queue_next(&thread->task_threads)) {
1669 if (c_thread == thread) {
1670 paniclog_append_noflush("\nThread %d crashed\n", j);
1671 break;
1672 }
1673 }
1674 }
1675
1676 #define PANICLOG_UUID_BUF_SIZE 256
1677
1678 void
print_uuid_info(task_t task)1679 print_uuid_info(task_t task)
1680 {
1681 uint32_t uuid_info_count = 0;
1682 mach_vm_address_t uuid_info_addr = 0;
1683 boolean_t have_map = (task->map != NULL) && (ml_validate_nofault((vm_offset_t)(task->map), sizeof(struct _vm_map)));
1684 boolean_t have_pmap = have_map && (task->map->pmap != NULL) && (ml_validate_nofault((vm_offset_t)(task->map->pmap), sizeof(struct pmap)));
1685 int task_pid = pid_from_task(task);
1686 char uuidbuf[PANICLOG_UUID_BUF_SIZE] = {0};
1687 char *uuidbufptr = uuidbuf;
1688 uint32_t k;
1689
1690 if (have_pmap && task->active && task_pid > 0) {
1691 /* Read dyld_all_image_infos struct from task memory to get UUID array count & location */
1692 struct user64_dyld_all_image_infos task_image_infos;
1693 if (debug_copyin(task->map->pmap, task->all_image_info_addr,
1694 &task_image_infos, sizeof(struct user64_dyld_all_image_infos))) {
1695 uuid_info_count = (uint32_t)task_image_infos.uuidArrayCount;
1696 uuid_info_addr = task_image_infos.uuidArray;
1697 }
1698
1699 /* If we get a NULL uuid_info_addr (which can happen when we catch dyld
1700 * in the middle of updating this data structure), we zero the
1701 * uuid_info_count so that we won't even try to save load info for this task
1702 */
1703 if (!uuid_info_addr) {
1704 uuid_info_count = 0;
1705 }
1706 }
1707
1708 if (task_pid > 0 && uuid_info_count > 0) {
1709 uint32_t uuid_info_size = sizeof(struct user64_dyld_uuid_info);
1710 uint32_t uuid_array_size = uuid_info_count * uuid_info_size;
1711 uint32_t uuid_copy_size = 0;
1712 uint32_t uuid_image_count = 0;
1713 char *current_uuid_buffer = NULL;
1714 /* Copy in the UUID info array. It may be nonresident, in which case just fix up nloadinfos to 0 */
1715
1716 paniclog_append_noflush("\nuuid info:\n");
1717 while (uuid_array_size) {
1718 if (uuid_array_size <= PANICLOG_UUID_BUF_SIZE) {
1719 uuid_copy_size = uuid_array_size;
1720 uuid_image_count = uuid_array_size / uuid_info_size;
1721 } else {
1722 uuid_image_count = PANICLOG_UUID_BUF_SIZE / uuid_info_size;
1723 uuid_copy_size = uuid_image_count * uuid_info_size;
1724 }
1725 if (have_pmap && !debug_copyin(task->map->pmap, uuid_info_addr, uuidbufptr,
1726 uuid_copy_size)) {
1727 paniclog_append_noflush("Error!! Failed to copy UUID info for task %p pid %d\n", task, task_pid);
1728 uuid_image_count = 0;
1729 break;
1730 }
1731
1732 if (uuid_image_count > 0) {
1733 current_uuid_buffer = uuidbufptr;
1734 for (k = 0; k < uuid_image_count; k++) {
1735 paniclog_append_noflush(" %#llx", *(uint64_t *)current_uuid_buffer);
1736 current_uuid_buffer += sizeof(uint64_t);
1737 uint8_t *uuid = (uint8_t *)current_uuid_buffer;
1738 paniclog_append_noflush("\tuuid = <%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x>\n",
1739 uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7], uuid[8],
1740 uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
1741 current_uuid_buffer += 16;
1742 }
1743 bzero(&uuidbuf, sizeof(uuidbuf));
1744 }
1745 uuid_info_addr += uuid_copy_size;
1746 uuid_array_size -= uuid_copy_size;
1747 }
1748 }
1749 }
1750
1751 void
print_launchd_info(void)1752 print_launchd_info(void)
1753 {
1754 task_t task = current_task();
1755 thread_t thread = current_thread();
1756 volatile uint32_t *ppbtcnt = &pbtcnt;
1757 uint64_t bt_tsc_timeout;
1758 int cn = cpu_number();
1759
1760 if (pbtcpu != cn) {
1761 os_atomic_inc(&pbtcnt, relaxed);
1762 /* Spin on print backtrace lock, which serializes output
1763 * Continue anyway if a timeout occurs.
1764 */
1765 (void)hw_lock_to(&pbtlock, LockTimeOutTSC * 4, panic_btlock_handler_spin, LCK_GRP_NULL);
1766 pbtcpu = cn;
1767 }
1768
1769 print_uuid_info(task);
1770 print_thread_num_that_crashed(task);
1771 print_threads_registers(thread);
1772 print_tasks_user_threads(task);
1773
1774 panic_display_system_configuration(TRUE);
1775
1776 /* Release print backtrace lock, to permit other callers in the
1777 * event of panics on multiple processors.
1778 */
1779 hw_lock_unlock(&pbtlock);
1780 os_atomic_dec(&pbtcnt, relaxed);
1781 /* Wait for other processors to complete output
1782 * Timeout and continue after PBT_TIMEOUT_CYCLES.
1783 */
1784 bt_tsc_timeout = rdtsc64() + PBT_TIMEOUT_CYCLES;
1785 while (*ppbtcnt && (rdtsc64() < bt_tsc_timeout)) {
1786 ;
1787 }
1788 }
1789
1790 /*
1791 * Compares 2 EFI GUIDs. Returns true if they match.
1792 */
1793 static bool
efi_compare_guids(EFI_GUID * guid1,EFI_GUID * guid2)1794 efi_compare_guids(EFI_GUID *guid1, EFI_GUID *guid2)
1795 {
1796 return (bcmp(guid1, guid2, sizeof(EFI_GUID)) == 0) ? true : false;
1797 }
1798
1799 /*
1800 * Converts from an efiboot-originated virtual address to a physical
1801 * address.
1802 */
1803 static inline uint64_t
efi_efiboot_virtual_to_physical(uint64_t addr)1804 efi_efiboot_virtual_to_physical(uint64_t addr)
1805 {
1806 if (addr >= VM_MIN_KERNEL_ADDRESS) {
1807 return addr & (0x40000000ULL - 1);
1808 } else {
1809 return addr;
1810 }
1811 }
1812
1813 /*
1814 * Convers from a efiboot-originated virtual address to an accessible
1815 * pointer to that physical address by translating it to a physmap-relative
1816 * address.
1817 */
1818 static void *
efi_efiboot_virtual_to_physmap_virtual(uint64_t addr)1819 efi_efiboot_virtual_to_physmap_virtual(uint64_t addr)
1820 {
1821 return PHYSMAP_PTOV(efi_efiboot_virtual_to_physical(addr));
1822 }
1823
1824 /*
1825 * Returns the physical address of the firmware table identified
1826 * by the passed-in GUID, or 0 if the table could not be located.
1827 */
1828 static uint64_t
efi_get_cfgtbl_by_guid(EFI_GUID * guidp)1829 efi_get_cfgtbl_by_guid(EFI_GUID *guidp)
1830 {
1831 EFI_CONFIGURATION_TABLE_64 *cfg_table_entp, *cfgTable;
1832 boot_args *args = (boot_args *)PE_state.bootArgs;
1833 EFI_SYSTEM_TABLE_64 *estp;
1834 uint32_t i, hdr_cksum, cksum;
1835
1836 estp = (EFI_SYSTEM_TABLE_64 *)efi_efiboot_virtual_to_physmap_virtual(args->efiSystemTable);
1837
1838 assert(estp != 0);
1839
1840 // Verify signature of the system table
1841 hdr_cksum = estp->Hdr.CRC32;
1842 estp->Hdr.CRC32 = 0;
1843 cksum = crc32(0L, estp, estp->Hdr.HeaderSize);
1844 estp->Hdr.CRC32 = hdr_cksum;
1845
1846 if (cksum != hdr_cksum) {
1847 DPRINTF("efi_get_cfgtbl_by_guid: EST CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
1848 DPRINTF("Bad EFI system table checksum\n");
1849 return 0;
1850 }
1851
1852 /*
1853 * efiboot can (and will) change the address of ConfigurationTable (and each table's VendorTable address)
1854 * to a kernel-virtual address. Reverse that to get the physical address, which we then use to get a
1855 * physmap-based virtual address.
1856 */
1857 cfgTable = (EFI_CONFIGURATION_TABLE_64 *)efi_efiboot_virtual_to_physmap_virtual(estp->ConfigurationTable);
1858
1859 for (i = 0; i < estp->NumberOfTableEntries; i++) {
1860 cfg_table_entp = (EFI_CONFIGURATION_TABLE_64 *)&cfgTable[i];
1861
1862 DPRINTF("EST: Comparing GUIDs for entry %d\n", i);
1863 if (cfg_table_entp == 0) {
1864 continue;
1865 }
1866
1867 if (efi_compare_guids(&cfg_table_entp->VendorGuid, guidp) == true) {
1868 DPRINTF("GUID match: returning %p\n", (void *)(uintptr_t)cfg_table_entp->VendorTable);
1869 return efi_efiboot_virtual_to_physical(cfg_table_entp->VendorTable);
1870 }
1871 }
1872
1873 /* Not found */
1874 return 0;
1875 }
1876
1877 /*
1878 * Returns the physical address of the RSDP (either v1 or >=v2) or 0
1879 * if the RSDP could not be located.
1880 */
1881 uint64_t
efi_get_rsdp_physaddr(void)1882 efi_get_rsdp_physaddr(void)
1883 {
1884 uint64_t rsdp_addr;
1885 #define ACPI_RSDP_GUID \
1886 { 0xeb9d2d30, 0x2d88, 0x11d3, {0x9a, 0x16, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d} }
1887 #define ACPI_20_RSDP_GUID \
1888 { 0x8868e871, 0xe4f1, 0x11d3, {0xbc, 0x22, 0x0, 0x80, 0xc7, 0x3c, 0x88, 0x81} }
1889
1890 static EFI_GUID EFI_RSDP_GUID_ACPI20 = ACPI_20_RSDP_GUID;
1891 static EFI_GUID EFI_RSDP_GUID_ACPI10 = ACPI_RSDP_GUID;
1892
1893 if ((rsdp_addr = efi_get_cfgtbl_by_guid(&EFI_RSDP_GUID_ACPI20)) == 0) {
1894 DPRINTF("RSDP ACPI 2.0 lookup failed. Trying RSDP ACPI 1.0...\n");
1895 rsdp_addr = efi_get_cfgtbl_by_guid(&EFI_RSDP_GUID_ACPI10);
1896 if (rsdp_addr == 0) {
1897 DPRINTF("RSDP ACPI 1.0 lookup failed also.\n");
1898 }
1899 }
1900
1901 return rsdp_addr;
1902 }
1903