How can I get the _GLOBAL_OFFSET_TABLE_ address in

2020-07-18 09:56发布

问题:

I want to get the address of _GLOBAL_OFFSET_TABLE_ in my program. One way is to use the nm command in Linux, maybe redirect the output to a file and parse that file to get address of _GLOBAL_OFFSET_TABLE_. However, that method seems to be quite inefficient. What are some more efficient methods of doing it?

回答1:

This appears to work:

#include <stdio.h>

extern void *_GLOBAL_OFFSET_TABLE_;

int main()
{
    printf("_GLOBAL_OFFSET_TABLE = %p\n", &_GLOBAL_OFFSET_TABLE_);
    return 0;
}

It gives:

$ ./test
_GLOBAL_OFFSET_TABLE = 0x6006d0

However, nm thinks different:

$ nm test | fgrep GLOBAL
0000000000600868 d _GLOBAL_OFFSET_TABLE_


回答2:

If you use assembly language, you can get _GLOBAL_OFFSET_TABLE_ address without get_pc_thunk.
It is tricky way. :)


Here is the sample code :

$ cat test.s

.global main
main:
 lea HEREIS, %eax   # Now %eax holds address of _GLOBAL_OFFSET_TABLE_      

.section .got
HEREIS:

$ gcc -o test test.s

This is available because .got section is adjacent to the <.got.plt>
Therefore the symbol HEREIS and _GLOBAL_OFFSET_TABLE_ locate at same address.


PS. You can check it works with objdump.

Disassembly of section .got:

080495e8 <HEREIS-0x4>:
 80495e8:   00 00                   add    %al,(%eax)
    ...

Disassembly of section .got.plt:

080495ec <_GLOBAL_OFFSET_TABLE_>:
 80495ec:   00 95 04 08 00 00       add    %dl,0x804(%ebp)
 80495f2:   00 00                   add    %al,(%eax)
 80495f4:   00 00                   add    %al,(%eax)


标签: c linux gcc x86-64