On Linux, dlopen does not return the address where the ELF binary was downloaded. struct link_map this it returns a struct link_map that has the member .l_addr . So you want something like:
struct link_map *lm = (struct link_map*) dlopen(0, RTLD_NOW); printf("%p\n", lm->l_addr);
However, despite what the comment says in /usr/include/link.h , .l_addr is not really a download address either. Instead, this is the difference between where the ELF image was associated with the download and where it was actually downloaded.
For the main executable without PIE, this difference is always 0. For a shared library without a link, this difference is always the download address (since shared ELF libraries without a link are associated with loading at address 0).
So how do you find the base address of the main executable? The easiest way is to use this code (associated with the main executable):
#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; const char *cb = (const char *)&callback; const char *base = (const char *)info->dlpi_addr; const ElfW(Phdr) *first_load = NULL; for (j = 0; j < info->dlpi_phnum; j++) { const ElfW(Phdr) *phdr = &info->dlpi_phdr[j]; if (phdr->p_type == PT_LOAD) { const char *beg = base + phdr->p_vaddr; const char *end = beg + phdr->p_memsz; if (first_load == NULL) first_load = phdr; if (beg <= cb && cb < end) { // Found PT_LOAD that "covers" callback(). printf("ELF header is at %p, image linked at 0x%zx, relocation: 0x%zx\n", base + first_load->p_vaddr, first_load->p_vaddr, info->dlpi_addr); return 1; } } } return 0; } int main(int argc, char *argv[]) { dl_iterate_phdr(callback, NULL); exit(EXIT_SUCCESS); }
Here is what you should see on a 32-bit system:
$ gcc -g tc -ldl -m32 && ./a.out ELF header is at 0x8048000, image linked at 0x8048000, relocation: 0x0 $ gcc -g tc -ldl -m32 -pie -fPIE && ./a.out ELF header is at 0xf779a000, image linked at 0x0, relocation: 0xf779a000
(Last address: 0xf779a000 will change from start to start if you have address randomization enabled (as it should be)).