How can I get the _GLOBAL_OFFSET_TABLE_ address in my program?

南笙酒味 提交于 2019-12-06 06:43:51

问题


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)


来源:https://stackoverflow.com/questions/9686764/how-can-i-get-the-global-offset-table-address-in-my-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!