I am trying to understand the relation between a compiled program in Linux and how it is loaded in the main memory.
I understand that when a program is loaded in memory, all its virtual pages go in some 'page frames' of the main memory.
Below is the snippet of readelf output for my program.
readelf --segments a.out
Elf file type is DYN (Shared object file)
Entry point 0x1060
There are 13 program headers, starting at offset 64
Program Headers:
Type Offset VirtAddr PhysAddr
FileSiz MemSiz Flags Align
......
LOAD 0x0000000000000000 0x0000000000000000 0x0000000000000000
0x0000000000000600 0x0000000000000600 R 0x1000
LOAD 0x0000000000001000 0x0000000000001000 0x0000000000001000
0x0000000000000fc5 0x0000000000000fc5 R E 0x1000
LOAD 0x0000000000002000 0x0000000000002000 0x0000000000002000
0x0000000000000190 0x0000000000000190 R 0x1000
LOAD 0x0000000000002db8 0x0000000000003db8 0x0000000000003db8
0x00000000000002cc 0x00000000000002d0 RW 0x1000
.......
Here,
(1) First segment (R) starts at the virtual address '0x0000000000000000' and has size '0x600'. Consumes 1 Page.
(2) Second segment (R,E, text segment) starts at the virtual address '0x0000000000001000' and has size '0xfc5'. Consumes 1 Page.
(3) Third segment (R) starts at the virtual address '0x0000000000002000' and has size '0x190'. Consumes 1 Page.
(4) Fourth segment (RW, data segment) stars at address '0x0000000000003db8', why?
The fourth segment should have started at '0x0000000000003000' as the third segment has size of only '0x190' bytes and also the Align for this segment is 0x1000(4096), which is a page boundary.
LOAD 0x0000000000002db8 0x0000000000003db8 0x0000000000003db8
0x00000000000002cc 0x00000000000002d0 RW 0x1000
After loading this program, the physical memory mappings are,
cat /proc/4125/maps
56028da61000-56028da62000 r--p 00000000 08:05 1442315 a.out
56028da62000-56028da63000 r-xp 00001000 08:05 1442315 a.out
56028da63000-56028da64000 r--p 00002000 08:05 1442315 a.out
56028da64000-56028da65000 r--p 00002000 08:05 1442315 a.out
56028da65000-56028da66000 rw-p 00003000 08:05 1442315 a.out