问题描述
有没有办法在 gdb 中定义新的数据类型(C 结构或联合).这个想法是定义一个结构,然后让 gdb 从解释为新定义的结构的地址打印数据.
Is there a way to define a new data type (C structure or union) in gdb. The idea is to define a structure and then make gdb print data from an address interpreted as the newly defined structure.
例如,假设我们有一个示例结构.
For example, lets say we have a sample structure.
struct sample {
int i;
struct sample *less;
struct sample *more;
}
如果 0x804b320 是 struct sample
数组的地址.该二进制文件没有调试信息,因此 gdb 可以理解 struct sample
.有什么方法可以在 gdb 会话中定义 struct sample
吗?这样我们就可以打印 p *(struct sample *)0x804b320
And if 0x804b320 is the address of an array of struct sample
. The binary doesn't have debugging information so that gdb understands struct sample
. Is there any way to define struct sample
in a gdb session? So that we can print p *(struct sample *)0x804b320
推荐答案
是的,这里是如何做到这一点的:
Yes, here is how to make this work:
// 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
", &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
:
No local variables, no type 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}
瞧!
这篇关于我们可以在 GDB 会话中定义新的数据类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!