Rijul Gupta
Rijul Gupta

Reputation: 1171

How to read .rodata from linked object files?

I am trying to access an externally linked data segment in a C/C++ program.

#include <iostream>

extern void *__foo;

int main(int argc, char **argv)
{
    const char *foo = reinterpret_cast<const char *>(__foo);
    std::cout << std::addressof(foo) << std::endl;
    std::cout << foo[0] << std::endl;
    return 0;
}

The symbol table obtained with objdump -t bar.o has the following

0000000000000000 g O .rodata 0000000000004d05 __foo

And symbol table of executable after compiling has the following

000000000004a9c1 g O .rodata 0000000000004d05 __foo

After compiling and executing the program I recieve the following results

0x7ffe616dbb30
Segmentation fault (core dumped)

Valgrind provides the following output

0x1ffefffec0
==14359== Invalid read of size 1
==14359==    at 0x11B5CF: main (main.cc:9)
==14359==  Address 0x4cfd is not stack'd, malloc'd or (recently) free'd
==14359== 
==14359== 

The valgrind error makes sense as the data section is indeed not allocated by the program, but since I am only trying to read the data I believe I should be able to access it.

How can I read this data section?

Upvotes: 0

Views: 294

Answers (1)

user14215102
user14215102

Reputation:

It appears that whatever __foo contains, it is not a valid pointer. If you are interested in the contents of __foo itself, declare it as extern char __foo[] and dump that.

Upvotes: 1

Related Questions