为了各种目的,我正在尝试获取主要可执行文件的ELF头的地址,而无需解析/ proc / self / maps.我尝试解析由dlopen / dlinfo函数给出的link_list链,但是它们不包含一个条目,其中l_addr指向主可执行文件的基址.有没有办法这样做(标准与否),无需解析/ proc / self / maps?
我想要做的一个例子:
- #include <stdio.h>
- #include <elf.h>
- int main()
- {
- Elf32_Ehdr* header = /* Somehow obtain the address of the ELF header of this program */;
- printf("%p\n",header);
- /* Read the header and do stuff,etc */
- return 0;
- }
解决方法
由dlopen(0,RTLD_LAZY)返回的void *指针给出一个对应于主可执行文件的struct link_map *.
调用dl_iterate_phdr也会在首次执行回调时返回主可执行文件的条目.
你可能会被链接映射中的.l_addr == 0这个事实所困惑,而使用dl_iterate_phdr的那个dlpi_addr == 0.
这正在发生,因为l_addr(和dlpi_addr)实际上并没有记录ELF映像的加载地址.相反,它们记录已应用于该映像的重定位.
通常,主可执行文件的加载位置为0x400000(对于x86_64 Linux)或0x08048000(对于ix86 Linux),并且加载在相同的地址(即它们不被重新定位).
但是如果您将可执行文件与-pie标记相链接,那么它将链接到0x0,并将其重定位到其他地址.
那么如何到达ELF标题?简单:
- #ifndef _GNU_SOURCE
- #define _GNU_SOURCE
- #endif
- #include <link.h>
- #include <stdio.h>
- #include <stdlib.h>
- 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