0

我正在处理调试信息。我正在尝试编写类似于“调试信息解析器”的方式,我正在使用 DWARF 和 ELF 库来执行此操作,但是除了内存空间的信息之外,它们不提供任何东西,我正在尝试获取该内存空间中的数据. 我迷上了这个程序。我正在使用一个名为 Pin 的工具,所以我实际上是在另一个程序中运行代码。这就是为什么我可以访问它的变量。

假设我有一个指向地址的指针,我想获取存储在该地址中的所有数据以及接下来的 4 个字节(例如)。

例如,假设我有一个地址 0xDEADBEEF,我想从该地址开始遍历接下来的 4 个字节并读取数据(取消引用每个字节上的指针)

我对 C 比较陌生,我想做的是:

char * address = "0xDEADBEEF";
unsigned int bytesize = 4;

ptr = (void *) address;
ptr_limit = ptr + bytesize;

for(ptr; ptr < ptr_limit; ptr++)
     cout << ptr;

我知道这可能是完全错误的,并且我遇到了很多编译错误,但这只是为了展示我正在尝试使用的一些逻辑......

4

4 回答 4

7

OK, C and C++ are low level, but they aren't the wild west. You aren't allowed to just make up an address and access it. You aren't allowed to do that in assembly on most OSs; this is where SegFaults come from.

The way you get memory is to allocate it. This process involves telling the OS that you want a piece of memory of some size. At which point, the OS does its stuff so that you can access a certain range of virtual memory. Attempts to access memory outside of this range (or any range that the OS has allowed you to access) will cause the OS to terminate your program.

In C, you generally use malloc/calloc/realloc to allocate memory and free to tell the OS that you're done with it. C++ uses new to allocate objects and delete to deallocate them.

I am trying to write kind of like a "debug information parser", I am using DWARF and ELF libraries to do this, but they do not offer anything besides information of the memory space, I am trying to get the data in that memory space

It'd be great if you put things like that in your question.

In any case, you're talking about accessing someone else's memory, which is not done. Well, it's not permitted by the rules of standard C and C++. The various OSs have calls that can allow you to map some address space of another processes onto yours. But that's much more complex and OS-specific.

于 2012-09-24T23:38:20.170 回答
1

内存地址是整数类型(读取数字)。
在您的示例中,您有一个char *(读取字符串)。

以下代码:

char * address = "0xDEADBEEF";
void * ptr     = ( void * )address;

只会将该char *变量的地址作为 avoid *放入p.
它不会将指针设置为内存地址0xDEADBEEF

如果你想访问那个特定的内存位置(假设你知道你在做什么),你需要类似的东西:

void * ptr = ( void * )0xDEADBEEF;

我说“假设你知道你在做什么”,因为访问这样一个特定地址最终会导致段错误,因为你基本上不知道这样一个地址在你的地址空间中,除非你在环 0 中做事(读取内核),例如,使用 DMA。
但是我会假设你知道指针是一个数字,而不是一个字符串......

于 2012-09-24T23:41:05.080 回答
0

代码可以很简单:

char *address, *limit;

for(address = (char *)0xdeadbeef, limit = address+4; address < limit; address++)
     cout << *address;

但是请注意,虽然允许将任意整数转换为地址,但使用结果指针的结果不是(甚至接近于)可移植的。根据您的评论(您通过调试信息获取地址),因此您获得的地址应该是有效的,结果应该正常工作(只是不能保证它是可移植的)。

于 2012-09-24T23:43:58.447 回答
0

将您的地址存储为 DWORD =>DWORD address = 0xDEADBEEF 然后将此地址转换为指针 =>void *ptr = (void *)address

这是一个例子:

char *pointer = "FOO";
DWORD address = (DWORD)pointer;
printf("0x%u\n", address);
printf("%s\n", (char *)address); // prints FOO

address++; //move 1 byte
printf("%s\n", (char *)address); // prints OO
于 2012-09-24T23:46:45.993 回答