<div dir="ltr"><div><div><div><div>Hello. Can anyone please explain what happens here? I am trying to compile and execute a position independent executable (further: PIE) on DragonFlyBSD 4.0. This is my test program test.c:<br><br>#include <stdio.h><br>#include <sys/mman.h><br><br>int main()<br>{<br>    int (*func)() = main;<br>    printf ("%p\n", func);<br><br>    void *ptr = mmap (NULL, 4096, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);<br>    printf ("%p\n", ptr);<br>    munmap (ptr, 4096);<br>    return 0;<br>}<br><br></div>I compile this code like this:<br></div>cc -fPIE -pie -o test test.c<br><br></div>And set vm.randomize_mmap sysctl to 1<br></div><div>Here is my program's output after it was launched 2 times:<br></div><div><br>> ./test<br>0x1021aa3<br>0x807c5c000<br>> ./test<br>0x1021aa3<br>0x80d01d000<br><br></div><div>As I can understand, the program is mmap()'ed into memory by dynamic linker (/libexec/ld-elf.so.2). The base address the program is mapped to is determined by content of p_vaddr filed in the first PT_LOAD program header in the file (as I learned from /usr/src/libexec/rtld-elf/map_object.c). It's usually 0x400000, but in my case of PIE it is 0x0 (info by readelf -l, some output dropped here):<br><br></div><div>> readelf -l test<br>Elf file type is DYN (Shared object file)<br>Entry point 0x84c<br>Program Headers:<br>  Type           Offset                              VirtAddr                   PhysAddr<br>                     FileSiz                              MemSiz                   Flags  Align<br>  LOAD      0x0000000000000000 0x0000000000000000  0x0000000000000000<br>                 0x0000000000000bf4  0x0000000000000bf4   R E    200000<br>  LOAD      0x0000000000000bf8  0x0000000000200bf8   0x0000000000200bf8<br>                 0x0000000000000238 0x0000000000000270   RW     200000<br><br></div><div>According mmap(2) manpage, if its first argument is 0, the system must choose an address for the mapping by itself, and as I can see from my test program, it is random  indeed, if I set vm.randomize_mmap=1.<br><br></div><div>So my questions  are so: why the address of main is always 0x1021aa3? Why it is not even aligned? What must be changed in DragonFlyBSD to handle PIEs properly?<br><br></div><div>I also have noticed, that dynamic libraries (.so) are loaded at random addresses with mmap randomization, so what is the difference between them and PIEs?<br></div></div>