VirtualBox

source: vbox/trunk/src/VBox/Runtime/r0drv/darwin/dbgkrnlinfo-r0drv-darwin.cpp@ 83087

Last change on this file since 83087 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.2 KB
Line 
1/* $Id: dbgkrnlinfo-r0drv-darwin.cpp 82968 2020-02-04 10:35:17Z vboxsync $ */
2/** @file
3 * IPRT - Kernel Debug Information, R0 Driver, Darwin.
4 */
5
6/*
7 * Copyright (C) 2011-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#ifdef IN_RING0
32# include "the-darwin-kernel.h"
33# include <sys/kauth.h>
34RT_C_DECLS_BEGIN /* Buggy 10.4 headers, fixed in 10.5. */
35# include <sys/kpi_mbuf.h>
36# include <net/kpi_interfacefilter.h>
37# include <sys/kpi_socket.h>
38# include <sys/kpi_socketfilter.h>
39RT_C_DECLS_END
40# include <sys/buf.h>
41# include <sys/vm.h>
42# include <sys/vnode_if.h>
43/*# include <sys/sysctl.h>*/
44# include <sys/systm.h>
45# include <vfs/vfs_support.h>
46/*# include <miscfs/specfs/specdev.h>*/
47#else
48# include <stdio.h> /* for printf */
49#endif
50
51#if !defined(IN_RING0) && !defined(DOXYGEN_RUNNING) /* A linking tweak for the testcase: */
52# include <iprt/cdefs.h>
53# undef RTR0DECL
54# define RTR0DECL(type) DECLHIDDEN(type) RTCALL
55#endif
56
57#include "internal/iprt.h"
58#include <iprt/dbg.h>
59
60#include <iprt/asm.h>
61#include <iprt/assert.h>
62#include <iprt/err.h>
63#include <iprt/assert.h>
64#include <iprt/file.h>
65#include <iprt/log.h>
66#include <iprt/mem.h>
67#include <iprt/string.h>
68#include <iprt/formats/mach-o.h>
69#include "internal/magics.h"
70
71/** @def MY_CPU_TYPE
72 * The CPU type targeted by the compiler. */
73/** @def MY_CPU_TYPE
74 * The "ALL" CPU subtype targeted by the compiler. */
75/** @def MY_MACHO_HEADER
76 * The Mach-O header targeted by the compiler. */
77/** @def MY_MACHO_MAGIC
78 * The Mach-O header magic we're targeting. */
79/** @def MY_SEGMENT_COMMAND
80 * The segment command targeted by the compiler. */
81/** @def MY_SECTION
82 * The section struture targeted by the compiler. */
83/** @def MY_NLIST
84 * The symbol table entry targeted by the compiler. */
85#ifdef RT_ARCH_X86
86# define MY_CPU_TYPE CPU_TYPE_I386
87# define MY_CPU_SUBTYPE_ALL CPU_SUBTYPE_I386_ALL
88# define MY_MACHO_HEADER mach_header_32_t
89# define MY_MACHO_MAGIC IMAGE_MACHO32_SIGNATURE
90# define MY_SEGMENT_COMMAND segment_command_32_t
91# define MY_SECTION section_32_t
92# define MY_NLIST macho_nlist_32_t
93
94#elif defined(RT_ARCH_AMD64)
95# define MY_CPU_TYPE CPU_TYPE_X86_64
96# define MY_CPU_SUBTYPE_ALL CPU_SUBTYPE_X86_64_ALL
97# define MY_MACHO_HEADER mach_header_64_t
98# define MY_MACHO_MAGIC IMAGE_MACHO64_SIGNATURE
99# define MY_SEGMENT_COMMAND segment_command_64_t
100# define MY_SECTION section_64_t
101# define MY_NLIST macho_nlist_64_t
102
103#else
104# error "Port me!"
105#endif
106
107/** @name Return macros for make it simpler to track down too paranoid code.
108 * @{
109 */
110#ifdef DEBUG
111# define RETURN_VERR_BAD_EXE_FORMAT \
112 do { Assert(!g_fBreakpointOnError); return VERR_BAD_EXE_FORMAT; } while (0)
113# define RETURN_VERR_LDR_UNEXPECTED \
114 do { Assert(!g_fBreakpointOnError); return VERR_LDR_UNEXPECTED; } while (0)
115# define RETURN_VERR_LDR_ARCH_MISMATCH \
116 do { Assert(!g_fBreakpointOnError); return VERR_LDR_ARCH_MISMATCH; } while (0)
117#else
118# define RETURN_VERR_BAD_EXE_FORMAT do { return VERR_BAD_EXE_FORMAT; } while (0)
119# define RETURN_VERR_LDR_UNEXPECTED do { return VERR_LDR_UNEXPECTED; } while (0)
120# define RETURN_VERR_LDR_ARCH_MISMATCH do { return VERR_LDR_ARCH_MISMATCH; } while (0)
121#endif
122#if defined(DEBUG_bird) && !defined(IN_RING3)
123# define LOG_MISMATCH(...) kprintf(__VA_ARGS__)
124# define LOG_NOT_PRESENT(...) kprintf(__VA_ARGS__)
125# define LOG_BAD_SYM(...) kprintf(__VA_ARGS__)
126# define LOG_SUCCESS(...) kprintf(__VA_ARGS__)
127#else
128# define LOG_MISMATCH(...) Log((__VA_ARGS__))
129# define LOG_NOT_PRESENT(...) Log((__VA_ARGS__))
130# define LOG_BAD_SYM(...) printf(__VA_ARGS__)
131# define LOG_SUCCESS(...) printf(__VA_ARGS__)
132#endif
133/** @} */
134
135#define VERR_LDR_UNEXPECTED (-641)
136
137#ifndef RT_OS_DARWIN
138# define MAC_OS_X_VERSION_MIN_REQUIRED 1050
139#endif
140
141
142/*********************************************************************************************************************************
143* Structures and Typedefs *
144*********************************************************************************************************************************/
145/**
146 * Our internal representation of the mach_kernel after loading it's symbols
147 * and successfully resolving their addresses.
148 */
149typedef struct RTDBGKRNLINFOINT
150{
151 /** Magic value (RTDBGKRNLINFO_MAGIC). */
152 uint32_t u32Magic;
153 /** Reference counter. */
154 uint32_t volatile cRefs;
155
156 /** Set if this is an in-memory rather than on-disk instance. */
157 bool fIsInMem;
158 bool afAlignment[7];
159
160 /** @name Result.
161 * @{ */
162 /** Pointer to the string table. */
163 char *pachStrTab;
164 /** The size of the string table. */
165 uint32_t cbStrTab;
166 /** The file offset of the string table. */
167 uint32_t offStrTab;
168 /** The link address of the string table. */
169 uintptr_t uStrTabLinkAddr;
170 /** Pointer to the symbol table. */
171 MY_NLIST *paSyms;
172 /** The size of the symbol table. */
173 uint32_t cSyms;
174 /** The file offset of the symbol table. */
175 uint32_t offSyms;
176 /** The link address of the symbol table. */
177 uintptr_t uSymTabLinkAddr;
178 /** The link address of the text segment. */
179 uintptr_t uTextSegLinkAddr;
180 /** Size of the text segment. */
181 uintptr_t cbTextSeg;
182 /** Offset between link address and actual load address. */
183 uintptr_t offLoad;
184 /** The minimum OS version (A.B.C; A is 16 bits, B & C each 8 bits). */
185 uint32_t uMinOsVer;
186 /** The SDK version (A.B.C; A is 16 bits, B & C each 8 bits). */
187 uint32_t uSdkVer;
188 /** The source version (A.B.C.D.E; A is 24 bits, the rest 10 each). */
189 uint64_t uSrcVer;
190 /** @} */
191
192 /** @name Used during loading.
193 * @{ */
194 /** The file handle. */
195 RTFILE hFile;
196 /** The architecture image offset (fat_arch_t::offset). */
197 uint64_t offArch;
198 /** The architecture image size (fat_arch_t::size). */
199 uint32_t cbArch;
200 /** The number of load commands (mach_header_XX_t::ncmds). */
201 uint32_t cLoadCmds;
202 /** The size of the load commands. */
203 uint32_t cbLoadCmds;
204 /** The load commands. */
205 load_command_t *pLoadCmds;
206 /** The number of segments. */
207 uint32_t cSegments;
208 /** The number of sections. */
209 uint32_t cSections;
210 /** Section pointer table (points into the load commands). */
211 MY_SEGMENT_COMMAND const *apSegments[MACHO_MAX_SECT / 2];
212 /** Section pointer table (points into the load commands). */
213 MY_SECTION const *apSections[MACHO_MAX_SECT];
214 /** @} */
215
216 /** Buffer space. */
217 char abBuf[_4K];
218} RTDBGKRNLINFOINT;
219
220
221/*********************************************************************************************************************************
222* Structures and Typedefs *
223*********************************************************************************************************************************/
224#ifdef DEBUG
225static bool g_fBreakpointOnError = false;
226#endif
227
228
229/**
230 * Close and free up resources we no longer needs.
231 *
232 * @param pThis The internal scratch data.
233 */
234static void rtR0DbgKrnlDarwinLoadDone(RTDBGKRNLINFOINT *pThis)
235{
236 if (!pThis->fIsInMem)
237 RTFileClose(pThis->hFile);
238 pThis->hFile = NIL_RTFILE;
239
240 if (!pThis->fIsInMem)
241 RTMemFree(pThis->pLoadCmds);
242 pThis->pLoadCmds = NULL;
243 RT_ZERO(pThis->apSections);
244 RT_ZERO(pThis->apSegments);
245}
246
247
248/**
249 * Looks up a kernel symbol.
250 *
251 * @returns The symbol address on success, 0 on failure.
252 * @param pThis The internal scratch data.
253 * @param pszSymbol The symbol to resolve. Automatically prefixed
254 * with an underscore.
255 */
256static uintptr_t rtR0DbgKrnlDarwinLookup(RTDBGKRNLINFOINT *pThis, const char *pszSymbol)
257{
258 uint32_t const cSyms = pThis->cSyms;
259 MY_NLIST const *pSym = pThis->paSyms;
260
261#if 1
262 /* linear search. */
263 for (uint32_t iSym = 0; iSym < cSyms; iSym++, pSym++)
264 {
265 if (pSym->n_type & MACHO_N_STAB)
266 continue;
267
268 const char *pszTabName= &pThis->pachStrTab[(uint32_t)pSym->n_un.n_strx];
269 if ( *pszTabName == '_'
270 && strcmp(pszTabName + 1, pszSymbol) == 0)
271 return pSym->n_value + pThis->offLoad;
272 }
273#else
274 /** @todo binary search. */
275
276#endif
277 return 0;
278}
279
280
281/* Rainy day: Find the right headers for these symbols ... if there are any. */
282extern "C" void ev_try_lock(void);
283extern "C" void OSMalloc(void);
284extern "C" void OSlibkernInit(void);
285extern "C" void kdp_set_interface(void);
286
287
288/**
289 * Check the symbol table against symbols we known symbols.
290 *
291 * This is done to detect whether the on disk image and the in
292 * memory images matches. Mismatches could stem from user
293 * replacing the default kernel image on disk.
294 *
295 * @returns IPRT status code.
296 * @param pThis The internal scratch data.
297 * @param pszKernelFile The name of the kernel file.
298 */
299static int rtR0DbgKrnlDarwinCheckStandardSymbols(RTDBGKRNLINFOINT *pThis, const char *pszKernelFile)
300{
301 static struct
302 {
303 const char *pszName;
304 uintptr_t uAddr;
305 } const s_aStandardCandles[] =
306 {
307#ifdef IN_RING0
308# define KNOWN_ENTRY(a_Sym) { #a_Sym, (uintptr_t)&a_Sym }
309#else
310# define KNOWN_ENTRY(a_Sym) { #a_Sym, 0 }
311#endif
312 /* IOKit: */
313 KNOWN_ENTRY(IOMalloc),
314 KNOWN_ENTRY(IOFree),
315 KNOWN_ENTRY(IOSleep),
316 KNOWN_ENTRY(IORWLockAlloc),
317 KNOWN_ENTRY(IORecursiveLockLock),
318 KNOWN_ENTRY(IOSimpleLockAlloc),
319 KNOWN_ENTRY(PE_cpu_halt),
320 KNOWN_ENTRY(gIOKitDebug),
321 KNOWN_ENTRY(gIOServicePlane),
322 KNOWN_ENTRY(ev_try_lock),
323
324 /* Libkern: */
325 KNOWN_ENTRY(OSAddAtomic),
326 KNOWN_ENTRY(OSBitAndAtomic),
327 KNOWN_ENTRY(OSBitOrAtomic),
328 KNOWN_ENTRY(OSBitXorAtomic),
329 KNOWN_ENTRY(OSCompareAndSwap),
330 KNOWN_ENTRY(OSMalloc),
331 KNOWN_ENTRY(OSlibkernInit),
332 KNOWN_ENTRY(bcmp),
333 KNOWN_ENTRY(copyout),
334 KNOWN_ENTRY(copyin),
335 KNOWN_ENTRY(kprintf),
336 KNOWN_ENTRY(printf),
337 KNOWN_ENTRY(lck_grp_alloc_init),
338 KNOWN_ENTRY(lck_mtx_alloc_init),
339 KNOWN_ENTRY(lck_rw_alloc_init),
340 KNOWN_ENTRY(lck_spin_alloc_init),
341 KNOWN_ENTRY(osrelease),
342 KNOWN_ENTRY(ostype),
343 KNOWN_ENTRY(panic),
344 KNOWN_ENTRY(strprefix),
345 //KNOWN_ENTRY(sysctlbyname), - we get kernel_sysctlbyname from the 10.10+ kernels.
346 KNOWN_ENTRY(vsscanf),
347 KNOWN_ENTRY(page_mask),
348
349 /* Mach: */
350 KNOWN_ENTRY(absolutetime_to_nanoseconds),
351 KNOWN_ENTRY(assert_wait),
352 KNOWN_ENTRY(clock_delay_until),
353 KNOWN_ENTRY(clock_get_uptime),
354 KNOWN_ENTRY(current_task),
355 KNOWN_ENTRY(current_thread),
356 KNOWN_ENTRY(kernel_task),
357 KNOWN_ENTRY(lck_mtx_sleep),
358 KNOWN_ENTRY(lck_rw_sleep),
359 KNOWN_ENTRY(lck_spin_sleep),
360 KNOWN_ENTRY(mach_absolute_time),
361 KNOWN_ENTRY(semaphore_create),
362 KNOWN_ENTRY(task_reference),
363 KNOWN_ENTRY(thread_block),
364 KNOWN_ENTRY(thread_reference),
365 KNOWN_ENTRY(thread_terminate),
366 KNOWN_ENTRY(thread_wakeup_prim),
367
368 /* BSDKernel: */
369 KNOWN_ENTRY(buf_size),
370 KNOWN_ENTRY(copystr),
371 KNOWN_ENTRY(current_proc),
372 KNOWN_ENTRY(ifnet_hdrlen),
373 KNOWN_ENTRY(ifnet_set_promiscuous),
374 KNOWN_ENTRY(kauth_getuid),
375#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
376 KNOWN_ENTRY(kauth_cred_unref),
377#else
378 KNOWN_ENTRY(kauth_cred_rele),
379#endif
380 KNOWN_ENTRY(mbuf_data),
381 KNOWN_ENTRY(msleep),
382 KNOWN_ENTRY(nanotime),
383 KNOWN_ENTRY(nop_close),
384 KNOWN_ENTRY(proc_pid),
385 KNOWN_ENTRY(sock_accept),
386 KNOWN_ENTRY(sockopt_name),
387 //KNOWN_ENTRY(spec_write),
388 KNOWN_ENTRY(suword),
389 //KNOWN_ENTRY(sysctl_int),
390 KNOWN_ENTRY(uio_rw),
391 KNOWN_ENTRY(vfs_flags),
392 KNOWN_ENTRY(vfs_name),
393 KNOWN_ENTRY(vfs_statfs),
394 KNOWN_ENTRY(VNOP_READ),
395 KNOWN_ENTRY(uio_create),
396 KNOWN_ENTRY(uio_addiov),
397 KNOWN_ENTRY(uio_free),
398 KNOWN_ENTRY(vnode_get),
399 KNOWN_ENTRY(vnode_open),
400 KNOWN_ENTRY(vnode_ref),
401 KNOWN_ENTRY(vnode_rele),
402 KNOWN_ENTRY(vnop_close_desc),
403 KNOWN_ENTRY(wakeup),
404 KNOWN_ENTRY(wakeup_one),
405
406 /* Unsupported: */
407 KNOWN_ENTRY(kdp_set_interface),
408 KNOWN_ENTRY(pmap_find_phys),
409 KNOWN_ENTRY(vm_map),
410 KNOWN_ENTRY(vm_protect),
411 KNOWN_ENTRY(vm_region),
412 KNOWN_ENTRY(vm_map_unwire), /* vm_map_wire has an alternative symbol, vm_map_wire_external, in 10.11 */
413 KNOWN_ENTRY(PE_kputc),
414 KNOWN_ENTRY(kernel_map),
415 KNOWN_ENTRY(kernel_pmap),
416 };
417
418 for (unsigned i = 0; i < RT_ELEMENTS(s_aStandardCandles); i++)
419 {
420 uintptr_t uAddr = rtR0DbgKrnlDarwinLookup(pThis, s_aStandardCandles[i].pszName);
421#ifdef IN_RING0
422 if (uAddr != s_aStandardCandles[i].uAddr)
423#else
424 if (uAddr == 0)
425#endif
426 {
427#if defined(IN_RING0) && defined(DEBUG_bird)
428 kprintf("RTR0DbgKrnlInfoOpen: error: %s (%p != %p) in %s\n",
429 s_aStandardCandles[i].pszName, (void *)uAddr, (void *)s_aStandardCandles[i].uAddr, pszKernelFile);
430#endif
431 printf("RTR0DbgKrnlInfoOpen: error: %s (%p != %p) in %s\n",
432 s_aStandardCandles[i].pszName, (void *)uAddr, (void *)s_aStandardCandles[i].uAddr, pszKernelFile);
433 return VERR_INTERNAL_ERROR_2;
434 }
435 }
436 return VINF_SUCCESS;
437}
438
439
440/**
441 * Loads and validates the symbol and string tables.
442 *
443 * @returns IPRT status code.
444 * @param pThis The internal scratch data.
445 * @param pszKernelFile The name of the kernel file.
446 */
447static int rtR0DbgKrnlDarwinParseSymTab(RTDBGKRNLINFOINT *pThis, const char *pszKernelFile)
448{
449 /*
450 * The first string table symbol must be a zero length name.
451 */
452 if (pThis->pachStrTab[0] != '\0')
453 RETURN_VERR_BAD_EXE_FORMAT;
454
455 /*
456 * Validate the symbol table.
457 */
458 const char *pszPrev = "";
459 uint32_t const cSyms = pThis->cSyms;
460 MY_NLIST const *pSym = pThis->paSyms;
461 for (uint32_t iSym = 0; iSym < cSyms; iSym++, pSym++)
462 {
463 if ((uint32_t)pSym->n_un.n_strx >= pThis->cbStrTab)
464 {
465 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Symbol #%u has a bad string table index: %#x vs cbStrTab=%#x\n",
466 pszKernelFile, iSym, pSym->n_un.n_strx, pThis->cbStrTab);
467 RETURN_VERR_BAD_EXE_FORMAT;
468 }
469 const char *pszSym = &pThis->pachStrTab[(uint32_t)pSym->n_un.n_strx];
470#ifdef IN_RING3
471 RTAssertMsg2("%05i: %02x:%08llx %02x %04x %s\n", iSym, pSym->n_sect, (uint64_t)pSym->n_value, pSym->n_type, pSym->n_desc, pszSym);
472#endif
473
474 if (strcmp(pszSym, pszPrev) < 0)
475 RETURN_VERR_BAD_EXE_FORMAT; /* not sorted */
476
477 if (!(pSym->n_type & MACHO_N_STAB))
478 {
479 switch (pSym->n_type & MACHO_N_TYPE)
480 {
481 case MACHO_N_SECT:
482 if (pSym->n_sect == MACHO_NO_SECT)
483 {
484 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Symbol #%u '%s' problem: n_sect = MACHO_NO_SECT\n",
485 pszKernelFile, iSym, pszSym);
486 RETURN_VERR_BAD_EXE_FORMAT;
487 }
488 if (pSym->n_sect > pThis->cSections)
489 {
490 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Symbol #%u '%s' problem: n_sect (%u) is higher than cSections (%u)\n",
491 pszKernelFile, iSym, pszSym, pSym->n_sect, pThis->cSections);
492 RETURN_VERR_BAD_EXE_FORMAT;
493 }
494 if (pSym->n_desc & ~(REFERENCED_DYNAMICALLY | N_WEAK_DEF))
495 {
496 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Symbol #%u '%s' problem: Unexpected value n_desc=%#x\n",
497 pszKernelFile, iSym, pszSym, pSym->n_desc);
498 RETURN_VERR_BAD_EXE_FORMAT;
499 }
500 if ( pSym->n_value < pThis->apSections[pSym->n_sect - 1]->addr
501 && strcmp(pszSym, "__mh_execute_header")) /* in 10.8 it's no longer absolute (PIE?). */
502 {
503 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Symbol #%u '%s' problem: n_value (%#llx) < section addr (%#llx)\n",
504 pszKernelFile, iSym, pszSym, pSym->n_value, pThis->apSections[pSym->n_sect - 1]->addr);
505 RETURN_VERR_BAD_EXE_FORMAT;
506 }
507 if ( pSym->n_value - pThis->apSections[pSym->n_sect - 1]->addr
508 > pThis->apSections[pSym->n_sect - 1]->size
509 && strcmp(pszSym, "__mh_execute_header")) /* see above. */
510 {
511 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Symbol #%u '%s' problem: n_value (%#llx) >= end of section (%#llx + %#llx)\n",
512 pszKernelFile, iSym, pszSym, pSym->n_value, pThis->apSections[pSym->n_sect - 1]->addr,
513 pThis->apSections[pSym->n_sect - 1]->size);
514 RETURN_VERR_BAD_EXE_FORMAT;
515 }
516 break;
517
518 case MACHO_N_ABS:
519 if ( pSym->n_sect != MACHO_NO_SECT
520 && ( strcmp(pszSym, "__mh_execute_header") /* n_sect=1 in 10.7/amd64 */
521 || pSym->n_sect > pThis->cSections) )
522 {
523 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Abs symbol #%u '%s' problem: n_sect (%u) is not MACHO_NO_SECT (cSections is %u)\n",
524 pszKernelFile, iSym, pszSym, pSym->n_sect, pThis->cSections);
525 RETURN_VERR_BAD_EXE_FORMAT;
526 }
527 if (pSym->n_desc & ~(REFERENCED_DYNAMICALLY | N_WEAK_DEF))
528 {
529 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Abs symbol #%u '%s' problem: Unexpected value n_desc=%#x\n",
530 pszKernelFile, iSym, pszSym, pSym->n_desc);
531 RETURN_VERR_BAD_EXE_FORMAT;
532 }
533 break;
534
535 case MACHO_N_UNDF:
536 /* No undefined or common symbols in the kernel. */
537 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Unexpected undefined symbol #%u '%s'\n", pszKernelFile, iSym, pszSym);
538 RETURN_VERR_BAD_EXE_FORMAT;
539
540 case MACHO_N_INDR:
541 /* No indirect symbols in the kernel. */
542 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Unexpected indirect symbol #%u '%s'\n", pszKernelFile, iSym, pszSym);
543 RETURN_VERR_BAD_EXE_FORMAT;
544
545 case MACHO_N_PBUD:
546 /* No prebound symbols in the kernel. */
547 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Unexpected prebound symbol #%u '%s'\n", pszKernelFile, iSym, pszSym);
548 RETURN_VERR_BAD_EXE_FORMAT;
549
550 default:
551 LOG_BAD_SYM("RTR0DbgKrnlInfoOpen: %s: Unexpected symbol n_type %#x for symbol #%u '%s'\n",
552 pszKernelFile, pSym->n_type, iSym, pszSym);
553 RETURN_VERR_BAD_EXE_FORMAT;
554 }
555 }
556 /* else: Ignore debug symbols. */
557 }
558
559 return VINF_SUCCESS;
560}
561
562
563/**
564 * Uses the segment table to translate a file offset into a virtual memory
565 * address.
566 *
567 * @returns The virtual memory address on success, 0 if not found.
568 * @param pThis The instance.
569 * @param offFile The file offset to translate.
570 */
571static uintptr_t rtR0DbgKrnlDarwinFileOffToVirtAddr(RTDBGKRNLINFOINT *pThis, uint64_t offFile)
572{
573 uint32_t iSeg = pThis->cSegments;
574 while (iSeg-- > 0)
575 {
576 uint64_t offSeg = offFile - pThis->apSegments[iSeg]->fileoff;
577 if (offSeg < pThis->apSegments[iSeg]->vmsize)
578 return pThis->apSegments[iSeg]->vmaddr + (uintptr_t)offSeg;
579 }
580 return 0;
581}
582
583
584/**
585 * Parses and validates the load commands.
586 *
587 * @returns IPRT status code.
588 * @param pThis The internal scratch data.
589 */
590static int rtR0DbgKrnlDarwinParseCommands(RTDBGKRNLINFOINT *pThis)
591{
592 Assert(pThis->pLoadCmds);
593
594 /*
595 * Reset the state.
596 */
597 pThis->offStrTab = 0;
598 pThis->cbStrTab = 0;
599 pThis->offSyms = 0;
600 pThis->cSyms = 0;
601 pThis->cSections = 0;
602 pThis->uTextSegLinkAddr = 0;
603 pThis->cbTextSeg = 0;
604 pThis->uMinOsVer = 0;
605 pThis->uSdkVer = 0;
606 pThis->uSrcVer = 0;
607
608 /*
609 * Validate the relevant commands, picking up sections and the symbol
610 * table location.
611 */
612 load_command_t const *pCmd = pThis->pLoadCmds;
613 for (uint32_t iCmd = 0; ; iCmd++)
614 {
615 /* cmd index & offset. */
616 uintptr_t offCmd = (uintptr_t)pCmd - (uintptr_t)pThis->pLoadCmds;
617 if (offCmd == pThis->cbLoadCmds && iCmd == pThis->cLoadCmds)
618 break;
619 if (offCmd + sizeof(*pCmd) > pThis->cbLoadCmds)
620 RETURN_VERR_BAD_EXE_FORMAT;
621 if (iCmd >= pThis->cLoadCmds)
622 RETURN_VERR_BAD_EXE_FORMAT;
623
624 /* cmdsize */
625 if (pCmd->cmdsize < sizeof(*pCmd))
626 RETURN_VERR_BAD_EXE_FORMAT;
627 if (pCmd->cmdsize > pThis->cbLoadCmds)
628 RETURN_VERR_BAD_EXE_FORMAT;
629 if (RT_ALIGN_32(pCmd->cmdsize, 4) != pCmd->cmdsize)
630 RETURN_VERR_BAD_EXE_FORMAT;
631
632 /* cmd */
633 switch (pCmd->cmd & ~LC_REQ_DYLD)
634 {
635 /* Validate and store the symbol table details. */
636 case LC_SYMTAB:
637 {
638 struct symtab_command const *pSymTab = (struct symtab_command const *)pCmd;
639 if (pSymTab->cmdsize != sizeof(*pSymTab))
640 RETURN_VERR_BAD_EXE_FORMAT;
641 if (pSymTab->nsyms > _1M)
642 RETURN_VERR_BAD_EXE_FORMAT;
643 if (pSymTab->strsize > _2M)
644 RETURN_VERR_BAD_EXE_FORMAT;
645
646 pThis->offStrTab = pSymTab->stroff;
647 pThis->cbStrTab = pSymTab->strsize;
648 pThis->offSyms = pSymTab->symoff;
649 pThis->cSyms = pSymTab->nsyms;
650 break;
651 }
652
653 /* Validate the segment. */
654#if ARCH_BITS == 32
655 case LC_SEGMENT_32:
656#elif ARCH_BITS == 64
657 case LC_SEGMENT_64:
658#else
659# error ARCH_BITS
660#endif
661 {
662 MY_SEGMENT_COMMAND const *pSeg = (MY_SEGMENT_COMMAND const *)pCmd;
663 if (pSeg->cmdsize < sizeof(*pSeg))
664 RETURN_VERR_BAD_EXE_FORMAT;
665
666 if (pSeg->segname[0] == '\0')
667 RETURN_VERR_BAD_EXE_FORMAT;
668
669 if (pSeg->nsects > MACHO_MAX_SECT)
670 RETURN_VERR_BAD_EXE_FORMAT;
671 if (pSeg->nsects * sizeof(MY_SECTION) + sizeof(*pSeg) != pSeg->cmdsize)
672 RETURN_VERR_BAD_EXE_FORMAT;
673
674 if (pSeg->flags & ~(SG_HIGHVM | SG_FVMLIB | SG_NORELOC | SG_PROTECTED_VERSION_1))
675 RETURN_VERR_BAD_EXE_FORMAT;
676
677 if ( pSeg->vmaddr != 0
678 || !strcmp(pSeg->segname, "__PAGEZERO"))
679 {
680 if (pSeg->vmaddr + RT_ALIGN_Z(pSeg->vmsize, RT_BIT_32(12)) < pSeg->vmaddr)
681 RETURN_VERR_BAD_EXE_FORMAT;
682 }
683 else if (pSeg->vmsize)
684 RETURN_VERR_BAD_EXE_FORMAT;
685
686 if (pSeg->maxprot & ~VM_PROT_ALL)
687 RETURN_VERR_BAD_EXE_FORMAT;
688 if (pSeg->initprot & ~VM_PROT_ALL)
689 RETURN_VERR_BAD_EXE_FORMAT;
690
691 /* Validate the sections. */
692 uint32_t uAlignment = 0;
693 MY_SECTION const *paSects = (MY_SECTION const *)(pSeg + 1);
694 for (uint32_t i = 0; i < pSeg->nsects; i++)
695 {
696 if (paSects[i].sectname[0] == '\0')
697 RETURN_VERR_BAD_EXE_FORMAT;
698 if (memcmp(paSects[i].segname, pSeg->segname, sizeof(pSeg->segname)))
699 RETURN_VERR_BAD_EXE_FORMAT;
700
701 switch (paSects[i].flags & SECTION_TYPE)
702 {
703 case S_REGULAR:
704 case S_CSTRING_LITERALS:
705 case S_NON_LAZY_SYMBOL_POINTERS:
706 case S_MOD_INIT_FUNC_POINTERS:
707 case S_MOD_TERM_FUNC_POINTERS:
708 case S_COALESCED:
709 case S_4BYTE_LITERALS:
710 if ( pSeg->filesize != 0
711 ? paSects[i].offset - pSeg->fileoff >= pSeg->filesize
712 : paSects[i].offset - pSeg->fileoff != pSeg->filesize)
713 RETURN_VERR_BAD_EXE_FORMAT;
714 if ( paSects[i].addr != 0
715 && paSects[i].offset - pSeg->fileoff != paSects[i].addr - pSeg->vmaddr)
716 RETURN_VERR_BAD_EXE_FORMAT;
717 break;
718
719 case S_ZEROFILL:
720 if (paSects[i].offset != 0)
721 RETURN_VERR_BAD_EXE_FORMAT;
722 break;
723
724 /* not observed */
725 case S_SYMBOL_STUBS:
726 case S_INTERPOSING:
727 case S_8BYTE_LITERALS:
728 case S_16BYTE_LITERALS:
729 case S_DTRACE_DOF:
730 case S_LAZY_SYMBOL_POINTERS:
731 case S_LAZY_DYLIB_SYMBOL_POINTERS:
732 RETURN_VERR_LDR_UNEXPECTED;
733 case S_GB_ZEROFILL:
734 RETURN_VERR_LDR_UNEXPECTED;
735 default:
736 RETURN_VERR_BAD_EXE_FORMAT;
737 }
738
739 if (paSects[i].align > 12)
740 RETURN_VERR_BAD_EXE_FORMAT;
741 if (paSects[i].align > uAlignment)
742 uAlignment = paSects[i].align;
743
744 /* Add to the section table. */
745 if (pThis->cSections >= RT_ELEMENTS(pThis->apSections))
746 RETURN_VERR_BAD_EXE_FORMAT;
747 pThis->apSections[pThis->cSections++] = &paSects[i];
748 }
749
750 if (RT_ALIGN_Z(pSeg->vmaddr, RT_BIT_32(uAlignment)) != pSeg->vmaddr)
751 RETURN_VERR_BAD_EXE_FORMAT;
752 if ( pSeg->filesize > RT_ALIGN_Z(pSeg->vmsize, RT_BIT_32(uAlignment))
753 && pSeg->vmsize != 0)
754 RETURN_VERR_BAD_EXE_FORMAT;
755
756 /*
757 * Add to the segment table.
758 */
759 if (pThis->cSegments >= RT_ELEMENTS(pThis->apSegments))
760 RETURN_VERR_BAD_EXE_FORMAT;
761 pThis->apSegments[pThis->cSegments++] = pSeg;
762
763 /*
764 * Take down the text segment size and link address (for in-mem variant):
765 */
766 if (!strcmp(pSeg->segname, "__TEXT"))
767 {
768 if (pThis->cbTextSeg != 0)
769 RETURN_VERR_BAD_EXE_FORMAT;
770 pThis->uTextSegLinkAddr = pSeg->vmaddr;
771 pThis->cbTextSeg = pSeg->vmsize;
772 }
773 break;
774 }
775
776 case LC_UUID:
777 if (pCmd->cmdsize != sizeof(uuid_command))
778 RETURN_VERR_BAD_EXE_FORMAT;
779 break;
780
781 case LC_DYSYMTAB:
782 case LC_UNIXTHREAD:
783 case LC_CODE_SIGNATURE:
784 case LC_VERSION_MIN_MACOSX:
785 case LC_FUNCTION_STARTS:
786 case LC_MAIN:
787 case LC_DATA_IN_CODE:
788 case LC_ENCRYPTION_INFO_64:
789 case LC_LINKER_OPTION:
790 case LC_LINKER_OPTIMIZATION_HINT:
791 case LC_VERSION_MIN_TVOS:
792 case LC_VERSION_MIN_WATCHOS:
793 case LC_NOTE:
794 break;
795
796 case LC_BUILD_VERSION:
797 if (pCmd->cmdsize >= RT_UOFFSETOF(build_version_command_t, aTools))
798 {
799 build_version_command_t *pBldVerCmd = (build_version_command_t *)pCmd;
800 pThis->uMinOsVer = pBldVerCmd->minos;
801 pThis->uSdkVer = pBldVerCmd->sdk;
802 }
803 break;
804
805 case LC_SOURCE_VERSION:
806 if (pCmd->cmdsize == sizeof(source_version_command_t))
807 {
808 source_version_command_t *pSrcVerCmd = (source_version_command_t *)pCmd;
809 pThis->uSrcVer = pSrcVerCmd->version;
810 }
811 break;
812
813 /* not observed */
814 case LC_SYMSEG:
815#if ARCH_BITS == 32
816 case LC_SEGMENT_64:
817#elif ARCH_BITS == 64
818 case LC_SEGMENT_32:
819#endif
820 case LC_ROUTINES_64:
821 case LC_ROUTINES:
822 case LC_THREAD:
823 case LC_LOADFVMLIB:
824 case LC_IDFVMLIB:
825 case LC_IDENT:
826 case LC_FVMFILE:
827 case LC_PREPAGE:
828 case LC_TWOLEVEL_HINTS:
829 case LC_PREBIND_CKSUM:
830 case LC_SEGMENT_SPLIT_INFO:
831 case LC_ENCRYPTION_INFO:
832 RETURN_VERR_LDR_UNEXPECTED;
833
834 /* no phones here yet */
835 case LC_VERSION_MIN_IPHONEOS:
836 RETURN_VERR_LDR_UNEXPECTED;
837
838 /* dylib */
839 case LC_LOAD_DYLIB:
840 case LC_ID_DYLIB:
841 case LC_LOAD_DYLINKER:
842 case LC_ID_DYLINKER:
843 case LC_PREBOUND_DYLIB:
844 case LC_LOAD_WEAK_DYLIB & ~LC_REQ_DYLD:
845 case LC_SUB_FRAMEWORK:
846 case LC_SUB_UMBRELLA:
847 case LC_SUB_CLIENT:
848 case LC_SUB_LIBRARY:
849 case LC_RPATH:
850 case LC_REEXPORT_DYLIB:
851 case LC_LAZY_LOAD_DYLIB:
852 case LC_DYLD_INFO:
853 case LC_DYLD_INFO_ONLY:
854 case LC_LOAD_UPWARD_DYLIB:
855 case LC_DYLD_ENVIRONMENT:
856 case LC_DYLIB_CODE_SIGN_DRS:
857 RETURN_VERR_LDR_UNEXPECTED;
858
859 default:
860 RETURN_VERR_BAD_EXE_FORMAT;
861 }
862
863 /* next */
864 pCmd = (load_command_t *)((uintptr_t)pCmd + pCmd->cmdsize);
865 }
866
867 /*
868 * Try figure out the virtual addresses for the symbol and string tables.
869 */
870 if (pThis->cbStrTab > 0)
871 pThis->uStrTabLinkAddr = rtR0DbgKrnlDarwinFileOffToVirtAddr(pThis, pThis->offStrTab);
872 if (pThis->cSyms > 0)
873 pThis->uSymTabLinkAddr = rtR0DbgKrnlDarwinFileOffToVirtAddr(pThis, pThis->offSyms);
874
875 return VINF_SUCCESS;
876}
877
878
879/**
880 * Loads and validates the symbol and string tables.
881 *
882 * @returns IPRT status code.
883 * @param pThis The internal scratch data.
884 * @param pszKernelFile The name of the kernel file.
885 */
886static int rtR0DbgKrnlDarwinLoadSymTab(RTDBGKRNLINFOINT *pThis, const char *pszKernelFile)
887{
888 /*
889 * Load the tables.
890 */
891 int rc;
892 pThis->paSyms = (MY_NLIST *)RTMemAllocZ(pThis->cSyms * sizeof(MY_NLIST));
893 if (pThis->paSyms)
894 {
895 rc = RTFileReadAt(pThis->hFile, pThis->offArch + pThis->offSyms, pThis->paSyms, pThis->cSyms * sizeof(MY_NLIST), NULL);
896 if (RT_SUCCESS(rc))
897 {
898 pThis->pachStrTab = (char *)RTMemAllocZ(pThis->cbStrTab + 1);
899 if (pThis->pachStrTab)
900 {
901 rc = RTFileReadAt(pThis->hFile, pThis->offArch + pThis->offStrTab, pThis->pachStrTab, pThis->cbStrTab, NULL);
902 if (RT_SUCCESS(rc))
903 {
904 /*
905 * Join paths with the in-memory code path.
906 */
907 rc = rtR0DbgKrnlDarwinParseSymTab(pThis, pszKernelFile);
908 }
909 }
910 else
911 rc = VERR_NO_MEMORY;
912 }
913 }
914 else
915 rc = VERR_NO_MEMORY;
916 return rc;
917}
918
919
920/**
921 * Loads the load commands and validates them.
922 *
923 * @returns IPRT status code.
924 * @param pThis The internal scratch data.
925 */
926static int rtR0DbgKrnlDarwinLoadCommands(RTDBGKRNLINFOINT *pThis)
927{
928 int rc;
929 pThis->pLoadCmds = (load_command_t *)RTMemAlloc(pThis->cbLoadCmds);
930 if (pThis->pLoadCmds)
931 {
932 rc = RTFileReadAt(pThis->hFile, pThis->offArch + sizeof(MY_MACHO_HEADER), pThis->pLoadCmds, pThis->cbLoadCmds, NULL);
933 if (RT_SUCCESS(rc))
934 rc = rtR0DbgKrnlDarwinParseCommands(pThis);
935 }
936 else
937 rc = VERR_NO_MEMORY;
938 return rc;
939}
940
941
942/**
943 * Loads the FAT and MACHO headers, noting down the relevant info.
944 *
945 * @returns IPRT status code.
946 * @param pThis The internal scratch data.
947 */
948static int rtR0DbgKrnlDarwinLoadFileHeaders(RTDBGKRNLINFOINT *pThis)
949{
950 uint32_t i;
951
952 pThis->offArch = 0;
953 pThis->cbArch = 0;
954
955 /*
956 * Read the first bit of the file, parse the FAT if found there.
957 */
958 int rc = RTFileReadAt(pThis->hFile, 0, pThis->abBuf, sizeof(fat_header_t) + sizeof(fat_arch_t) * 16, NULL);
959 if (RT_FAILURE(rc))
960 return rc;
961
962 fat_header_t *pFat = (fat_header *)pThis->abBuf;
963 fat_arch_t *paFatArches = (fat_arch_t *)(pFat + 1);
964
965 /* Correct FAT endian first. */
966 if (pFat->magic == IMAGE_FAT_SIGNATURE_OE)
967 {
968 pFat->magic = RT_BSWAP_U32(pFat->magic);
969 pFat->nfat_arch = RT_BSWAP_U32(pFat->nfat_arch);
970 i = RT_MIN(pFat->nfat_arch, 16);
971 while (i-- > 0)
972 {
973 paFatArches[i].cputype = RT_BSWAP_U32(paFatArches[i].cputype);
974 paFatArches[i].cpusubtype = RT_BSWAP_U32(paFatArches[i].cpusubtype);
975 paFatArches[i].offset = RT_BSWAP_U32(paFatArches[i].offset);
976 paFatArches[i].size = RT_BSWAP_U32(paFatArches[i].size);
977 paFatArches[i].align = RT_BSWAP_U32(paFatArches[i].align);
978 }
979 }
980
981 /* Lookup our architecture in the FAT. */
982 if (pFat->magic == IMAGE_FAT_SIGNATURE)
983 {
984 if (pFat->nfat_arch > 16)
985 RETURN_VERR_BAD_EXE_FORMAT;
986
987 for (i = 0; i < pFat->nfat_arch; i++)
988 {
989 if ( paFatArches[i].cputype == MY_CPU_TYPE
990 && paFatArches[i].cpusubtype == MY_CPU_SUBTYPE_ALL)
991 {
992 pThis->offArch = paFatArches[i].offset;
993 pThis->cbArch = paFatArches[i].size;
994 if (!pThis->cbArch)
995 RETURN_VERR_BAD_EXE_FORMAT;
996 if (pThis->offArch < sizeof(fat_header_t) + sizeof(fat_arch_t) * pFat->nfat_arch)
997 RETURN_VERR_BAD_EXE_FORMAT;
998 if (pThis->offArch + pThis->cbArch <= pThis->offArch)
999 RETURN_VERR_LDR_ARCH_MISMATCH;
1000 break;
1001 }
1002 }
1003 if (i >= pFat->nfat_arch)
1004 RETURN_VERR_LDR_ARCH_MISMATCH;
1005 }
1006
1007 /*
1008 * Read the Mach-O header and validate it.
1009 */
1010 rc = RTFileReadAt(pThis->hFile, pThis->offArch, pThis->abBuf, sizeof(MY_MACHO_HEADER), NULL);
1011 if (RT_FAILURE(rc))
1012 return rc;
1013 MY_MACHO_HEADER const *pHdr = (MY_MACHO_HEADER const *)pThis->abBuf;
1014 if (pHdr->magic != MY_MACHO_MAGIC)
1015 {
1016 if ( pHdr->magic == IMAGE_MACHO32_SIGNATURE
1017 || pHdr->magic == IMAGE_MACHO32_SIGNATURE_OE
1018 || pHdr->magic == IMAGE_MACHO64_SIGNATURE
1019 || pHdr->magic == IMAGE_MACHO64_SIGNATURE_OE)
1020 RETURN_VERR_LDR_ARCH_MISMATCH;
1021 RETURN_VERR_BAD_EXE_FORMAT;
1022 }
1023
1024 if (pHdr->cputype != MY_CPU_TYPE)
1025 RETURN_VERR_LDR_ARCH_MISMATCH;
1026 if (pHdr->cpusubtype != MY_CPU_SUBTYPE_ALL)
1027 RETURN_VERR_LDR_ARCH_MISMATCH;
1028 if (pHdr->filetype != MH_EXECUTE)
1029 RETURN_VERR_LDR_UNEXPECTED;
1030 if (pHdr->ncmds < 4)
1031 RETURN_VERR_LDR_UNEXPECTED;
1032 if (pHdr->ncmds > 256)
1033 RETURN_VERR_LDR_UNEXPECTED;
1034 if (pHdr->sizeofcmds <= pHdr->ncmds * sizeof(load_command_t))
1035 RETURN_VERR_LDR_UNEXPECTED;
1036 if (pHdr->sizeofcmds >= _1M)
1037 RETURN_VERR_LDR_UNEXPECTED;
1038 if (pHdr->flags & ~MH_VALID_FLAGS)
1039 RETURN_VERR_LDR_UNEXPECTED;
1040
1041 pThis->cLoadCmds = pHdr->ncmds;
1042 pThis->cbLoadCmds = pHdr->sizeofcmds;
1043 return VINF_SUCCESS;
1044}
1045
1046
1047/**
1048 * Destructor.
1049 *
1050 * @param pThis The instance to destroy.
1051 */
1052static void rtR0DbgKrnlDarwinDtor(RTDBGKRNLINFOINT *pThis)
1053{
1054 pThis->u32Magic = ~RTDBGKRNLINFO_MAGIC;
1055
1056 if (!pThis->fIsInMem)
1057 RTMemFree(pThis->pachStrTab);
1058 pThis->pachStrTab = NULL;
1059
1060 if (!pThis->fIsInMem)
1061 RTMemFree(pThis->paSyms);
1062 pThis->paSyms = NULL;
1063
1064 RTMemFree(pThis);
1065}
1066
1067
1068/**
1069 * Completes a handle, logging details.
1070 *
1071 * @returns VINF_SUCCESS
1072 * @param phKrnlInfo Where to return the handle.
1073 * @param pThis The instance to complete.
1074 * @param pszKernelFile What kernel file it's based on.
1075 */
1076static int rtR0DbgKrnlDarwinSuccess(PRTDBGKRNLINFO phKrnlInfo, RTDBGKRNLINFOINT *pThis, const char *pszKernelFile)
1077{
1078 pThis->u32Magic = RTDBGKRNLINFO_MAGIC;
1079 pThis->cRefs = 1;
1080
1081#if defined(DEBUG) || defined(IN_RING3)
1082 LOG_SUCCESS("RTR0DbgKrnlInfoOpen: Found: %#zx + %#zx - %s\n", pThis->uTextSegLinkAddr, pThis->offLoad, pszKernelFile);
1083#else
1084 LOG_SUCCESS("RTR0DbgKrnlInfoOpen: Found: %s\n", pszKernelFile);
1085#endif
1086 LOG_SUCCESS("RTR0DbgKrnlInfoOpen: SDK version: %u.%u.%u MinOS version: %u.%u.%u Source version: %u.%u.%u.%u.%u\n",
1087 pThis->uSdkVer >> 16, (pThis->uSdkVer >> 8) & 0xff, pThis->uSdkVer & 0xff,
1088 pThis->uMinOsVer >> 16, (pThis->uMinOsVer >> 8) & 0xff, pThis->uMinOsVer & 0xff,
1089 (uint32_t)(pThis->uSrcVer >> 40),
1090 (uint32_t)(pThis->uSrcVer >> 30) & 0x3ff,
1091 (uint32_t)(pThis->uSrcVer >> 20) & 0x3ff,
1092 (uint32_t)(pThis->uSrcVer >> 10) & 0x3ff,
1093 (uint32_t)(pThis->uSrcVer) & 0x3ff);
1094
1095 *phKrnlInfo = pThis;
1096 return VINF_SUCCESS;
1097}
1098
1099
1100static int rtR0DbgKrnlDarwinOpen(PRTDBGKRNLINFO phKrnlInfo, const char *pszKernelFile)
1101{
1102 RTDBGKRNLINFOINT *pThis = (RTDBGKRNLINFOINT *)RTMemAllocZ(sizeof(*pThis));
1103 if (!pThis)
1104 return VERR_NO_MEMORY;
1105 pThis->hFile = NIL_RTFILE;
1106
1107 int rc = RTFileOpen(&pThis->hFile, pszKernelFile, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1108 if (RT_SUCCESS(rc))
1109 rc = rtR0DbgKrnlDarwinLoadFileHeaders(pThis);
1110 if (RT_SUCCESS(rc))
1111 rc = rtR0DbgKrnlDarwinLoadCommands(pThis);
1112 if (RT_SUCCESS(rc))
1113 rc = rtR0DbgKrnlDarwinLoadSymTab(pThis, pszKernelFile);
1114 if (RT_SUCCESS(rc))
1115 {
1116#ifdef IN_RING0
1117 /*
1118 * Determine the load displacement (10.8 kernels are PIE).
1119 */
1120 uintptr_t uLinkAddr = rtR0DbgKrnlDarwinLookup(pThis, "kernel_map");
1121 if (uLinkAddr != 0)
1122 pThis->offLoad = (uintptr_t)&kernel_map - uLinkAddr;
1123#endif
1124 rc = rtR0DbgKrnlDarwinCheckStandardSymbols(pThis, pszKernelFile);
1125 }
1126
1127 rtR0DbgKrnlDarwinLoadDone(pThis);
1128 if (RT_SUCCESS(rc))
1129 rtR0DbgKrnlDarwinSuccess(phKrnlInfo, pThis, pszKernelFile);
1130 else
1131 rtR0DbgKrnlDarwinDtor(pThis);
1132 return rc;
1133}
1134
1135
1136#ifdef IN_RING0
1137
1138/**
1139 * Checks if a page is present.
1140 * @returns true if it is, false if it isn't.
1141 * @param uPageAddr The address of/in the page to check.
1142 */
1143static bool rtR0DbgKrnlDarwinIsPagePresent(uintptr_t uPageAddr)
1144{
1145 /** @todo the dtrace code subjects the result to pmap_is_valid, but that
1146 * isn't exported, so we'll have to make to with != 0 here. */
1147 return pmap_find_phys(kernel_pmap, uPageAddr) != 0;
1148}
1149
1150
1151/**
1152 * Used to check whether a memory range is present or not.
1153 *
1154 * This is applied to the to the load commands and selected portions of the link
1155 * edit segment.
1156 *
1157 * @returns true if all present, false if not.
1158 * @param uAddress The start address.
1159 * @param cb Number of bytes to check.
1160 * @param pszWhat What we're checking, for logging.
1161 * @param pHdr The header address (for logging).
1162 */
1163static bool rtR0DbgKrnlDarwinIsRangePresent(uintptr_t uAddress, size_t cb,
1164 const char *pszWhat, MY_MACHO_HEADER const volatile *pHdr)
1165{
1166 uintptr_t const uStartAddress = uAddress;
1167 intptr_t cPages = RT_ALIGN_Z(cb + (uAddress & PAGE_OFFSET_MASK), PAGE_SIZE);
1168 RT_NOREF(uStartAddress, pszWhat, pHdr);
1169 for (;;)
1170 {
1171 if (!rtR0DbgKrnlDarwinIsPagePresent(uAddress))
1172 {
1173 LOG_NOT_PRESENT("RTR0DbgInfo: %p: Page in %s is not present: %#zx - rva %#zx; in structure %#zx (%#zx LB %#zx)\n",
1174 pHdr, pszWhat, uAddress, uAddress - (uintptr_t)pHdr, uAddress - uStartAddress, uStartAddress, cb);
1175 return false;
1176 }
1177
1178 cPages -= 1;
1179 if (cPages <= 0)
1180 uAddress += PAGE_SIZE;
1181 else
1182 return true;
1183 }
1184}
1185
1186
1187/**
1188 * Try "open" the in-memory kernel image
1189 *
1190 * @returns IPRT stauts code
1191 * @param phKrnlInfo Where to return the info instance on success.
1192 */
1193static int rtR0DbgKrnlDarwinOpenInMemory(PRTDBGKRNLINFO phKrnlInfo)
1194{
1195 RTDBGKRNLINFOINT *pThis = (RTDBGKRNLINFOINT *)RTMemAllocZ(sizeof(*pThis));
1196 if (!pThis)
1197 return VERR_NO_MEMORY;
1198 pThis->hFile = NIL_RTFILE;
1199 pThis->fIsInMem = true;
1200
1201 /*
1202 * Figure the search range based on a symbol that is supposed to be in
1203 * kernel text segment, using it as the upper boundrary. The lower boundary
1204 * is determined by subtracting a max kernel size of 64MB (the largest kernel
1205 * file, kernel.kasan, is around 45MB, but the end of __TEXT is about 27 MB,
1206 * which means we should still have plenty of room for future growth with 64MB).
1207 */
1208 uintptr_t const uSomeKernelAddr = (uintptr_t)&absolutetime_to_nanoseconds;
1209 uintptr_t const uLowestKernelAddr = uSomeKernelAddr - _64M;
1210
1211 /*
1212 * The kernel is probably aligned at some boundrary larger than a page size,
1213 * so to speed things up we start by assuming the alignment is page directory
1214 * sized. In case we're wrong and it's smaller, we decrease the alignment till
1215 * we've reach the page size.
1216 */
1217 uintptr_t fPrevAlignMask = ~(uintptr_t)0;
1218 uintptr_t uCurAlign = _2M; /* ASSUMES the kernel is typically 2MB aligned. */
1219 while (uCurAlign >= PAGE_SIZE)
1220 {
1221 /*
1222 * Search down from the symbol address looking for a mach-O header that
1223 * looks like it might belong to the kernel.
1224 */
1225 for (uintptr_t uCur = uSomeKernelAddr & ~(uCurAlign - 1); uCur >= uLowestKernelAddr; uCur -= uCurAlign)
1226 {
1227 /* Skip pages we've checked in previous iterations and pages that aren't present: */
1228 /** @todo This is a little bogus in case the header is paged out. */
1229 if ( (uCur & fPrevAlignMask)
1230 && rtR0DbgKrnlDarwinIsPagePresent(uCur))
1231 {
1232 /*
1233 * Look for valid mach-o header (we skip cpusubtype on purpose here).
1234 */
1235 MY_MACHO_HEADER const volatile *pHdr = (MY_MACHO_HEADER const volatile *)uCur;
1236 if ( pHdr->magic == MY_MACHO_MAGIC
1237 && pHdr->filetype == MH_EXECUTE
1238 && pHdr->cputype == MY_CPU_TYPE)
1239 {
1240 /* More header validation: */
1241 pThis->cLoadCmds = pHdr->ncmds;
1242 pThis->cbLoadCmds = pHdr->sizeofcmds;
1243 if (pHdr->ncmds < 4)
1244 LOG_MISMATCH("RTR0DbgInfo: %p: ncmds=%u is too small\n", pHdr, pThis->cLoadCmds);
1245 else if (pThis->cLoadCmds > 256)
1246 LOG_MISMATCH("RTR0DbgInfo: %p: ncmds=%u is too big\n", pHdr, pThis->cLoadCmds);
1247 else if (pThis->cbLoadCmds <= pThis->cLoadCmds * sizeof(load_command_t))
1248 LOG_MISMATCH("RTR0DbgInfo: %p: sizeofcmds=%u is too small for ncmds=%u\n",
1249 pHdr, pThis->cbLoadCmds, pThis->cLoadCmds);
1250 else if (pThis->cbLoadCmds >= _1M)
1251 LOG_MISMATCH("RTR0DbgInfo: %p: sizeofcmds=%u is too big\n", pHdr, pThis->cbLoadCmds);
1252 else if (pHdr->flags & ~MH_VALID_FLAGS)
1253 LOG_MISMATCH("RTR0DbgInfo: %p: invalid flags=%#x\n", pHdr, pHdr->flags);
1254 /*
1255 * Check that we can safely read the load commands, then parse & validate them.
1256 */
1257 else if (rtR0DbgKrnlDarwinIsRangePresent((uintptr_t)(pHdr + 1), pThis->cbLoadCmds, "load commands", pHdr))
1258 {
1259 pThis->pLoadCmds = (load_command_t *)(pHdr + 1);
1260 int rc = rtR0DbgKrnlDarwinParseCommands(pThis);
1261 if (RT_SUCCESS(rc))
1262 {
1263 /* Calculate the slide value. This is typically zero as the
1264 load commands has been relocated (the case with 10.14.0 at least). */
1265 /** @todo ASSUMES that the __TEXT segment comes first and includes the
1266 * mach-o header and load commands and all that. */
1267 pThis->offLoad = uCur - pThis->uTextSegLinkAddr;
1268
1269 /* Check that the kernel symbol is in the text segment: */
1270 uintptr_t const offSomeKernAddr = uSomeKernelAddr - uCur;
1271 if (offSomeKernAddr >= pThis->cbTextSeg)
1272 LOG_MISMATCH("RTR0DbgInfo: %p: Our symbol at %zx (off %zx) isn't within the text segment (size %#zx)\n",
1273 pHdr, uSomeKernelAddr, offSomeKernAddr, pThis->cbTextSeg);
1274 /*
1275 * Parse the symbol+string tables.
1276 */
1277 else if (pThis->uSymTabLinkAddr == 0)
1278 LOG_MISMATCH("RTR0DbgInfo: %p: No symbol table VA (off %#x L %#x)\n",
1279 pHdr, pThis->offSyms, pThis->cSyms);
1280 else if (pThis->uStrTabLinkAddr == 0)
1281 LOG_MISMATCH("RTR0DbgInfo: %p: No string table VA (off %#x LB %#x)\n",
1282 pHdr, pThis->offSyms, pThis->cbStrTab);
1283 else if ( rtR0DbgKrnlDarwinIsRangePresent(pThis->uStrTabLinkAddr + pThis->offLoad,
1284 pThis->cbStrTab, "string table", pHdr)
1285 && rtR0DbgKrnlDarwinIsRangePresent(pThis->uSymTabLinkAddr + pThis->offLoad,
1286 pThis->cSyms * sizeof(pThis->paSyms),
1287 "symbol table", pHdr))
1288 {
1289 pThis->pachStrTab = (char *)pThis->uStrTabLinkAddr + pThis->offLoad;
1290 pThis->paSyms = (MY_NLIST *)pThis->uSymTabLinkAddr + pThis->offLoad;
1291 rc = rtR0DbgKrnlDarwinParseSymTab(pThis, "in-memory");
1292 if (RT_SUCCESS(rc))
1293 {
1294 /*
1295 * Finally check the standard candles.
1296 */
1297 rc = rtR0DbgKrnlDarwinCheckStandardSymbols(pThis, "in-memory");
1298 rtR0DbgKrnlDarwinLoadDone(pThis);
1299 if (RT_SUCCESS(rc))
1300 return rtR0DbgKrnlDarwinSuccess(phKrnlInfo, pThis, "in-memory");
1301 }
1302 }
1303 }
1304
1305 RT_ZERO(pThis->apSections);
1306 RT_ZERO(pThis->apSegments);
1307 pThis->pLoadCmds = NULL;
1308 }
1309 }
1310 }
1311 }
1312
1313 fPrevAlignMask = uCurAlign - 1;
1314 uCurAlign >>= 1;
1315 }
1316
1317 RTMemFree(pThis);
1318 return VERR_GENERAL_FAILURE;
1319}
1320
1321#endif /* IN_RING0 */
1322
1323RTR0DECL(int) RTR0DbgKrnlInfoOpen(PRTDBGKRNLINFO phKrnlInfo, uint32_t fFlags)
1324{
1325 AssertPtrReturn(phKrnlInfo, VERR_INVALID_POINTER);
1326 *phKrnlInfo = NIL_RTDBGKRNLINFO;
1327 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
1328
1329#ifdef IN_RING0
1330 /*
1331 * Try see if we can use the kernel memory directly. This depends on not
1332 * having the __LINKEDIT segment jettisoned or swapped out. For older
1333 * kernels this is typically the case, unless kallsyms=1 is in boot-args.
1334 */
1335 int rc = rtR0DbgKrnlDarwinOpenInMemory(phKrnlInfo);
1336 if (RT_SUCCESS(rc))
1337 {
1338 Log(("RTR0DbgKrnlInfoOpen: Using in-memory kernel.\n"));
1339 return rc;
1340 }
1341#else
1342 int rc = VERR_WRONG_ORDER; /* shut up stupid MSC */
1343#endif
1344
1345 /*
1346 * Go thru likely kernel locations
1347 *
1348 * Note! Check the OS X version and reorder the list?
1349 * Note! We should try fish kcsuffix out of bootargs or somewhere one day.
1350 */
1351 static bool s_fFirstCall = true;
1352#ifdef IN_RING3
1353 extern const char *g_pszTestKernel;
1354#endif
1355 struct
1356 {
1357 const char *pszLocation;
1358 int rc;
1359 } aKernels[] =
1360 {
1361#ifdef IN_RING3
1362 { g_pszTestKernel, VERR_WRONG_ORDER },
1363#endif
1364 { "/System/Library/Kernels/kernel", VERR_WRONG_ORDER },
1365 { "/System/Library/Kernels/kernel.development", VERR_WRONG_ORDER },
1366 { "/System/Library/Kernels/kernel.debug", VERR_WRONG_ORDER },
1367 { "/mach_kernel", VERR_WRONG_ORDER },
1368 };
1369 for (uint32_t i = 0; i < RT_ELEMENTS(aKernels); i++)
1370 {
1371 aKernels[i].rc = rc = rtR0DbgKrnlDarwinOpen(phKrnlInfo, aKernels[i].pszLocation);
1372 if (RT_SUCCESS(rc))
1373 {
1374 if (s_fFirstCall)
1375 {
1376 printf("RTR0DbgKrnlInfoOpen: Using kernel file '%s'\n", aKernels[i].pszLocation);
1377 s_fFirstCall = false;
1378 }
1379 return rc;
1380 }
1381 }
1382
1383 /*
1384 * Failed.
1385 */
1386 /* Pick the best error code. */
1387 for (uint32_t i = 0; rc == VERR_FILE_NOT_FOUND && i < RT_ELEMENTS(aKernels); i++)
1388 if (aKernels[i].rc != VERR_FILE_NOT_FOUND)
1389 rc = aKernels[i].rc;
1390
1391 /* Bitch about it. */
1392 printf("RTR0DbgKrnlInfoOpen: failed to find matching kernel file! rc=%d\n", rc);
1393 if (s_fFirstCall)
1394 {
1395 for (uint32_t i = 0; i < RT_ELEMENTS(aKernels); i++)
1396 printf("RTR0DbgKrnlInfoOpen: '%s' -> %d\n", aKernels[i].pszLocation, aKernels[i].rc);
1397 s_fFirstCall = false;
1398 }
1399
1400 return rc;
1401}
1402
1403
1404RTR0DECL(uint32_t) RTR0DbgKrnlInfoRetain(RTDBGKRNLINFO hKrnlInfo)
1405{
1406 RTDBGKRNLINFOINT *pThis = hKrnlInfo;
1407 AssertPtrReturn(pThis, UINT32_MAX);
1408 AssertMsgReturn(pThis->u32Magic == RTDBGKRNLINFO_MAGIC, ("%p: u32Magic=%RX32\n", pThis, pThis->u32Magic), UINT32_MAX);
1409
1410 uint32_t cRefs = ASMAtomicIncU32(&pThis->cRefs);
1411 Assert(cRefs && cRefs < 100000);
1412 return cRefs;
1413}
1414
1415
1416RTR0DECL(uint32_t) RTR0DbgKrnlInfoRelease(RTDBGKRNLINFO hKrnlInfo)
1417{
1418 RTDBGKRNLINFOINT *pThis = hKrnlInfo;
1419 if (pThis == NIL_RTDBGKRNLINFO)
1420 return 0;
1421 AssertPtrReturn(pThis, UINT32_MAX);
1422 AssertMsgReturn(pThis->u32Magic == RTDBGKRNLINFO_MAGIC, ("%p: u32Magic=%RX32\n", pThis, pThis->u32Magic), UINT32_MAX);
1423
1424 uint32_t cRefs = ASMAtomicDecU32(&pThis->cRefs);
1425 if (cRefs == 0)
1426 rtR0DbgKrnlDarwinDtor(pThis);
1427 return cRefs;
1428}
1429
1430
1431RTR0DECL(int) RTR0DbgKrnlInfoQueryMember(RTDBGKRNLINFO hKrnlInfo, const char *pszModule, const char *pszStructure,
1432 const char *pszMember, size_t *poffMember)
1433{
1434 RTDBGKRNLINFOINT *pThis = hKrnlInfo;
1435 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1436 AssertMsgReturn(pThis->u32Magic == RTDBGKRNLINFO_MAGIC, ("%p: u32Magic=%RX32\n", pThis, pThis->u32Magic), VERR_INVALID_HANDLE);
1437 AssertPtrReturn(pszMember, VERR_INVALID_POINTER);
1438 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
1439 AssertPtrReturn(pszStructure, VERR_INVALID_POINTER);
1440 AssertPtrReturn(poffMember, VERR_INVALID_POINTER);
1441 return VERR_NOT_FOUND;
1442}
1443
1444
1445RTR0DECL(int) RTR0DbgKrnlInfoQuerySymbol(RTDBGKRNLINFO hKrnlInfo, const char *pszModule,
1446 const char *pszSymbol, void **ppvSymbol)
1447{
1448 RTDBGKRNLINFOINT *pThis = hKrnlInfo;
1449 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
1450 AssertMsgReturn(pThis->u32Magic == RTDBGKRNLINFO_MAGIC, ("%p: u32Magic=%RX32\n", pThis, pThis->u32Magic), VERR_INVALID_HANDLE);
1451 AssertPtrReturn(pszSymbol, VERR_INVALID_PARAMETER);
1452 AssertPtrNullReturn(ppvSymbol, VERR_INVALID_PARAMETER);
1453 AssertReturn(!pszModule, VERR_MODULE_NOT_FOUND);
1454
1455 uintptr_t uValue = rtR0DbgKrnlDarwinLookup(pThis, pszSymbol);
1456 if (ppvSymbol)
1457 *ppvSymbol = (void *)uValue;
1458 if (uValue)
1459 return VINF_SUCCESS;
1460 return VERR_SYMBOL_NOT_FOUND;
1461}
1462
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette