Position independent executable support in DragonFlyBSD

Vasily Postnicov shamaz.mazum at gmail.com
Fri Nov 20 23:49:53 PST 2015


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:

#include <stdio.h>
#include <sys/mman.h>

int main()
{
    int (*func)() = main;
    printf ("%p\n", func);

    void *ptr = mmap (NULL, 4096, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
    printf ("%p\n", ptr);
    munmap (ptr, 4096);
    return 0;
}

I compile this code like this:
cc -fPIE -pie -o test test.c

And set vm.randomize_mmap sysctl to 1
Here is my program's output after it was launched 2 times:

> ./test
0x1021aa3
0x807c5c000
> ./test
0x1021aa3
0x80d01d000

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):

> readelf -l test
Elf file type is DYN (Shared object file)
Entry point 0x84c
Program Headers:
  Type           Offset                              VirtAddr
    PhysAddr
                     FileSiz                              MemSiz
       Flags  Align
  LOAD      0x0000000000000000 0x0000000000000000  0x0000000000000000
                 0x0000000000000bf4  0x0000000000000bf4   R E    200000
  LOAD      0x0000000000000bf8  0x0000000000200bf8   0x0000000000200bf8
                 0x0000000000000238 0x0000000000000270   RW     200000

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.

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?

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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.dragonflybsd.org/pipermail/users/attachments/20151121/ccd49907/attachment.html>


More information about the Users mailing list