elfmmap

mmap with file as an input, with unaligned offset


I'm writing a simple userspace ELF loader.

These are the segments in the ELF: (provided by readelf)

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x0000000000000518 0x0000000000000518  R      0x1000
  LOAD           0x0000000000001000 0x0000000000401000 0x0000000000401000
                 0x0000000000077b11 0x0000000000077b11  R E    0x1000
  LOAD           0x0000000000079000 0x0000000000479000 0x0000000000479000
                 0x0000000000026f7c 0x0000000000026f7c  R      0x1000
  LOAD           0x00000000000a06d8 0x00000000004a06d8 0x00000000004a06d8
                 0x0000000000005b98 0x000000000000b3c8  RW     0x1000

a few things don't make sense to me:

  1. the last segment has unaligned virtual address (0x4a06d8)... how is this possible? shouldn't all the addresses be page aligned?
  2. I'm mapping the segments to mem using mmap. from what I understand mmap only accepts page aligned file offsets. (in my case 0x1000). why does the offset need to be page aligned too? I'm using it only to read from the file...

thanks in advance


Solution

  • the last segment has unaligned virtual address (0x4a06d8)... how is this possible?

    Note that .p_vaddr - .p_offset is page-aligned.

    The kernel rounds down both .p_vaddr and .p_offset to page size before making the mmap call. See this answer.

    why does the offset need to be page aligned too?

    It doesn't. Only .p_vaddr - .p_offset must be page aligned (but if .p_vaddr is page aligned, then it follows that .p_offset also must be).