"""Write tiny-x86_64, a 736-byte ELF executable, from the standard library alone. The program writes "ok\n" to file descriptor 1 and exits with status 42 on Linux x86-64. Layout: ELF header, two program headers, .text, .rodata, .symtab, .strtab, .shstrtab, then the section header table. One PT_LOAD maps the whole file read-and-execute. Field layouts: System V gABI, Figures 4-3 (Elf64_Ehdr), 4-8 (Elf64_Shdr), 4-18 (Elf64_Sym), 5-1 (Elf64_Phdr). Run `python3 build_tiny_elf.py` in this directory. The output is deterministic. """ from __future__ import annotations import struct from pathlib import Path BASE = 0x400000 PAGE = 0x1000 EHDR_SIZE = 64 PHDR_SIZE = 56 SHDR_SIZE = 64 SYM_SIZE = 24 PT_LOAD = 1 PT_GNU_STACK = 0x6474E551 PF_X, PF_W, PF_R = 1, 2, 4 SHT_PROGBITS, SHT_SYMTAB, SHT_STRTAB = 1, 2, 3 SHF_WRITE, SHF_ALLOC, SHF_EXECINSTR = 1, 2, 4 STB_LOCAL, STB_GLOBAL = 0, 1 STT_OBJECT, STT_FUNC = 1, 2 def string_table(names: list[str]) -> tuple[bytes, dict[str, int]]: table = bytearray(b"\0") offsets = {"": 0} for name in names: offsets[name] = len(table) table += name.encode("ascii") + b"\0" return bytes(table), offsets def align(value: int, boundary: int) -> int: return (value + boundary - 1) // boundary * boundary def build() -> bytes: phdr_off = EHDR_SIZE text_off = phdr_off + 2 * PHDR_SIZE message = b"ok\n" code_without_lea = 5 + 7 + 5 + 5 + 2 + 5 + 5 + 2 rodata_off = text_off + code_without_lea lea_end = text_off + 5 + 7 disp = rodata_off - lea_end code = b"".join( [ b"\xbf\x01\x00\x00\x00", b"\x48\x8d\x35" + struct.pack("