2011-09-01 73 views
24

有沒有辦法在gdb中定義新的數據類型(C結構或聯合)?這個想法是定義一個結構,然後從一個解釋爲新定義結構的地址創建gdb打印數據。我們可以在GDB會話中定義新的數據類型嗎

例如,假設我們有一個樣本結構。

struct sample { 
    int i; 
    struct sample *less; 
    struct sample *more; 
} 

並且如果0x804b320是struct sample的數組的地址。該二進制文件沒有調試信息,因此gdb可以理解struct sample。有沒有什麼辦法在gdb會話中定義struct sample?這樣我們就可以打印p *(struct sample *)0x804b320

回答

38

是的,這裏是如何使這項工作:

// sample.h 
struct sample { 
    int i; 
    struct sample *less; 
    struct sample *more; 
}; 

// main.c 
#include <stdio.h> 
#include <assert.h> 
#include "sample.h" 
int main() 
{ 
    struct sample sm; 
    sm.i = 42; 
    sm.less = sm.more = &sm; 

    printf("&sm = %p\n", &sm); 
    assert(sm.i == 0); // will fail 
} 

gcc main.c # Note: no '-g' flag 

gdb -q ./a.out 
(gdb) run 
&sm = 0x7fffffffd6b0 
a.out: main.c:11: main: Assertion `sm.i == 0' failed. 

Program received signal SIGABRT, Aborted. 
0x00007ffff7a8da75 in raise() 
(gdb) fr 3 
#3 0x00000000004005cc in main() 

沒有局部變量,沒有類型struct sample

(gdb) p sm 
No symbol "sm" in current context. 
(gdb) p (struct sample *)0x7fffffffd6b0 
No struct type named sample. 

所以我們開始工作:

// sample.c 
#include "sample.h" 
struct sample foo; 

gcc -g -c sample.c 

(gdb) add-symbol-file sample.o 0 
add symbol table from file "sample.o" at 
    .text_addr = 0x0 

(gdb) p (struct sample *)0x7fffffffd6b0 
$1 = (struct sample *) 0x7fffffffd6b0 
(gdb) p *$1 
$2 = {i = 42, less = 0x7fffffffd6b0, more = 0x7fffffffd6b0} 

Voilà!

+1

鬼鬼祟祟。我喜歡。 –

相關問題