如何获取结构转储中字段的相对地址。 [C] [英] How to get the relative address of a field in a structure dump. [C]

查看:95
本文介绍了如何获取结构转储中字段的相对地址。 [C]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在研究在Linux下使用arm-eabi-gcc编译的C程序。

We're working on a C program compiled with arm-eabi-gcc under Linux.

我们正在使用大型结构的转储,并且在确定应读取哪种地址(例如其中的50个)时遇到问题, (对我而言,内存对齐和填充不是那么可预测的。)

We're using a dump of a large structure and we're having problems determining at which adress we should read various fields of our structure (like 50 of them), (memory alignement and padding aren't so predictable to me).

有没有办法获取编译器生成的结构的内存映射。 gdb中的一个选项?还是有任何工具可以帮助我们找到转储中字段和地址之间的对应关系?

Is there any way to get the memory mapping of the structure produced by a our compiler. An option in gdb? Or any tool helping us find the correspondance between fields and adress in the dump?

推荐答案

您可以使用 gdb 来完成。例如,我将使用以下来源:

You can do it with gdb. As an example, I'll use this source:

struct A {
  int a;
  char b;
  short c;
};

int main() {
  struct A a;
}

gdb

(gdb) print (int)&((struct A*)0)->a
$1 = 0
(gdb) print (int)&((struct A*)0)->b
$2 = 4
(gdb) print (int)&((struct A*)0)->c
$3 = 6

更新:

如果您需要对大量字段进行操作,那么使用GDB的新python接口(您可能会很方便)需要使用最新版本的GDB才能使用,我使用的是7.4)。我已经创建了offsets.py:

If you need to do it for a large number of fields, then you may find it handy to use GDB's new python interface (you'll need a recent version of GDB to use it, I'm using 7.4). I've created offsets.py:

import gdb

class Offsets(gdb.Command):
    def __init__(self):
        super (Offsets, self).__init__ ('offsets-of', gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            raise gdb.GdbError('offsets-of takes exactly 1 argument.')

        stype = gdb.lookup_type(argv[0])

        print argv[0], '{'
        for field in stype.fields():
            print '    %s => %d' % (field.name, field.bitpos//8)
        print '}'

Offsets()

然后您可以添加到.gdbinit中:

Then you can add to your .gdbinit:

python
sys.path.insert(0, '/path/to/script/dir')
import offsets
end

然后在GDB中使用它,例如:

Then using it in GDB, like:

(gdb) offsets-of "struct A"
struct A {
    a => 0
    b => 4
    c => 6
}

此脚本做出了一些简化的假设,例如您没有使用位字段,并且它不会挖掘嵌套的结构,但是如果需要,这些更改非常简单。

This script makes a few simplifying assumptions, like that you don't use bitfields, and it doesn't dig into nested structs, but those changes are3 fairly straightforward if you need them.

这篇关于如何获取结构转储中字段的相对地址。 [C]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆