From 613c6e4ea4b9a2dc91e148bcfbaf430c1631771d Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:10:19 +0000 Subject: [PATCH] Step 4: linking and output link.pas marks the chunks reachable from the entry point, places them and patches every fixup. elf.pas writes a static ELF executable with a symbol table. test/handtest.pas builds a program chunk by chunk; it prints and exits with 42, and leaves out the chunk nothing reaches. test/enctest.pas emits one of each instruction for objdump. --- diff --git a/Makefile b/Makefile index d4ca04c..e8f1b11 100644 --- a/Makefile +++ b/Makefile @@ -8,13 +8,19 @@ $(FPC) $(FPCFLAGS) -ojed src/jed.pas units: src/*.pas | build - $(FPC) $(FPCFLAGS) src/scan.pas - $(FPC) $(FPCFLAGS) src/sym.pas + for u in scan sym x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done +# tests of the parts below the parser, built from test/ +tests: units + $(FPC) $(FPCFLAGS) -Fusrc -obuild/scantest test/scantest.pas + $(FPC) $(FPCFLAGS) -Fusrc -obuild/enctest test/enctest.pas + $(FPC) $(FPCFLAGS) -Fusrc -obuild/handtest test/handtest.pas + build/handtest build/hand && build/hand; test $$? = 42 + build: mkdir -p build clean: rm -rf build jed -.PHONY: units clean +.PHONY: units tests clean diff --git a/src/elf.pas b/src/elf.pas new file mode 100644 index 0000000..f71d108 --- /dev/null +++ b/src/elf.pas @@ -0,0 +1,185 @@ +{ elf.pas: the executable file. + + Writes a static ELF64 executable for x86-64 Linux: the ELF header, + one program header per section that has anything in it, the linked + text and rodata, and section headers with a symbol table, so that + objdump and gdb can name each procedure and variable. + + Depends on: link for the images and addresses, x64 for the chunks, + scan for names and errors, BaseUnix to write the file. + Leaves out: dynamic linking, for now. } + +unit elf; + +{$mode objfpc}{$H-} + +interface + +uses scan, x64, link; + +const + HeaderSize = 64 + 3 * 56; { the ELF header and up to three program headers } + +procedure WriteElf(const path: shortstring; entry: longint); + +implementation + +uses BaseUnix; + +var + buf: PBytes; + len, cap: int64; + +procedure Room(n: int64); +begin + if len + n > cap then begin + cap := cap * 2 + n; + buf := ReAllocMem(buf, cap); + end; +end; + +procedure PutN(v: qword; n: longint); +var i: longint; +begin + Room(n); + for i := 0 to n - 1 do begin + buf^[len] := byte(v); + v := v shr 8; + inc(len); + end; +end; + +procedure PutBytes(p: PBytes; n: int64); +begin + Room(n); + if n > 0 then Move(p^, buf^[len], n); + len := len + n; +end; + +procedure PadTo(off: int64); +begin + while len < off do PutN(0, 1); +end; + +procedure Patch(at: int64; v: qword; n: longint); +var i: longint; +begin + for i := 0 to n - 1 do begin + buf^[at + i] := byte(v); + v := v shr 8; + end; +end; + +procedure Phdr(flags: longint; off, adr, filesz, memsz: int64); +begin + PutN(1, 4); { PT_LOAD } + PutN(flags, 4); + PutN(off, 8); + PutN(adr, 8); + PutN(adr, 8); + PutN(filesz, 8); + PutN(memsz, 8); + PutN(Page, 8); +end; + +procedure Shdr(name, typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64); +begin + PutN(name, 4); PutN(typ, 4); PutN(flags, 8); PutN(adr, 8); + PutN(off, 8); PutN(size, 8); PutN(lnk, 4); PutN(info, 4); + PutN(align, 8); PutN(entsize, 8); +end; + +procedure WriteElf(const path: shortstring; entry: longint); +const + ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0; +var + nph, c, nsym, fd: longint; + symOff, strOff, shstrOff, shOff, strLen: int64; + strs: PBytes; + s, p: shortstring; + sec: longint; +begin + cap := 1 shl 16; + buf := GetMem(cap); + len := 0; + nph := 1; + if roSize > 0 then inc(nph); + if bssSize > 0 then inc(nph); + + { ELF header } + PutN($464C457F, 4); PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); + PutN(2, 2); { ET_EXEC } + PutN(62, 2); { EM_X86_64 } + PutN(1, 4); + PutN(chunks^[entry].adr, 8); + PutN(64, 8); { program headers follow } + PutN(0, 8); { section headers: patched below } + PutN(0, 4); + PutN(64, 2); PutN(56, 2); PutN(nph, 2); + PutN(64, 2); PutN(7, 2); PutN(6, 2); + + { the first segment maps the headers too, so text can follow them } + Phdr(5, 0, Base, textOff + textSize, textOff + textSize); + if roSize > 0 then Phdr(4, roOff, Base + roOff, roSize, roSize); + if bssSize > 0 then Phdr(6, 0, bssAdr, 0, bssSize); + + PadTo(textOff); + PutBytes(textImg, textSize); + PadTo(roOff); { even when empty, so that every section lies in the file } + PutBytes(roImg, roSize); + + { the symbol table: one local symbol for each named live chunk } + PadTo((len + 7) div 8 * 8); + symOff := len; + strs := GetMem(1 shl 16); + strLen := 1; + strs^[0] := 0; + PutN(0, 24); + nsym := 1; + for c := 0 to numChunks - 1 do + if chunks^[c].live and (chunks^[c].name >= 0) then begin + s := ChunkName(c); + if strLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strLen * 2 + 256); + Move(s[1], strs^[strLen], length(s)); + strs^[strLen + length(s)] := 0; + case chunks^[c].sec of + secText: sec := 1; + secRodata: sec := 2; + else sec := 3; + end; + PutN(strLen, 4); + if sec = 1 then PutN(2, 1) else PutN(1, 1); { STT_FUNC, STT_OBJECT } + PutN(0, 1); + PutN(sec, 2); + PutN(chunks^[c].adr, 8); + PutN(chunks^[c].size, 8); + strLen := strLen + length(s) + 1; + inc(nsym); + end; + strOff := len; + PutBytes(strs, strLen); + shstrOff := len; + s := ShNames; + PutBytes(@s[1], length(s)); + + PadTo((len + 7) div 8 * 8); + shOff := len; + Patch(40, shOff, 8); + Shdr(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + Shdr(1, 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0); + Shdr(7, 1, 2, Base + roOff, roOff, roSize, 0, 0, 16, 0); + Shdr(15, 8, 3, bssAdr, roOff + roSize, bssSize, 0, 0, 16, 0); + Shdr(20, 2, 0, 0, symOff, nsym * 24, 5, nsym, 8, 24); + Shdr(28, 3, 0, 0, strOff, strLen, 0, 0, 1, 0); + Shdr(36, 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0); + + p := path + #0; + fd := FpOpen(@p[1], O_WRONLY or O_CREAT or O_TRUNC, &755); + if fd < 0 then Fatal('can''t write ' + path); + if FpWrite(fd, buf^, len) <> len then Fatal('can''t write ' + path); + FpClose(fd); + FreeMem(strs); + FreeMem(buf); +end; + +end. diff --git a/src/link.pas b/src/link.pas new file mode 100644 index 0000000..6e8cb46 --- /dev/null +++ b/src/link.pas @@ -0,0 +1,123 @@ +{ link.pas: tree shaking, layout and patching. + + Starting from the entry chunk, marks every chunk the program can + reach through fixups; the rest is left out. Then gives each live + chunk its address and builds the images of text and rodata, with + every fixup patched. + + The file is laid out so that each section can be mapped as it lies: + text right after the headers, rodata on the next page, bss after + that, in memory only. + + Depends on: x64 for chunks and fixups, scan for names and errors. + Leaves out: the file format; that is elf.pas. } + +unit link; + +{$mode objfpc}{$H-} + +interface + +uses scan, x64; + +const + Base = $400000; + Page = 4096; + +var + textOff, textSize: int64; { file offset and size of text } + roOff, roSize: int64; + bssAdr, bssSize: int64; + textImg, roImg: PBytes; + +procedure LinkAll(entry: longint; headerSize: longint); +function ChunkName(c: longint): shortstring; + +implementation + +function ChunkName(c: longint): shortstring; +begin + if chunks^[c].name < 0 then exit('a literal'); + if chunks^[c].module < 0 then exit(NameOf(chunks^[c].name)); + ChunkName := NameOf(chunks^[c].module) + '.' + NameOf(chunks^[c].name); +end; + +procedure MarkLive(entry: longint); +var stack: PLongs; sp, c, f, t: longint; +begin + stack := GetMem(numChunks * 4); + sp := 0; + chunks^[entry].live := true; + stack^[0] := entry; + sp := 1; + while sp > 0 do begin + dec(sp); + c := stack^[sp]; + if chunks^[c].size < 0 then Fatal(ChunkName(c) + ' is declared but never defined'); + if chunks^[c].sec <> secText then continue; + for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin + t := fixups^[f].chunk; + if not chunks^[t].live then begin + chunks^[t].live := true; + stack^[sp] := t; + inc(sp); + end; + end; + end; + FreeMem(stack); +end; + +{ Gives the live chunks of one section their places, from start; + returns the end. } +function Place(sec: TSection; start: int64): int64; +var c: longint; a: int64; +begin + a := start; + for c := 0 to numChunks - 1 do + if chunks^[c].live and (chunks^[c].sec = sec) then begin + a := (a + chunks^[c].align - 1) div chunks^[c].align * chunks^[c].align; + chunks^[c].adr := a; + a := a + chunks^[c].size; + end; + Place := a; +end; + +procedure LinkAll(entry: longint; headerSize: longint); +var c, f, at: longint; e, p, v: int64; +begin + MarkLive(entry); + textOff := (headerSize + 15) div 16 * 16; + e := Place(secText, Base + textOff); + textSize := e - (Base + textOff); + roOff := (textOff + textSize + Page - 1) div Page * Page; + e := Place(secRodata, Base + roOff); + roSize := e - (Base + roOff); + bssAdr := (Base + roOff + roSize + Page - 1) div Page * Page; + e := Place(secBss, bssAdr); + bssSize := e - bssAdr; + + textImg := GetMem(textSize + 1); + FillChar(textImg^, textSize + 1, $CC); + roImg := GetMem(roSize + 1); + FillChar(roImg^, roSize + 1, 0); + for c := 0 to numChunks - 1 do + if chunks^[c].live then + case chunks^[c].sec of + secText: begin + p := chunks^[c].adr - (Base + textOff); + Move(code^[chunks^[c].start], textImg^[p], chunks^[c].size); + for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin + at := fixups^[f].at - chunks^[c].start; + { rel32: from the end of the field to the target } + v := chunks^[fixups^[f].chunk].adr + fixups^[f].addend + - (chunks^[c].adr + at + 4); + PLongint(@textImg^[p + at])^ := longint(v); + end; + end; + secRodata: + Move(rodata^[chunks^[c].start], roImg^[chunks^[c].adr - (Base + roOff)], + chunks^[c].size); + end; +end; + +end. diff --git a/test/enctest.pas b/test/enctest.pas new file mode 100644 index 0000000..0831667 --- /dev/null +++ b/test/enctest.pas @@ -0,0 +1,32 @@ +{ Emits one of each instruction form into a chunk, for objdump: a test + of the encoder in x64.pas. } +program enctest; +{$mode objfpc}{$H-} +uses scan, x64, link, elf; +var e, d: longint; L: longint; +begin + d := NewChunk(secBss, -1, Intern('data', 4)); SetBss(d, 8, 8); + e := NewChunk(secText, -1, Intern('start', 5)); + BeginChunk(e); + MovRR(RAX, RCX); MovRR(R11, RDI); MovRR(RSI, R9); + MovRI(RAX, 0); MovRI(RCX, 5); MovRI(RDX, -5); MovRI(R10, $FFFFFFFF); MovRI(RAX, $123456789A); + Load(RAX, Mem(RBP, -8), 8, true); Load(RAX, Mem(RBP, -200), 4, true); Load(RCX, Mem(RAX, 0), 4, false); + Load(RAX, Mem(RCX, 16), 2, true); Load(RAX, Mem(RAX, 3), 2, false); Load(RAX, Mem(RSP, 8), 1, true); + Load(RAX, Mem(RBP, 0), 1, false); Load(R10, Mem(12, 0), 8, true); Load(RAX, Mem(13, 0), 8, true); + Store(Mem(RBP, -16), RAX, 8); Store(Mem(RBP, -16), RSI, 1); Store(Mem(RCX, 0), RAX, 2); Store(Mem(RCX, 4), RDX, 4); + Store(MemIdx(RBP, R10, 8, 0), RAX, 8); Store(MemRip(d, 0), RAX, 8); Lea(RAX, MemRip(d, 4)); + Alu(aluAdd, RAX, RCX); Alu(aluSub, RCX, RAX); Alu(aluCmp, RAX, RCX); Alu(aluXor, R8, R9); + AluI(aluAdd, RAX, 1); AluI(aluAnd, RAX, 1000); AluI(aluCmp, RSP, 8); AluM(aluCmp, RAX, Mem(RCX, 8)); AluM(aluAdd, RAX, Mem(RCX, 0)); + Imul(RAX, RCX); ImulI(RAX, 24); Shift(shShl, RAX); Shift(shSar, RAX); ShiftI(shShr, RCX, 3); + Unary(2, RAX); Unary(3, RAX); Unary(6, RCX); Unary(7, RCX); Cqo; + Extend(RAX, 1, true); Extend(RAX, 1, false); Extend(RAX, 2, true); Extend(RAX, 2, false); Extend(RAX, 4, true); Extend(RAX, 4, false); + SetCC(ccL, RAX); SetCC(ccA, RCX); TestRR(RAX, RAX); + Push(RAX); Push(12); Pop(RCX); Pop(R11); CallR(R11); Ret; Leave; Syscall; Mfence; Ud2; RepMovsb; RepStosb; + LockCmpxchg(Mem(RCX, 0), RDX); Xchg(Mem(RCX, 0), RAX); LockXadd(Mem(RCX, 0), RAX); + MovqXR(0, RAX); MovqXR(1, RCX); MovqRX(RAX, 0); MovsdXM(2, Mem(RBP, -8)); MovsdMX(Mem(RBP, -8), 7); + Sse($58, 0, 1); Sse($5E, 0, 1); Ucomisd(0, 1); Cvtsi2sd(0, RAX); Cvttsd2si(RAX, 0); Btc(RAX, 63); + L := NoLabel; Jcc(ccE, L); Jmp(L); FixLink(L); JmpBack(chunks^[e].start); JccBack(ccNE, chunks^[e].start); + EndChunk(e); + LinkAll(e, HeaderSize); + WriteElf(ParamStr(1), e); +end. diff --git a/test/handtest.pas b/test/handtest.pas new file mode 100644 index 0000000..c2c43f8 --- /dev/null +++ b/test/handtest.pas @@ -0,0 +1,46 @@ +{ Builds a program by hand, chunk by chunk, links it and writes it: + a test of x64.pas, link.pas and elf.pas. The program writes "hand" + from rodata, adds one to a bss variable through a call, and exits + with that variable plus 41: status 42. A chunk nothing reaches is + left out. } +program handtest; +{$mode objfpc}{$H-} +uses scan, x64, link, elf; +var entry, msg, count, bump, unused: longint; s: shortstring; +begin + s := 'hand'#10; + msg := NewChunk(secRodata, -1, Intern('msg', 3)); + SetData(msg, @s[1], length(s), 1); + count := NewChunk(secBss, -1, Intern('count', 5)); + SetBss(count, 8, 8); + bump := NewChunk(secText, -1, Intern('bump', 4)); + unused := NewChunk(secText, -1, Intern('unused', 6)); + entry := NewChunk(secText, -1, Intern('start', 5)); + + BeginChunk(bump); { count := count + 1 } + Load(RAX, MemRip(count, 0), 8, true); + AluI(aluAdd, RAX, 1); + Store(MemRip(count, 0), RAX, 8); + Ret; + EndChunk(bump); + + BeginChunk(unused); + Ud2; + EndChunk(unused); + + BeginChunk(entry); + MovRI(RAX, 1); { write(1, msg, 5) } + MovRI(RDI, 1); + Lea(RSI, MemRip(msg, 0)); + MovRI(RDX, length(s)); + Syscall; + CallChunk(bump); + Load(RDI, MemRip(count, 0), 8, true); + AluI(aluAdd, RDI, 41); + MovRI(RAX, 60); { exit(count + 41) } + Syscall; + EndChunk(entry); + + LinkAll(entry, HeaderSize); + WriteElf(ParamStr(1), entry); +end.