(* Link: 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, then a writable page that starts with the table the dynamic loader reads (none in a static program) and goes on as bss, in memory only. The loader's other tables come at the end of rodata; Exe writes them in the room left there. Mach-O, Exe.darwin.raz's, is laid out otherwise (setPaged): each segment starts on a page of its own, in the file as in memory, at base plus its offset in the file; and, since macOS loads a program anywhere, every address held in rodata is listed (rebases), for the loader to move with it. arm64's fixups, fields of an instruction, are patched here too. Also here, shared by both executable formats, the DWARF the line table needs (debugInfo, debugAbbrev): the one compile unit that points to it. Depends on: Chunk for chunks and fixups, Scan for names and memory, Diag for errors and paths, Sys for the working directory. Leaves out: the file format; that is Exe. *) module Link; import Sys, Fmt, Diag, Scan, Chunk; import SYSTEM; const Page* = 4096; Low* = 80000000H; (* the image lies below Low, or at -Low or above *) var base*: INT; (* where the file is loaded: raz -base, 400000H if not *) textOff*, textSize*: INT; (* file offset and size of text, at base + textOff *) roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *) roAdr*: INT; (* where rodata is loaded *) extraAdr*: INT; (* that room *) bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *) bssOff*: INT; (* the file offset of that table *) textImg*, roImg*: ^U8; placesChunk*: INT; (* the rodata chunk of the places, made by the caller *) linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *) paged*: INT; (* 0, ELF's layout; or Mach-O's page, each segment on one *) rebases*: ^INT; (* the addresses of rodata's words that hold an address *) numRebases*: INT; proc setBase*(a: INT); begin base := a; end; (* Mach-O's layout, its segments on pages of page bytes *) proc setPaged*(page: INT); begin paged := page; end; proc setPlaces*(c: INT); begin placesChunk := c; end; (* Marks live each chunk reached from entry through the fixups. *) proc markLive*(entry: INT); var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup; begin stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); Chunk.setLive(entry); stack[0] := entry; sp := 1; while sp > 0 do DEC(sp); c := stack[sp]; if Chunk.chunks[c].size < 0 then Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))])); end; (* code and constants have fixups; variables start at zero, holding no addresses *) match Chunk.chunks[c].sec of | secText: fx := Chunk.fixups; | secRodata: fx := Chunk.dataFixups; | secBss: fx := nil; end; if fx # nil then for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do t := fx[f].chunk; if not Chunk.chunks[t].live then Chunk.setLive(t); stack[sp] := t; INC(sp); end; end; end; end; (* the places hold the line table a debugger reads, so they are made even when Rt takes no address of them, a kernel's Rt with no places *) if (placesChunk >= 0) and not Chunk.chunks[placesChunk].live then Chunk.setLive(placesChunk); end; end; (* Gives the live chunks of one section their places, from start; returns the end. *) proc place(sec: Chunk.Section; start: INT): INT; var c, a: INT; begin a := start; for c := 0 to Chunk.numChunks - 1 do if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align; Chunk.setAdr(c, a); a := a + Chunk.chunks[c].size; end; end; return a; end; (* The line table, DWARF 4's line program, which gdb reads as .debug_line and Rt to say where code comes from: one sequence for each live procedure with lines, a row for each place noted, its address, file, line and column. A row whose address and line move a little is one byte, a special opcode; the others are made of the standard ones. Made in lp, lpLen bytes long. *) const LineBase = -5; LineRange = 14; OpcodeBase = 13; (* the special opcodes' *) var lp: ^U8; lpLen, lpCap: INT; proc putB(v: INT); begin if lpLen = lpCap then lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256); lpCap := lpCap * 2 + 256; end; lp[lpLen] := U8(v & 0FFH); INC(lpLen); end; (* The n low bytes of v, least significant first *) proc putN(v: INT; n: INT); var i: INT; begin for i := 1 to n do putB(v); v := v shr 8; end; end; (* LEB128, unsigned and signed *) proc putU(v: INT); begin while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end; putB(v); end; proc putS(v: INT); begin while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end; putB(v & 7FH); end; (* v as the four bytes at at in p *) proc patch4(p: ^U8; at, v: INT); var i: INT; begin for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; end; (* v as the eight bytes at at in p *) proc patch8(p: ^U8; at, v: INT); var i: INT; begin for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; end; (* Whether the standard opcode i takes an operand *) proc takesOperand(i: INT): BOOL; begin return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12); end; (* The line program of the files paths, nfiles of them, numbered from 1, as they are written in the table *) proc makeLines(paths: ^INT; nfiles: INT); var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []const U8; begin lpLen := 0; putN(0, 4); (* unit_length, patched below *) putN(4, 2); (* version *) putN(0, 4); (* header_length, patched below *) putB(1); putB(1); (* minimum_instruction_length, maximum_operations *) putB(1); (* default_is_stmt *) putB(LineBase); putB(LineRange); putB(OpcodeBase); for i := 1 to OpcodeBase - 1 do if takesOperand(i) then putB(1); else putB(0); end; (* their operands *) end; putB(0); (* no include directories *) for f := 0 to nfiles - 1 do s := Diag.shownPath(Scan.nameOf(paths[f])); for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end; putN(0, 4); (* its end, directory, time, length *) end; putB(0); patch4(lp, 6, lpLen - 10); i := 0; while i < Chunk.numLines do c := Chunk.lines[i].chunk; if not Chunk.chunks[c].live then INC(i); else putB(0); putU(9); putB(2); (* DW_LNE_set_address *) putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8); at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0; while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do f := 1; while paths[f - 1] # Chunk.lines[i].path do INC(f); end; if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *) if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *) da := Chunk.lines[i].at - at; dl := Chunk.lines[i].line - cl; op := (dl - LineBase) + LineRange * da + OpcodeBase; if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then putB(op); (* a special opcode: a row *) else if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *) if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *) putB(1); (* DW_LNS_copy: a row *) end; at := Chunk.lines[i].at; cl := Chunk.lines[i].line; INC(i); end; putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at); putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *) end; end; patch4(lp, 0, lpLen - 4); end; var buf: ^U8; (* the places, being made *) at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *) (* The name s, in the pool, and its offset from the pool's start, at at *) proc putName(s: []const U8); begin patch4(buf, at, names - poolAt); COPY(buf[names..names + LEN(s)], s); buf[names + LEN(s)] := 0; names := names + LEN(s) + 1; at := at + 4; end; (* Whether chunk c is a live procedure, whose places Rt knows *) proc isProc(c: INT): BOOL; begin return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0); end; (* The places that Rt reads to say where a failed check or a signal was, and what calls were under way: where the line table is in them, where text starts and stops, the numbers of procedures and of their variables (I64s); for each live procedure where it starts and stops, the offset of its name, its first variable and how many it has, and the registers of variables it saves, as bits of Gen's VarRegs, and the frame offset they are saved at (U32s); for each variable the offset of its name, its place in the frame and its kind, as Parse's VarKind (U32s); then the names, each ending in a zero byte; then the line table (makeLines), at linesOff. They are in no order, since Rt looks at them only as the program stops. *) proc makePlaces(start, stop: INT); var files, first, count: ^INT; i, f, nfiles, np, nv, c, v: INT; begin files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT))); first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end; for v := Chunk.numVarNotes - 1 to 0 by -1 do first[Chunk.varNotes[v].chunk] := v; INC(count[Chunk.varNotes[v].chunk]); end; nfiles := 0; poolAt := 0; np := 0; nv := 0; for i := 0 to Chunk.numLines - 1 do if Chunk.chunks[Chunk.lines[i].chunk].live then f := 0; while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end; if f = nfiles then files[f] := Chunk.lines[i].path; INC(nfiles); end; end; end; makeLines(files, nfiles); for c := 0 to Chunk.numChunks - 1 do if isProc(c) then INC(np); poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1; for v := first[c] to first[c] + count[c] - 1 do poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1; end; nv := nv + count[c]; end; end; buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen); (* the pool of names starts at poolAt, the line table after it *) poolAt := 40 + 28 * np + 12 * nv; names := poolAt; at := 40; v := 0; for c := 0 to Chunk.numChunks - 1 do if isProc(c) then patch4(buf, at, Chunk.chunks[c].adr); patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size); at := at + 8; putName(Chunk.chunkName(c)); patch4(buf, at, v); patch4(buf, at + 4, count[c]); patch4(buf, at + 8, Chunk.chunks[c].saveMask); patch4(buf, at + 12, Chunk.chunks[c].saveAt); at := at + 16; v := v + count[c]; end; end; for c := 0 to Chunk.numChunks - 1 do if isProc(c) then for v := first[c] to first[c] + count[c] - 1 do putName(Scan.nameOf(Chunk.varNotes[v].name)); patch4(buf, at, Chunk.varNotes[v].off); patch4(buf, at + 4, Chunk.varNotes[v].kind); at := at + 8; end; end; end; linesOff := names; linesSize := lpLen; COPY(buf[names..names + lpLen], lp[0..lpLen]); patch8(buf, 0, linesOff); patch8(buf, 8, start); patch8(buf, 16, stop); patch8(buf, 24, np); patch8(buf, 32, nv); Chunk.setData(placesChunk, buf, names + lpLen, 8); end; (* The compile unit that names the line table, and its abbreviation, DWARF 4's .debug_info and .debug_abbrev: the main module's file and the directory it was compiled in, the producer, the line table (at 0 of its section), and the code, all of it. No types and no variables. Each is made in lp, which the line table has left, and returned: copy it before the next call. The address unit of the line table is a byte (minimum_instruction_length 1, in makeLines), so its rows hold, and its advances count, bytes, on arm64 too, where every row is a multiple of 4: DWARF takes that, and no row needs dividing. *) proc putStr(s: []const U8); var i: INT; begin for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end; putB(0); end; proc debugInfo*(name: []const U8): []const U8; var cwd: []const U8; err: INT; begin lpLen := 0; putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *) putU(1); (* abbreviation 1 *) putStr(name); cwd, err := Sys.workDir(); if err # 0 then cwd := ""; end; putStr(cwd); putStr("raz"); putN(0, 4); (* the line table, at 0 *) putN(base + textOff, 8); putN(textSize, 8); (* the code, all of it *) patch4(lp, 0, lpLen - 4); return lp[0..lpLen]; end; proc debugAbbrev*: []const U8; begin lpLen := 0; putU(1); putU(11H); putB(0); (* 1: a compile unit, no children *) putU(03H); putU(08H); (* name, a string *) putU(1BH); putU(08H); (* comp_dir, a string *) putU(25H); putU(08H); (* producer, a string *) putU(10H); putU(17H); (* stmt_list, a section offset *) putU(11H); putU(01H); (* low_pc, an address *) putU(12H); putU(07H); (* high_pc, a length in 8 bytes *) putN(0, 2); putB(0); return lp[0..lpLen]; end; (* The address a as raz writes it, in hexadecimal: 0FFFFFFFF80000000H *) proc literal(a: INT): []const U8; var s: []const U8; begin s := Diag.say("{}H", [Fmt.hex(U64(a))]); if s[0] > '9' then s := Diag.say("0{}", [Fmt.str(s)]); end; return s; end; (* The arm64 instruction at at in text, at address pc, made to reach the address v, as its kind says (Chunk.FixKind): fxBranch26 b, bl: (v - pc) / 4 in imm26, bits 0 to 25 fxPage21 adrp: v's page less pc's, in pages of 4 KB, its low two bits in immlo (29, 30), the rest in immhi (5 to 23) fxPageOff12 add: v's place in its page in imm12 (10 to 21); a load or store (bits 27 to 29 111, 24 and 25 01) that place divided by the size it moves, 1 shl its bits 30 and 31, or 16 for a q register (bit 26, the reals', with bit 23) The fields hold zeros, as A64 left them. *) proc patchArm(at: INT; kind: Chunk.FixKind; pc, v: INT); var insn, d, sc: INT; begin insn := 0; for d := 3 to 0 by -1 do insn := insn * 256 + INT(textImg[at + d]); end; match kind of | fxBranch26: d := (v - pc) div 4; if (d < -(1 shl 25)) or (d >= 1 shl 25) then Diag.fatal("the program's code is more than 128 MB"); end; insn := insn | (d & 3FFFFFFH); | fxPage21: d := (v shr 12) - (pc shr 12); insn := insn | ((d & 3) shl 29) | (((d shr 2) & 7FFFFH) shl 5); | fxPageOff12: d := v & 0FFFH; if (insn & 3B000000H) = 39000000H then sc := (insn shr 30) & 3; if (insn & 04800000H) = 04800000H then sc := 4; end; d := d shr sc; end; insn := insn | (d shl 10); | else: end; patch4(textImg, at, insn); end; (* Places the live chunks, leaving roExtra bytes at the end of rodata and dynSize at the start of the writable segment. The segments follow each other in the file with no padding, and each is loaded a page further from its file offset than the one before: rodata at base + Page + roOff, the writable segment at base + 2 * Page + bssOff. So an address and its offset agree within a page, as the loader needs, and no two segments, with their different permissions, share a page. The bss of a program without the loader's table has no bytes in the file, and starts on a page of its own. *) proc linkAll*(headerSize, roExtra, dynSize: INT); var c, f, at, p, e, v: INT; begin textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *) e := place(Chunk.secText, base + textOff); textSize := e - (base + textOff); if placesChunk >= 0 then makePlaces(base + textOff, e); end; roOff := (textOff + textSize + 31) div 32 * 32; roAdr := base + Page + roOff; if paged > 0 then (* Mach-O: rodata on a page of its own, at its offset *) roOff := (textOff + textSize + paged - 1) div paged * paged; roAdr := base + roOff; end; e := place(Chunk.secRodata, roAdr); extraAdr := (e + 7) div 8 * 8; if roExtra > 0 then e := extraAdr + roExtra; end; roSize := e - roAdr; bssOff := (roOff + roSize + 31) div 32 * 32; if paged > 0 then bssOff := (roOff + roSize + paged - 1) div paged * paged; bssAdr := base + bssOff; elsif dynSize > 0 then bssAdr := base + 2 * Page + bssOff; else bssAdr := (roAdr + roSize + Page - 1) div Page * Page; end; e := place(Chunk.secBss, bssAdr + dynSize); bssSize := e - bssAdr; (* An address X64.memAbs makes is 32 bits, which the machine extends by their sign, so the image must lie where such an address reaches: the low 2 GB, as at 400000H, or the top 2 GB, as a higher-half kernel at 0FFFFFFFF80000000H. The places keep each procedure's start and stop in 32 bits too, which Rt.procAt reads so. Mach-O's image lies at 4 GB and up, which arm64's code reaches by adrp, and whose places, below 4 GB of it, keep their order in 32 bits. *) (* By the size, e - base, which can't overflow, where e itself might *) if (paged = 0) and not (((base >= 0) and (base <= Low - (e - base))) or ((base >= -Low) and (base <= -(e - base)))) then Diag.fatal(Diag.say("-base {}: the program must lie in the low or the top 2 GB, where a 32-bit address reaches, and from there it doesn't", [Fmt.str(literal(base))])); end; textImg := Scan.grab(textSize + 1); (* the gaps between code chunks are Gen's trap, as in Chunk *) for p := 0 to textSize do textImg[p] := U8((Chunk.pad shr (8 * ((textOff + p) & 3))) & 0FFH); end; roImg := Scan.grab(roSize + 1); rebases := ^INT(Scan.grab(Chunk.numDataFixups * SIZE(INT) + SIZE(INT))); numRebases := 0; for p := 0 to roSize do roImg[p] := 0; end; for c := 0 to Chunk.numChunks - 1 do if Chunk.chunks[c].live then if Chunk.chunks[c].sec = Chunk.secText then p := Chunk.chunks[c].adr - (base + textOff); COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do at := Chunk.fixups[f].at - Chunk.chunks[c].start; v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend; if Chunk.fixups[f].kind # Chunk.fxRel32 then patchArm(p + at, Chunk.fixups[f].kind, Chunk.chunks[c].adr + at, v); else (* rel32: from the end of the field to the target; or, X64.memAbs's, the target's address *) if not Chunk.fixups[f].abs then v := v - (Chunk.chunks[c].adr + at + 4); end; patch4(textImg, p + at, v); end; end; elsif Chunk.chunks[c].sec = Chunk.secRodata then p := Chunk.chunks[c].adr - roAdr; COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do patch8(roImg, p + Chunk.dataFixups[f].at, Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend); rebases[numRebases] := Chunk.chunks[c].adr + Chunk.dataFixups[f].at; INC(numRebases); end; end; end; end; end; begin placesChunk := -1; base := 400000H; paged := 0; end Link.