elf 取路径_c – 获取主要可执行文件的ELF标题
由dlopen(0,RTLD_LAZY)返回的void *指針給出一個對應于主可執(zhí)行文件的struct link_map *.
調用dl_iterate_phdr也會在首次執(zhí)行回調時返回主可執(zhí)行文件的條目.
你可能會被鏈接映射中的.l_addr == 0這個事實所困惑,而使用dl_iterate_phdr的那個dlpi_addr == 0.
這正在發(fā)生,因為l_addr(和dlpi_addr)實際上并沒有記錄ELF映像的加載地址.相反,它們記錄已應用于該映像的重定位.
通常,主可執(zhí)行文件的加載位置為0x400000(對于x86_64 Linux)或0x08048000(對于ix86 Linux),并且加載在相同的地址(即它們不被重新定位).
但是如果您將可執(zhí)行文件與-pie標記相鏈接,那么它將鏈接到0x0,并將其重定位到其他地址.
那么如何到達ELF標題?簡單:
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include
#include
#include
static int
callback(struct dl_phdr_info *info,size_t size,void *data)
{
int j;
static int once = 0;
if (once) return 0;
once = 1;
printf("relocation: 0x%lx\n",(long)info->dlpi_addr);
for (j = 0; j < info->dlpi_phnum; j++) {
if (info->dlpi_phdr[j].p_type == PT_LOAD) {
printf("a.out loaded at %p\n",(void *) (info->dlpi_addr + info->dlpi_phdr[j].p_vaddr));
break;
}
}
return 0;
}
int
main(int argc,char *argv[])
{
dl_iterate_phdr(callback,NULL);
exit(EXIT_SUCCESS);
}
$gcc -m32 t.c && ./a.out
relocation: 0x0
a.out loaded at 0x8048000
$gcc -m64 t.c && ./a.out
relocation: 0x0
a.out loaded at 0x400000
$gcc -m32 -pie -fPIC t.c && ./a.out
relocation: 0xf7789000
a.out loaded at 0xf7789000
$gcc -m64 -pie -fPIC t.c && ./a.out
relocation: 0x7f3824964000
a.out loaded at 0x7f3824964000
更新:
Why does the man page say “base address” and not relocation?
這是一個bug
總結
以上是生活随笔為你收集整理的elf 取路径_c – 获取主要可执行文件的ELF标题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华字后面配什么字比较好_女孩叫华什么名字
- 下一篇: svn切换分支 如何判断 是否完成_SV