--- title: "What Actually Happens When You Run a Linux Program: From ELF to Execution" source: "https://x.com/TheGracia_here/status/2030004825346163074" author: - "[[Unknown]]" published: 2026-03-07 created: 2026-03-07 description: tags: - "clippings" --- Every time you type ./hello and hit enter, a surprising amount of stuff happens before your main() function gets called. most developers never actually look at what happens between pressing enter and your code running, but the mechanism is pretty interesting once you start peeling back the layers. ## The Role of execve When your shell sees you want to run a program, it eventually calls the execve() system call. This is the actual entry point into asking the kernel to transform your process into a running program. execve takes three arguments: the path to the executable, the argument array, and the environment array. ```c #include int main(void) { char *argv[] = {"/bin/ls", "-la", NULL}; char *envp[] = {"PATH=/bin", NULL}; execve("/bin/ls", argv, envp); return 0; // unreachable if execve succeeds } ``` When execve returns successfully, your process is now a totally different program. The old code, data, and stack are gone, replaced by whatever ELF file you specified. If execve fails, it returns -1 and sets errno. ## Understanding the ELF Format Linux uses the Executable and Linkable Format (ELF) for binaries. Every executable starts with a header that tells the kernel exactly what it is looking at. The kernel reads this header to figure out how to set up memory, where the entry point is, and how to interpret the rest of the file. The ELF header sits at the very beginning of the file and contains fields like: - Magic bytes (0x7f, E, L, F) to identify it as ELF - Whether it is 32-bit or 64-bit - The target architecture (x86\_64, ARM, etc.) - The entry point virtual address - File offsets to the program header table and section header table a minimal C program that reads and prints the ELF header from a binary: ```c #include #include #include #include #include #include void print_elf64_header(const Elf64_Ehdr *hdr) { fprintf(stderr, "Magic: "); for (int i = 0; i < EI_NIDENT; i++) { fprintf(stderr, "%02x ", hdr->e_ident[i]); } fprintf(stderr, "\\n"); fprintf(stderr, "Entry point: 0x%lx\\n", hdr->e_entry); fprintf(stderr, "Program header offset: %lu bytes\\n", hdr->e_phoff); fprintf(stderr, "Number of program headers: %d\\n", hdr->e_phnum); fprintf(stderr, "Section header offset: %lu bytes\\n", hdr->e_shoff); fprintf(stderr, "Number of section headers: %d\\n", hdr->e_shnum); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s \\n", argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); return 1; } Elf64_Ehdr hdr; if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) { perror("read"); close(fd); return 1; } if (hdr.e_ident[EI_MAG0] != ELFMAG0 || hdr.e_ident[EI_MAG1] != ELFMAG1 || hdr.e_ident[EI_MAG2] != ELFMAG2 || hdr.e_ident[EI_MAG3] != ELFMAG3) { fprintf(stderr, "Not an ELF file\\n"); close(fd); return 1; } print_elf64_header(&hdr); close(fd); return 0; } ``` The magic bytes are always 0x7f followed by ELF in ASCII. If those are not there, the kernel will reject the file immediately. The e\_entry field tells the kernel where to start execution once everything is loaded. ## Program Headers and Memory Mapping The ELF header points to a program header table, which describes segments that need to be loaded into memory. Typical segments include: - PT\_LOAD: Actual code and data to map into memory - PT\_INTERP: Path to the dynamic linker (usually /lib64/ld-linux-x86-64.so.2) - PT\_DYNAMIC: Information for dynamic linking - PT\_PHDR: The program header table itself Each PT\_LOAD segment has a file offset, a virtual address where it should live in memory, file size, and memory size. The kernel uses mmap to map these segments into the process address space. You can inspect these with readelf -l: ```plaintext $ readelf -l /bin/ls Elf file type is DYN (Shared object file) Entry point 0x4040 There are 11 program headers, starting at offset 64 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align PHDR 0x0000000000000040 0x0000000000000040 0x0000000000000040 0x0000000000000268 0x0000000000000268 R 0x8 INTERP 0x00000000000002a8 0x00000000000002a8 0x00000000000002a8 0x000000000000001c 0x000000000000001c R 0x1 [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2] LOAD 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000002398 0x0000000000002398 R 0x1000 LOAD 0x0000000000003000 0x0000000000003000 0x0000000000003000 0x0000000000015a1d 0x0000000000015a1d R E 0x1000 ``` The flags show read (R), write (W), and execute (X) permissions for each segment. The first LOAD segment is typically read-only data, the second is executable code. ## Stack Setup and Process Initialization Before jumping to the entry point, the kernel sets up the initial stack with specific information the program needs. The stack layout is: ```plaintext High addresses ... envp[n] = NULL envp[n-1] ... envp[0] argv[argc] = NULL argv[argc-1] ... argv[0] argc <-- stack pointer points here Low addresses ``` Following the environment pointers comes the auxiliary vector (auxv), which is an array of key-value pairs passed from kernel to userspace. These include things like: - AT\_ENTRY: Entry point address - AT\_EXECFD: File descriptor (if using execve without mmap) - AT\_PAGESZ: System page size - AT\_RANDOM: Address of random bytes (for stack canaries) The C library startup code (\_start) reads this information to initialize the runtime before calling main(). ## The Entry Point (\_start) Here is the thing that trips up a lot of people: execution does not start at main(). It starts at \_start, which is a small piece of assembly provided by the C library (or by your code if you are not using libc). The \_start routine: 1. Sets up the stack frame 2. Extracts argc, argv, and envp from the stack 3. Calls global constructors for C++ or other initialization 4. Calls \_\_libc\_start\_main, which eventually calls your main() 5. After main() returns, calls exit() You can see the entry point of a binary: ```plaintext $ readelf -h /bin/ls | grep Entry Entry point address: 0x4040 ``` That address points to \_start, not main. ## A Small ELF Parser in C Let us build a simple ELF parser step by step. We will start by opening a file and verifying it is ELF: ```c #include #include #include #include #include int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s \\n", argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); return 1; } Elf64_Ehdr ehdr; if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr)) { perror("read"); close(fd); return 1; } // Check magic bytes if (ehdr.e_ident[EI_MAG0] != 0x7f || ehdr.e_ident[EI_MAG1] != 'E' || ehdr.e_ident[EI_MAG2] != 'L' || ehdr.e_ident[EI_MAG3] != 'F') { fprintf(stderr, "Not a valid ELF file\\n"); close(fd); return 1; } printf("Valid ELF file detected\\n"); printf("Entry point: 0x%lx\\n", ehdr.e_entry); close(fd); return 0; } ``` Next, let us add code to read and print the program headers: ```c // After reading the ELF header, seek to program header table off_t phoff = ehdr.e_phoff; uint16_t phnum = ehdr.e_phnum; uint16_t phentsize = ehdr.e_phentsize; // Seek to program header table if (lseek(fd, phoff, SEEK_SET) < 0) { perror("lseek"); close(fd); return 1; } printf("\\nProgram headers:\\n"); for (int i = 0; i < phnum; i++) { Elf64_Phdr phdr; if (read(fd, &phdr, sizeof(phdr)) != sizeof(phdr)) { perror("read phdr"); close(fd); return 1; } const char *type_str = "UNKNOWN"; switch (phdr.p_type) { case PT_NULL: type_str = "NULL"; break; case PT_LOAD: type_str = "LOAD"; break; case PT_DYNAMIC: type_str = "DYNAMIC"; break; case PT_INTERP: type_str = "INTERP"; break; case PT_NOTE: type_str = "NOTE"; break; case PT_PHDR: type_str = "PHDR"; break; case PT_TLS: type_str = "TLS"; break; } printf(" [%d] Type: %s, Offset: 0x%lx, VA: 0x%lx, FileSz: %lu, MemSz: %lu, Flags: %c%c%c\\n", i, type_str, phdr.p_offset, phdr.p_vaddr, phdr.p_filesz, phdr.p_memsz, (phdr.p_flags & PF_R) ? 'R' : '-', (phdr.p_flags & PF_W) ? 'W' : '-', (phdr.p_flags & PF_X) ? 'X' : '-'); } ``` **Complete ELF Parser Program:** here is the full working program that puts it all together ```c #include #include #include #include #include #include #include static const char *get_phdr_type(uint32_t type) { switch (type) { case PT_NULL: return "NULL"; case PT_LOAD: return "LOAD"; case PT_DYNAMIC: return "DYNAMIC"; case PT_INTERP: return "INTERP"; case PT_NOTE: return "NOTE"; case PT_SHLIB: return "SHLIB"; case PT_PHDR: return "PHDR"; case PT_TLS: return "TLS"; default: return "UNKNOWN"; } } static const char *get_class(uint8_t c) { switch (c) { case ELFCLASS32: return "32-bit"; case ELFCLASS64: return "64-bit"; default: return "Invalid"; } } static const char *get_encoding(uint8_t e) { switch (e) { case ELFDATA2LSB: return "Little Endian"; case ELFDATA2MSB: return "Big Endian"; default: return "Invalid"; } } static const char *get_osabi(uint8_t o) { switch (o) { case ELFOSABI_SYSV: return "UNIX System V"; case ELFOSABI_HPUX: return "HP-UX"; case ELFOSABI_NETBSD: return "NetBSD"; case ELFOSABI_LINUX: return "Linux"; case ELFOSABI_SOLARIS: return "Solaris"; case ELFOSABI_FREEBSD: return "FreeBSD"; default: return "Unknown"; } } static const char *get_machine(uint16_t m) { switch (m) { case EM_386: return "Intel 80386"; case EM_X86_64: return "AMD x86-64"; case EM_ARM: return "ARM"; case EM_AARCH64: return "ARM AARCH64"; case EM_RISCV: return "RISC-V"; default: return "Unknown"; } } static const char *get_et_type(uint16_t t) { switch (t) { case ET_NONE: return "NONE"; case ET_REL: return "REL (Relocatable)"; case ET_EXEC: return "EXEC (Executable)"; case ET_DYN: return "DYN (Shared object)"; case ET_CORE: return "CORE (Core file)"; default: return "Unknown"; } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s \\n", argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); return 1; } Elf64_Ehdr ehdr; if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr)) { perror("read"); close(fd); return 1; } // Verify magic bytes if (ehdr.e_ident[EI_MAG0] != 0x7f || ehdr.e_ident[EI_MAG1] != 'E' || ehdr.e_ident[EI_MAG2] != 'L' || ehdr.e_ident[EI_MAG3] != 'F') { fprintf(stderr, "Error: Not a valid ELF file\\n"); close(fd); return 1; } printf("=== ELF Header ===\\n"); printf(" Magic: "); for (int i = 0; i < EI_NIDENT; i++) { printf("%02x ", ehdr.e_ident[i]); } printf("\\n"); printf(" Class: %s\\n", get_class(ehdr.e_ident[EI_CLASS])); printf(" Data: %s\\n", get_encoding(ehdr.e_ident[EI_DATA])); printf(" Version: %d\\n", ehdr.e_ident[EI_VERSION]); printf(" OS/ABI: %s\\n", get_osabi(ehdr.e_ident[EI_OSABI])); printf(" Type: %s\\n", get_et_type(ehdr.e_type)); printf(" Machine: %s\\n", get_machine(ehdr.e_machine)); printf(" Version: 0x%x\\n", ehdr.e_version); printf(" Entry point address: 0x%lx\\n", ehdr.e_entry); printf(" Start of program headers: %lu (bytes into file)\\n", ehdr.e_phoff); printf(" Start of section headers: %lu (bytes into file)\\n", ehdr.e_shoff); printf(" Flags: 0x%x\\n", ehdr.e_flags); printf(" Size of this header: %d (bytes)\\n", ehdr.e_ehsize); printf(" Size of program headers: %d (bytes)\\n", ehdr.e_phentsize); printf(" Number of program headers: %d\\n", ehdr.e_phnum); printf(" Size of section headers: %d (bytes)\\n", ehdr.e_shentsize); printf(" Number of section headers: %d\\n", ehdr.e_shnum); printf(" Section header string table index: %d\\n", ehdr.e_shstrndx); // Read program headers if (ehdr.e_phnum > 0) { printf("\\n=== Program Headers ===\\n"); printf(" Type Offset VirtAddr PhysAddr\\n"); ``` the whole process happens in microseconds. but now you know exactly what's happening in each one of them and you have a parser that lets you inspect it directly.