VirtualBox

source: vbox/trunk/src/VBox/Debugger/DBGPlugInLinux.cpp@ 78003

Last change on this file since 78003 was 77874, checked in by vboxsync, 6 years ago

DBGPlugInLinux: Started looking for kernel modules. Works to some extent for 2.6.24.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 111.7 KB
Line 
1/* $Id: DBGPlugInLinux.cpp 77874 2019-03-26 01:37:19Z vboxsync $ */
2/** @file
3 * DBGPlugInLinux - Debugger and Guest OS Digger Plugin For Linux.
4 */
5
6/*
7 * Copyright (C) 2008-2019 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
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DBGF /// @todo add new log group.
23#include "DBGPlugIns.h"
24#include "DBGPlugInCommonELF.h"
25#include <VBox/vmm/dbgf.h>
26#include <VBox/dis.h>
27#include <iprt/ctype.h>
28#include <iprt/file.h>
29#include <iprt/err.h>
30#include <iprt/mem.h>
31#include <iprt/stream.h>
32#include <iprt/string.h>
33#include <iprt/vfs.h>
34#include <iprt/zip.h>
35
36
37/*********************************************************************************************************************************
38* Structures and Typedefs *
39*********************************************************************************************************************************/
40
41/** @name InternalLinux structures
42 * @{ */
43
44
45/** @} */
46
47
48/**
49 * Config item type.
50 */
51typedef enum DBGDIGGERLINUXCFGITEMTYPE
52{
53 /** Invalid type. */
54 DBGDIGGERLINUXCFGITEMTYPE_INVALID = 0,
55 /** String. */
56 DBGDIGGERLINUXCFGITEMTYPE_STRING,
57 /** Number. */
58 DBGDIGGERLINUXCFGITEMTYPE_NUMBER,
59 /** Flag whether this feature is included in the
60 * kernel or as a module. */
61 DBGDIGGERLINUXCFGITEMTYPE_FLAG
62} DBGDIGGERLINUXCFGITEMTYPE;
63
64/**
65 * Item in the config database.
66 */
67typedef struct DBGDIGGERLINUXCFGITEM
68{
69 /** String space core. */
70 RTSTRSPACECORE Core;
71 /** Config item type. */
72 DBGDIGGERLINUXCFGITEMTYPE enmType;
73 /** Data based on the type. */
74 union
75 {
76 /** Number. */
77 int64_t i64Num;
78 /** Flag. */
79 bool fModule;
80 /** String - variable in size. */
81 char aszString[1];
82 } u;
83} DBGDIGGERLINUXCFGITEM;
84/** Pointer to a config database item. */
85typedef DBGDIGGERLINUXCFGITEM *PDBGDIGGERLINUXCFGITEM;
86/** Pointer to a const config database item. */
87typedef const DBGDIGGERLINUXCFGITEM *PCDBGDIGGERLINUXCFGITEM;
88
89/**
90 * Linux guest OS digger instance data.
91 */
92typedef struct DBGDIGGERLINUX
93{
94 /** Whether the information is valid or not.
95 * (For fending off illegal interface method calls.) */
96 bool fValid;
97 /** Set if 64-bit, clear if 32-bit. */
98 bool f64Bit;
99 /** Set if the kallsyms table uses relative addressing, clear
100 * if absolute addresses are used. */
101 bool fRelKrnlAddr;
102 /** The relative base when kernel symbols use offsets rather than
103 * absolute addresses. */
104 RTGCUINTPTR uKernelRelativeBase;
105
106 /** The address of the linux banner.
107 * This is set during probing. */
108 DBGFADDRESS AddrLinuxBanner;
109 /** Kernel base address.
110 * This is set during probing, refined during kallsyms parsing. */
111 DBGFADDRESS AddrKernelBase;
112 /** The kernel size. */
113 uint32_t cbKernel;
114
115 /** The number of kernel symbols (kallsyms_num_syms).
116 * This is set during init. */
117 uint32_t cKernelSymbols;
118 /** The size of the kernel name table (sizeof(kallsyms_names)). */
119 uint32_t cbKernelNames;
120 /** Number of entries in the kernel_markers table. */
121 uint32_t cKernelNameMarkers;
122 /** The size of the kernel symbol token table. */
123 uint32_t cbKernelTokenTable;
124 /** The address of the encoded kernel symbol names (kallsyms_names). */
125 DBGFADDRESS AddrKernelNames;
126 /** The address of the kernel symbol addresses (kallsyms_addresses). */
127 DBGFADDRESS AddrKernelAddresses;
128 /** The address of the kernel symbol name markers (kallsyms_markers). */
129 DBGFADDRESS AddrKernelNameMarkers;
130 /** The address of the kernel symbol token table (kallsyms_token_table). */
131 DBGFADDRESS AddrKernelTokenTable;
132 /** The address of the kernel symbol token index table (kallsyms_token_index). */
133 DBGFADDRESS AddrKernelTokenIndex;
134
135 /** The kernel message log interface. */
136 DBGFOSIDMESG IDmesg;
137
138 /** The config database root. */
139 RTSTRSPACE hCfgDb;
140} DBGDIGGERLINUX;
141/** Pointer to the linux guest OS digger instance data. */
142typedef DBGDIGGERLINUX *PDBGDIGGERLINUX;
143
144
145/**
146 * The current printk_log structure.
147 */
148typedef struct LNXPRINTKHDR
149{
150 /** Monotonic timestamp. */
151 uint64_t nsTimestamp;
152 /** The total size of this message record. */
153 uint16_t cbTotal;
154 /** The size of the text part (immediately follows the header). */
155 uint16_t cbText;
156 /** The size of the optional dictionary part (follows the text). */
157 uint16_t cbDict;
158 /** The syslog facility number. */
159 uint8_t bFacility;
160 /** First 5 bits are internal flags, next 3 bits are log level. */
161 uint8_t fFlagsAndLevel;
162} LNXPRINTKHDR;
163AssertCompileSize(LNXPRINTKHDR, 2*sizeof(uint64_t));
164/** Pointer to linux printk_log header. */
165typedef LNXPRINTKHDR *PLNXPRINTKHDR;
166/** Pointer to linux const printk_log header. */
167typedef LNXPRINTKHDR const *PCLNXPRINTKHDR;
168
169
170/*********************************************************************************************************************************
171* Defined Constants And Macros *
172*********************************************************************************************************************************/
173/** First kernel map address for 32bit Linux hosts (__START_KERNEL_map). */
174#define LNX32_KERNEL_ADDRESS_START UINT32_C(0xc0000000)
175/** First kernel map address for 64bit Linux hosts (__START_KERNEL_map). */
176#define LNX64_KERNEL_ADDRESS_START UINT64_C(0xffffffff80000000)
177/** Validates a 32-bit linux kernel address */
178#define LNX32_VALID_ADDRESS(Addr) ((Addr) > UINT32_C(0x80000000) && (Addr) < UINT32_C(0xfffff000))
179/** Validates a 64-bit linux kernel address */
180#define LNX64_VALID_ADDRESS(Addr) ((Addr) > UINT64_C(0xffff800000000000) && (Addr) < UINT64_C(0xfffffffffffff000))
181
182/** The max kernel size. */
183#define LNX_MAX_KERNEL_SIZE UINT32_C(0x0f000000)
184
185/** The maximum size we expect for kallsyms_names. */
186#define LNX_MAX_KALLSYMS_NAMES_SIZE UINT32_C(0x200000)
187/** The maximum size we expect for kallsyms_token_table. */
188#define LNX_MAX_KALLSYMS_TOKEN_TABLE_SIZE UINT32_C(0x10000)
189/** The minimum number of symbols we expect in kallsyms_num_syms. */
190#define LNX_MIN_KALLSYMS_SYMBOLS UINT32_C(2048)
191/** The maximum number of symbols we expect in kallsyms_num_syms. */
192#define LNX_MAX_KALLSYMS_SYMBOLS UINT32_C(1048576)
193/** The min length an encoded symbol in kallsyms_names is expected to have. */
194#define LNX_MIN_KALLSYMS_ENC_LENGTH UINT8_C(1)
195/** The max length an encoded symbol in kallsyms_names is expected to have.
196 * @todo check real life here. */
197#define LNX_MAX_KALLSYMS_ENC_LENGTH UINT8_C(28)
198/** The approximate maximum length of a string token. */
199#define LNX_MAX_KALLSYMS_TOKEN_LEN UINT16_C(32)
200/** Maximum compressed config size expected. */
201#define LNX_MAX_COMPRESSED_CFG_SIZE _1M
202
203/** Module tag for linux ('linuxmod' on little endian ASCII systems). */
204#define DIG_LNX_MOD_TAG UINT64_C(0x545f5d78758e898c)
205
206
207/*********************************************************************************************************************************
208* Internal Functions *
209*********************************************************************************************************************************/
210static DECLCALLBACK(int) dbgDiggerLinuxInit(PUVM pUVM, void *pvData);
211
212
213/*********************************************************************************************************************************
214* Global Variables *
215*********************************************************************************************************************************/
216/** Table of common linux kernel addresses. */
217static uint64_t g_au64LnxKernelAddresses[] =
218{
219 UINT64_C(0xc0100000),
220 UINT64_C(0x90100000),
221 UINT64_C(0xffffffff80200000)
222};
223
224static const uint8_t g_abLinuxVersion[] = "Linux version ";
225
226/**
227 * Converts a given offset into an absolute address if relative kernel offsets are used for
228 * kallsyms.
229 *
230 * @returns The absolute kernel address.
231 * @param pThis The Linux digger data.
232 * @param uOffset The offset to convert.
233 */
234DECLINLINE(RTGCUINTPTR) dbgDiggerLinuxConvOffsetToAddr(PDBGDIGGERLINUX pThis, int32_t uOffset)
235{
236 RTGCUINTPTR uAddr;
237
238 /*
239 * How the absolute address is calculated from the offset depends on the
240 * CONFIG_KALLSYMS_ABSOLUTE_PERCPU config which is only set for 64bit
241 * SMP kernels (we assume that all 64bit kernels always have SMP enabled too).
242 */
243 if (pThis->f64Bit)
244 {
245 if (uOffset >= 0)
246 uAddr = uOffset;
247 else
248 uAddr = pThis->uKernelRelativeBase - 1 - uOffset;
249 }
250 else
251 uAddr = pThis->uKernelRelativeBase + (uint32_t)uOffset;
252
253 return uAddr;
254}
255
256/**
257 * Disassembles a simple getter returning the value for it.
258 *
259 * @returns VBox status code.
260 * @param pThis The Linux digger data.
261 * @param pUVM The VM handle.
262 * @param hMod The module to use.
263 * @param pszSymbol The symbol of the getter.
264 * @param pvVal Where to store the value on success.
265 * @param cbVal Size of the value in bytes.
266 */
267static int dbgDiggerLinuxDisassembleSimpleGetter(PDBGDIGGERLINUX pThis, PUVM pUVM, RTDBGMOD hMod,
268 const char *pszSymbol, void *pvVal, uint32_t cbVal)
269{
270 int rc = VINF_SUCCESS;
271
272 RTDBGSYMBOL SymInfo;
273 rc = RTDbgModSymbolByName(hMod, pszSymbol, &SymInfo);
274 if (RT_SUCCESS(rc))
275 {
276 /*
277 * Do the diassembling. Disassemble until a ret instruction is encountered
278 * or a limit is reached (don't want to disassemble for too long as the getter
279 * should be short).
280 * push and pop instructions are skipped as well as any mov instructions not
281 * touching the rax or eax register (depending on the size of the value).
282 */
283 unsigned cInstrDisassembled = 0;
284 uint32_t offInstr = 0;
285 bool fRet = false;
286 DISSTATE DisState;
287 RT_ZERO(DisState);
288
289 do
290 {
291 DBGFADDRESS Addr;
292 RTGCPTR GCPtrCur = (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr + offInstr;
293 DBGFR3AddrFromFlat(pUVM, &Addr, GCPtrCur);
294
295 /* Prefetch the instruction. */
296 uint8_t abInstr[32];
297 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &abInstr[0], sizeof(abInstr));
298 if (RT_SUCCESS(rc))
299 {
300 uint32_t cbInstr = 0;
301
302 rc = DISInstr(&abInstr[0], pThis->f64Bit ? DISCPUMODE_64BIT : DISCPUMODE_32BIT, &DisState, &cbInstr);
303 if (RT_SUCCESS(rc))
304 {
305 switch (DisState.pCurInstr->uOpcode)
306 {
307 case OP_PUSH:
308 case OP_POP:
309 case OP_NOP:
310 case OP_LEA:
311 break;
312 case OP_RETN:
313 /* Getter returned, abort disassembling. */
314 fRet = true;
315 break;
316 case OP_MOV:
317 /*
318 * Check that the destination is either rax or eax depending on the
319 * value size.
320 *
321 * Param1 is the destination and Param2 the source.
322 */
323 if ( ( ( (DisState.Param1.fUse & (DISUSE_BASE | DISUSE_REG_GEN32))
324 && cbVal == sizeof(uint32_t))
325 || ( (DisState.Param1.fUse & (DISUSE_BASE | DISUSE_REG_GEN64))
326 && cbVal == sizeof(uint64_t)))
327 && DisState.Param1.Base.idxGenReg == DISGREG_RAX)
328 {
329 /* Parse the source. */
330 if (DisState.Param2.fUse & (DISUSE_IMMEDIATE32 | DISUSE_IMMEDIATE64))
331 memcpy(pvVal, &DisState.Param2.uValue, cbVal);
332 else if (DisState.Param2.fUse & (DISUSE_RIPDISPLACEMENT32|DISUSE_DISPLACEMENT32|DISUSE_DISPLACEMENT64))
333 {
334 RTGCPTR GCPtrVal = 0;
335
336 if (DisState.Param2.fUse & DISUSE_RIPDISPLACEMENT32)
337 GCPtrVal = GCPtrCur + DisState.Param2.uDisp.i32 + cbInstr;
338 else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT32)
339 GCPtrVal = (RTGCPTR)DisState.Param2.uDisp.u32;
340 else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT64)
341 GCPtrVal = (RTGCPTR)DisState.Param2.uDisp.u64;
342 else
343 AssertMsgFailedBreakStmt(("Invalid displacement\n"), rc = VERR_INVALID_STATE);
344
345 DBGFADDRESS AddrVal;
346 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/,
347 DBGFR3AddrFromFlat(pUVM, &AddrVal, GCPtrVal),
348 pvVal, cbVal);
349 }
350 }
351 break;
352 default:
353 /* All other instructions will cause an error for now (playing safe here). */
354 rc = VERR_INVALID_PARAMETER;
355 break;
356 }
357 cInstrDisassembled++;
358 offInstr += cbInstr;
359 }
360 }
361 } while ( RT_SUCCESS(rc)
362 && cInstrDisassembled < 20
363 && !fRet);
364 }
365
366 return rc;
367}
368
369/**
370 * Try to get at the log buffer starting address and size by disassembling emit_log_char.
371 *
372 * @returns VBox status code.
373 * @param pThis The Linux digger data.
374 * @param pUVM The VM handle.
375 * @param hMod The module to use.
376 * @param pGCPtrLogBuf Where to store the log buffer pointer on success.
377 * @param pcbLogBuf Where to store the size of the log buffer on success.
378 */
379static int dbgDiggerLinuxQueryAsciiLogBufferPtrs(PDBGDIGGERLINUX pThis, PUVM pUVM, RTDBGMOD hMod,
380 RTGCPTR *pGCPtrLogBuf, uint32_t *pcbLogBuf)
381{
382 int rc = VINF_SUCCESS;
383
384 /**
385 * We disassemble emit_log_char to get at the log buffer address and size.
386 * This is used in case the symbols are not exported in kallsyms.
387 *
388 * This is what it typically looks like:
389 * vmlinux!emit_log_char:
390 * %00000000c01204a1 56 push esi
391 * %00000000c01204a2 8b 35 d0 1c 34 c0 mov esi, dword [0c0341cd0h]
392 * %00000000c01204a8 53 push ebx
393 * %00000000c01204a9 8b 1d 74 3b 3e c0 mov ebx, dword [0c03e3b74h]
394 * %00000000c01204af 8b 0d d8 1c 34 c0 mov ecx, dword [0c0341cd8h]
395 * %00000000c01204b5 8d 56 ff lea edx, [esi-001h]
396 * %00000000c01204b8 21 da and edx, ebx
397 * %00000000c01204ba 88 04 11 mov byte [ecx+edx], al
398 * %00000000c01204bd 8d 53 01 lea edx, [ebx+001h]
399 * %00000000c01204c0 89 d0 mov eax, edx
400 * [...]
401 */
402 RTDBGSYMBOL SymInfo;
403 rc = RTDbgModSymbolByName(hMod, "emit_log_char", &SymInfo);
404 if (RT_SUCCESS(rc))
405 {
406 /*
407 * Do the diassembling. Disassemble until a ret instruction is encountered
408 * or a limit is reached (don't want to disassemble for too long as the getter
409 * should be short). Certain instructions found are ignored (push, nop, etc.).
410 */
411 unsigned cInstrDisassembled = 0;
412 uint32_t offInstr = 0;
413 bool fRet = false;
414 DISSTATE DisState;
415 unsigned cAddressesUsed = 0;
416 struct { size_t cb; RTGCPTR GCPtrOrigSrc; } aAddresses[5];
417 RT_ZERO(DisState);
418 RT_ZERO(aAddresses);
419
420 do
421 {
422 DBGFADDRESS Addr;
423 RTGCPTR GCPtrCur = (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr + offInstr;
424 DBGFR3AddrFromFlat(pUVM, &Addr, GCPtrCur);
425
426 /* Prefetch the instruction. */
427 uint8_t abInstr[32];
428 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &abInstr[0], sizeof(abInstr));
429 if (RT_SUCCESS(rc))
430 {
431 uint32_t cbInstr = 0;
432
433 rc = DISInstr(&abInstr[0], pThis->f64Bit ? DISCPUMODE_64BIT : DISCPUMODE_32BIT, &DisState, &cbInstr);
434 if (RT_SUCCESS(rc))
435 {
436 switch (DisState.pCurInstr->uOpcode)
437 {
438 case OP_PUSH:
439 case OP_POP:
440 case OP_NOP:
441 case OP_LEA:
442 case OP_AND:
443 case OP_CBW:
444 break;
445 case OP_RETN:
446 /* emit_log_char returned, abort disassembling. */
447 rc = VERR_NOT_FOUND;
448 fRet = true;
449 break;
450 case OP_MOV:
451 case OP_MOVSXD:
452 /*
453 * If a mov is encountered writing to memory with al (or dil for amd64) being the source the
454 * character is stored and we can infer the base address and size of the log buffer from
455 * the source addresses.
456 */
457 if ( (DisState.Param2.fUse & DISUSE_REG_GEN8)
458 && ( (DisState.Param2.Base.idxGenReg == DISGREG_AL && !pThis->f64Bit)
459 || (DisState.Param2.Base.idxGenReg == DISGREG_DIL && pThis->f64Bit))
460 && DISUSE_IS_EFFECTIVE_ADDR(DisState.Param1.fUse))
461 {
462 RTGCPTR GCPtrLogBuf = 0;
463 uint32_t cbLogBuf = 0;
464
465 /*
466 * We can stop disassembling now and inspect all registers, look for a valid kernel address first.
467 * Only one of the accessed registers should hold a valid kernel address.
468 * For the log size look for the biggest non kernel address.
469 */
470 for (unsigned i = 0; i < cAddressesUsed; i++)
471 {
472 DBGFADDRESS AddrVal;
473 union { uint8_t abVal[8]; uint32_t u32Val; uint64_t u64Val; } Val;
474
475 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/,
476 DBGFR3AddrFromFlat(pUVM, &AddrVal, aAddresses[i].GCPtrOrigSrc),
477 &Val.abVal[0], aAddresses[i].cb);
478 if (RT_SUCCESS(rc))
479 {
480 if (pThis->f64Bit && aAddresses[i].cb == sizeof(uint64_t))
481 {
482 if (LNX64_VALID_ADDRESS(Val.u64Val))
483 {
484 if (GCPtrLogBuf == 0)
485 GCPtrLogBuf = Val.u64Val;
486 else
487 {
488 rc = VERR_NOT_FOUND;
489 break;
490 }
491 }
492 }
493 else
494 {
495 AssertMsgBreakStmt(aAddresses[i].cb == sizeof(uint32_t),
496 ("Invalid value size\n"), rc = VERR_INVALID_STATE);
497
498 /* Might be a kernel address or a size indicator. */
499 if (!pThis->f64Bit && LNX32_VALID_ADDRESS(Val.u32Val))
500 {
501 if (GCPtrLogBuf == 0)
502 GCPtrLogBuf = Val.u32Val;
503 else
504 {
505 rc = VERR_NOT_FOUND;
506 break;
507 }
508 }
509 else
510 {
511 /*
512 * The highest value will be the log buffer because the other
513 * accessed variables are indexes into the buffer and hence
514 * always smaller than the size.
515 */
516 if (cbLogBuf < Val.u32Val)
517 cbLogBuf = Val.u32Val;
518 }
519 }
520 }
521 }
522
523 if ( RT_SUCCESS(rc)
524 && GCPtrLogBuf != 0
525 && cbLogBuf != 0)
526 {
527 *pGCPtrLogBuf = GCPtrLogBuf;
528 *pcbLogBuf = cbLogBuf;
529 }
530 else if (RT_SUCCESS(rc))
531 rc = VERR_NOT_FOUND;
532
533 fRet = true;
534 break;
535 }
536 else
537 {
538 /*
539 * In case of a memory to register move store the destination register index and the
540 * source address in the relation table for later processing.
541 */
542 if ( (DisState.Param1.fUse & (DISUSE_BASE | DISUSE_REG_GEN32 | DISUSE_REG_GEN64))
543 && (DisState.Param2.cb == sizeof(uint32_t) || DisState.Param2.cb == sizeof(uint64_t))
544 && (DisState.Param2.fUse & (DISUSE_RIPDISPLACEMENT32|DISUSE_DISPLACEMENT32|DISUSE_DISPLACEMENT64)))
545 {
546 RTGCPTR GCPtrVal = 0;
547
548 if (DisState.Param2.fUse & DISUSE_RIPDISPLACEMENT32)
549 GCPtrVal = GCPtrCur + DisState.Param2.uDisp.i32 + cbInstr;
550 else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT32)
551 GCPtrVal = (RTGCPTR)DisState.Param2.uDisp.u32;
552 else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT64)
553 GCPtrVal = (RTGCPTR)DisState.Param2.uDisp.u64;
554 else
555 AssertMsgFailedBreakStmt(("Invalid displacement\n"), rc = VERR_INVALID_STATE);
556
557 if (cAddressesUsed < RT_ELEMENTS(aAddresses))
558 {
559 /* movsxd reads always 32bits. */
560 if (DisState.pCurInstr->uOpcode == OP_MOVSXD)
561 aAddresses[cAddressesUsed].cb = sizeof(uint32_t);
562 else
563 aAddresses[cAddressesUsed].cb = DisState.Param2.cb;
564 aAddresses[cAddressesUsed].GCPtrOrigSrc = GCPtrVal;
565 cAddressesUsed++;
566 }
567 else
568 {
569 rc = VERR_INVALID_PARAMETER;
570 break;
571 }
572 }
573 }
574 break;
575 default:
576 /* All other instructions will cause an error for now (playing safe here). */
577 rc = VERR_INVALID_PARAMETER;
578 break;
579 }
580 cInstrDisassembled++;
581 offInstr += cbInstr;
582 }
583 }
584 } while ( RT_SUCCESS(rc)
585 && cInstrDisassembled < 20
586 && !fRet);
587 }
588
589 return rc;
590}
591
592/**
593 * Try to get at the log buffer starting address and size by disassembling some exposed helpers.
594 *
595 * @returns VBox status code.
596 * @param pThis The Linux digger data.
597 * @param pUVM The VM handle.
598 * @param hMod The module to use.
599 * @param pGCPtrLogBuf Where to store the log buffer pointer on success.
600 * @param pcbLogBuf Where to store the size of the log buffer on success.
601 */
602static int dbgDiggerLinuxQueryLogBufferPtrs(PDBGDIGGERLINUX pThis, PUVM pUVM, RTDBGMOD hMod,
603 RTGCPTR *pGCPtrLogBuf, uint32_t *pcbLogBuf)
604{
605 int rc = VINF_SUCCESS;
606
607 struct { void *pvVar; uint32_t cbHost, cbGuest; const char *pszSymbol; } aSymbols[] =
608 {
609 { pGCPtrLogBuf, (uint32_t)sizeof(RTGCPTR), (uint32_t)(pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t)), "log_buf_addr_get" },
610 { pcbLogBuf, (uint32_t)sizeof(uint32_t), (uint32_t)sizeof(uint32_t), "log_buf_len_get" }
611 };
612 for (uint32_t i = 0; i < RT_ELEMENTS(aSymbols) && RT_SUCCESS(rc); i++)
613 {
614 RT_BZERO(aSymbols[i].pvVar, aSymbols[i].cbHost);
615 Assert(aSymbols[i].cbHost >= aSymbols[i].cbGuest);
616 rc = dbgDiggerLinuxDisassembleSimpleGetter(pThis, pUVM, hMod, aSymbols[i].pszSymbol,
617 aSymbols[i].pvVar, aSymbols[i].cbGuest);
618 }
619
620 return rc;
621}
622
623/**
624 * Returns whether the log buffer is a simple ascii buffer or a record based implementation
625 * based on the kernel version found.
626 *
627 * @returns Flag whether the log buffer is the simple ascii buffer.
628 * @param pThis The Linux digger data.
629 * @param pUVM The user mode VM handle.
630 */
631static bool dbgDiggerLinuxLogBufferIsAsciiBuffer(PDBGDIGGERLINUX pThis, PUVM pUVM)
632{
633 char szTmp[128];
634 char const *pszVer = &szTmp[sizeof(g_abLinuxVersion) - 1];
635
636 RT_ZERO(szTmp);
637 int rc = DBGFR3MemReadString(pUVM, 0, &pThis->AddrLinuxBanner, szTmp, sizeof(szTmp) - 1);
638 if ( RT_SUCCESS(rc)
639 && RTStrVersionCompare(pszVer, "3.4") == -1)
640 return true;
641
642 return false;
643}
644
645/**
646 * Worker to get at the kernel log for pre 3.4 kernels where the log buffer was just a char buffer.
647 *
648 * @returns VBox status code.
649 * @param pThis The Linux digger data.
650 * @param pUVM The VM user mdoe handle.
651 * @param hMod The debug module handle.
652 * @param fFlags Flags reserved for future use, MBZ.
653 * @param cMessages The number of messages to retrieve, counting from the
654 * end of the log (i.e. like tail), use UINT32_MAX for all.
655 * @param pszBuf The output buffer.
656 * @param cbBuf The buffer size.
657 * @param pcbActual Where to store the number of bytes actually returned,
658 * including zero terminator. On VERR_BUFFER_OVERFLOW this
659 * holds the necessary buffer size. Optional.
660 */
661static int dbgDiggerLinuxLogBufferQueryAscii(PDBGDIGGERLINUX pThis, PUVM pUVM, RTDBGMOD hMod,
662 uint32_t fFlags, uint32_t cMessages,
663 char *pszBuf, size_t cbBuf, size_t *pcbActual)
664{
665 RT_NOREF2(fFlags, cMessages);
666 int rc = VINF_SUCCESS;
667 RTGCPTR GCPtrLogBuf;
668 uint32_t cbLogBuf;
669
670 struct { void *pvVar; size_t cbHost, cbGuest; const char *pszSymbol; } aSymbols[] =
671 {
672 { &GCPtrLogBuf, sizeof(GCPtrLogBuf), pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t), "log_buf" },
673 { &cbLogBuf, sizeof(cbLogBuf), sizeof(cbLogBuf), "log_buf_len" },
674 };
675 for (uint32_t i = 0; i < RT_ELEMENTS(aSymbols); i++)
676 {
677 RTDBGSYMBOL SymInfo;
678 rc = RTDbgModSymbolByName(hMod, aSymbols[i].pszSymbol, &SymInfo);
679 if (RT_SUCCESS(rc))
680 {
681 RT_BZERO(aSymbols[i].pvVar, aSymbols[i].cbHost);
682 Assert(aSymbols[i].cbHost >= aSymbols[i].cbGuest);
683 DBGFADDRESS Addr;
684 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/,
685 DBGFR3AddrFromFlat(pUVM, &Addr, (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr),
686 aSymbols[i].pvVar, aSymbols[i].cbGuest);
687 if (RT_SUCCESS(rc))
688 continue;
689 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Reading '%s' at %RGv: %Rrc\n", aSymbols[i].pszSymbol, Addr.FlatPtr, rc));
690 }
691 else
692 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error looking up '%s': %Rrc\n", aSymbols[i].pszSymbol, rc));
693 rc = VERR_NOT_FOUND;
694 break;
695 }
696
697 /*
698 * Some kernels don't expose the variables in kallsyms so we have to try disassemble
699 * some public helpers to get at the addresses.
700 *
701 * @todo: Maybe cache those values so we don't have to do the heavy work every time?
702 */
703 if (rc == VERR_NOT_FOUND)
704 {
705 rc = dbgDiggerLinuxQueryAsciiLogBufferPtrs(pThis, pUVM, hMod, &GCPtrLogBuf, &cbLogBuf);
706 if (RT_FAILURE(rc))
707 return rc;
708 }
709
710 /*
711 * Check if the values make sense.
712 */
713 if (pThis->f64Bit ? !LNX64_VALID_ADDRESS(GCPtrLogBuf) : !LNX32_VALID_ADDRESS(GCPtrLogBuf))
714 {
715 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf' value %RGv is not valid.\n", GCPtrLogBuf));
716 return VERR_NOT_FOUND;
717 }
718 if ( cbLogBuf < 4096
719 || !RT_IS_POWER_OF_TWO(cbLogBuf)
720 || cbLogBuf > 16*_1M)
721 {
722 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf_len' value %#x is not valid.\n", cbLogBuf));
723 return VERR_NOT_FOUND;
724 }
725
726 /*
727 * Read the whole log buffer.
728 */
729 uint8_t *pbLogBuf = (uint8_t *)RTMemAlloc(cbLogBuf);
730 if (!pbLogBuf)
731 {
732 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Failed to allocate %#x bytes for log buffer\n", cbLogBuf));
733 return VERR_NO_MEMORY;
734 }
735 DBGFADDRESS Addr;
736 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, GCPtrLogBuf), pbLogBuf, cbLogBuf);
737 if (RT_FAILURE(rc))
738 {
739 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error reading %#x bytes of log buffer at %RGv: %Rrc\n",
740 cbLogBuf, Addr.FlatPtr, rc));
741 RTMemFree(pbLogBuf);
742 return VERR_NOT_FOUND;
743 }
744
745 /** @todo Try to parse where the single messages start to make use of cMessages. */
746 size_t cchLength = RTStrNLen((const char *)pbLogBuf, cbLogBuf);
747 memcpy(&pszBuf[0], pbLogBuf, RT_MIN(cbBuf, cchLength));
748
749 /* Done with the buffer. */
750 RTMemFree(pbLogBuf);
751
752 /* Set return size value. */
753 if (pcbActual)
754 *pcbActual = RT_MIN(cbBuf, cchLength);
755
756 return cbBuf <= cchLength ? VERR_BUFFER_OVERFLOW : VINF_SUCCESS;
757}
758
759/**
760 * Worker to get at the kernel log for post 3.4 kernels where the log buffer contains records.
761 *
762 * @returns VBox status code.
763 * @param pThis The Linux digger data.
764 * @param pUVM The VM user mdoe handle.
765 * @param hMod The debug module handle.
766 * @param fFlags Flags reserved for future use, MBZ.
767 * @param cMessages The number of messages to retrieve, counting from the
768 * end of the log (i.e. like tail), use UINT32_MAX for all.
769 * @param pszBuf The output buffer.
770 * @param cbBuf The buffer size.
771 * @param pcbActual Where to store the number of bytes actually returned,
772 * including zero terminator. On VERR_BUFFER_OVERFLOW this
773 * holds the necessary buffer size. Optional.
774 */
775static int dbgDiggerLinuxLogBufferQueryRecords(PDBGDIGGERLINUX pThis, PUVM pUVM, RTDBGMOD hMod,
776 uint32_t fFlags, uint32_t cMessages,
777 char *pszBuf, size_t cbBuf, size_t *pcbActual)
778{
779 RT_NOREF1(fFlags);
780 int rc = VINF_SUCCESS;
781 RTGCPTR GCPtrLogBuf;
782 uint32_t cbLogBuf;
783 uint32_t idxFirst;
784 uint32_t idxNext;
785
786 struct { void *pvVar; size_t cbHost, cbGuest; const char *pszSymbol; } aSymbols[] =
787 {
788 { &GCPtrLogBuf, sizeof(GCPtrLogBuf), pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t), "log_buf" },
789 { &cbLogBuf, sizeof(cbLogBuf), sizeof(cbLogBuf), "log_buf_len" },
790 { &idxFirst, sizeof(idxFirst), sizeof(idxFirst), "log_first_idx" },
791 { &idxNext, sizeof(idxNext), sizeof(idxNext), "log_next_idx" },
792 };
793 for (uint32_t i = 0; i < RT_ELEMENTS(aSymbols); i++)
794 {
795 RTDBGSYMBOL SymInfo;
796 rc = RTDbgModSymbolByName(hMod, aSymbols[i].pszSymbol, &SymInfo);
797 if (RT_SUCCESS(rc))
798 {
799 RT_BZERO(aSymbols[i].pvVar, aSymbols[i].cbHost);
800 Assert(aSymbols[i].cbHost >= aSymbols[i].cbGuest);
801 DBGFADDRESS Addr;
802 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/,
803 DBGFR3AddrFromFlat(pUVM, &Addr, (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr),
804 aSymbols[i].pvVar, aSymbols[i].cbGuest);
805 if (RT_SUCCESS(rc))
806 continue;
807 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Reading '%s' at %RGv: %Rrc\n", aSymbols[i].pszSymbol, Addr.FlatPtr, rc));
808 }
809 else
810 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error looking up '%s': %Rrc\n", aSymbols[i].pszSymbol, rc));
811 rc = VERR_NOT_FOUND;
812 break;
813 }
814
815 /*
816 * Some kernels don't expose the variables in kallsyms so we have to try disassemble
817 * some public helpers to get at the addresses.
818 *
819 * @todo: Maybe cache those values so we don't have to do the heavy work every time?
820 */
821 if (rc == VERR_NOT_FOUND)
822 {
823 idxFirst = 0;
824 idxNext = 0;
825 rc = dbgDiggerLinuxQueryLogBufferPtrs(pThis, pUVM, hMod, &GCPtrLogBuf, &cbLogBuf);
826 if (RT_FAILURE(rc))
827 return rc;
828 }
829
830 /*
831 * Check if the values make sense.
832 */
833 if (pThis->f64Bit ? !LNX64_VALID_ADDRESS(GCPtrLogBuf) : !LNX32_VALID_ADDRESS(GCPtrLogBuf))
834 {
835 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf' value %RGv is not valid.\n", GCPtrLogBuf));
836 return VERR_NOT_FOUND;
837 }
838 if ( cbLogBuf < 4096
839 || !RT_IS_POWER_OF_TWO(cbLogBuf)
840 || cbLogBuf > 16*_1M)
841 {
842 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf_len' value %#x is not valid.\n", cbLogBuf));
843 return VERR_NOT_FOUND;
844 }
845 uint32_t const cbLogAlign = 4;
846 if ( idxFirst > cbLogBuf - sizeof(LNXPRINTKHDR)
847 || (idxFirst & (cbLogAlign - 1)) != 0)
848 {
849 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_first_idx' value %#x is not valid.\n", idxFirst));
850 return VERR_NOT_FOUND;
851 }
852 if ( idxNext > cbLogBuf - sizeof(LNXPRINTKHDR)
853 || (idxNext & (cbLogAlign - 1)) != 0)
854 {
855 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_next_idx' value %#x is not valid.\n", idxNext));
856 return VERR_NOT_FOUND;
857 }
858
859 /*
860 * Read the whole log buffer.
861 */
862 uint8_t *pbLogBuf = (uint8_t *)RTMemAlloc(cbLogBuf);
863 if (!pbLogBuf)
864 {
865 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Failed to allocate %#x bytes for log buffer\n", cbLogBuf));
866 return VERR_NO_MEMORY;
867 }
868 DBGFADDRESS Addr;
869 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, GCPtrLogBuf), pbLogBuf, cbLogBuf);
870 if (RT_FAILURE(rc))
871 {
872 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error reading %#x bytes of log buffer at %RGv: %Rrc\n",
873 cbLogBuf, Addr.FlatPtr, rc));
874 RTMemFree(pbLogBuf);
875 return VERR_NOT_FOUND;
876 }
877
878 /*
879 * Count the messages in the buffer while doing some basic validation.
880 */
881 uint32_t const cbUsed = idxFirst == idxNext ? cbLogBuf /* could be empty... */
882 : idxFirst < idxNext ? idxNext - idxFirst : cbLogBuf - idxFirst + idxNext;
883 uint32_t cbLeft = cbUsed;
884 uint32_t offCur = idxFirst;
885 uint32_t cLogMsgs = 0;
886
887 while (cbLeft > 0)
888 {
889 PCLNXPRINTKHDR pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
890 if (!pHdr->cbTotal)
891 {
892 /* Wrap around packet, most likely... */
893 if (cbLogBuf - offCur >= cbLeft)
894 break;
895 offCur = 0;
896 pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
897 }
898 if (RT_UNLIKELY( pHdr->cbTotal > cbLogBuf - sizeof(*pHdr) - offCur
899 || pHdr->cbTotal > cbLeft
900 || (pHdr->cbTotal & (cbLogAlign - 1)) != 0
901 || pHdr->cbTotal < (uint32_t)pHdr->cbText + (uint32_t)pHdr->cbDict + sizeof(*pHdr) ))
902 {
903 LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Invalid printk_log record at %#x: cbTotal=%#x cbText=%#x cbDict=%#x cbLogBuf=%#x cbLeft=%#x\n",
904 offCur, pHdr->cbTotal, pHdr->cbText, pHdr->cbDict, cbLogBuf, cbLeft));
905 rc = VERR_INVALID_STATE;
906 break;
907 }
908
909 if (pHdr->cbText > 0)
910 cLogMsgs++;
911
912 /* next */
913 offCur += pHdr->cbTotal;
914 cbLeft -= pHdr->cbTotal;
915 }
916 if (RT_FAILURE(rc))
917 {
918 RTMemFree(pbLogBuf);
919 return rc;
920 }
921
922 /*
923 * Copy the messages into the output buffer.
924 */
925 offCur = idxFirst;
926 cbLeft = cbUsed;
927
928 /* Skip messages that the caller doesn't want. */
929 if (cMessages < cLogMsgs)
930 {
931 uint32_t cToSkip = cLogMsgs - cMessages;
932 while (cToSkip > 0)
933 {
934 PCLNXPRINTKHDR pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
935 if (!pHdr->cbTotal)
936 {
937 offCur = 0;
938 pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
939 }
940 if (pHdr->cbText > 0)
941 cToSkip--;
942
943 /* next */
944 offCur += pHdr->cbTotal;
945 cbLeft -= pHdr->cbTotal;
946 }
947 }
948
949 /* Now copy the messages. */
950 size_t offDst = 0;
951 while (cbLeft > 0)
952 {
953 PCLNXPRINTKHDR pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
954 if (!pHdr->cbTotal)
955 {
956 if (cbLogBuf - offCur >= cbLeft)
957 break;
958 offCur = 0;
959 pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
960 }
961
962 if (pHdr->cbText > 0)
963 {
964 char *pchText = (char *)(pHdr + 1);
965 size_t cchText = RTStrNLen(pchText, pHdr->cbText);
966 if (offDst + cchText < cbBuf)
967 {
968 memcpy(&pszBuf[offDst], pHdr + 1, cchText);
969 pszBuf[offDst + cchText] = '\n';
970 }
971 else if (offDst < cbBuf)
972 memcpy(&pszBuf[offDst], pHdr + 1, cbBuf - offDst);
973 offDst += cchText + 1;
974 }
975
976 /* next */
977 offCur += pHdr->cbTotal;
978 cbLeft -= pHdr->cbTotal;
979 }
980
981 /* Done with the buffer. */
982 RTMemFree(pbLogBuf);
983
984 /* Make sure we've reserved a char for the terminator. */
985 if (!offDst)
986 offDst = 1;
987
988 /* Set return size value. */
989 if (pcbActual)
990 *pcbActual = offDst;
991
992 if (offDst <= cbBuf)
993 return VINF_SUCCESS;
994 return VERR_BUFFER_OVERFLOW;
995}
996
997/**
998 * @interface_method_impl{DBGFOSIDMESG,pfnQueryKernelLog}
999 */
1000static DECLCALLBACK(int) dbgDiggerLinuxIDmsg_QueryKernelLog(PDBGFOSIDMESG pThis, PUVM pUVM, uint32_t fFlags, uint32_t cMessages,
1001 char *pszBuf, size_t cbBuf, size_t *pcbActual)
1002{
1003 PDBGDIGGERLINUX pData = RT_FROM_MEMBER(pThis, DBGDIGGERLINUX, IDmesg);
1004
1005 if (cMessages < 1)
1006 return VERR_INVALID_PARAMETER;
1007
1008 /*
1009 * Resolve the symbols we need and read their values.
1010 */
1011 RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
1012 RTDBGMOD hMod;
1013 int rc = RTDbgAsModuleByName(hAs, "vmlinux", 0, &hMod);
1014 RTDbgAsRelease(hAs);
1015 if (RT_FAILURE(rc))
1016 return VERR_NOT_FOUND;
1017
1018 /*
1019 * Check whether the kernel log buffer is a simple char buffer or the newer
1020 * record based implementation.
1021 * The record based implementation was presumably introduced with kernel 3.4,
1022 * see: http://thread.gmane.org/gmane.linux.kernel/1284184
1023 */
1024 size_t cbActual;
1025 if (dbgDiggerLinuxLogBufferIsAsciiBuffer(pData, pUVM))
1026 rc = dbgDiggerLinuxLogBufferQueryAscii(pData, pUVM, hMod, fFlags, cMessages, pszBuf, cbBuf, &cbActual);
1027 else
1028 rc = dbgDiggerLinuxLogBufferQueryRecords(pData, pUVM, hMod, fFlags, cMessages, pszBuf, cbBuf, &cbActual);
1029
1030 /* Release the module in any case. */
1031 RTDbgModRelease(hMod);
1032
1033 if (RT_FAILURE(rc) && rc != VERR_BUFFER_OVERFLOW)
1034 return rc;
1035
1036 if (pcbActual)
1037 *pcbActual = cbActual;
1038
1039 /*
1040 * All VBox strings are UTF-8 and bad things may in theory happen if we
1041 * pass bad UTF-8 to code which assumes it's all valid. So, we enforce
1042 * UTF-8 upon the guest kernel messages here even if they (probably) have
1043 * no defined code set in reality.
1044 */
1045 if ( RT_SUCCESS(rc)
1046 && cbActual <= cbBuf)
1047 {
1048 pszBuf[cbActual - 1] = '\0';
1049 RTStrPurgeEncoding(pszBuf);
1050 return VINF_SUCCESS;
1051 }
1052
1053 if (cbBuf)
1054 {
1055 pszBuf[cbBuf - 1] = '\0';
1056 RTStrPurgeEncoding(pszBuf);
1057 }
1058 return VERR_BUFFER_OVERFLOW;
1059}
1060
1061
1062/**
1063 * Worker destroying the config database.
1064 */
1065static DECLCALLBACK(int) dbgDiggerLinuxCfgDbDestroyWorker(PRTSTRSPACECORE pStr, void *pvUser)
1066{
1067 PDBGDIGGERLINUXCFGITEM pCfgItem = (PDBGDIGGERLINUXCFGITEM)pStr;
1068 RTStrFree((char *)pCfgItem->Core.pszString);
1069 RTMemFree(pCfgItem);
1070 NOREF(pvUser);
1071 return 0;
1072}
1073
1074
1075/**
1076 * Destroy the config database.
1077 *
1078 * @returns nothing.
1079 * @param pThis The Linux digger data.
1080 */
1081static void dbgDiggerLinuxCfgDbDestroy(PDBGDIGGERLINUX pThis)
1082{
1083 RTStrSpaceDestroy(&pThis->hCfgDb, dbgDiggerLinuxCfgDbDestroyWorker, NULL);
1084}
1085
1086
1087/**
1088 * @copydoc DBGFOSREG::pfnStackUnwindAssist
1089 */
1090static DECLCALLBACK(int) dbgDiggerLinuxStackUnwindAssist(PUVM pUVM, void *pvData, VMCPUID idCpu, PDBGFSTACKFRAME pFrame,
1091 PRTDBGUNWINDSTATE pState, PCCPUMCTX pInitialCtx, RTDBGAS hAs,
1092 uint64_t *puScratch)
1093{
1094 RT_NOREF(pUVM, pvData, idCpu, pFrame, pState, pInitialCtx, hAs, puScratch);
1095 return VINF_SUCCESS;
1096}
1097
1098
1099/**
1100 * @copydoc DBGFOSREG::pfnQueryInterface
1101 */
1102static DECLCALLBACK(void *) dbgDiggerLinuxQueryInterface(PUVM pUVM, void *pvData, DBGFOSINTERFACE enmIf)
1103{
1104 RT_NOREF1(pUVM);
1105 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
1106 switch (enmIf)
1107 {
1108 case DBGFOSINTERFACE_DMESG:
1109 return &pThis->IDmesg;
1110
1111 default:
1112 return NULL;
1113 }
1114}
1115
1116
1117/**
1118 * @copydoc DBGFOSREG::pfnQueryVersion
1119 */
1120static DECLCALLBACK(int) dbgDiggerLinuxQueryVersion(PUVM pUVM, void *pvData, char *pszVersion, size_t cchVersion)
1121{
1122 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
1123 Assert(pThis->fValid);
1124
1125 /*
1126 * It's all in the linux banner.
1127 */
1128 int rc = DBGFR3MemReadString(pUVM, 0, &pThis->AddrLinuxBanner, pszVersion, cchVersion);
1129 if (RT_SUCCESS(rc))
1130 {
1131 char *pszEnd = RTStrEnd(pszVersion, cchVersion);
1132 AssertReturn(pszEnd, VERR_BUFFER_OVERFLOW);
1133 while ( pszEnd > pszVersion
1134 && RT_C_IS_SPACE(pszEnd[-1]))
1135 pszEnd--;
1136 *pszEnd = '\0';
1137 }
1138 else
1139 RTStrPrintf(pszVersion, cchVersion, "DBGFR3MemRead -> %Rrc", rc);
1140
1141 return rc;
1142}
1143
1144
1145/**
1146 * @copydoc DBGFOSREG::pfnTerm
1147 */
1148static DECLCALLBACK(void) dbgDiggerLinuxTerm(PUVM pUVM, void *pvData)
1149{
1150 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
1151 Assert(pThis->fValid);
1152
1153 /*
1154 * Destroy configuration database.
1155 */
1156 dbgDiggerLinuxCfgDbDestroy(pThis);
1157
1158 /*
1159 * Unlink and release our modules.
1160 */
1161 RTDBGAS hDbgAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
1162 if (hDbgAs != NIL_RTDBGAS)
1163 {
1164 uint32_t iMod = RTDbgAsModuleCount(hDbgAs);
1165 while (iMod-- > 0)
1166 {
1167 RTDBGMOD hMod = RTDbgAsModuleByIndex(hDbgAs, iMod);
1168 if (hMod != NIL_RTDBGMOD)
1169 {
1170 if (RTDbgModGetTag(hMod) == DIG_LNX_MOD_TAG)
1171 {
1172 int rc = RTDbgAsModuleUnlink(hDbgAs, hMod);
1173 AssertRC(rc);
1174 }
1175 RTDbgModRelease(hMod);
1176 }
1177 }
1178 RTDbgAsRelease(hDbgAs);
1179 }
1180
1181 pThis->fValid = false;
1182}
1183
1184
1185/**
1186 * @copydoc DBGFOSREG::pfnRefresh
1187 */
1188static DECLCALLBACK(int) dbgDiggerLinuxRefresh(PUVM pUVM, void *pvData)
1189{
1190 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
1191 NOREF(pThis);
1192 Assert(pThis->fValid);
1193
1194 /*
1195 * For now we'll flush and reload everything.
1196 */
1197 dbgDiggerLinuxTerm(pUVM, pvData);
1198 return dbgDiggerLinuxInit(pUVM, pvData);
1199}
1200
1201
1202/**
1203 * Worker for dbgDiggerLinuxFindStartOfNamesAndSymbolCount that update the
1204 * digger data.
1205 *
1206 * @returns VINF_SUCCESS.
1207 * @param pThis The Linux digger data to update.
1208 * @param pAddrKernelNames The kallsyms_names address.
1209 * @param cKernelSymbols The number of kernel symbol.
1210 * @param cbAddress The guest address size.
1211 */
1212static int dbgDiggerLinuxFoundStartOfNames(PDBGDIGGERLINUX pThis, PCDBGFADDRESS pAddrKernelNames,
1213 uint32_t cKernelSymbols, uint32_t cbAddress)
1214{
1215 pThis->cKernelSymbols = cKernelSymbols;
1216 pThis->AddrKernelNames = *pAddrKernelNames;
1217 pThis->AddrKernelAddresses = *pAddrKernelNames;
1218 uint32_t cbSymbolsSkip = (pThis->fRelKrnlAddr ? 2 : 1) * cbAddress; /* Relative addressing introduces kallsyms_relative_base. */
1219 uint32_t cbOffsets = pThis->fRelKrnlAddr ? sizeof(int32_t) : cbAddress; /* Offsets are always 32bits wide for relative addressing. */
1220 uint32_t cbAlign = 0;
1221
1222 /*
1223 * If the number of symbols is odd there is padding to align the following guest pointer
1224 * sized data properly on 64bit systems with relative addressing.
1225 */
1226 if ( pThis->fRelKrnlAddr
1227 && pThis->f64Bit
1228 && (pThis->cKernelSymbols & 1))
1229 cbAlign = sizeof(int32_t);
1230 DBGFR3AddrSub(&pThis->AddrKernelAddresses, cKernelSymbols * cbOffsets + cbSymbolsSkip + cbAlign);
1231
1232 Log(("dbgDiggerLinuxFoundStartOfNames: AddrKernelAddresses=%RGv\n"
1233 "dbgDiggerLinuxFoundStartOfNames: cKernelSymbols=%#x (at %RGv)\n"
1234 "dbgDiggerLinuxFoundStartOfNames: AddrKernelName=%RGv\n",
1235 pThis->AddrKernelAddresses.FlatPtr,
1236 pThis->cKernelSymbols, pThis->AddrKernelNames.FlatPtr - cbAddress,
1237 pThis->AddrKernelNames.FlatPtr));
1238 return VINF_SUCCESS;
1239}
1240
1241
1242/**
1243 * Tries to find the address of the kallsyms_names, kallsyms_num_syms and
1244 * kallsyms_addresses symbols.
1245 *
1246 * The kallsyms_num_syms is read and stored in pThis->cKernelSymbols, while the
1247 * addresses of the other two are stored as pThis->AddrKernelNames and
1248 * pThis->AddrKernelAddresses.
1249 *
1250 * @returns VBox status code, success indicating that all three variables have
1251 * been found and taken down.
1252 * @param pUVM The user mode VM handle.
1253 * @param pThis The Linux digger data.
1254 * @param pHitAddr An address we think is inside kallsyms_names.
1255 */
1256static int dbgDiggerLinuxFindStartOfNamesAndSymbolCount(PUVM pUVM, PDBGDIGGERLINUX pThis, PCDBGFADDRESS pHitAddr)
1257{
1258 /*
1259 * Search backwards in chunks.
1260 */
1261 union
1262 {
1263 uint8_t ab[0x1000];
1264 uint32_t au32[0x1000 / sizeof(uint32_t)];
1265 uint64_t au64[0x1000 / sizeof(uint64_t)];
1266 } uBuf;
1267 uint32_t cbLeft = LNX_MAX_KALLSYMS_NAMES_SIZE;
1268 uint32_t cbBuf = pHitAddr->FlatPtr & (sizeof(uBuf) - 1);
1269 DBGFADDRESS CurAddr = *pHitAddr;
1270 DBGFR3AddrSub(&CurAddr, cbBuf);
1271 cbBuf += sizeof(uint64_t) - 1; /* In case our kobj hit is in the first 4/8 bytes. */
1272 for (;;)
1273 {
1274 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &CurAddr, &uBuf, sizeof(uBuf));
1275 if (RT_FAILURE(rc))
1276 return rc;
1277
1278 /*
1279 * Since Linux 4.6 there are two different methods to store the kallsyms addresses
1280 * in the image.
1281 *
1282 * The first and longer existing method is to store the absolute addresses in an
1283 * array starting at kallsyms_addresses followed by a field which stores the number
1284 * of kernel symbols called kallsyms_num_syms.
1285 * The newer method is to use offsets stored in kallsyms_offsets and have a base pointer
1286 * to relate the offsets to called kallsyms_relative_base. One entry in kallsyms_offsets is
1287 * always 32bit wide regardless of the guest pointer size (this halves the table on 64bit
1288 * systems) but means more work for us for the 64bit case.
1289 *
1290 * When absolute addresses are used the following assumptions hold:
1291 *
1292 * We assume that the three symbols are aligned on guest pointer boundary.
1293 *
1294 * The boundary between the two tables should be noticable as the number
1295 * is unlikely to be more than 16 millions, there will be at least one zero
1296 * byte where it is, 64-bit will have 5 zero bytes. Zero bytes aren't all
1297 * that common in the kallsyms_names table.
1298 *
1299 * Also the kallsyms_names table starts with a length byte, which means
1300 * we're likely to see a byte in the range 1..31.
1301 *
1302 * The kallsyms_addresses are mostly sorted (except for the start where the
1303 * absolute symbols are), so we'll spot a bunch of kernel addresses
1304 * immediately preceeding the kallsyms_num_syms field.
1305 *
1306 * Lazy bird: If kallsyms_num_syms is on a buffer boundrary, we skip
1307 * the check for kernel addresses preceeding it.
1308 *
1309 * For relative offsets most of the assumptions from above are true too
1310 * except that we have to distinguish between the relative base address and the offsets.
1311 * Every observed kernel has a valid kernel address fo the relative base and kallsyms_relative_base
1312 * always comes before kallsyms_num_syms and is aligned on a guest pointer boundary.
1313 * Offsets are stored before kallsyms_relative_base and don't contain valid kernel addresses.
1314 *
1315 * To distinguish between absolute and relative offsetting we check the data before a candidate
1316 * for kallsyms_num_syms. If all entries before the kallsyms_num_syms candidate are valid kernel
1317 * addresses absolute addresses are assumed. If this is not the case but the first entry before
1318 * kallsyms_num_syms is a valid kernel address we check whether the data before and the possible
1319 * relative base form a valid kernel address and assume relative offsets.
1320 */
1321 if (pThis->f64Bit)
1322 {
1323 uint32_t i = cbBuf / sizeof(uint64_t);
1324 while (i-- > 0)
1325 if ( uBuf.au64[i] <= LNX_MAX_KALLSYMS_SYMBOLS
1326 && uBuf.au64[i] >= LNX_MIN_KALLSYMS_SYMBOLS)
1327 {
1328 uint8_t *pb = (uint8_t *)&uBuf.au64[i + 1];
1329 if ( pb[0] <= LNX_MAX_KALLSYMS_ENC_LENGTH
1330 && pb[0] >= LNX_MIN_KALLSYMS_ENC_LENGTH)
1331 {
1332 /*
1333 * Check whether we have a valid kernel address and try to distinguish
1334 * whether the kernel uses relative offsetting or absolute addresses.
1335 */
1336 if ( (i >= 1 && LNX64_VALID_ADDRESS(uBuf.au64[i - 1]))
1337 && (i >= 2 && !LNX64_VALID_ADDRESS(uBuf.au64[i - 2]))
1338 && (i >= 3 && !LNX64_VALID_ADDRESS(uBuf.au64[i - 3])))
1339 {
1340 RTGCUINTPTR uKrnlRelBase = uBuf.au64[i - 1];
1341 DBGFADDRESS RelAddr = CurAddr;
1342 int32_t aiRelOff[3];
1343 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrAdd(&RelAddr, (i - 1) * sizeof(uint64_t) - sizeof(aiRelOff)),
1344 &aiRelOff[0], sizeof(aiRelOff));
1345 if ( RT_SUCCESS(rc)
1346 && LNX64_VALID_ADDRESS(uKrnlRelBase + aiRelOff[0])
1347 && LNX64_VALID_ADDRESS(uKrnlRelBase + aiRelOff[1])
1348 && LNX64_VALID_ADDRESS(uKrnlRelBase + aiRelOff[2]))
1349 {
1350 Log(("dbgDiggerLinuxFindStartOfNamesAndSymbolCount: relative base %RGv (at %RGv)\n",
1351 uKrnlRelBase, CurAddr.FlatPtr + (i - 1) * sizeof(uint64_t)));
1352 pThis->fRelKrnlAddr = true;
1353 pThis->uKernelRelativeBase = uKrnlRelBase;
1354 return dbgDiggerLinuxFoundStartOfNames(pThis,
1355 DBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint64_t)),
1356 (uint32_t)uBuf.au64[i], sizeof(uint64_t));
1357 }
1358 }
1359
1360 if ( (i <= 0 || LNX64_VALID_ADDRESS(uBuf.au64[i - 1]))
1361 && (i <= 1 || LNX64_VALID_ADDRESS(uBuf.au64[i - 2]))
1362 && (i <= 2 || LNX64_VALID_ADDRESS(uBuf.au64[i - 3])))
1363 return dbgDiggerLinuxFoundStartOfNames(pThis,
1364 DBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint64_t)),
1365 (uint32_t)uBuf.au64[i], sizeof(uint64_t));
1366 }
1367 }
1368 }
1369 else
1370 {
1371 uint32_t i = cbBuf / sizeof(uint32_t);
1372 while (i-- > 0)
1373 if ( uBuf.au32[i] <= LNX_MAX_KALLSYMS_SYMBOLS
1374 && uBuf.au32[i] >= LNX_MIN_KALLSYMS_SYMBOLS)
1375 {
1376 uint8_t *pb = (uint8_t *)&uBuf.au32[i + 1];
1377 if ( pb[0] <= LNX_MAX_KALLSYMS_ENC_LENGTH
1378 && pb[0] >= LNX_MIN_KALLSYMS_ENC_LENGTH)
1379 {
1380 /* Check for relative base addressing. */
1381 if (i >= 1 && LNX32_VALID_ADDRESS(uBuf.au32[i - 1]))
1382 {
1383 RTGCUINTPTR uKrnlRelBase = uBuf.au32[i - 1];
1384 if ( (i <= 1 || LNX32_VALID_ADDRESS(uKrnlRelBase + uBuf.au32[i - 2]))
1385 && (i <= 2 || LNX32_VALID_ADDRESS(uKrnlRelBase + uBuf.au32[i - 3])))
1386 {
1387 Log(("dbgDiggerLinuxFindStartOfNamesAndSymbolCount: relative base %RGv (at %RGv)\n",
1388 uKrnlRelBase, CurAddr.FlatPtr + (i - 1) * sizeof(uint32_t)));
1389 pThis->fRelKrnlAddr = true;
1390 pThis->uKernelRelativeBase = uKrnlRelBase;
1391 return dbgDiggerLinuxFoundStartOfNames(pThis,
1392 DBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint32_t)),
1393 uBuf.au32[i], sizeof(uint32_t));
1394 }
1395 }
1396
1397 if ( (i <= 0 || LNX32_VALID_ADDRESS(uBuf.au32[i - 1]))
1398 && (i <= 1 || LNX32_VALID_ADDRESS(uBuf.au32[i - 2]))
1399 && (i <= 2 || LNX32_VALID_ADDRESS(uBuf.au32[i - 3])))
1400 return dbgDiggerLinuxFoundStartOfNames(pThis,
1401 DBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint32_t)),
1402 uBuf.au32[i], sizeof(uint32_t));
1403 }
1404 }
1405 }
1406
1407 /*
1408 * Advance
1409 */
1410 if (RT_UNLIKELY(cbLeft <= sizeof(uBuf)))
1411 {
1412 Log(("dbgDiggerLinuxFindStartOfNamesAndSymbolCount: failed (pHitAddr=%RGv)\n", pHitAddr->FlatPtr));
1413 return VERR_NOT_FOUND;
1414 }
1415 cbLeft -= sizeof(uBuf);
1416 DBGFR3AddrSub(&CurAddr, sizeof(uBuf));
1417 cbBuf = sizeof(uBuf);
1418 }
1419}
1420
1421
1422/**
1423 * Worker for dbgDiggerLinuxFindEndNames that records the findings.
1424 *
1425 * @returns VINF_SUCCESS
1426 * @param pThis The linux digger data to update.
1427 * @param pAddrMarkers The address of the marker (kallsyms_markers).
1428 * @param cbMarkerEntry The size of a marker entry (32-bit or 64-bit).
1429 */
1430static int dbgDiggerLinuxFoundMarkers(PDBGDIGGERLINUX pThis, PCDBGFADDRESS pAddrMarkers, uint32_t cbMarkerEntry)
1431{
1432 pThis->cbKernelNames = pAddrMarkers->FlatPtr - pThis->AddrKernelNames.FlatPtr;
1433 pThis->AddrKernelNameMarkers = *pAddrMarkers;
1434 pThis->cKernelNameMarkers = RT_ALIGN_32(pThis->cKernelSymbols, 256) / 256;
1435 pThis->AddrKernelTokenTable = *pAddrMarkers;
1436 DBGFR3AddrAdd(&pThis->AddrKernelTokenTable, pThis->cKernelNameMarkers * cbMarkerEntry);
1437
1438 Log(("dbgDiggerLinuxFoundMarkers: AddrKernelNames=%RGv cbKernelNames=%#x\n"
1439 "dbgDiggerLinuxFoundMarkers: AddrKernelNameMarkers=%RGv cKernelNameMarkers=%#x\n"
1440 "dbgDiggerLinuxFoundMarkers: AddrKernelTokenTable=%RGv\n",
1441 pThis->AddrKernelNames.FlatPtr, pThis->cbKernelNames,
1442 pThis->AddrKernelNameMarkers.FlatPtr, pThis->cKernelNameMarkers,
1443 pThis->AddrKernelTokenTable.FlatPtr));
1444 return VINF_SUCCESS;
1445}
1446
1447
1448/**
1449 * Tries to find the end of kallsyms_names and thereby the start of
1450 * kallsyms_markers and kallsyms_token_table.
1451 *
1452 * The kallsyms_names size is stored in pThis->cbKernelNames, the addresses of
1453 * the two other symbols in pThis->AddrKernelNameMarkers and
1454 * pThis->AddrKernelTokenTable. The number of marker entries is stored in
1455 * pThis->cKernelNameMarkers.
1456 *
1457 * @returns VBox status code, success indicating that all three variables have
1458 * been found and taken down.
1459 * @param pUVM The user mode VM handle.
1460 * @param pThis The Linux digger data.
1461 * @param pHitAddr An address we think is inside kallsyms_names.
1462 */
1463static int dbgDiggerLinuxFindEndOfNamesAndMore(PUVM pUVM, PDBGDIGGERLINUX pThis, PCDBGFADDRESS pHitAddr)
1464{
1465 /*
1466 * Search forward in chunks.
1467 */
1468 union
1469 {
1470 uint8_t ab[0x1000];
1471 uint32_t au32[0x1000 / sizeof(uint32_t)];
1472 uint64_t au64[0x1000 / sizeof(uint64_t)];
1473 } uBuf;
1474 bool fPendingZeroHit = false;
1475 uint32_t cbLeft = LNX_MAX_KALLSYMS_NAMES_SIZE + sizeof(uBuf);
1476 uint32_t offBuf = pHitAddr->FlatPtr & (sizeof(uBuf) - 1);
1477 DBGFADDRESS CurAddr = *pHitAddr;
1478 DBGFR3AddrSub(&CurAddr, offBuf);
1479 for (;;)
1480 {
1481 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &CurAddr, &uBuf, sizeof(uBuf));
1482 if (RT_FAILURE(rc))
1483 return rc;
1484
1485 /*
1486 * The kallsyms_names table is followed by kallsyms_markers we assume,
1487 * using sizeof(unsigned long) alignment like the preceeding symbols.
1488 *
1489 * The kallsyms_markers table has entried sizeof(unsigned long) and
1490 * contains offsets into kallsyms_names. The kallsyms_markers used to
1491 * index kallsyms_names and reduce seek time when looking up the name
1492 * of an address/symbol. Each entry in kallsyms_markers covers 256
1493 * symbol names.
1494 *
1495 * Because of this, the first entry is always zero and all the entries
1496 * are ascending. It also follows that the size of the table can be
1497 * calculated from kallsyms_num_syms.
1498 *
1499 * Note! We could also have walked kallsyms_names by skipping
1500 * kallsyms_num_syms names, but this is faster and we will
1501 * validate the encoded names later.
1502 */
1503 if (pThis->f64Bit)
1504 {
1505 if ( RT_UNLIKELY(fPendingZeroHit)
1506 && uBuf.au64[0] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
1507 && uBuf.au64[0] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
1508 return dbgDiggerLinuxFoundMarkers(pThis, DBGFR3AddrSub(&CurAddr, sizeof(uint64_t)), sizeof(uint64_t));
1509
1510 uint32_t const cEntries = sizeof(uBuf) / sizeof(uint64_t);
1511 for (uint32_t i = offBuf / sizeof(uint64_t); i < cEntries; i++)
1512 if (uBuf.au64[i] == 0)
1513 {
1514 if (RT_UNLIKELY(i + 1 >= cEntries))
1515 {
1516 fPendingZeroHit = true;
1517 break;
1518 }
1519 if ( uBuf.au64[i + 1] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
1520 && uBuf.au64[i + 1] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
1521 return dbgDiggerLinuxFoundMarkers(pThis, DBGFR3AddrAdd(&CurAddr, i * sizeof(uint64_t)), sizeof(uint64_t));
1522 }
1523 }
1524 else
1525 {
1526 if ( RT_UNLIKELY(fPendingZeroHit)
1527 && uBuf.au32[0] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
1528 && uBuf.au32[0] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
1529 return dbgDiggerLinuxFoundMarkers(pThis, DBGFR3AddrSub(&CurAddr, sizeof(uint32_t)), sizeof(uint32_t));
1530
1531 uint32_t const cEntries = sizeof(uBuf) / sizeof(uint32_t);
1532 for (uint32_t i = offBuf / sizeof(uint32_t); i < cEntries; i++)
1533 if (uBuf.au32[i] == 0)
1534 {
1535 if (RT_UNLIKELY(i + 1 >= cEntries))
1536 {
1537 fPendingZeroHit = true;
1538 break;
1539 }
1540 if ( uBuf.au32[i + 1] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
1541 && uBuf.au32[i + 1] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
1542 return dbgDiggerLinuxFoundMarkers(pThis, DBGFR3AddrAdd(&CurAddr, i * sizeof(uint32_t)), sizeof(uint32_t));
1543 }
1544 }
1545
1546 /*
1547 * Advance
1548 */
1549 if (RT_UNLIKELY(cbLeft <= sizeof(uBuf)))
1550 {
1551 Log(("dbgDiggerLinuxFindEndOfNamesAndMore: failed (pHitAddr=%RGv)\n", pHitAddr->FlatPtr));
1552 return VERR_NOT_FOUND;
1553 }
1554 cbLeft -= sizeof(uBuf);
1555 DBGFR3AddrAdd(&CurAddr, sizeof(uBuf));
1556 offBuf = 0;
1557 }
1558}
1559
1560
1561/**
1562 * Locates the kallsyms_token_index table.
1563 *
1564 * Storing the address in pThis->AddrKernelTokenIndex and the size of the token
1565 * table in pThis->cbKernelTokenTable.
1566 *
1567 * @returns VBox status code.
1568 * @param pUVM The user mode VM handle.
1569 * @param pThis The Linux digger data.
1570 */
1571static int dbgDiggerLinuxFindTokenIndex(PUVM pUVM, PDBGDIGGERLINUX pThis)
1572{
1573 /*
1574 * The kallsyms_token_table is very much like a string table. Due to the
1575 * nature of the compression algorithm it is reasonably short (one example
1576 * here is 853 bytes), so we'll not be reading it in chunks but in full.
1577 * To be on the safe side, we read 8KB, ASSUMING we won't run into unmapped
1578 * memory or any other nasty stuff...
1579 */
1580 union
1581 {
1582 uint8_t ab[0x2000];
1583 uint16_t au16[0x2000 / sizeof(uint16_t)];
1584 } uBuf;
1585 DBGFADDRESS CurAddr = pThis->AddrKernelTokenTable;
1586 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &CurAddr, &uBuf, sizeof(uBuf));
1587 if (RT_FAILURE(rc))
1588 return rc;
1589
1590 /*
1591 * We've got two choices here, either walk the string table or look for
1592 * the next structure, kallsyms_token_index.
1593 *
1594 * The token index is a table of 256 uint16_t entries (index by bytes
1595 * from kallsyms_names) that gives offsets in kallsyms_token_table. It
1596 * starts with a zero entry and the following entries are sorted in
1597 * ascending order. The range of the entries are reasonably small since
1598 * kallsyms_token_table is small.
1599 *
1600 * The alignment seems to be sizeof(unsigned long), just like
1601 * kallsyms_token_table.
1602 *
1603 * So, we start by looking for a zero 16-bit entry.
1604 */
1605 uint32_t cIncr = (pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t)) / sizeof(uint16_t);
1606
1607 for (uint32_t i = 0; i < sizeof(uBuf) / sizeof(uint16_t) - 16; i += cIncr)
1608 if ( uBuf.au16[i] == 0
1609 && uBuf.au16[i + 1] > 0
1610 && uBuf.au16[i + 1] <= LNX_MAX_KALLSYMS_TOKEN_LEN
1611 && (uint16_t)(uBuf.au16[i + 2] - uBuf.au16[i + 1] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
1612 && (uint16_t)(uBuf.au16[i + 3] - uBuf.au16[i + 2] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
1613 && (uint16_t)(uBuf.au16[i + 4] - uBuf.au16[i + 3] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
1614 && (uint16_t)(uBuf.au16[i + 5] - uBuf.au16[i + 4] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
1615 && (uint16_t)(uBuf.au16[i + 6] - uBuf.au16[i + 5] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
1616 )
1617 {
1618 pThis->AddrKernelTokenIndex = CurAddr;
1619 DBGFR3AddrAdd(&pThis->AddrKernelTokenIndex, i * sizeof(uint16_t));
1620 pThis->cbKernelTokenTable = i * sizeof(uint16_t);
1621 return VINF_SUCCESS;
1622 }
1623
1624 Log(("dbgDiggerLinuxFindTokenIndex: Failed (%RGv..%RGv)\n", CurAddr.FlatPtr, CurAddr.FlatPtr + (RTGCUINTPTR)sizeof(uBuf)));
1625 return VERR_NOT_FOUND;
1626}
1627
1628
1629/**
1630 * Loads the kernel symbols from the given kallsyms offset table decoding the symbol names
1631 * (worker common for dbgDiggerLinuxLoadKernelSymbolsAbsolute() and dbgDiggerLinuxLoadKernelSymbolsRelative()).
1632 *
1633 * @returns VBox status code.
1634 * @param pUVM The user mode VM handle.
1635 * @param pThis The Linux digger data.
1636 * @param uKernelStart Flat kernel start address.
1637 * @param cbKernel Size of the kernel in bytes.
1638 * @param pauSymOff Pointer to the array of symbol offsets in the kallsyms table
1639 * relative to the start of the kernel.
1640 */
1641static int dbgDiggerLinuxLoadKernelSymbolsWorker(PUVM pUVM, PDBGDIGGERLINUX pThis, RTGCUINTPTR uKernelStart,
1642 RTGCUINTPTR cbKernel, RTGCUINTPTR *pauSymOff)
1643{
1644 uint8_t *pbNames = (uint8_t *)RTMemAllocZ(pThis->cbKernelNames);
1645 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelNames, pbNames, pThis->cbKernelNames);
1646 if (RT_SUCCESS(rc))
1647 {
1648 char *pszzTokens = (char *)RTMemAllocZ(pThis->cbKernelTokenTable);
1649 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelTokenTable, pszzTokens, pThis->cbKernelTokenTable);
1650 if (RT_SUCCESS(rc))
1651 {
1652 uint16_t *paoffTokens = (uint16_t *)RTMemAllocZ(256 * sizeof(uint16_t));
1653 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelTokenIndex, paoffTokens, 256 * sizeof(uint16_t));
1654 if (RT_SUCCESS(rc))
1655 {
1656 /*
1657 * Create a module for the kernel.
1658 */
1659 RTDBGMOD hMod;
1660 rc = RTDbgModCreate(&hMod, "vmlinux", cbKernel, 0 /*fFlags*/);
1661 if (RT_SUCCESS(rc))
1662 {
1663 rc = RTDbgModSetTag(hMod, DIG_LNX_MOD_TAG); AssertRC(rc);
1664 rc = VINF_SUCCESS;
1665
1666 /*
1667 * Enumerate the symbols.
1668 */
1669 uint32_t offName = 0;
1670 uint32_t cLeft = pThis->cKernelSymbols;
1671 while (cLeft-- > 0 && RT_SUCCESS(rc))
1672 {
1673 /* Decode the symbol name first. */
1674 if (RT_LIKELY(offName < pThis->cbKernelNames))
1675 {
1676 uint8_t cbName = pbNames[offName++];
1677 if (RT_LIKELY(offName + cbName <= pThis->cbKernelNames))
1678 {
1679 char szSymbol[4096];
1680 uint32_t offSymbol = 0;
1681 while (cbName-- > 0)
1682 {
1683 uint8_t bEnc = pbNames[offName++];
1684 uint16_t offToken = paoffTokens[bEnc];
1685 if (RT_LIKELY(offToken < pThis->cbKernelTokenTable))
1686 {
1687 const char *pszToken = &pszzTokens[offToken];
1688 char ch;
1689 while ((ch = *pszToken++) != '\0')
1690 if (offSymbol < sizeof(szSymbol) - 1)
1691 szSymbol[offSymbol++] = ch;
1692 }
1693 else
1694 {
1695 rc = VERR_INVALID_UTF8_ENCODING;
1696 break;
1697 }
1698 }
1699 szSymbol[offSymbol < sizeof(szSymbol) ? offSymbol : sizeof(szSymbol) - 1] = '\0';
1700
1701 /* The offset. */
1702 RTGCUINTPTR uSymOff = *pauSymOff;
1703 pauSymOff++;
1704
1705 /* Add it without the type char. */
1706 if (uSymOff <= cbKernel)
1707 {
1708 rc = RTDbgModSymbolAdd(hMod, &szSymbol[1], RTDBGSEGIDX_RVA, uSymOff,
1709 0 /*cb*/, 0 /*fFlags*/, NULL);
1710 if (RT_FAILURE(rc))
1711 {
1712 if ( rc == VERR_DBG_SYMBOL_NAME_OUT_OF_RANGE
1713 || rc == VERR_DBG_INVALID_RVA
1714 || rc == VERR_DBG_ADDRESS_CONFLICT
1715 || rc == VERR_DBG_DUPLICATE_SYMBOL)
1716 {
1717 Log2(("dbgDiggerLinuxLoadKernelSymbols: RTDbgModSymbolAdd(,%s,) failed %Rrc (ignored)\n", szSymbol, rc));
1718 rc = VINF_SUCCESS;
1719 }
1720 else
1721 Log(("dbgDiggerLinuxLoadKernelSymbols: RTDbgModSymbolAdd(,%s,) failed %Rrc\n", szSymbol, rc));
1722 }
1723 }
1724 }
1725 else
1726 {
1727 rc = VERR_END_OF_STRING;
1728 Log(("dbgDiggerLinuxLoadKernelSymbols: offName=%#x cLeft=%#x cbName=%#x cbKernelNames=%#x\n",
1729 offName, cLeft, cbName, pThis->cbKernelNames));
1730 }
1731 }
1732 else
1733 {
1734 rc = VERR_END_OF_STRING;
1735 Log(("dbgDiggerLinuxLoadKernelSymbols: offName=%#x cLeft=%#x cbKernelNames=%#x\n",
1736 offName, cLeft, pThis->cbKernelNames));
1737 }
1738 }
1739
1740 /*
1741 * Link the module into the address space.
1742 */
1743 if (RT_SUCCESS(rc))
1744 {
1745 RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
1746 if (hAs != NIL_RTDBGAS)
1747 rc = RTDbgAsModuleLink(hAs, hMod, uKernelStart, RTDBGASLINK_FLAGS_REPLACE);
1748 else
1749 rc = VERR_INTERNAL_ERROR;
1750 RTDbgAsRelease(hAs);
1751 }
1752 else
1753 Log(("dbgDiggerLinuxLoadKernelSymbols: Failed: %Rrc\n", rc));
1754 RTDbgModRelease(hMod);
1755 }
1756 else
1757 Log(("dbgDiggerLinuxLoadKernelSymbols: RTDbgModCreate failed: %Rrc\n", rc));
1758 }
1759 else
1760 Log(("dbgDiggerLinuxLoadKernelSymbols: Reading token index at %RGv failed: %Rrc\n",
1761 pThis->AddrKernelTokenIndex.FlatPtr, rc));
1762 RTMemFree(paoffTokens);
1763 }
1764 else
1765 Log(("dbgDiggerLinuxLoadKernelSymbols: Reading token table at %RGv failed: %Rrc\n",
1766 pThis->AddrKernelTokenTable.FlatPtr, rc));
1767 RTMemFree(pszzTokens);
1768 }
1769 else
1770 Log(("dbgDiggerLinuxLoadKernelSymbols: Reading encoded names at %RGv failed: %Rrc\n",
1771 pThis->AddrKernelNames.FlatPtr, rc));
1772 RTMemFree(pbNames);
1773
1774 return rc;
1775}
1776
1777/**
1778 * Loads the kernel symbols from the kallsyms table if it contains absolute addresses
1779 *
1780 * @returns VBox status code.
1781 * @param pUVM The user mode VM handle.
1782 * @param pThis The Linux digger data.
1783 */
1784static int dbgDiggerLinuxLoadKernelSymbolsAbsolute(PUVM pUVM, PDBGDIGGERLINUX pThis)
1785{
1786 /*
1787 * Allocate memory for temporary table copies, reading the tables as we go.
1788 */
1789 uint32_t const cbGuestAddr = pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t);
1790 void *pvAddresses = RTMemAllocZ(pThis->cKernelSymbols * cbGuestAddr);
1791 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelAddresses, pvAddresses, pThis->cKernelSymbols * cbGuestAddr);
1792 if (RT_SUCCESS(rc))
1793 {
1794 /*
1795 * Figure out the kernel start and end and convert the absolute addresses to relative offsets.
1796 */
1797 RTGCUINTPTR uKernelStart = pThis->AddrKernelAddresses.FlatPtr;
1798 RTGCUINTPTR uKernelEnd = pThis->AddrKernelTokenIndex.FlatPtr + 256 * sizeof(uint16_t);
1799 RTGCUINTPTR *pauSymOff = (RTGCUINTPTR *)RTMemTmpAllocZ(pThis->cKernelSymbols * sizeof(RTGCUINTPTR));
1800 uint32_t i;
1801 if (cbGuestAddr == sizeof(uint64_t))
1802 {
1803 uint64_t *pauAddrs = (uint64_t *)pvAddresses;
1804 for (i = 0; i < pThis->cKernelSymbols; i++)
1805 if ( pauAddrs[i] < uKernelStart
1806 && LNX64_VALID_ADDRESS(pauAddrs[i])
1807 && uKernelStart - pauAddrs[i] < LNX_MAX_KERNEL_SIZE)
1808 uKernelStart = pauAddrs[i];
1809
1810 for (i = pThis->cKernelSymbols - 1; i > 0; i--)
1811 if ( pauAddrs[i] > uKernelEnd
1812 && LNX64_VALID_ADDRESS(pauAddrs[i])
1813 && pauAddrs[i] - uKernelEnd < LNX_MAX_KERNEL_SIZE)
1814 uKernelEnd = pauAddrs[i];
1815
1816 for (i = 0; i < pThis->cKernelSymbols; i++)
1817 pauSymOff[i] = pauAddrs[i] - uKernelStart;
1818 }
1819 else
1820 {
1821 uint32_t *pauAddrs = (uint32_t *)pvAddresses;
1822 for (i = 0; i < pThis->cKernelSymbols; i++)
1823 if ( pauAddrs[i] < uKernelStart
1824 && LNX32_VALID_ADDRESS(pauAddrs[i])
1825 && uKernelStart - pauAddrs[i] < LNX_MAX_KERNEL_SIZE)
1826 uKernelStart = pauAddrs[i];
1827
1828 for (i = pThis->cKernelSymbols - 1; i > 0; i--)
1829 if ( pauAddrs[i] > uKernelEnd
1830 && LNX32_VALID_ADDRESS(pauAddrs[i])
1831 && pauAddrs[i] - uKernelEnd < LNX_MAX_KERNEL_SIZE)
1832 uKernelEnd = pauAddrs[i];
1833
1834 for (i = 0; i < pThis->cKernelSymbols; i++)
1835 pauSymOff[i] = pauAddrs[i] - uKernelStart;
1836 }
1837
1838 RTGCUINTPTR cbKernel = uKernelEnd - uKernelStart;
1839 pThis->cbKernel = (uint32_t)cbKernel;
1840 DBGFR3AddrFromFlat(pUVM, &pThis->AddrKernelBase, uKernelStart);
1841 Log(("dbgDiggerLinuxLoadKernelSymbolsAbsolute: uKernelStart=%RGv cbKernel=%#x\n", uKernelStart, cbKernel));
1842
1843 rc = dbgDiggerLinuxLoadKernelSymbolsWorker(pUVM, pThis, uKernelStart, cbKernel, pauSymOff);
1844 if (RT_FAILURE(rc))
1845 Log(("dbgDiggerLinuxLoadKernelSymbolsAbsolute: Loading symbols from given offset table failed: %Rrc\n", rc));
1846 RTMemTmpFree(pauSymOff);
1847 }
1848 else
1849 Log(("dbgDiggerLinuxLoadKernelSymbolsAbsolute: Reading symbol addresses at %RGv failed: %Rrc\n",
1850 pThis->AddrKernelAddresses.FlatPtr, rc));
1851 RTMemFree(pvAddresses);
1852
1853 return rc;
1854}
1855
1856
1857/**
1858 * Loads the kernel symbols from the kallsyms table if it contains absolute addresses
1859 *
1860 * @returns VBox status code.
1861 * @param pUVM The user mode VM handle.
1862 * @param pThis The Linux digger data.
1863 */
1864static int dbgDiggerLinuxLoadKernelSymbolsRelative(PUVM pUVM, PDBGDIGGERLINUX pThis)
1865{
1866 /*
1867 * Allocate memory for temporary table copies, reading the tables as we go.
1868 */
1869 int32_t *pai32Offsets = (int32_t *)RTMemAllocZ(pThis->cKernelSymbols * sizeof(int32_t));
1870 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelAddresses, pai32Offsets, pThis->cKernelSymbols * sizeof(int32_t));
1871 if (RT_SUCCESS(rc))
1872 {
1873 /*
1874 * Figure out the kernel start and end and convert the absolute addresses to relative offsets.
1875 */
1876 RTGCUINTPTR uKernelStart = pThis->AddrKernelAddresses.FlatPtr;
1877 RTGCUINTPTR uKernelEnd = pThis->AddrKernelTokenIndex.FlatPtr + 256 * sizeof(uint16_t);
1878 RTGCUINTPTR *pauSymOff = (RTGCUINTPTR *)RTMemTmpAllocZ(pThis->cKernelSymbols * sizeof(RTGCUINTPTR));
1879 uint32_t i;
1880
1881 for (i = 0; i < pThis->cKernelSymbols; i++)
1882 {
1883 RTGCUINTPTR uSymAddr = dbgDiggerLinuxConvOffsetToAddr(pThis, pai32Offsets[i]);
1884
1885 if ( uSymAddr < uKernelStart
1886 && (pThis->f64Bit ? LNX64_VALID_ADDRESS(uSymAddr) : LNX32_VALID_ADDRESS(uSymAddr))
1887 && uKernelStart - uSymAddr < LNX_MAX_KERNEL_SIZE)
1888 uKernelStart = uSymAddr;
1889 }
1890
1891 for (i = pThis->cKernelSymbols - 1; i > 0; i--)
1892 {
1893 RTGCUINTPTR uSymAddr = dbgDiggerLinuxConvOffsetToAddr(pThis, pai32Offsets[i]);
1894
1895 if ( uSymAddr > uKernelEnd
1896 && (pThis->f64Bit ? LNX64_VALID_ADDRESS(uSymAddr) : LNX32_VALID_ADDRESS(uSymAddr))
1897 && uSymAddr - uKernelEnd < LNX_MAX_KERNEL_SIZE)
1898 uKernelEnd = uSymAddr;
1899
1900 /* Store the offset from the derived kernel start address. */
1901 pauSymOff[i] = uSymAddr - uKernelStart;
1902 }
1903
1904 RTGCUINTPTR cbKernel = uKernelEnd - uKernelStart;
1905 pThis->cbKernel = (uint32_t)cbKernel;
1906 DBGFR3AddrFromFlat(pUVM, &pThis->AddrKernelBase, uKernelStart);
1907 Log(("dbgDiggerLinuxLoadKernelSymbolsRelative: uKernelStart=%RGv cbKernel=%#x\n", uKernelStart, cbKernel));
1908
1909 rc = dbgDiggerLinuxLoadKernelSymbolsWorker(pUVM, pThis, uKernelStart, cbKernel, pauSymOff);
1910 if (RT_FAILURE(rc))
1911 Log(("dbgDiggerLinuxLoadKernelSymbolsRelative: Loading symbols from given offset table failed: %Rrc\n", rc));
1912 RTMemTmpFree(pauSymOff);
1913 }
1914 else
1915 Log(("dbgDiggerLinuxLoadKernelSymbolsRelative: Reading symbol addresses at %RGv failed: %Rrc\n",
1916 pThis->AddrKernelAddresses.FlatPtr, rc));
1917 RTMemFree(pai32Offsets);
1918
1919 return rc;
1920}
1921
1922
1923/**
1924 * Loads the kernel symbols.
1925 *
1926 * @returns VBox status code.
1927 * @param pUVM The user mode VM handle.
1928 * @param pThis The Linux digger data.
1929 */
1930static int dbgDiggerLinuxLoadKernelSymbols(PUVM pUVM, PDBGDIGGERLINUX pThis)
1931{
1932 /*
1933 * First the kernel itself.
1934 */
1935 if (pThis->fRelKrnlAddr)
1936 return dbgDiggerLinuxLoadKernelSymbolsRelative(pUVM, pThis);
1937 return dbgDiggerLinuxLoadKernelSymbolsAbsolute(pUVM, pThis);
1938}
1939
1940
1941/*
1942 * The module structure changed it was easier to produce different code for
1943 * each version of the structure. The C preprocessor rules!
1944 */
1945#define LNX_TEMPLATE_HEADER "DBGPlugInLinuxModuleCodeTmpl.cpp.h"
1946
1947#define LNX_BIT_SUFFIX _amd64
1948#define LNX_PTR_T uint64_t
1949#define LNX_64BIT 1
1950#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"
1951
1952#define LNX_BIT_SUFFIX _x86
1953#define LNX_PTR_T uint32_t
1954#define LNX_64BIT 0
1955#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"
1956
1957#undef LNX_TEMPLATE_HEADER
1958
1959static const struct
1960{
1961 uint32_t uVersion;
1962 bool f64Bit;
1963 uint64_t (*pfnProcessModule)(PDBGDIGGERLINUX pThis, PUVM pUVM, PDBGFADDRESS pAddrModule);
1964} g_aModVersions[] =
1965{
1966#define LNX_TEMPLATE_HEADER "DBGPlugInLinuxModuleTableEntryTmpl.cpp.h"
1967
1968#define LNX_BIT_SUFFIX _amd64
1969#define LNX_64BIT 1
1970#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"
1971
1972#define LNX_BIT_SUFFIX _x86
1973#define LNX_64BIT 0
1974#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"
1975
1976#undef LNX_TEMPLATE_HEADER
1977};
1978
1979
1980/**
1981 * Tries to find and process the module list.
1982 *
1983 * @returns VBox status code.
1984 * @param pThis The Linux digger data.
1985 * @param pUVM The user mode VM handle.
1986 */
1987static int dbgDiggerLinuxLoadModules(PDBGDIGGERLINUX pThis, PUVM pUVM)
1988{
1989 /*
1990 * Locate the list head.
1991 */
1992 RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
1993 RTDBGSYMBOL SymInfo;
1994 int rc = RTDbgAsSymbolByName(hAs, "vmlinux!modules", &SymInfo, NULL);
1995 RTDbgAsRelease(hAs);
1996 if (RT_FAILURE(rc))
1997 return VERR_NOT_FOUND;
1998
1999 if (RT_FAILURE(rc))
2000 {
2001 LogRel(("dbgDiggerLinuxLoadModules: Failed to locate the module list (%Rrc).\n", rc));
2002 return VERR_NOT_FOUND;
2003 }
2004
2005 /*
2006 * Read the list anchor.
2007 */
2008 union
2009 {
2010 uint32_t volatile u32Pair[2];
2011 uint64_t u64Pair[2];
2012 } uListAnchor;
2013 DBGFADDRESS Addr;
2014 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, SymInfo.Value),
2015 &uListAnchor, pThis->f64Bit ? sizeof(uListAnchor.u64Pair) : sizeof(uListAnchor.u32Pair));
2016 if (RT_FAILURE(rc))
2017 {
2018 LogRel(("dbgDiggerLinuxLoadModules: Error reading list anchor at %RX64: %Rrc\n", SymInfo.Value, rc));
2019 return VERR_NOT_FOUND;
2020 }
2021 if (!pThis->f64Bit)
2022 {
2023 uListAnchor.u64Pair[1] = uListAnchor.u32Pair[1];
2024 ASMCompilerBarrier();
2025 uListAnchor.u64Pair[0] = uListAnchor.u32Pair[0];
2026 }
2027
2028 /*
2029 * Get a numerical version number.
2030 */
2031 char szVersion[256] = "Linux version 4.19.0";
2032 bool fValid = pThis->fValid;
2033 pThis->fValid = true;
2034 dbgDiggerLinuxQueryVersion(pUVM, pThis, szVersion, sizeof(szVersion));
2035 pThis->fValid = fValid;
2036
2037 const char *pszVersion = szVersion;
2038 while (*pszVersion && !RT_C_IS_DIGIT(*pszVersion))
2039 pszVersion++;
2040
2041 size_t offVersion = 0;
2042 uint32_t uMajor = 0;
2043 while (pszVersion[offVersion] && RT_C_IS_DIGIT(pszVersion[offVersion]))
2044 uMajor = uMajor * 10 + pszVersion[offVersion++] - '0';
2045
2046 if (pszVersion[offVersion] == '.')
2047 offVersion++;
2048
2049 uint32_t uMinor = 0;
2050 while (pszVersion[offVersion] && RT_C_IS_DIGIT(pszVersion[offVersion]))
2051 uMinor = uMinor * 10 + pszVersion[offVersion++] - '0';
2052
2053 if (pszVersion[offVersion] == '.')
2054 offVersion++;
2055
2056 uint32_t uBuild = 0;
2057 while (pszVersion[offVersion] && RT_C_IS_DIGIT(pszVersion[offVersion]))
2058 uBuild = uBuild * 10 + pszVersion[offVersion++] - '0';
2059
2060 uint32_t const uGuestVer = LNX_MK_VER(uMajor, uMinor, uBuild);
2061 if (uGuestVer == 0)
2062 {
2063 LogRel(("dbgDiggerLinuxLoadModules: Failed to parse version string: %s\n", pszVersion));
2064 return VERR_NOT_FOUND;
2065 }
2066
2067 /*
2068 * Find the g_aModVersion entry that fits the best.
2069 * ASSUMES strict descending order by bitcount and version.
2070 */
2071 Assert(g_aModVersions[0].f64Bit == true);
2072 unsigned i = 0;
2073 if (!pThis->f64Bit)
2074 while (i < RT_ELEMENTS(g_aModVersions) && g_aModVersions[i].f64Bit)
2075 i++;
2076 while ( i < RT_ELEMENTS(g_aModVersions)
2077 && g_aModVersions[i].f64Bit == pThis->f64Bit
2078 && uGuestVer < g_aModVersions[i].uVersion)
2079 i++;
2080 if (i >= RT_ELEMENTS(g_aModVersions))
2081 {
2082 LogRel(("dbgDiggerLinuxLoadModules: Failed to find anything matching version: %u.%u.%u (%s)\n",
2083 uMajor, uMinor, uBuild, pszVersion));
2084 return VERR_NOT_FOUND;
2085 }
2086
2087 /*
2088 * Walk the list.
2089 */
2090 uint64_t uModAddr = uListAnchor.u64Pair[0];
2091 for (size_t iModule = 0; iModule < 4096 && uModAddr != SymInfo.Value && uModAddr != 0; iModule++)
2092 uModAddr = g_aModVersions[i].pfnProcessModule(pThis, pUVM, DBGFR3AddrFromFlat(pUVM, &Addr, uModAddr));
2093
2094 return VINF_SUCCESS;
2095}
2096
2097
2098/**
2099 * Checks if there is a likely kallsyms_names fragment at pHitAddr.
2100 *
2101 * @returns true if it's a likely fragment, false if not.
2102 * @param pUVM The user mode VM handle.
2103 * @param pHitAddr The address where paNeedle was found.
2104 * @param pabNeedle The fragment we've been searching for.
2105 * @param cbNeedle The length of the fragment.
2106 */
2107static bool dbgDiggerLinuxIsLikelyNameFragment(PUVM pUVM, PCDBGFADDRESS pHitAddr, uint8_t const *pabNeedle, uint8_t cbNeedle)
2108{
2109 /*
2110 * Examples of lead and tail bytes of our choosen needle in a randomly
2111 * picked kernel:
2112 * k o b j
2113 * 22 6b 6f 62 6a aa
2114 * fc 6b 6f 62 6a aa
2115 * 82 6b 6f 62 6a 5f - ascii trail byte (_).
2116 * ee 6b 6f 62 6a aa
2117 * fc 6b 6f 62 6a 5f - ascii trail byte (_).
2118 * 0a 74 6b 6f 62 6a 5f ea - ascii lead (t) and trail (_) bytes.
2119 * 0b 54 6b 6f 62 6a aa - ascii lead byte (T).
2120 * ... omitting 29 samples similar to the last two ...
2121 * d8 6b 6f 62 6a aa
2122 * d8 6b 6f 62 6a aa
2123 * d8 6b 6f 62 6a aa
2124 * d8 6b 6f 62 6a aa
2125 * f9 5f 6b 6f 62 6a 5f 94 - ascii lead and trail bytes (_)
2126 * f9 5f 6b 6f 62 6a 0c - ascii lead byte (_).
2127 * fd 6b 6f 62 6a 0f
2128 * ... enough.
2129 */
2130 uint8_t abBuf[32];
2131 DBGFADDRESS ReadAddr = *pHitAddr;
2132 DBGFR3AddrSub(&ReadAddr, 2);
2133 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &ReadAddr, abBuf, 2 + cbNeedle + 2);
2134 if (RT_SUCCESS(rc))
2135 {
2136 if (memcmp(&abBuf[2], pabNeedle, cbNeedle) == 0) /* paranoia */
2137 {
2138 uint8_t const bLead = abBuf[1] == '_' || abBuf[1] == 'T' || abBuf[1] == 't' ? abBuf[0] : abBuf[1];
2139 uint8_t const offTail = 2 + cbNeedle;
2140 uint8_t const bTail = abBuf[offTail] == '_' ? abBuf[offTail] : abBuf[offTail + 1];
2141 if ( bLead >= 1 && (bLead < 0x20 || bLead >= 0x80)
2142 && bTail >= 1 && (bTail < 0x20 || bTail >= 0x80))
2143 return true;
2144 Log(("dbgDiggerLinuxIsLikelyNameFragment: failed at %RGv: bLead=%#x bTail=%#x (offTail=%#x)\n",
2145 pHitAddr->FlatPtr, bLead, bTail, offTail));
2146 }
2147 else
2148 Log(("dbgDiggerLinuxIsLikelyNameFragment: failed at %RGv: Needle changed!\n", pHitAddr->FlatPtr));
2149 }
2150 else
2151 Log(("dbgDiggerLinuxIsLikelyNameFragment: failed at %RGv: %Rrc\n", pHitAddr->FlatPtr, rc));
2152
2153 return false;
2154}
2155
2156/**
2157 * Tries to find and load the kernel symbol table with the given needle.
2158 *
2159 * @returns VBox status code.
2160 * @param pThis The Linux digger data.
2161 * @param pUVM The user mode VM handle.
2162 * @param pabNeedle The needle to use for searching.
2163 * @param cbNeedle Size of the needle in bytes.
2164 */
2165static int dbgDiggerLinuxFindSymbolTableFromNeedle(PDBGDIGGERLINUX pThis, PUVM pUVM, uint8_t const *pabNeedle, uint8_t cbNeedle)
2166{
2167 int rc = VINF_SUCCESS;
2168
2169 /*
2170 * Go looking for the kallsyms table. If it's there, it will be somewhere
2171 * after the linux_banner symbol, so use it for starting the search.
2172 */
2173 DBGFADDRESS CurAddr = pThis->AddrLinuxBanner;
2174 uint32_t cbLeft = LNX_MAX_KERNEL_SIZE;
2175 while (cbLeft > 4096)
2176 {
2177 DBGFADDRESS HitAddr;
2178 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &CurAddr, cbLeft, 1 /*uAlign*/,
2179 pabNeedle, cbNeedle, &HitAddr);
2180 if (RT_FAILURE(rc))
2181 break;
2182 if (dbgDiggerLinuxIsLikelyNameFragment(pUVM, &HitAddr, pabNeedle, cbNeedle))
2183 {
2184 /* There will be another hit near by. */
2185 DBGFR3AddrAdd(&HitAddr, 1);
2186 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &HitAddr, LNX_MAX_KALLSYMS_NAMES_SIZE, 1 /*uAlign*/,
2187 pabNeedle, cbNeedle, &HitAddr);
2188 if ( RT_SUCCESS(rc)
2189 && dbgDiggerLinuxIsLikelyNameFragment(pUVM, &HitAddr, pabNeedle, cbNeedle))
2190 {
2191 /*
2192 * We've got a very likely candidate for a location inside kallsyms_names.
2193 * Try find the start of it, that is to say, try find kallsyms_num_syms.
2194 * kallsyms_num_syms is aligned on sizeof(unsigned long) boundrary
2195 */
2196 rc = dbgDiggerLinuxFindStartOfNamesAndSymbolCount(pUVM, pThis, &HitAddr);
2197 if (RT_SUCCESS(rc))
2198 rc = dbgDiggerLinuxFindEndOfNamesAndMore(pUVM, pThis, &HitAddr);
2199 if (RT_SUCCESS(rc))
2200 rc = dbgDiggerLinuxFindTokenIndex(pUVM, pThis);
2201 if (RT_SUCCESS(rc))
2202 rc = dbgDiggerLinuxLoadKernelSymbols(pUVM, pThis);
2203 if (RT_SUCCESS(rc))
2204 {
2205 rc = dbgDiggerLinuxLoadModules(pThis, pUVM);
2206 break;
2207 }
2208 }
2209 }
2210
2211 /*
2212 * Advance.
2213 */
2214 RTGCUINTPTR cbDistance = HitAddr.FlatPtr - CurAddr.FlatPtr + cbNeedle;
2215 if (RT_UNLIKELY(cbDistance >= cbLeft))
2216 {
2217 Log(("dbgDiggerLinuxInit: Failed to find kallsyms\n"));
2218 break;
2219 }
2220 cbLeft -= cbDistance;
2221 DBGFR3AddrAdd(&CurAddr, cbDistance);
2222
2223 }
2224
2225 return rc;
2226}
2227
2228/**
2229 * Skips whitespace and comments in the given config returning the pointer
2230 * to the first non whitespace character.
2231 *
2232 * @returns Pointer to the first non whitespace character or NULL if the end
2233 * of the string was reached.
2234 * @param pszCfg The config string.
2235 */
2236static const char *dbgDiggerLinuxCfgSkipWhitespace(const char *pszCfg)
2237{
2238 do
2239 {
2240 while ( *pszCfg != '\0'
2241 && ( RT_C_IS_SPACE(*pszCfg)
2242 || *pszCfg == '\n'))
2243 pszCfg++;
2244
2245 /* Do we have a comment? Skip it. */
2246 if (*pszCfg == '#')
2247 {
2248 while ( *pszCfg != '\n'
2249 && *pszCfg != '\0')
2250 pszCfg++;
2251 }
2252 } while ( *pszCfg != '\0'
2253 && ( RT_C_IS_SPACE(*pszCfg)
2254 || *pszCfg == '\n'
2255 || *pszCfg == '#'));
2256
2257 return pszCfg;
2258}
2259
2260/**
2261 * Parses an identifier at the given position.
2262 *
2263 * @returns VBox status code.
2264 * @param pszCfg The config data.
2265 * @param ppszCfgNext Where to store the pointer to the data following the identifier.
2266 * @param ppszIde Where to store the pointer to the identifier on success.
2267 * Free with RTStrFree().
2268 */
2269static int dbgDiggerLinuxCfgParseIde(const char *pszCfg, const char **ppszCfgNext, char **ppszIde)
2270{
2271 int rc = VINF_SUCCESS;
2272 size_t cchIde = 0;
2273
2274 while ( *pszCfg != '\0'
2275 && ( RT_C_IS_ALNUM(*pszCfg)
2276 || *pszCfg == '_'))
2277 {
2278 cchIde++;
2279 pszCfg++;
2280 }
2281
2282 if (cchIde)
2283 {
2284 *ppszIde = RTStrDupN(pszCfg - cchIde, cchIde);
2285 if (!*ppszIde)
2286 rc = VERR_NO_STR_MEMORY;
2287 }
2288
2289 *ppszCfgNext = pszCfg;
2290 return rc;
2291}
2292
2293/**
2294 * Parses a value for a config item.
2295 *
2296 * @returns VBox status code.
2297 * @param pszCfg The config data.
2298 * @param ppszCfgNext Where to store the pointer to the data following the identifier.
2299 * @param ppCfgItem Where to store the created config item on success.
2300 */
2301static int dbgDiggerLinuxCfgParseVal(const char *pszCfg, const char **ppszCfgNext,
2302 PDBGDIGGERLINUXCFGITEM *ppCfgItem)
2303{
2304 int rc = VINF_SUCCESS;
2305 PDBGDIGGERLINUXCFGITEM pCfgItem = NULL;
2306
2307 if (RT_C_IS_DIGIT(*pszCfg) || *pszCfg == '-')
2308 {
2309 /* Parse the number. */
2310 int64_t i64Num;
2311 rc = RTStrToInt64Ex(pszCfg, (char **)ppszCfgNext, 0, &i64Num);
2312 if ( RT_SUCCESS(rc)
2313 || rc == VWRN_TRAILING_CHARS
2314 || rc == VWRN_TRAILING_SPACES)
2315 {
2316 pCfgItem = (PDBGDIGGERLINUXCFGITEM)RTMemAllocZ(sizeof(DBGDIGGERLINUXCFGITEM));
2317 if (pCfgItem)
2318 {
2319 pCfgItem->enmType = DBGDIGGERLINUXCFGITEMTYPE_NUMBER;
2320 pCfgItem->u.i64Num = i64Num;
2321 }
2322 else
2323 rc = VERR_NO_MEMORY;
2324 }
2325 }
2326 else if (*pszCfg == '\"')
2327 {
2328 /* Parse a string. */
2329 const char *pszCfgCur = pszCfg + 1;
2330 while ( *pszCfgCur != '\0'
2331 && *pszCfgCur != '\"')
2332 pszCfgCur++;
2333
2334 if (*pszCfgCur == '\"')
2335 {
2336 pCfgItem = (PDBGDIGGERLINUXCFGITEM)RTMemAllocZ(RT_UOFFSETOF_DYN(DBGDIGGERLINUXCFGITEM,
2337 u.aszString[pszCfgCur - pszCfg + 1]));
2338 if (pCfgItem)
2339 {
2340 pCfgItem->enmType = DBGDIGGERLINUXCFGITEMTYPE_STRING;
2341 RTStrCopyEx(&pCfgItem->u.aszString[0], pszCfgCur - pszCfg + 1, pszCfg, pszCfgCur - pszCfg);
2342 *ppszCfgNext = pszCfgCur + 1;
2343 }
2344 else
2345 rc = VERR_NO_MEMORY;
2346 }
2347 else
2348 rc = VERR_INVALID_STATE;
2349 }
2350 else if ( *pszCfg == 'y'
2351 || *pszCfg == 'm')
2352 {
2353 /* Included or module. */
2354 pCfgItem = (PDBGDIGGERLINUXCFGITEM)RTMemAllocZ(sizeof(DBGDIGGERLINUXCFGITEM));
2355 if (pCfgItem)
2356 {
2357 pCfgItem->enmType = DBGDIGGERLINUXCFGITEMTYPE_FLAG;
2358 pCfgItem->u.fModule = *pszCfg == 'm';
2359 }
2360 else
2361 rc = VERR_NO_MEMORY;
2362 pszCfg++;
2363 *ppszCfgNext = pszCfg;
2364 }
2365 else
2366 rc = VERR_INVALID_STATE;
2367
2368 if (RT_SUCCESS(rc))
2369 *ppCfgItem = pCfgItem;
2370 else if (pCfgItem)
2371 RTMemFree(pCfgItem);
2372
2373 return rc;
2374}
2375
2376/**
2377 * Parses the given kernel config and creates the config database.
2378 *
2379 * @returns VBox status code
2380 * @param pThis The Linux digger data.
2381 * @param pszCfg The config string.
2382 */
2383static int dbgDiggerLinuxCfgParse(PDBGDIGGERLINUX pThis, const char *pszCfg)
2384{
2385 int rc = VINF_SUCCESS;
2386
2387 /*
2388 * The config is a text file with the following elements:
2389 * # starts a comment which goes till the end of the line
2390 * <Ide>=<val> where <Ide> is an identifier consisting of
2391 * alphanumerical characters (including _)
2392 * <val> denotes the value for the identifier and can have the following
2393 * formats:
2394 * (-)[0-9]* for numbers
2395 * "..." for a string value
2396 * m when a feature is enabled as a module
2397 * y when a feature is enabled
2398 * Newlines are used as a separator between values and mark the end
2399 * of a comment
2400 */
2401 const char *pszCfgCur = pszCfg;
2402 while ( RT_SUCCESS(rc)
2403 && *pszCfgCur != '\0')
2404 {
2405 /* Start skipping the whitespace. */
2406 pszCfgCur = dbgDiggerLinuxCfgSkipWhitespace(pszCfgCur);
2407 if ( pszCfgCur
2408 && *pszCfgCur != '\0')
2409 {
2410 char *pszIde = NULL;
2411 /* Must be an identifier, parse it. */
2412 rc = dbgDiggerLinuxCfgParseIde(pszCfgCur, &pszCfgCur, &pszIde);
2413 if (RT_SUCCESS(rc))
2414 {
2415 /*
2416 * Skip whitespace again (shouldn't be required because = follows immediately
2417 * in the observed configs).
2418 */
2419 pszCfgCur = dbgDiggerLinuxCfgSkipWhitespace(pszCfgCur);
2420 if ( pszCfgCur
2421 && *pszCfgCur == '=')
2422 {
2423 pszCfgCur++;
2424 pszCfgCur = dbgDiggerLinuxCfgSkipWhitespace(pszCfgCur);
2425 if ( pszCfgCur
2426 && *pszCfgCur != '\0')
2427 {
2428 /* Get the value. */
2429 PDBGDIGGERLINUXCFGITEM pCfgItem = NULL;
2430 rc = dbgDiggerLinuxCfgParseVal(pszCfgCur, &pszCfgCur, &pCfgItem);
2431 if (RT_SUCCESS(rc))
2432 {
2433 pCfgItem->Core.pszString = pszIde;
2434 bool fRc = RTStrSpaceInsert(&pThis->hCfgDb, &pCfgItem->Core);
2435 if (!fRc)
2436 {
2437 RTStrFree(pszIde);
2438 RTMemFree(pCfgItem);
2439 rc = VERR_INVALID_STATE;
2440 }
2441 }
2442 }
2443 else
2444 rc = VERR_EOF;
2445 }
2446 else
2447 rc = VERR_INVALID_STATE;
2448 }
2449
2450 if (RT_FAILURE(rc))
2451 RTStrFree(pszIde);
2452 }
2453 else
2454 break; /* Reached the end of the config. */
2455 }
2456
2457 if (RT_FAILURE(rc))
2458 dbgDiggerLinuxCfgDbDestroy(pThis);
2459
2460 return rc;
2461}
2462
2463/**
2464 * Decompresses the given config and validates the UTF-8 encoding.
2465 *
2466 * @returns VBox status code.
2467 * @param pbCfgComp The compressed config.
2468 * @param cbCfgComp Size of the compressed config.
2469 * @param ppszCfg Where to store the pointer to the decompressed config
2470 * on success.
2471 */
2472static int dbgDiggerLinuxCfgDecompress(const uint8_t *pbCfgComp, size_t cbCfgComp, char **ppszCfg)
2473{
2474 int rc = VINF_SUCCESS;
2475 RTVFSIOSTREAM hVfsIos = NIL_RTVFSIOSTREAM;
2476
2477 rc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pbCfgComp, cbCfgComp, &hVfsIos);
2478 if (RT_SUCCESS(rc))
2479 {
2480 RTVFSIOSTREAM hVfsIosDecomp = NIL_RTVFSIOSTREAM;
2481 rc = RTZipGzipDecompressIoStream(hVfsIos, RTZIPGZIPDECOMP_F_ALLOW_ZLIB_HDR, &hVfsIosDecomp);
2482 if (RT_SUCCESS(rc))
2483 {
2484 char *pszCfg = NULL;
2485 size_t cchCfg = 0;
2486 size_t cbRead = 0;
2487
2488 do
2489 {
2490 uint8_t abBuf[_64K];
2491 rc = RTVfsIoStrmRead(hVfsIosDecomp, abBuf, sizeof(abBuf), true /*fBlocking*/, &cbRead);
2492 if (rc == VINF_EOF && cbRead == 0)
2493 rc = VINF_SUCCESS;
2494 if ( RT_SUCCESS(rc)
2495 && cbRead > 0)
2496 {
2497 /* Append data. */
2498 char *pszCfgNew = pszCfg;
2499 rc = RTStrRealloc(&pszCfgNew, cchCfg + cbRead + 1);
2500 if (RT_SUCCESS(rc))
2501 {
2502 pszCfg = pszCfgNew;
2503 memcpy(pszCfg + cchCfg, &abBuf[0], cbRead);
2504 cchCfg += cbRead;
2505 pszCfg[cchCfg] = '\0'; /* Enforce string termination. */
2506 }
2507 }
2508 } while (RT_SUCCESS(rc) && cbRead > 0);
2509
2510 if (RT_SUCCESS(rc))
2511 *ppszCfg = pszCfg;
2512 else if (RT_FAILURE(rc) && pszCfg)
2513 RTStrFree(pszCfg);
2514
2515 RTVfsIoStrmRelease(hVfsIosDecomp);
2516 }
2517 RTVfsIoStrmRelease(hVfsIos);
2518 }
2519
2520 return rc;
2521}
2522
2523/**
2524 * Reads and decodes the compressed kernel config.
2525 *
2526 * @returns VBox status code.
2527 * @param pThis The Linux digger data.
2528 * @param pUVM The user mode VM handle.
2529 * @param pAddrStart The start address of the compressed config.
2530 * @param cbCfgComp The size of the compressed config.
2531 */
2532static int dbgDiggerLinuxCfgDecode(PDBGDIGGERLINUX pThis, PUVM pUVM,
2533 PCDBGFADDRESS pAddrStart, size_t cbCfgComp)
2534{
2535 int rc = VINF_SUCCESS;
2536 uint8_t *pbCfgComp = (uint8_t *)RTMemTmpAlloc(cbCfgComp);
2537 if (!pbCfgComp)
2538 return VERR_NO_MEMORY;
2539
2540 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, pAddrStart, pbCfgComp, cbCfgComp);
2541 if (RT_SUCCESS(rc))
2542 {
2543 char *pszCfg = NULL;
2544 rc = dbgDiggerLinuxCfgDecompress(pbCfgComp, cbCfgComp, &pszCfg);
2545 if (RT_SUCCESS(rc))
2546 {
2547 if (RTStrIsValidEncoding(pszCfg))
2548 rc = dbgDiggerLinuxCfgParse(pThis, pszCfg);
2549 else
2550 rc = VERR_INVALID_UTF8_ENCODING;
2551 RTStrFree(pszCfg);
2552 }
2553 }
2554
2555 RTMemFree(pbCfgComp);
2556 return rc;
2557}
2558
2559/**
2560 * Tries to find the compressed kernel config in the kernel address space
2561 * and sets up the config database.
2562 *
2563 * @returns VBox status code.
2564 * @param pThis The Linux digger data.
2565 * @param pUVM The user mode VM handle.
2566 */
2567static int dbgDiggerLinuxCfgFind(PDBGDIGGERLINUX pThis, PUVM pUVM)
2568{
2569 int rc = VINF_SUCCESS;
2570
2571 /*
2572 * Go looking for the IKCFG_ST string which indicates the start
2573 * of the compressed config file.
2574 */
2575 static const uint8_t s_abCfgNeedleStart[] = "IKCFG_ST";
2576 static const uint8_t s_abCfgNeedleEnd[] = "IKCFG_ED";
2577 DBGFADDRESS CurAddr = pThis->AddrLinuxBanner;
2578 uint32_t cbLeft = LNX_MAX_KERNEL_SIZE;
2579 while (cbLeft > 4096)
2580 {
2581 DBGFADDRESS HitAddrStart;
2582 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &CurAddr, cbLeft, 1 /*uAlign*/,
2583 s_abCfgNeedleStart, sizeof(s_abCfgNeedleStart) - 1, &HitAddrStart);
2584 if (RT_FAILURE(rc))
2585 break;
2586
2587 /* Check for the end marker which shouldn't be that far away. */
2588 DBGFR3AddrAdd(&HitAddrStart, sizeof(s_abCfgNeedleStart) - 1);
2589 DBGFADDRESS HitAddrEnd;
2590 rc = DBGFR3MemScan(pUVM, 0 /* idCpu */, &HitAddrStart, LNX_MAX_COMPRESSED_CFG_SIZE,
2591 1 /* uAlign */, s_abCfgNeedleEnd, sizeof(s_abCfgNeedleEnd) - 1, &HitAddrEnd);
2592 if (RT_SUCCESS(rc))
2593 {
2594 /* Allocate a buffer to hold the compressed data between the markers and fetch it. */
2595 RTGCUINTPTR cbCfg = HitAddrEnd.FlatPtr - HitAddrStart.FlatPtr;
2596 Assert(cbCfg == (size_t)cbCfg);
2597 rc = dbgDiggerLinuxCfgDecode(pThis, pUVM, &HitAddrStart, cbCfg);
2598 if (RT_SUCCESS(rc))
2599 break;
2600 }
2601
2602 /*
2603 * Advance.
2604 */
2605 RTGCUINTPTR cbDistance = HitAddrStart.FlatPtr - CurAddr.FlatPtr + sizeof(s_abCfgNeedleStart) - 1;
2606 if (RT_UNLIKELY(cbDistance >= cbLeft))
2607 {
2608 LogFunc(("Failed to find compressed kernel config\n"));
2609 break;
2610 }
2611 cbLeft -= cbDistance;
2612 DBGFR3AddrAdd(&CurAddr, cbDistance);
2613
2614 }
2615
2616 return rc;
2617}
2618
2619/**
2620 * Probes for a Linux kernel starting at the given address.
2621 *
2622 * @returns Flag whether something which looks like a valid Linux kernel was found.
2623 * @param pThis The Linux digger data.
2624 * @param pUVM The user mode VM handle.
2625 * @param uAddrStart The address to start scanning at.
2626 * @param cbScan How much to scan.
2627 */
2628static bool dbgDiggerLinuxProbeWithAddr(PDBGDIGGERLINUX pThis, PUVM pUVM, RTGCUINTPTR uAddrStart, size_t cbScan)
2629{
2630 /*
2631 * Look for "Linux version " at the start of the rodata segment.
2632 * Hope that this comes before any message buffer or other similar string.
2633 */
2634 DBGFADDRESS KernelAddr;
2635 DBGFR3AddrFromFlat(pUVM, &KernelAddr, uAddrStart);
2636 DBGFADDRESS HitAddr;
2637 int rc = DBGFR3MemScan(pUVM, 0, &KernelAddr, cbScan, 1,
2638 g_abLinuxVersion, sizeof(g_abLinuxVersion) - 1, &HitAddr);
2639 if (RT_SUCCESS(rc))
2640 {
2641 char szTmp[128];
2642 char const *pszX = &szTmp[sizeof(g_abLinuxVersion) - 1];
2643 rc = DBGFR3MemReadString(pUVM, 0, &HitAddr, szTmp, sizeof(szTmp));
2644 if ( RT_SUCCESS(rc)
2645 && ( ( pszX[0] == '2' /* 2.x.y with x in {0..6} */
2646 && pszX[1] == '.'
2647 && pszX[2] >= '0'
2648 && pszX[2] <= '6')
2649 || ( pszX[0] >= '3' /* 3.x, 4.x, ... 9.x */
2650 && pszX[0] <= '9'
2651 && pszX[1] == '.'
2652 && pszX[2] >= '0'
2653 && pszX[2] <= '9')
2654 )
2655 )
2656 {
2657 pThis->AddrKernelBase = KernelAddr;
2658 pThis->AddrLinuxBanner = HitAddr;
2659 return true;
2660 }
2661 }
2662
2663 return false;
2664}
2665
2666/**
2667 * Probes for a Linux kernel which has KASLR enabled.
2668 *
2669 * @returns Flag whether a possible candidate location was found.
2670 * @param pThis The Linux digger data.
2671 * @param pUVM The user mode VM handle.
2672 * @param uAddrKernelStart The first address the kernel is expected at.
2673 */
2674static bool dbgDiggerLinuxProbeKaslr(PDBGDIGGERLINUX pThis, PUVM pUVM, RTGCUINTPTR uAddrKernelStart)
2675{
2676 /**
2677 * With KASLR the kernel is loaded at a different address at each boot making detection
2678 * more difficult for us.
2679 *
2680 * The randomization is done in arch/x86/boot/compressed/kaslr.c:choose_random_location() (as of Nov 2017).
2681 * At the end of the method a random offset is chosen using find_random_virt_addr() which is added to the
2682 * kernel map start in the caller (the start of the kernel depends on the bit size, see LNX32_KERNEL_ADDRESS_START
2683 * and LNX64_KERNEL_ADDRESS_START for 32bit and 64bit kernels respectively).
2684 * The lowest offset possible is LOAD_PHYSICAL_ADDR which is defined in arch/x86/include/asm/boot.h
2685 * using CONFIG_PHYSICAL_START aligned to CONFIG_PHYSICAL_ALIGN.
2686 * The default CONFIG_PHYSICAL_START and CONFIG_PHYSICAL_ALIGN are both 0x1000000 no matter whether a 32bit
2687 * or a 64bit kernel is used. So the lowest offset to the kernel start address is 0x1000000.
2688 * The find_random_virt_addr() the number of possible slots where the kernel can be placed based on the image size
2689 * is calculated using the following formula:
2690 * cSlots = ((KERNEL_IMAGE_SIZE - 0x1000000 (minimum) - image_size) / 0x1000000 (CONFIG_PHYSICAL_ALIGN)) + 1
2691 *
2692 * KERNEL_IMAGE_SIZE is 1GB for 64bit kernels and 512MB for 32bit kernels, so the maximum number of slots (resulting
2693 * in the largest possible offset) can be achieved when image_size (which contains the real size of the kernel image
2694 * which is unknown for us) goes to 0 and a 1GB KERNEL_IMAGE_SIZE is assumed. With that the biggest cSlots which can be
2695 * achieved is 64. The chosen random offset is taken from a random long integer using kaslr_get_random_long() modulo the
2696 * number of slots which selects a slot between 0 and 63. The final offset is calculated using:
2697 * offAddr = random_addr * 0x1000000 (CONFIG_PHYSICAL_ALIGN) + 0x1000000 (minimum)
2698 *
2699 * So the highest offset the kernel can start is 0x40000000 which is 1GB (plus the maximum kernel size we defined).
2700 */
2701 if (dbgDiggerLinuxProbeWithAddr(pThis, pUVM, uAddrKernelStart, _1G + LNX_MAX_KERNEL_SIZE))
2702 return true;
2703
2704 return false;
2705}
2706
2707/**
2708 * @copydoc DBGFOSREG::pfnInit
2709 */
2710static DECLCALLBACK(int) dbgDiggerLinuxInit(PUVM pUVM, void *pvData)
2711{
2712 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
2713 Assert(!pThis->fValid);
2714
2715 /*
2716 * Assume 64-bit kernels all live way beyond 32-bit address space.
2717 */
2718 pThis->f64Bit = pThis->AddrLinuxBanner.FlatPtr > UINT32_MAX;
2719 pThis->fRelKrnlAddr = false;
2720
2721 pThis->hCfgDb = NULL;
2722
2723 /*
2724 * Try to find the compressed kernel config and parse it before we try
2725 * to get the symbol table, the config database is required to select
2726 * the method to use.
2727 */
2728 int rc = dbgDiggerLinuxCfgFind(pThis, pUVM);
2729 if (RT_FAILURE(rc))
2730 LogFlowFunc(("Failed to find kernel config (%Rrc), no config database available\n", rc));
2731
2732 static const uint8_t s_abNeedle[] = "kobj";
2733 rc = dbgDiggerLinuxFindSymbolTableFromNeedle(pThis, pUVM, s_abNeedle, sizeof(s_abNeedle) - 1);
2734 if (RT_FAILURE(rc))
2735 {
2736 /* Try alternate needle (seen on older x86 Linux kernels). */
2737 static const uint8_t s_abNeedleAlt[] = "kobjec";
2738 rc = dbgDiggerLinuxFindSymbolTableFromNeedle(pThis, pUVM, s_abNeedleAlt, sizeof(s_abNeedleAlt) - 1);
2739 if (RT_FAILURE(rc))
2740 {
2741 static const uint8_t s_abNeedleOSuseX86[] = "nmi"; /* OpenSuSe 10.2 x86 */
2742 rc = dbgDiggerLinuxFindSymbolTableFromNeedle(pThis, pUVM, s_abNeedleOSuseX86, sizeof(s_abNeedleOSuseX86) - 1);
2743 }
2744 }
2745
2746 pThis->fValid = true;
2747 return VINF_SUCCESS;
2748}
2749
2750
2751/**
2752 * @copydoc DBGFOSREG::pfnProbe
2753 */
2754static DECLCALLBACK(bool) dbgDiggerLinuxProbe(PUVM pUVM, void *pvData)
2755{
2756 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
2757
2758 for (unsigned i = 0; i < RT_ELEMENTS(g_au64LnxKernelAddresses); i++)
2759 {
2760 if (dbgDiggerLinuxProbeWithAddr(pThis, pUVM, g_au64LnxKernelAddresses[i], LNX_MAX_KERNEL_SIZE))
2761 return true;
2762 }
2763
2764 /* Maybe the kernel uses KASLR. */
2765 if (dbgDiggerLinuxProbeKaslr(pThis, pUVM, LNX32_KERNEL_ADDRESS_START))
2766 return true;
2767
2768 if (dbgDiggerLinuxProbeKaslr(pThis, pUVM, LNX64_KERNEL_ADDRESS_START))
2769 return true;
2770
2771 return false;
2772}
2773
2774
2775/**
2776 * @copydoc DBGFOSREG::pfnDestruct
2777 */
2778static DECLCALLBACK(void) dbgDiggerLinuxDestruct(PUVM pUVM, void *pvData)
2779{
2780 RT_NOREF2(pUVM, pvData);
2781}
2782
2783
2784/**
2785 * @copydoc DBGFOSREG::pfnConstruct
2786 */
2787static DECLCALLBACK(int) dbgDiggerLinuxConstruct(PUVM pUVM, void *pvData)
2788{
2789 RT_NOREF1(pUVM);
2790 PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
2791 pThis->IDmesg.u32Magic = DBGFOSIDMESG_MAGIC;
2792 pThis->IDmesg.pfnQueryKernelLog = dbgDiggerLinuxIDmsg_QueryKernelLog;
2793 pThis->IDmesg.u32EndMagic = DBGFOSIDMESG_MAGIC;
2794
2795 return VINF_SUCCESS;
2796}
2797
2798
2799const DBGFOSREG g_DBGDiggerLinux =
2800{
2801 /* .u32Magic = */ DBGFOSREG_MAGIC,
2802 /* .fFlags = */ 0,
2803 /* .cbData = */ sizeof(DBGDIGGERLINUX),
2804 /* .szName = */ "Linux",
2805 /* .pfnConstruct = */ dbgDiggerLinuxConstruct,
2806 /* .pfnDestruct = */ dbgDiggerLinuxDestruct,
2807 /* .pfnProbe = */ dbgDiggerLinuxProbe,
2808 /* .pfnInit = */ dbgDiggerLinuxInit,
2809 /* .pfnRefresh = */ dbgDiggerLinuxRefresh,
2810 /* .pfnTerm = */ dbgDiggerLinuxTerm,
2811 /* .pfnQueryVersion = */ dbgDiggerLinuxQueryVersion,
2812 /* .pfnQueryInterface = */ dbgDiggerLinuxQueryInterface,
2813 /* .pfnStackUnwindAssist = */ dbgDiggerLinuxStackUnwindAssist,
2814 /* .u32EndMagic = */ DBGFOSREG_MAGIC
2815};
2816
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