raz / src / Link.raz

531 lines · 21.2 KiB · raw · history · last change b6a29ae3

1(* Link: tree shaking, layout and patching.
2
3 Starting from the entry chunk, marks every chunk the program can
4 reach through fixups; the rest is left out. Then gives each live
5 chunk its address and builds the images of text and rodata, with
6 every fixup patched.
7
8 The file is laid out so that each section can be mapped as it lies:
9 text right after the headers, rodata on the next page, then a
10 writable page that starts with the table the dynamic loader reads
11 (none in a static program) and goes on as bss, in memory only. The
12 loader's other tables come at the end of rodata; Exe writes them
13 in the room left there.
14
15 Mach-O, Exe.darwin.raz's, is laid out otherwise (setPaged): each
16 segment starts on a page of its own, in the file as in memory, at
17 base plus its offset in the file; and, since macOS loads a program
18 anywhere, every address held in rodata is listed (rebases), for the
19 loader to move with it. arm64's fixups, fields of an instruction,
20 are patched here too.
21
22 Also here, shared by both executable formats, the DWARF the line table
23 needs (debugInfo, debugAbbrev): the one compile unit that points to it.
24
25 Depends on: Chunk for chunks and fixups, Scan for names and memory,
26 Diag for errors and paths, Sys for the working directory.
27 Leaves out: the file format; that is Exe. *)
28module Link;
29import Sys, Fmt, Diag, Scan, Chunk;
30import SYSTEM;
31
32const
33 Page* = 4096;
34 Low* = 80000000H; (* the image lies below Low, or at -Low or above *)
35
36var
37 base*: INT; (* where the file is loaded: raz -base, 400000H if not *)
38 textOff*, textSize*: INT; (* file offset and size of text, at base + textOff *)
39 roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *)
40 roAdr*: INT; (* where rodata is loaded *)
41 extraAdr*: INT; (* that room *)
42 bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *)
43 bssOff*: INT; (* the file offset of that table *)
44 textImg*, roImg*: ^U8;
45 placesChunk*: INT; (* the rodata chunk of the places, made by the caller *)
46 linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *)
47 paged*: INT; (* 0, ELF's layout; or Mach-O's page, each segment on one *)
48 rebases*: ^INT; (* the addresses of rodata's words that hold an address *)
49 numRebases*: INT;
50
51proc setBase*(a: INT);
52begin
53 base := a;
54end;
55
56(* Mach-O's layout, its segments on pages of page bytes *)
57proc setPaged*(page: INT);
58begin
59 paged := page;
60end;
61
62proc setPlaces*(c: INT);
63begin
64 placesChunk := c;
65end;
66
67(* Marks live each chunk reached from entry through the fixups. *)
68proc markLive*(entry: INT);
69var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup;
70begin
71 stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
72 Chunk.setLive(entry);
73 stack[0] := entry;
74 sp := 1;
75 while sp > 0 do
76 DEC(sp);
77 c := stack[sp];
78 if Chunk.chunks[c].size < 0 then
79 Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))]));
80 end;
81 (* code and constants have fixups; variables start at zero, holding
82 no addresses *)
83 match Chunk.chunks[c].sec of
84 | secText: fx := Chunk.fixups;
85 | secRodata: fx := Chunk.dataFixups;
86 | secBss: fx := nil;
87 end;
88 if fx # nil then
89 for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
90 t := fx[f].chunk;
91 if not Chunk.chunks[t].live then
92 Chunk.setLive(t);
93 stack[sp] := t;
94 INC(sp);
95 end;
96 end;
97 end;
98 end;
99 (* the places hold the line table a debugger reads, so they are made
100 even when Rt takes no address of them, a kernel's Rt with no places *)
101 if (placesChunk >= 0) and not Chunk.chunks[placesChunk].live then Chunk.setLive(placesChunk); end;
102end;
103
104(* Gives the live chunks of one section their places, from start;
105 returns the end. *)
106proc place(sec: Chunk.Section; start: INT): INT;
107var c, a: INT;
108begin
109 a := start;
110 for c := 0 to Chunk.numChunks - 1 do
111 if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then
112 a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align;
113 Chunk.setAdr(c, a);
114 a := a + Chunk.chunks[c].size;
115 end;
116 end;
117 return a;
118end;
119
120(* The line table, DWARF 4's line program, which gdb reads as
121 .debug_line and Rt to say where code comes from: one sequence for
122 each live procedure with lines, a row for each place noted, its
123 address, file, line and column. A row whose address and line move a
124 little is one byte, a special opcode; the others are made of the
125 standard ones. Made in lp, lpLen bytes long. *)
126const
127 LineBase = -5; LineRange = 14; OpcodeBase = 13; (* the special opcodes' *)
128
129var
130 lp: ^U8;
131 lpLen, lpCap: INT;
132
133proc putB(v: INT);
134begin
135 if lpLen = lpCap then
136 lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256);
137 lpCap := lpCap * 2 + 256;
138 end;
139 lp[lpLen] := U8(v & 0FFH);
140 INC(lpLen);
141end;
142
143(* The n low bytes of v, least significant first *)
144proc putN(v: INT; n: INT);
145var i: INT;
146begin
147 for i := 1 to n do putB(v); v := v shr 8; end;
148end;
149
150(* LEB128, unsigned and signed *)
151proc putU(v: INT);
152begin
153 while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end;
154 putB(v);
155end;
156
157proc putS(v: INT);
158begin
159 while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end;
160 putB(v & 7FH);
161end;
162
163(* v as the four bytes at at in p *)
164proc patch4(p: ^U8; at, v: INT);
165var i: INT;
166begin
167 for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end;
168end;
169
170(* v as the eight bytes at at in p *)
171proc patch8(p: ^U8; at, v: INT);
172var i: INT;
173begin
174 for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end;
175end;
176
177(* Whether the standard opcode i takes an operand *)
178proc takesOperand(i: INT): BOOL;
179begin
180 return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12);
181end;
182
183(* The line program of the files paths, nfiles of them, numbered from
184 1, as they are written in the table *)
185proc makeLines(paths: ^INT; nfiles: INT);
186var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []const U8;
187begin
188 lpLen := 0;
189 putN(0, 4); (* unit_length, patched below *)
190 putN(4, 2); (* version *)
191 putN(0, 4); (* header_length, patched below *)
192 putB(1); putB(1); (* minimum_instruction_length, maximum_operations *)
193 putB(1); (* default_is_stmt *)
194 putB(LineBase); putB(LineRange); putB(OpcodeBase);
195 for i := 1 to OpcodeBase - 1 do
196 if takesOperand(i) then putB(1); else putB(0); end; (* their operands *)
197 end;
198 putB(0); (* no include directories *)
199 for f := 0 to nfiles - 1 do
200 s := Diag.shownPath(Scan.nameOf(paths[f]));
201 for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end;
202 putN(0, 4); (* its end, directory, time, length *)
203 end;
204 putB(0);
205 patch4(lp, 6, lpLen - 10);
206 i := 0;
207 while i < Chunk.numLines do
208 c := Chunk.lines[i].chunk;
209 if not Chunk.chunks[c].live then
210 INC(i);
211 else
212 putB(0); putU(9); putB(2); (* DW_LNE_set_address *)
213 putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8);
214 at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0;
215 while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do
216 f := 1;
217 while paths[f - 1] # Chunk.lines[i].path do INC(f); end;
218 if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *)
219 if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *)
220 da := Chunk.lines[i].at - at;
221 dl := Chunk.lines[i].line - cl;
222 op := (dl - LineBase) + LineRange * da + OpcodeBase;
223 if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then
224 putB(op); (* a special opcode: a row *)
225 else
226 if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *)
227 if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *)
228 putB(1); (* DW_LNS_copy: a row *)
229 end;
230 at := Chunk.lines[i].at; cl := Chunk.lines[i].line;
231 INC(i);
232 end;
233 putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at);
234 putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *)
235 end;
236 end;
237 patch4(lp, 0, lpLen - 4);
238end;
239
240var
241 buf: ^U8; (* the places, being made *)
242 at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *)
243
244(* The name s, in the pool, and its offset from the pool's start, at at *)
245proc putName(s: []const U8);
246begin
247 patch4(buf, at, names - poolAt);
248 COPY(buf[names..names + LEN(s)], s);
249 buf[names + LEN(s)] := 0;
250 names := names + LEN(s) + 1;
251 at := at + 4;
252end;
253
254(* Whether chunk c is a live procedure, whose places Rt knows *)
255proc isProc(c: INT): BOOL;
256begin
257 return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0);
258end;
259
260(* The places that Rt reads to say where a failed check or a signal
261 was, and what calls were under way: where the line table is in them,
262 where text starts and stops, the numbers of procedures and of their
263 variables (I64s); for each live procedure where it starts and stops,
264 the offset of its name, its first variable and how many it has, and
265 the registers of variables it saves, as bits of Gen's VarRegs, and
266 the frame offset they are saved at (U32s); for each variable the
267 offset of its name, its place in the frame and its kind, as
268 Parse's VarKind (U32s); then the names, each ending in a zero
269 byte; then the line table (makeLines), at linesOff. They are in no
270 order, since Rt looks at them only as the program stops. *)
271proc makePlaces(start, stop: INT);
272var
273 files, first, count: ^INT;
274 i, f, nfiles, np, nv, c, v: INT;
275begin
276 files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT)));
277 first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
278 count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
279 for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end;
280 for v := Chunk.numVarNotes - 1 to 0 by -1 do
281 first[Chunk.varNotes[v].chunk] := v;
282 INC(count[Chunk.varNotes[v].chunk]);
283 end;
284 nfiles := 0; poolAt := 0; np := 0; nv := 0;
285 for i := 0 to Chunk.numLines - 1 do
286 if Chunk.chunks[Chunk.lines[i].chunk].live then
287 f := 0;
288 while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end;
289 if f = nfiles then
290 files[f] := Chunk.lines[i].path;
291 INC(nfiles);
292 end;
293 end;
294 end;
295 makeLines(files, nfiles);
296 for c := 0 to Chunk.numChunks - 1 do
297 if isProc(c) then
298 INC(np);
299 poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1;
300 for v := first[c] to first[c] + count[c] - 1 do
301 poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1;
302 end;
303 nv := nv + count[c];
304 end;
305 end;
306 buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen);
307 (* the pool of names starts at poolAt, the line table after it *)
308 poolAt := 40 + 28 * np + 12 * nv;
309 names := poolAt;
310 at := 40;
311 v := 0;
312 for c := 0 to Chunk.numChunks - 1 do
313 if isProc(c) then
314 patch4(buf, at, Chunk.chunks[c].adr);
315 patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size);
316 at := at + 8;
317 putName(Chunk.chunkName(c));
318 patch4(buf, at, v);
319 patch4(buf, at + 4, count[c]);
320 patch4(buf, at + 8, Chunk.chunks[c].saveMask);
321 patch4(buf, at + 12, Chunk.chunks[c].saveAt);
322 at := at + 16;
323 v := v + count[c];
324 end;
325 end;
326 for c := 0 to Chunk.numChunks - 1 do
327 if isProc(c) then
328 for v := first[c] to first[c] + count[c] - 1 do
329 putName(Scan.nameOf(Chunk.varNotes[v].name));
330 patch4(buf, at, Chunk.varNotes[v].off);
331 patch4(buf, at + 4, Chunk.varNotes[v].kind);
332 at := at + 8;
333 end;
334 end;
335 end;
336 linesOff := names;
337 linesSize := lpLen;
338 COPY(buf[names..names + lpLen], lp[0..lpLen]);
339 patch8(buf, 0, linesOff);
340 patch8(buf, 8, start);
341 patch8(buf, 16, stop);
342 patch8(buf, 24, np);
343 patch8(buf, 32, nv);
344 Chunk.setData(placesChunk, buf, names + lpLen, 8);
345end;
346
347(* The compile unit that names the line table, and its abbreviation, DWARF
348 4's .debug_info and .debug_abbrev: the main module's file and the
349 directory it was compiled in, the producer, the line table (at 0 of its
350 section), and the code, all of it. No types and no variables. Each is
351 made in lp, which the line table has left, and returned: copy it
352 before the next call. The address unit of the line table is a byte
353 (minimum_instruction_length 1, in makeLines), so its rows hold, and
354 its advances count, bytes, on arm64 too, where every row is a multiple
355 of 4: DWARF takes that, and no row needs dividing. *)
356proc putStr(s: []const U8);
357var i: INT;
358begin
359 for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end;
360 putB(0);
361end;
362
363proc debugInfo*(name: []const U8): []const U8;
364var cwd: []const U8; err: INT;
365begin
366 lpLen := 0;
367 putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *)
368 putU(1); (* abbreviation 1 *)
369 putStr(name);
370 cwd, err := Sys.workDir();
371 if err # 0 then cwd := ""; end;
372 putStr(cwd);
373 putStr("raz");
374 putN(0, 4); (* the line table, at 0 *)
375 putN(base + textOff, 8); putN(textSize, 8); (* the code, all of it *)
376 patch4(lp, 0, lpLen - 4);
377 return lp[0..lpLen];
378end;
379
380proc debugAbbrev*: []const U8;
381begin
382 lpLen := 0;
383 putU(1); putU(11H); putB(0); (* 1: a compile unit, no children *)
384 putU(03H); putU(08H); (* name, a string *)
385 putU(1BH); putU(08H); (* comp_dir, a string *)
386 putU(25H); putU(08H); (* producer, a string *)
387 putU(10H); putU(17H); (* stmt_list, a section offset *)
388 putU(11H); putU(01H); (* low_pc, an address *)
389 putU(12H); putU(07H); (* high_pc, a length in 8 bytes *)
390 putN(0, 2); putB(0);
391 return lp[0..lpLen];
392end;
393
394(* The address a as raz writes it, in hexadecimal: 0FFFFFFFF80000000H *)
395proc literal(a: INT): []const U8;
396var s: []const U8;
397begin
398 s := Diag.say("{}H", [Fmt.hex(U64(a))]);
399 if s[0] > '9' then s := Diag.say("0{}", [Fmt.str(s)]); end;
400 return s;
401end;
402
403(* The arm64 instruction at at in text, at address pc, made to reach
404 the address v, as its kind says (Chunk.FixKind):
405 fxBranch26 b, bl: (v - pc) / 4 in imm26, bits 0 to 25
406 fxPage21 adrp: v's page less pc's, in pages of 4 KB, its low
407 two bits in immlo (29, 30), the rest in immhi (5 to 23)
408 fxPageOff12 add: v's place in its page in imm12 (10 to 21); a load
409 or store (bits 27 to 29 111, 24 and 25 01) that place
410 divided by the size it moves, 1 shl its bits 30 and 31,
411 or 16 for a q register (bit 26, the reals', with bit 23)
412 The fields hold zeros, as A64 left them. *)
413proc patchArm(at: INT; kind: Chunk.FixKind; pc, v: INT);
414var insn, d, sc: INT;
415begin
416 insn := 0;
417 for d := 3 to 0 by -1 do insn := insn * 256 + INT(textImg[at + d]); end;
418 match kind of
419 | fxBranch26:
420 d := (v - pc) div 4;
421 if (d < -(1 shl 25)) or (d >= 1 shl 25) then Diag.fatal("the program's code is more than 128 MB"); end;
422 insn := insn | (d & 3FFFFFFH);
423 | fxPage21:
424 d := (v shr 12) - (pc shr 12);
425 insn := insn | ((d & 3) shl 29) | (((d shr 2) & 7FFFFH) shl 5);
426 | fxPageOff12:
427 d := v & 0FFFH;
428 if (insn & 3B000000H) = 39000000H then
429 sc := (insn shr 30) & 3;
430 if (insn & 04800000H) = 04800000H then sc := 4; end;
431 d := d shr sc;
432 end;
433 insn := insn | (d shl 10);
434 | else:
435 end;
436 patch4(textImg, at, insn);
437end;
438
439(* Places the live chunks, leaving roExtra bytes at the end of rodata
440 and dynSize at the start of the writable segment. The segments follow
441 each other in the file with no padding, and each is loaded a page
442 further from its file offset than the one before: rodata at base +
443 Page + roOff, the writable segment at base + 2 * Page + bssOff. So an
444 address and its offset agree within a page, as the loader needs, and
445 no two segments, with their different permissions, share a page.
446 The bss of a program without the loader's table has no bytes in the
447 file, and starts on a page of its own. *)
448proc linkAll*(headerSize, roExtra, dynSize: INT);
449var c, f, at, p, e, v: INT;
450begin
451 textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *)
452 e := place(Chunk.secText, base + textOff);
453 textSize := e - (base + textOff);
454 if placesChunk >= 0 then makePlaces(base + textOff, e); end;
455 roOff := (textOff + textSize + 31) div 32 * 32;
456 roAdr := base + Page + roOff;
457 if paged > 0 then (* Mach-O: rodata on a page of its own, at its offset *)
458 roOff := (textOff + textSize + paged - 1) div paged * paged;
459 roAdr := base + roOff;
460 end;
461 e := place(Chunk.secRodata, roAdr);
462 extraAdr := (e + 7) div 8 * 8;
463 if roExtra > 0 then e := extraAdr + roExtra; end;
464 roSize := e - roAdr;
465 bssOff := (roOff + roSize + 31) div 32 * 32;
466 if paged > 0 then
467 bssOff := (roOff + roSize + paged - 1) div paged * paged;
468 bssAdr := base + bssOff;
469 elsif dynSize > 0 then
470 bssAdr := base + 2 * Page + bssOff;
471 else
472 bssAdr := (roAdr + roSize + Page - 1) div Page * Page;
473 end;
474 e := place(Chunk.secBss, bssAdr + dynSize);
475 bssSize := e - bssAdr;
476 (* An address X64.memAbs makes is 32 bits, which the machine extends
477 by their sign, so the image must lie where such an address reaches:
478 the low 2 GB, as at 400000H, or the top 2 GB, as a higher-half
479 kernel at 0FFFFFFFF80000000H. The places keep each procedure's
480 start and stop in 32 bits too, which Rt.procAt reads so. Mach-O's
481 image lies at 4 GB and up, which arm64's code reaches by adrp, and
482 whose places, below 4 GB of it, keep their order in 32 bits. *)
483 (* By the size, e - base, which can't overflow, where e itself might *)
484 if (paged = 0) and not (((base >= 0) and (base <= Low - (e - base))) or ((base >= -Low) and (base <= -(e - base)))) then
485 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",
486 [Fmt.str(literal(base))]));
487 end;
488
489 textImg := Scan.grab(textSize + 1);
490 (* the gaps between code chunks are Gen's trap, as in Chunk *)
491 for p := 0 to textSize do textImg[p] := U8((Chunk.pad shr (8 * ((textOff + p) & 3))) & 0FFH); end;
492 roImg := Scan.grab(roSize + 1);
493 rebases := ^INT(Scan.grab(Chunk.numDataFixups * SIZE(INT) + SIZE(INT)));
494 numRebases := 0;
495 for p := 0 to roSize do roImg[p] := 0; end;
496 for c := 0 to Chunk.numChunks - 1 do
497 if Chunk.chunks[c].live then
498 if Chunk.chunks[c].sec = Chunk.secText then
499 p := Chunk.chunks[c].adr - (base + textOff);
500 COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
501 for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
502 at := Chunk.fixups[f].at - Chunk.chunks[c].start;
503 v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend;
504 if Chunk.fixups[f].kind # Chunk.fxRel32 then
505 patchArm(p + at, Chunk.fixups[f].kind, Chunk.chunks[c].adr + at, v);
506 else
507 (* rel32: from the end of the field to the target;
508 or, X64.memAbs's, the target's address *)
509 if not Chunk.fixups[f].abs then v := v - (Chunk.chunks[c].adr + at + 4); end;
510 patch4(textImg, p + at, v);
511 end;
512 end;
513 elsif Chunk.chunks[c].sec = Chunk.secRodata then
514 p := Chunk.chunks[c].adr - roAdr;
515 COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
516 for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
517 patch8(roImg, p + Chunk.dataFixups[f].at,
518 Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend);
519 rebases[numRebases] := Chunk.chunks[c].adr + Chunk.dataFixups[f].at;
520 INC(numRebases);
521 end;
522 end;
523 end;
524 end;
525end;
526
527begin
528 placesChunk := -1;
529 base := 400000H;
530 paged := 0;
531end Link.