1pub const Atom = @import("Elf/Atom.zig");
2
3base: link.File,
4zig_object: ?*ZigObject,
5rpath_table: std.array_hash_map.String(void),
6image_base: u64,
7z_nodelete: bool,
8z_notext: bool,
9z_defs: bool,
10z_origin: bool,
11z_nocopyreloc: bool,
12z_now: bool,
13z_relro: bool,
14/// TODO make this non optional and resolve the default in open()
15z_common_page_size: ?u64,
16/// TODO make this non optional and resolve the default in open()
17z_max_page_size: ?u64,
18soname: ?[]const u8,
19entry_name: ?[]const u8,
20
21ptr_width: PtrWidth,
22
23/// A list of all input files.
24/// First index is a special "null file". Order is otherwise not observed.
25files: std.MultiArrayList(File.Entry) = .{},
26/// Long-lived list of all file descriptors.
27/// We store them globally rather than per actual File so that we can re-use
28/// one file handle per every object file within an archive.
29file_handles: std.ArrayList(File.Handle) = .empty,
30zig_object_index: ?File.Index = null,
31linker_defined_index: ?File.Index = null,
32objects: std.ArrayList(File.Index) = .empty,
33shared_objects: std.array_hash_map.String(File.Index) = .empty,
34
35/// List of all output sections and their associated metadata.
36sections: std.MultiArrayList(Section) = .{},
37/// File offset into the shdr table.
38shdr_table_offset: ?u64 = null,
39
40/// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
41/// Same order as in the file.
42phdrs: ProgramHeaderList = .empty,
43
44/// Special program headers.
45phdr_indexes: ProgramHeaderIndexes = .{},
46section_indexes: SectionIndexes = .{},
47
48page_size: u32,
49default_sym_version: elf.Versym,
50
51/// .shstrtab buffer
52shstrtab: std.ArrayList(u8) = .empty,
53/// .symtab buffer
54symtab: std.ArrayList(elf.Elf64_Sym) = .empty,
55/// .strtab buffer
56strtab: std.ArrayList(u8) = .empty,
57/// Dynamic symbol table. Only populated and emitted when linking dynamically.
58dynsym: DynsymSection = .{},
59/// .dynstrtab buffer
60dynstrtab: std.ArrayList(u8) = .empty,
61/// Version symbol table. Only populated and emitted when linking dynamically.
62versym: std.ArrayList(elf.Versym) = .empty,
63/// .verneed section
64verneed: VerneedSection = .{},
65/// .got section
66got: GotSection = .{},
67/// .rela.dyn section
68rela_dyn: std.ArrayList(elf.Elf64_Rela) = .empty,
69/// .dynamic section
70dynamic: DynamicSection = .{},
71/// .hash section
72hash: HashSection = .{},
73/// .gnu.hash section
74gnu_hash: GnuHashSection = .{},
75/// .plt section
76plt: PltSection = .{},
77/// .got.plt section
78got_plt: GotPltSection = .{},
79/// .plt.got section
80plt_got: PltGotSection = .{},
81/// .copyrel section
82copy_rel: CopyRelSection = .{},
83/// .rela.plt section
84rela_plt: std.ArrayList(elf.Elf64_Rela) = .empty,
85/// SHT_GROUP sections
86/// Applies only to a relocatable.
87group_sections: std.ArrayList(GroupSection) = .empty,
88
89resolver: SymbolResolver = .{},
90
91has_text_reloc: bool = false,
92num_ifunc_dynrelocs: usize = 0,
93
94/// List of range extension thunks.
95thunks: std.ArrayList(Thunk) = .empty,
96
97/// List of output merge sections with deduped contents.
98merge_sections: std.ArrayList(Merge.Section) = .empty,
99comment_merge_section_index: ?Merge.Section.Index = null,
100
101/// `--verbose-link` output.
102/// Initialized on creation, appended to as inputs are added, printed during `flush`.
103dump_argv_list: std.ArrayList([]const u8),
104
105const SectionIndexes = struct {
106 copy_rel: ?u32 = null,
107 dynamic: ?u32 = null,
108 dynstrtab: ?u32 = null,
109 dynsymtab: ?u32 = null,
110 eh_frame: ?u32 = null,
111 eh_frame_rela: ?u32 = null,
112 eh_frame_hdr: ?u32 = null,
113 hash: ?u32 = null,
114 gnu_hash: ?u32 = null,
115 got: ?u32 = null,
116 got_plt: ?u32 = null,
117 interp: ?u32 = null,
118 plt: ?u32 = null,
119 plt_got: ?u32 = null,
120 rela_dyn: ?u32 = null,
121 rela_plt: ?u32 = null,
122 versym: ?u32 = null,
123 verneed: ?u32 = null,
124
125 shstrtab: ?u32 = null,
126 strtab: ?u32 = null,
127 symtab: ?u32 = null,
128};
129
130const ProgramHeaderList = std.ArrayList(elf.Elf64.Phdr);
131
132const OptionalProgramHeaderIndex = enum(u16) {
133 none = std.math.maxInt(u16),
134 _,
135
136 fn unwrap(i: OptionalProgramHeaderIndex) ?ProgramHeaderIndex {
137 if (i == .none) return null;
138 return @fromBackingInt(@intCast(@backingInt(i)));
139 }
140
141 fn int(i: OptionalProgramHeaderIndex) ?u16 {
142 if (i == .none) return null;
143 return @backingInt(i);
144 }
145};
146
147const ProgramHeaderIndex = enum(u16) {
148 _,
149
150 fn toOptional(i: ProgramHeaderIndex) OptionalProgramHeaderIndex {
151 const result: OptionalProgramHeaderIndex = @fromBackingInt(@intCast(@backingInt(i)));
152 assert(result != .none);
153 return result;
154 }
155
156 fn int(i: ProgramHeaderIndex) u16 {
157 return @backingInt(i);
158 }
159};
160
161const ProgramHeaderIndexes = struct {
162 /// PT.PHDR
163 table: OptionalProgramHeaderIndex = .none,
164 /// PT.LOAD for PHDR table
165 /// We add this special load segment to ensure the EHDR and PHDR table are always
166 /// loaded into memory.
167 table_load: OptionalProgramHeaderIndex = .none,
168 /// PT.INTERP
169 interp: OptionalProgramHeaderIndex = .none,
170 /// PT.DYNAMIC
171 dynamic: OptionalProgramHeaderIndex = .none,
172 /// PT.GNU_EH_FRAME
173 gnu_eh_frame: OptionalProgramHeaderIndex = .none,
174 /// PT.GNU_STACK
175 gnu_stack: OptionalProgramHeaderIndex = .none,
176 /// PT.TLS
177 /// TODO I think ELF permits multiple TLS segments but for now, assume one per file.
178 tls: OptionalProgramHeaderIndex = .none,
179};
180
181/// When allocating, the ideal_capacity is calculated by
182/// actual_capacity + (actual_capacity / ideal_factor)
183const ideal_factor = 3;
184
185/// In order for a slice of bytes to be considered eligible to keep metadata pointing at
186/// it as a possible place to put new symbols, it must have enough room for this many bytes
187/// (plus extra for reserved capacity).
188const minimum_atom_size = 64;
189pub const min_text_capacity = padToIdeal(minimum_atom_size);
190
191pub const PtrWidth = enum { p32, p64 };
192
193pub fn createEmpty(
194 arena: Allocator,
195 comp: *Compilation,
196 emit: Path,
197 options: link.File.OpenOptions,
198) !*Elf {
199 const target = &comp.root_mod.resolved_target.result;
200 assert(target.ofmt == .elf);
201
202 const use_llvm = comp.config.use_llvm;
203 const opt_zcu = comp.zcu;
204 const output_mode = comp.config.output_mode;
205 const link_mode = comp.config.link_mode;
206 const optimize_mode = comp.root_mod.optimize_mode;
207 const is_native_os = comp.root_mod.resolved_target.is_native_os;
208 const ptr_width: PtrWidth = switch (target.ptrBitWidth()) {
209 0...32 => .p32,
210 33...64 => .p64,
211 else => return error.UnsupportedELFArchitecture,
212 };
213
214 // This is the max page size that the target system can run with, aka the ABI page size. Not to
215 // be confused with the common page size, which is the page size that's used in practice on most
216 // systems.
217 const page_size: u32 = switch (target.cpu.arch) {
218 .bpfel,
219 .bpfeb,
220 .sparc64,
221 => 0x100000,
222 .aarch64,
223 .aarch64_be,
224 .amdgcn,
225 .hexagon,
226 .mips,
227 .mipsel,
228 .mips64,
229 .mips64el,
230 .powerpc,
231 .powerpcle,
232 .powerpc64,
233 .powerpc64le,
234 .sparc,
235 => 0x10000,
236 .loongarch32,
237 .loongarch64,
238 => 0x4000,
239 .arc,
240 .m68k,
241 => 0x2000,
242 .msp430,
243 => 0x4,
244 .avr,
245 => 0x1,
246 else => 0x1000,
247 };
248
249 const is_dyn_lib = output_mode == .Lib and link_mode == .dynamic;
250 const default_sym_version: elf.Versym = if (is_dyn_lib or comp.config.rdynamic) .GLOBAL else .LOCAL;
251
252 var rpath_table: std.array_hash_map.String(void) = .empty;
253 try rpath_table.entries.resize(arena, options.rpath_list.len);
254 @memcpy(rpath_table.entries.items(.key), options.rpath_list);
255 try rpath_table.reIndex(arena);
256
257 const self = try arena.create(Elf);
258 self.* = .{
259 .base = .{
260 .tag = .elf,
261 .comp = comp,
262 .emit = emit,
263 .gc_sections = options.gc_sections orelse (optimize_mode != .debug and output_mode != .Obj),
264 .print_gc_sections = options.print_gc_sections,
265 .stack_size = options.stack_size orelse 16777216,
266 .allow_shlib_undefined = options.allow_shlib_undefined orelse !is_native_os,
267 .file = null,
268 .build_id = options.build_id,
269 },
270 .zig_object = null,
271 .rpath_table = rpath_table,
272 .ptr_width = ptr_width,
273 .page_size = page_size,
274 .default_sym_version = default_sym_version,
275
276 .entry_name = switch (options.entry) {
277 .disabled => null,
278 .default => if (output_mode != .Exe) null else defaultEntrySymbolName(target.cpu.arch),
279 .enabled => defaultEntrySymbolName(target.cpu.arch),
280 .named => |name| name,
281 },
282
283 .image_base = b: {
284 if (is_dyn_lib) break :b 0;
285 if (output_mode == .Exe and (comp.config.pie or target.os.tag == .haiku)) break :b 0;
286 break :b options.image_base orelse switch (ptr_width) {
287 .p32 => 0x10000,
288 .p64 => 0x1000000,
289 };
290 },
291
292 .z_nodelete = options.z_nodelete,
293 .z_notext = options.z_notext,
294 .z_defs = options.z_defs,
295 .z_origin = options.z_origin,
296 .z_nocopyreloc = options.z_nocopyreloc,
297 .z_now = options.z_now,
298 .z_relro = options.z_relro,
299 .z_common_page_size = options.z_common_page_size,
300 .z_max_page_size = options.z_max_page_size,
301 .soname = options.soname,
302 .dump_argv_list = .empty,
303 };
304 errdefer self.base.destroy();
305
306 // --verbose-link
307 if (comp.verbose_link) try dumpArgvInit(self, arena);
308
309 const is_obj = output_mode == .Obj;
310 const is_obj_or_ar = is_obj or (output_mode == .Lib and link_mode == .static);
311
312 const io = comp.io;
313
314 // What path should this ELF linker code output to?
315 const sub_path = emit.sub_path;
316 self.base.file = try emit.root_dir.handle.createFile(io, sub_path, .{
317 .truncate = true,
318 .read = true,
319 .permissions = link.File.determinePermissions(output_mode, link_mode),
320 });
321
322 const gpa = comp.gpa;
323
324 // Append null file at index 0
325 try self.files.append(gpa, .null);
326 // Append null byte to string tables
327 try self.shstrtab.append(gpa, 0);
328 try self.strtab.append(gpa, 0);
329 // There must always be a null shdr in index 0
330 _ = try self.addSection(.{});
331 // Append null symbol in output symtab
332 try self.symtab.append(gpa, null_sym);
333
334 if (!is_obj_or_ar) {
335 try self.dynstrtab.append(gpa, 0);
336
337 // Initialize PT.PHDR program header
338 const p_align: u16 = switch (self.ptr_width) {
339 .p32 => @alignOf(elf.Elf32.Phdr),
340 .p64 => @alignOf(elf.Elf64.Phdr),
341 };
342 const ehsize: u64 = switch (self.ptr_width) {
343 .p32 => @sizeOf(elf.Elf32_Ehdr),
344 .p64 => @sizeOf(elf.Elf64_Ehdr),
345 };
346 const phsize: u64 = switch (self.ptr_width) {
347 .p32 => @sizeOf(elf.Elf32.Phdr),
348 .p64 => @sizeOf(elf.Elf64.Phdr),
349 };
350 const max_nphdrs = comptime getMaxNumberOfPhdrs();
351 const reserved: u64 = mem.alignForward(u64, padToIdeal(max_nphdrs * phsize), self.page_size);
352 self.phdr_indexes.table = (try self.addPhdr(.{
353 .type = @backingInt(elf.PT.PHDR),
354 .flags = elf.PF_R,
355 .@"align" = p_align,
356 .addr = self.image_base + ehsize,
357 .offset = ehsize,
358 .filesz = reserved,
359 .memsz = reserved,
360 })).toOptional();
361 self.phdr_indexes.table_load = (try self.addPhdr(.{
362 .type = @backingInt(elf.PT.LOAD),
363 .flags = elf.PF_R,
364 .@"align" = self.page_size,
365 .addr = self.image_base,
366 .offset = 0,
367 .filesz = reserved + ehsize,
368 .memsz = reserved + ehsize,
369 })).toOptional();
370 }
371
372 if (opt_zcu) |zcu| {
373 if (!use_llvm) {
374 const index: File.Index = @intCast(try self.files.addOne(gpa));
375 self.files.set(index, .zig_object);
376 self.zig_object_index = index;
377 const zig_object = try arena.create(ZigObject);
378 self.zig_object = zig_object;
379 zig_object.* = .{
380 .index = index,
381 .basename = try std.fmt.allocPrint(arena, "{s}.o", .{
382 fs.path.stem(zcu.main_mod.root_src_path),
383 }),
384 };
385 try zig_object.init(self, .{
386 .symbol_count_hint = options.symbol_count_hint,
387 .program_code_size_hint = options.program_code_size_hint,
388 });
389 }
390 }
391
392 return self;
393}
394
395pub fn open(
396 arena: Allocator,
397 comp: *Compilation,
398 emit: Path,
399 options: link.File.OpenOptions,
400) !*Elf {
401 // TODO: restore saved linker state, don't truncate the file, and
402 // participate in incremental compilation.
403 return createEmpty(arena, comp, emit, options);
404}
405
406pub fn deinit(self: *Elf) void {
407 const comp = self.base.comp;
408 const gpa = comp.gpa;
409 const io = comp.io;
410
411 for (self.file_handles.items) |fh| {
412 fh.close(io);
413 }
414 self.file_handles.deinit(gpa);
415
416 for (self.files.items(.tags), self.files.items(.data)) |tag, *data| switch (tag) {
417 .null, .zig_object => {},
418 .linker_defined => data.linker_defined.deinit(gpa),
419 .object => data.object.deinit(gpa),
420 .shared_object => data.shared_object.deinit(gpa),
421 };
422 if (self.zig_object) |zig_object| {
423 zig_object.deinit(gpa);
424 }
425 self.files.deinit(gpa);
426 self.objects.deinit(gpa);
427 self.shared_objects.deinit(gpa);
428
429 for (self.sections.items(.atom_list_2), self.sections.items(.atom_list), self.sections.items(.free_list)) |*atom_list, *atoms, *free_list| {
430 atom_list.deinit(gpa);
431 atoms.deinit(gpa);
432 free_list.deinit(gpa);
433 }
434 self.sections.deinit(gpa);
435 self.phdrs.deinit(gpa);
436 self.shstrtab.deinit(gpa);
437 self.symtab.deinit(gpa);
438 self.strtab.deinit(gpa);
439 self.resolver.deinit(gpa);
440
441 for (self.thunks.items) |*th| {
442 th.deinit(gpa);
443 }
444 self.thunks.deinit(gpa);
445 for (self.merge_sections.items) |*sect| {
446 sect.deinit(gpa);
447 }
448 self.merge_sections.deinit(gpa);
449
450 self.got.deinit(gpa);
451 self.plt.deinit(gpa);
452 self.plt_got.deinit(gpa);
453 self.dynsym.deinit(gpa);
454 self.dynstrtab.deinit(gpa);
455 self.dynamic.deinit(gpa);
456 self.hash.deinit(gpa);
457 self.versym.deinit(gpa);
458 self.verneed.deinit(gpa);
459 self.copy_rel.deinit(gpa);
460 self.rela_dyn.deinit(gpa);
461 self.rela_plt.deinit(gpa);
462 self.group_sections.deinit(gpa);
463 self.dump_argv_list.deinit(gpa);
464}
465
466pub fn getNavVAddr(self: *Elf, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index, reloc_info: link.File.RelocInfo) !u64 {
467 return self.zigObjectPtr().?.getNavVAddr(self, pt, nav_index, reloc_info);
468}
469
470pub fn lowerUav(
471 self: *Elf,
472 pt: Zcu.PerThread,
473 uav: InternPool.Index,
474 explicit_alignment: InternPool.Alignment,
475) !link.File.SymbolId {
476 return self.zigObjectPtr().?.lowerUav(self, pt, uav, explicit_alignment);
477}
478
479pub fn getUavVAddr(self: *Elf, uav: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
480 return self.zigObjectPtr().?.getUavVAddr(self, uav, reloc_info);
481}
482
483/// Returns end pos of collision, if any.
484fn detectAllocCollision(self: *Elf, start: u64, size: u64) !?u64 {
485 const comp = self.base.comp;
486 const io = comp.io;
487 const small_ptr = self.ptr_width == .p32;
488 const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr);
489 if (start < ehdr_size)
490 return ehdr_size;
491
492 var at_end = true;
493 const end = start + padToIdeal(size);
494
495 if (self.shdr_table_offset) |off| {
496 const shdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Shdr) else @sizeOf(elf.Elf64_Shdr);
497 const tight_size = self.sections.items(.shdr).len * shdr_size;
498 const increased_size = padToIdeal(tight_size);
499 const test_end = off +| increased_size;
500 if (start < test_end) {
501 if (end > off) return test_end;
502 if (test_end < std.math.maxInt(u64)) at_end = false;
503 }
504 }
505
506 for (self.sections.items(.shdr)) |shdr| {
507 if (shdr.sh_type == elf.SHT_NOBITS) continue;
508 const increased_size = padToIdeal(shdr.sh_size);
509 const test_end = shdr.sh_offset +| increased_size;
510 if (start < test_end) {
511 if (end > shdr.sh_offset) return test_end;
512 if (test_end < std.math.maxInt(u64)) at_end = false;
513 }
514 }
515
516 for (self.phdrs.items) |phdr| {
517 if (phdr.type != .LOAD) continue;
518 const increased_size = padToIdeal(phdr.filesz);
519 const test_end = phdr.offset +| increased_size;
520 if (start < test_end) {
521 if (end > phdr.offset) return test_end;
522 if (test_end < std.math.maxInt(u64)) at_end = false;
523 }
524 }
525
526 if (at_end) try self.base.file.?.setLength(io, end);
527 return null;
528}
529
530pub fn allocatedSize(self: *Elf, start: u64) u64 {
531 if (start == 0) return 0;
532 var min_pos: u64 = std.math.maxInt(u64);
533 if (self.shdr_table_offset) |off| {
534 if (off > start and off < min_pos) min_pos = off;
535 }
536 for (self.sections.items(.shdr)) |section| {
537 if (section.sh_offset <= start) continue;
538 if (section.sh_offset < min_pos) min_pos = section.sh_offset;
539 }
540 for (self.phdrs.items) |phdr| {
541 if (phdr.offset <= start) continue;
542 if (phdr.offset < min_pos) min_pos = phdr.offset;
543 }
544 return min_pos - start;
545}
546
547pub fn findFreeSpace(self: *Elf, object_size: u64, min_alignment: u64) !u64 {
548 var start: u64 = 0;
549 while (try self.detectAllocCollision(start, object_size)) |item_end| {
550 start = mem.alignForward(u64, item_end, min_alignment);
551 }
552 return start;
553}
554
555pub fn growSection(self: *Elf, shdr_index: u32, needed_size: u64, min_alignment: u64) !void {
556 const comp = self.base.comp;
557 const io = comp.io;
558 const shdr = &self.sections.items(.shdr)[shdr_index];
559
560 if (shdr.sh_type != elf.SHT_NOBITS) {
561 const allocated_size = self.allocatedSize(shdr.sh_offset);
562 log.debug("allocated size {x} of '{s}', needed size {x}", .{
563 allocated_size,
564 self.getShString(shdr.sh_name),
565 needed_size,
566 });
567
568 if (needed_size > allocated_size) {
569 const existing_size = shdr.sh_size;
570 shdr.sh_size = 0;
571 // Must move the entire section.
572 const new_offset = try self.findFreeSpace(needed_size, min_alignment);
573
574 log.debug("moving '{s}' from 0x{x} to 0x{x}", .{
575 self.getShString(shdr.sh_name),
576 shdr.sh_offset,
577 new_offset,
578 });
579
580 try self.base.copyRangeAll(shdr.sh_offset, new_offset, existing_size);
581
582 shdr.sh_offset = new_offset;
583 } else if (shdr.sh_offset + allocated_size == std.math.maxInt(u64)) {
584 try self.base.file.?.setLength(io, shdr.sh_offset + needed_size);
585 }
586 }
587
588 shdr.sh_size = needed_size;
589 self.markDirty(shdr_index);
590}
591
592fn markDirty(self: *Elf, shdr_index: u32) void {
593 if (self.zigObjectPtr()) |zo| {
594 for ([_]?Symbol.Index{
595 zo.debug_info_index,
596 zo.debug_abbrev_index,
597 zo.debug_aranges_index,
598 zo.debug_str_index,
599 zo.debug_line_index,
600 zo.debug_line_str_index,
601 zo.debug_loclists_index,
602 zo.debug_rnglists_index,
603 }, [_]*bool{
604 &zo.debug_info_section_dirty,
605 &zo.debug_abbrev_section_dirty,
606 &zo.debug_aranges_section_dirty,
607 &zo.debug_str_section_dirty,
608 &zo.debug_line_section_dirty,
609 &zo.debug_line_str_section_dirty,
610 &zo.debug_loclists_section_dirty,
611 &zo.debug_rnglists_section_dirty,
612 }) |maybe_sym_index, dirty| {
613 const sym_index = maybe_sym_index orelse continue;
614 if (zo.symbol(sym_index).atom(self).?.output_section_index == shdr_index) {
615 dirty.* = true;
616 break;
617 }
618 }
619 }
620}
621
622const AllocateChunkResult = struct {
623 value: u64,
624 placement: Ref,
625};
626
627pub fn allocateChunk(self: *Elf, args: struct {
628 size: u64,
629 shndx: u32,
630 alignment: Atom.Alignment,
631 requires_padding: bool = true,
632}) !AllocateChunkResult {
633 const slice = self.sections.slice();
634 const shdr = &slice.items(.shdr)[args.shndx];
635 const free_list = &slice.items(.free_list)[args.shndx];
636 const last_atom_ref = &slice.items(.last_atom)[args.shndx];
637 const new_atom_ideal_capacity = if (args.requires_padding) padToIdeal(args.size) else args.size;
638
639 // First we look for an appropriately sized free list node.
640 // The list is unordered. We'll just take the first thing that works.
641 const res: AllocateChunkResult = blk: {
642 var i: usize = if (self.base.child_pid == null) 0 else free_list.items.len;
643 while (i < free_list.items.len) {
644 const big_atom_ref = free_list.items[i];
645 const big_atom = self.atom(big_atom_ref).?;
646 // We now have a pointer to a live atom that has too much capacity.
647 // Is it enough that we could fit this new atom?
648 const cap = big_atom.capacity(self);
649 const ideal_capacity = if (args.requires_padding) padToIdeal(cap) else cap;
650 const ideal_capacity_end_vaddr = std.math.add(u64, @intCast(big_atom.value), ideal_capacity) catch ideal_capacity;
651 const capacity_end_vaddr = @as(u64, @intCast(big_atom.value)) + cap;
652 const new_start_vaddr_unaligned = capacity_end_vaddr - new_atom_ideal_capacity;
653 const new_start_vaddr = args.alignment.backward(new_start_vaddr_unaligned);
654 if (new_start_vaddr < ideal_capacity_end_vaddr) {
655 // Additional bookkeeping here to notice if this free list node
656 // should be deleted because the block that it points to has grown to take up
657 // more of the extra capacity.
658 if (!big_atom.freeListEligible(self)) {
659 _ = free_list.swapRemove(i);
660 } else {
661 i += 1;
662 }
663 continue;
664 }
665 // At this point we know that we will place the new block here. But the
666 // remaining question is whether there is still yet enough capacity left
667 // over for there to still be a free list node.
668 const remaining_capacity = new_start_vaddr - ideal_capacity_end_vaddr;
669 const keep_free_list_node = remaining_capacity >= min_text_capacity;
670
671 if (!keep_free_list_node) {
672 _ = free_list.swapRemove(i);
673 }
674 break :blk .{ .value = new_start_vaddr, .placement = big_atom_ref };
675 } else if (self.atom(last_atom_ref.*)) |last_atom| {
676 const ideal_capacity = if (args.requires_padding) padToIdeal(last_atom.size) else last_atom.size;
677 const ideal_capacity_end_vaddr = @as(u64, @intCast(last_atom.value)) + ideal_capacity;
678 const new_start_vaddr = args.alignment.forward(ideal_capacity_end_vaddr);
679 break :blk .{ .value = new_start_vaddr, .placement = last_atom.ref() };
680 } else {
681 break :blk .{ .value = 0, .placement = .{} };
682 }
683 };
684
685 const expand_section = if (self.atom(res.placement)) |placement_atom|
686 placement_atom.nextAtom(self) == null
687 else
688 true;
689 if (expand_section) {
690 const needed_size = res.value + args.size;
691 try self.growSection(args.shndx, needed_size, args.alignment.toByteUnits().?);
692 }
693
694 log.debug("allocated chunk (size({x}),align({x})) in {s} at 0x{x} (file(0x{x}))", .{
695 args.size,
696 args.alignment.toByteUnits().?,
697 self.getShString(shdr.sh_name),
698 shdr.sh_addr + res.value,
699 shdr.sh_offset + res.value,
700 });
701 log.debug(" placement {f}, {s}", .{
702 res.placement,
703 if (self.atom(res.placement)) |atom_ptr| atom_ptr.name(self) else "",
704 });
705
706 return res;
707}
708
709pub fn loadInput(self: *Elf, input: link.Input) !void {
710 const comp = self.base.comp;
711 const gpa = comp.gpa;
712 const io = comp.io;
713 const diags = &comp.link_diags;
714 const target = self.getTarget();
715 const debug_fmt_strip = comp.config.debug_format == .strip;
716 const default_sym_version = self.default_sym_version;
717
718 if (comp.verbose_link) {
719 comp.mutex.lockUncancelable(io); // protect comp.arena
720 defer comp.mutex.unlock(io);
721
722 const argv = &self.dump_argv_list;
723 switch (input) {
724 .res => unreachable,
725 .dso_exact => |dso_exact| try argv.appendSlice(gpa, &.{ "-l", dso_exact.name }),
726 .object, .archive => |obj| try argv.append(gpa, try obj.path.toString(comp.arena)),
727 .dso => |dso| try argv.append(gpa, try dso.path.toString(comp.arena)),
728 }
729 }
730
731 switch (input) {
732 .res => unreachable,
733 .dso_exact => @panic("TODO"),
734 .object => |obj| try parseObject(self, obj),
735 .archive => |obj| if (self.base.isStaticLib()) {
736 // Ignore static library inputs when generating a static library.
737 } else {
738 try parseArchive(gpa, io, diags, &self.file_handles, &self.files, target, debug_fmt_strip, default_sym_version, &self.objects, obj);
739 },
740 .dso => |dso| try parseDso(gpa, io, diags, dso, &self.shared_objects, &self.files, target),
741 }
742}
743
744pub fn flush(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.Error!void {
745 const tracy = trace(@src());
746 defer tracy.end();
747
748 const comp = self.base.comp;
749 const io = comp.io;
750 const diags = &comp.link_diags;
751
752 if (comp.verbose_link) try Compilation.dumpArgv(io, self.dump_argv_list.items);
753
754 const sub_prog_node = prog_node.start("ELF Flush", 0);
755 defer sub_prog_node.end();
756
757 return flushInner(self, arena, tid) catch |err| switch (err) {
758 error.OutOfMemory, error.AlreadyReported => |e| return e,
759 else => |e| return diags.fail("ELF flush failed: {t}", .{e}),
760 };
761}
762
763fn flushInner(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id) !void {
764 _ = arena;
765
766 const comp = self.base.comp;
767 const gpa = comp.gpa;
768 const diags = &comp.link_diags;
769
770 if (self.zigObjectPtr()) |zig_object| try zig_object.flush(self, tid);
771
772 switch (comp.config.output_mode) {
773 .Obj => return relocatable.flushObject(self, comp),
774 .Lib => switch (comp.config.link_mode) {
775 .dynamic => {},
776 .static => return relocatable.flushStaticLib(self, comp),
777 },
778 .Exe => {},
779 }
780
781 if (diags.hasErrors()) return error.AlreadyReported;
782
783 // If we haven't already, create a linker-generated input file comprising of
784 // linker-defined synthetic symbols only such as `_DYNAMIC`, etc.
785 if (self.linker_defined_index == null) {
786 const index: File.Index = @intCast(try self.files.addOne(gpa));
787 self.files.set(index, .{ .linker_defined = .{ .index = index } });
788 self.linker_defined_index = index;
789 const object = self.linkerDefinedPtr().?;
790 try object.init(gpa);
791 try object.initSymbols(self);
792 }
793
794 // Now, we are ready to resolve the symbols across all input files.
795 // We will first resolve the files in the ZigObject, next in the parsed
796 // input Object files.
797 // Any qualifing unresolved symbol will be upgraded to an absolute, weak
798 // symbol for potential resolution at load-time.
799 try self.resolveSymbols();
800 self.markEhFrameAtomsDead();
801 try self.resolveMergeSections();
802
803 for (self.objects.items) |index| {
804 try self.file(index).?.object.convertCommonSymbols(self);
805 }
806 self.markImportsExports();
807
808 if (self.base.gc_sections) {
809 try gc.gcAtoms(self);
810 }
811
812 self.checkDuplicates() catch |err| switch (err) {
813 error.HasDuplicates => return error.AlreadyReported,
814 else => |e| return e,
815 };
816
817 try self.addCommentString();
818 try self.finalizeMergeSections();
819 try self.initOutputSections();
820 if (self.linkerDefinedPtr()) |obj| {
821 try obj.initStartStopSymbols(self);
822 }
823 self.claimUnresolved();
824
825 // Scan and create missing synthetic entries such as GOT indirection.
826 try self.scanRelocs();
827
828 // Generate and emit synthetic sections.
829 try self.initSyntheticSections();
830 try self.initSpecialPhdrs();
831 try sortShdrs(
832 gpa,
833 &self.section_indexes,
834 &self.sections,
835 self.shstrtab.items,
836 self.merge_sections.items,
837 self.group_sections.items,
838 self.zigObjectPtr(),
839 self.files,
840 );
841
842 try self.setDynamicSection(self.rpath_table.keys());
843 self.sortDynamicSymtab();
844 try self.setHashSections();
845 try self.setVersionSymtab();
846
847 try self.sortInitFini();
848 try self.updateMergeSectionSizes();
849 try self.updateSectionSizes();
850
851 try self.addLoadPhdrs();
852 try self.allocatePhdrTable();
853 try self.allocateAllocSections();
854 try sortPhdrs(gpa, &self.phdrs, &self.phdr_indexes, self.sections.items(.phndx));
855 try self.allocateNonAllocSections();
856 self.allocateSpecialPhdrs();
857 if (self.linkerDefinedPtr()) |obj| {
858 obj.allocateSymbols(self);
859 }
860
861 // Dump the state for easy debugging.
862 // State can be dumped via `--debug-log link_state`.
863 if (build_options.enable_logging) {
864 state_log.debug("{f}", .{self.dumpState()});
865 }
866
867 // Beyond this point, everything has been allocated a virtual address and we can resolve
868 // the relocations, and commit objects to file.
869 for (self.objects.items) |index| {
870 self.file(index).?.object.dirty = false;
871 }
872 // TODO: would state tracking be more appropriate here? perhaps even custom relocation type?
873 self.rela_dyn.clearRetainingCapacity();
874 self.rela_plt.clearRetainingCapacity();
875
876 if (self.zigObjectPtr()) |zo| {
877 var undefs: std.array_hash_map.Auto(SymbolResolver.Index, std.array_list.Managed(Ref)) = .empty;
878 defer {
879 for (undefs.values()) |*refs| refs.deinit();
880 undefs.deinit(gpa);
881 }
882
883 var has_reloc_errors = false;
884 for (zo.atoms_indexes.items) |atom_index| {
885 const atom_ptr = zo.atom(atom_index) orelse continue;
886 if (!atom_ptr.alive) continue;
887 const out_shndx = atom_ptr.output_section_index;
888 const shdr = &self.sections.items(.shdr)[out_shndx];
889 if (shdr.sh_type == elf.SHT_NOBITS) continue;
890 const code = try zo.codeAlloc(self, atom_index);
891 defer gpa.free(code);
892 const file_offset = atom_ptr.offset(self);
893 (if (shdr.sh_flags & elf.SHF_ALLOC == 0)
894 atom_ptr.resolveRelocsNonAlloc(self, code, &undefs)
895 else
896 atom_ptr.resolveRelocsAlloc(self, code)) catch |err| switch (err) {
897 error.RelocFailure, error.RelaxFailure => has_reloc_errors = true,
898 error.UnsupportedCpuArch => {
899 try self.reportUnsupportedCpuArch();
900 return error.AlreadyReported;
901 },
902 else => |e| return e,
903 };
904 try self.pwriteAll(code, file_offset);
905 }
906
907 try self.reportUndefinedSymbols(&undefs);
908
909 if (has_reloc_errors) return error.AlreadyReported;
910 }
911
912 try self.writePhdrTable();
913 try self.writeShdrTable();
914 try self.writeAtoms();
915 try self.writeMergeSections();
916
917 self.writeSyntheticSections() catch |err| switch (err) {
918 error.RelocFailure => return error.AlreadyReported,
919 error.UnsupportedCpuArch => {
920 try self.reportUnsupportedCpuArch();
921 return error.AlreadyReported;
922 },
923 else => |e| return e,
924 };
925
926 if (self.base.isExe() and self.linkerDefinedPtr().?.entry_index == null) {
927 log.debug("flushing. no_entry_point_found = true", .{});
928 diags.flags.no_entry_point_found = true;
929 } else {
930 log.debug("flushing. no_entry_point_found = false", .{});
931 diags.flags.no_entry_point_found = false;
932 try self.writeElfHeader();
933 }
934
935 if (diags.hasErrors()) return error.AlreadyReported;
936}
937
938fn dumpArgvInit(self: *Elf, arena: Allocator) !void {
939 const comp = self.base.comp;
940 const gpa = comp.gpa;
941 const target = self.getTarget();
942 const full_out_path = try self.base.emit.root_dir.join(arena, &[_][]const u8{self.base.emit.sub_path});
943
944 const argv = &self.dump_argv_list;
945
946 try argv.append(gpa, "zig");
947
948 if (self.base.isStaticLib()) {
949 try argv.append(gpa, "ar");
950 } else {
951 try argv.append(gpa, "ld");
952 }
953
954 if (self.base.isObject()) {
955 try argv.append(gpa, "-r");
956 }
957
958 try argv.append(gpa, "-o");
959 try argv.append(gpa, full_out_path);
960
961 if (!self.base.isRelocatable()) {
962 if (!self.base.isStatic()) {
963 if (target.dynamic_linker.get()) |path| {
964 try argv.appendSlice(gpa, &.{ "-dynamic-linker", try arena.dupe(u8, path) });
965 }
966 }
967
968 if (self.base.isDynLib()) {
969 if (self.soname) |name| {
970 try argv.append(gpa, "-soname");
971 try argv.append(gpa, name);
972 }
973 }
974
975 if (self.entry_name) |name| {
976 try argv.appendSlice(gpa, &.{ "--entry", name });
977 }
978
979 for (self.rpath_table.keys()) |rpath| {
980 try argv.appendSlice(gpa, &.{ "-rpath", rpath });
981 }
982
983 try argv.appendSlice(gpa, &.{
984 "-z",
985 try std.fmt.allocPrint(arena, "stack-size={d}", .{self.base.stack_size}),
986 });
987
988 try argv.append(gpa, try std.fmt.allocPrint(arena, "--image-base={d}", .{self.image_base}));
989
990 if (self.base.gc_sections) {
991 try argv.append(gpa, "--gc-sections");
992 }
993
994 if (self.base.print_gc_sections) {
995 try argv.append(gpa, "--print-gc-sections");
996 }
997
998 if (comp.link_eh_frame_hdr) {
999 try argv.append(gpa, "--eh-frame-hdr");
1000 }
1001
1002 if (comp.config.rdynamic) {
1003 try argv.append(gpa, "--export-dynamic");
1004 }
1005
1006 if (self.z_notext) {
1007 try argv.append(gpa, "-z");
1008 try argv.append(gpa, "notext");
1009 }
1010
1011 if (self.z_nocopyreloc) {
1012 try argv.append(gpa, "-z");
1013 try argv.append(gpa, "nocopyreloc");
1014 }
1015
1016 if (self.z_now) {
1017 try argv.append(gpa, "-z");
1018 try argv.append(gpa, "now");
1019 }
1020
1021 if (self.base.isStatic()) {
1022 try argv.append(gpa, "-static");
1023 } else if (self.isEffectivelyDynLib()) {
1024 try argv.append(gpa, "-shared");
1025 }
1026
1027 if (comp.config.pie and self.base.isExe()) {
1028 try argv.append(gpa, "-pie");
1029 }
1030
1031 if (comp.config.debug_format == .strip) {
1032 try argv.append(gpa, "-s");
1033 }
1034
1035 if (comp.config.link_libc) {
1036 if (self.base.comp.libc_installation) |lci| {
1037 try argv.append(gpa, "-L");
1038 try argv.append(gpa, lci.crt_dir.?);
1039 }
1040 }
1041 }
1042}
1043
1044fn parseObject(self: *Elf, obj: link.Input.Object) !void {
1045 const tracy = trace(@src());
1046 defer tracy.end();
1047
1048 const comp = self.base.comp;
1049 const io = comp.io;
1050 const gpa = comp.gpa;
1051 const diags = &comp.link_diags;
1052 const target = &comp.root_mod.resolved_target.result;
1053 const debug_fmt_strip = comp.config.debug_format == .strip;
1054 const default_sym_version = self.default_sym_version;
1055 const file_handles = &self.file_handles;
1056
1057 const handle = obj.file;
1058 const fh = try addFileHandle(gpa, file_handles, handle);
1059
1060 const index: File.Index = @intCast(try self.files.addOne(gpa));
1061 self.files.set(index, .{ .object = .{
1062 .path = .{
1063 .root_dir = obj.path.root_dir,
1064 .sub_path = try gpa.dupe(u8, obj.path.sub_path),
1065 },
1066 .file_handle = fh,
1067 .index = index,
1068 } });
1069 try self.objects.append(gpa, index);
1070
1071 const object = self.file(index).?.object;
1072 try object.parseCommon(gpa, io, diags, obj.path, handle, target);
1073 if (!self.base.isStaticLib()) {
1074 try object.parse(gpa, io, diags, obj.path, handle, target, debug_fmt_strip, default_sym_version);
1075 }
1076}
1077
1078fn parseArchive(
1079 gpa: Allocator,
1080 io: Io,
1081 diags: *Diags,
1082 file_handles: *std.ArrayList(File.Handle),
1083 files: *std.MultiArrayList(File.Entry),
1084 target: *const std.Target,
1085 debug_fmt_strip: bool,
1086 default_sym_version: elf.Versym,
1087 objects: *std.ArrayList(File.Index),
1088 obj: link.Input.Object,
1089) !void {
1090 const tracy = trace(@src());
1091 defer tracy.end();
1092
1093 const fh = try addFileHandle(gpa, file_handles, obj.file);
1094 var archive = try Archive.parse(gpa, io, diags, file_handles, obj.path, fh);
1095 defer archive.deinit(gpa);
1096
1097 for (archive.objects) |extracted| {
1098 const index: File.Index = @intCast(try files.addOne(gpa));
1099 files.set(index, .{ .object = extracted });
1100 const object = &files.items(.data)[index].object;
1101 object.index = index;
1102 object.alive = obj.must_link;
1103 try object.parseCommon(gpa, io, diags, obj.path, obj.file, target);
1104 try object.parse(gpa, io, diags, obj.path, obj.file, target, debug_fmt_strip, default_sym_version);
1105 try objects.append(gpa, index);
1106 }
1107}
1108
1109fn parseDso(
1110 gpa: Allocator,
1111 io: Io,
1112 diags: *Diags,
1113 dso: link.Input.Dso,
1114 shared_objects: *std.array_hash_map.String(File.Index),
1115 files: *std.MultiArrayList(File.Entry),
1116 target: *const std.Target,
1117) !void {
1118 const tracy = trace(@src());
1119 defer tracy.end();
1120
1121 const handle = dso.file;
1122
1123 const stat = Stat.fromFs(try handle.stat(io));
1124 var header = try SharedObject.parseHeader(gpa, io, diags, dso.path, handle, stat, target);
1125 defer header.deinit(gpa);
1126
1127 const soname = header.soname() orelse dso.path.basename();
1128
1129 const gop = try shared_objects.getOrPut(gpa, soname);
1130 if (gop.found_existing) return;
1131 errdefer _ = shared_objects.pop();
1132
1133 const index: File.Index = @intCast(try files.addOne(gpa));
1134 errdefer _ = files.pop();
1135
1136 gop.value_ptr.* = index;
1137
1138 var parsed = try SharedObject.parse(gpa, io, &header, handle);
1139 errdefer parsed.deinit(gpa);
1140
1141 const duped_path: Path = .{
1142 .root_dir = dso.path.root_dir,
1143 .sub_path = try gpa.dupe(u8, dso.path.sub_path),
1144 };
1145 errdefer gpa.free(duped_path.sub_path);
1146
1147 files.set(index, .{
1148 .shared_object = .{
1149 .parsed = parsed,
1150 .path = duped_path,
1151 .index = index,
1152 .needed = dso.needed,
1153 .alive = dso.needed,
1154 .aliases = null,
1155 .symbols = .empty,
1156 .symbols_extra = .empty,
1157 .symbols_resolver = .empty,
1158 .output_symtab_ctx = .{},
1159 },
1160 });
1161 const so = fileLookup(files.*, index, null).?.shared_object;
1162
1163 // TODO: save this work for later
1164 const nsyms = parsed.symbols.len;
1165 try so.symbols.ensureTotalCapacityPrecise(gpa, nsyms);
1166 try so.symbols_extra.ensureTotalCapacityPrecise(gpa, nsyms * @typeInfo(Symbol.Extra).@"struct".field_names.len);
1167 try so.symbols_resolver.ensureTotalCapacityPrecise(gpa, nsyms);
1168 so.symbols_resolver.appendNTimesAssumeCapacity(0, nsyms);
1169
1170 for (parsed.symtab, parsed.symbols, parsed.versyms, 0..) |esym, sym, versym, i| {
1171 const out_sym_index = so.addSymbolAssumeCapacity();
1172 const out_sym = &so.symbols.items[out_sym_index];
1173 out_sym.value = @intCast(esym.st_value);
1174 out_sym.name_offset = sym.mangled_name;
1175 out_sym.ref = .{ .index = 0, .file = 0 };
1176 out_sym.esym_index = @intCast(i);
1177 out_sym.version_index = versym;
1178 out_sym.extra_index = so.addSymbolExtraAssumeCapacity(.{});
1179 }
1180}
1181
1182/// When resolving symbols, we approach the problem similarly to `mold`.
1183/// 1. Resolve symbols across all objects (including those preemptively extracted archives).
1184/// 2. Resolve symbols across all shared objects.
1185/// 3. Mark live objects (see `Elf.markLive`)
1186/// 4. Reset state of all resolved globals since we will redo this bit on the pruned set.
1187/// 5. Remove references to dead objects/shared objects
1188/// 6. Re-run symbol resolution on pruned objects and shared objects sets.
1189pub fn resolveSymbols(self: *Elf) !void {
1190 // This function mutates `shared_objects`.
1191 const shared_objects = &self.shared_objects;
1192
1193 // Resolve symbols in the ZigObject. For now, we assume that it's always live.
1194 if (self.zigObjectPtr()) |zo| try zo.asFile().resolveSymbols(self);
1195 // Resolve symbols on the set of all objects and shared objects (even if some are unneeded).
1196 for (self.objects.items) |index| try self.file(index).?.resolveSymbols(self);
1197 for (shared_objects.values()) |index| try self.file(index).?.resolveSymbols(self);
1198 if (self.linkerDefinedPtr()) |obj| try obj.asFile().resolveSymbols(self);
1199
1200 // Mark live objects.
1201 self.markLive();
1202
1203 // Reset state of all globals after marking live objects.
1204 self.resolver.reset();
1205
1206 // Prune dead objects and shared objects.
1207 var i: usize = 0;
1208 while (i < self.objects.items.len) {
1209 const index = self.objects.items[i];
1210 if (!self.file(index).?.isAlive()) {
1211 _ = self.objects.orderedRemove(i);
1212 } else i += 1;
1213 }
1214 // TODO This loop has 2 major flaws:
1215 // 1. It is O(N^2) which is never allowed in the codebase.
1216 // 2. It mutates shared_objects, which is a non-starter for incremental compilation.
1217 i = 0;
1218 while (i < shared_objects.values().len) {
1219 const index = shared_objects.values()[i];
1220 if (!self.file(index).?.isAlive()) {
1221 _ = shared_objects.orderedRemoveAt(i);
1222 } else i += 1;
1223 }
1224
1225 {
1226 // Dedup groups.
1227 var table = std.StringHashMap(Ref).init(self.base.comp.gpa);
1228 defer table.deinit();
1229
1230 for (self.objects.items) |index| {
1231 try self.file(index).?.object.resolveGroups(self, &table);
1232 }
1233
1234 for (self.objects.items) |index| {
1235 self.file(index).?.object.markGroupsDead(self);
1236 }
1237 }
1238
1239 // Re-resolve the symbols.
1240 if (self.zigObjectPtr()) |zo| try zo.asFile().resolveSymbols(self);
1241 for (self.objects.items) |index| try self.file(index).?.resolveSymbols(self);
1242 for (shared_objects.values()) |index| try self.file(index).?.resolveSymbols(self);
1243 if (self.linkerDefinedPtr()) |obj| try obj.asFile().resolveSymbols(self);
1244}
1245
1246/// Traverses all objects and shared objects marking any object referenced by
1247/// a live object/shared object as alive itself.
1248/// This routine will prune unneeded objects extracted from archives and
1249/// unneeded shared objects.
1250fn markLive(self: *Elf) void {
1251 const shared_objects = self.shared_objects.values();
1252 if (self.zigObjectPtr()) |zig_object| zig_object.asFile().markLive(self);
1253 for (self.objects.items) |index| {
1254 const file_ptr = self.file(index).?;
1255 if (file_ptr.isAlive()) file_ptr.markLive(self);
1256 }
1257 for (shared_objects) |index| {
1258 const file_ptr = self.file(index).?;
1259 if (file_ptr.isAlive()) file_ptr.markLive(self);
1260 }
1261}
1262
1263pub fn markEhFrameAtomsDead(self: *Elf) void {
1264 for (self.objects.items) |index| {
1265 const file_ptr = self.file(index).?;
1266 if (!file_ptr.isAlive()) continue;
1267 file_ptr.object.markEhFrameAtomsDead(self);
1268 }
1269}
1270
1271fn markImportsExports(self: *Elf) void {
1272 const shared_objects = self.shared_objects.values();
1273 if (self.zigObjectPtr()) |zo| {
1274 zo.markImportsExports(self);
1275 }
1276 for (self.objects.items) |index| {
1277 self.file(index).?.object.markImportsExports(self);
1278 }
1279 if (!self.isEffectivelyDynLib()) {
1280 for (shared_objects) |index| {
1281 self.file(index).?.shared_object.markImportExports(self);
1282 }
1283 }
1284}
1285
1286fn claimUnresolved(self: *Elf) void {
1287 if (self.zigObjectPtr()) |zig_object| {
1288 zig_object.claimUnresolved(self);
1289 }
1290 for (self.objects.items) |index| {
1291 self.file(index).?.object.claimUnresolved(self);
1292 }
1293}
1294
1295/// In scanRelocs we will go over all live atoms and scan their relocs.
1296/// This will help us work out what synthetics to emit, GOT indirection, etc.
1297/// This is also the point where we will report undefined symbols for any
1298/// alloc sections.
1299fn scanRelocs(self: *Elf) !void {
1300 const gpa = self.base.comp.gpa;
1301 const shared_objects = self.shared_objects.values();
1302
1303 var undefs: std.array_hash_map.Auto(SymbolResolver.Index, std.array_list.Managed(Ref)) = .empty;
1304 defer {
1305 for (undefs.values()) |*refs| refs.deinit();
1306 undefs.deinit(gpa);
1307 }
1308
1309 var has_reloc_errors = false;
1310 if (self.zigObjectPtr()) |zo| {
1311 zo.asFile().scanRelocs(self, &undefs) catch |err| switch (err) {
1312 error.RelaxFailure => unreachable,
1313 error.UnsupportedCpuArch => {
1314 try self.reportUnsupportedCpuArch();
1315 return error.AlreadyReported;
1316 },
1317 error.RelocFailure => has_reloc_errors = true,
1318 else => |e| return e,
1319 };
1320 }
1321 for (self.objects.items) |index| {
1322 self.file(index).?.scanRelocs(self, &undefs) catch |err| switch (err) {
1323 error.RelaxFailure => unreachable,
1324 error.UnsupportedCpuArch => {
1325 try self.reportUnsupportedCpuArch();
1326 return error.AlreadyReported;
1327 },
1328 error.RelocFailure => has_reloc_errors = true,
1329 else => |e| return e,
1330 };
1331 }
1332
1333 try self.reportUndefinedSymbols(&undefs);
1334
1335 if (has_reloc_errors) return error.AlreadyReported;
1336
1337 if (self.zigObjectPtr()) |zo| {
1338 try zo.asFile().createSymbolIndirection(self);
1339 }
1340 for (self.objects.items) |index| {
1341 try self.file(index).?.createSymbolIndirection(self);
1342 }
1343 for (shared_objects) |index| {
1344 try self.file(index).?.createSymbolIndirection(self);
1345 }
1346 if (self.linkerDefinedPtr()) |obj| {
1347 try obj.asFile().createSymbolIndirection(self);
1348 }
1349 if (self.got.flags.needs_tlsld) {
1350 log.debug("program needs TLSLD", .{});
1351 try self.got.addTlsLdSymbol(self);
1352 }
1353}
1354
1355pub fn initOutputSection(self: *Elf, args: struct {
1356 name: [:0]const u8,
1357 flags: u64,
1358 type: u32,
1359}) error{OutOfMemory}!u32 {
1360 const name = blk: {
1361 if (self.base.isRelocatable()) break :blk args.name;
1362 if (args.flags & elf.SHF_MERGE != 0) break :blk args.name;
1363 const name_prefixes: []const [:0]const u8 = &.{
1364 ".text", ".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss",
1365 ".preinit_array", ".init_array", ".fini_array", ".tbss", ".tdata", ".gcc_except_table",
1366 ".ctors", ".dtors", ".gnu.warning",
1367 };
1368 inline for (name_prefixes) |prefix| {
1369 if (mem.eql(u8, args.name, prefix) or mem.startsWith(u8, args.name, prefix ++ ".")) {
1370 break :blk prefix;
1371 }
1372 }
1373 break :blk args.name;
1374 };
1375 const @"type" = tt: {
1376 if (self.getTarget().cpu.arch == .x86_64 and args.type == elf.SHT_X86_64_UNWIND)
1377 break :tt elf.SHT_PROGBITS;
1378 switch (args.type) {
1379 elf.SHT_NULL => unreachable,
1380 elf.SHT_PROGBITS => {
1381 if (mem.eql(u8, args.name, ".preinit_array") or mem.startsWith(u8, args.name, ".preinit_array."))
1382 break :tt elf.SHT_PREINIT_ARRAY;
1383 if (mem.eql(u8, args.name, ".init_array") or mem.startsWith(u8, args.name, ".init_array."))
1384 break :tt elf.SHT_INIT_ARRAY;
1385 if (mem.eql(u8, args.name, ".fini_array") or mem.startsWith(u8, args.name, ".fini_array."))
1386 break :tt elf.SHT_FINI_ARRAY;
1387 break :tt args.type;
1388 },
1389 else => break :tt args.type,
1390 }
1391 };
1392 const flags = blk: {
1393 var flags = args.flags;
1394 if (!self.base.isRelocatable()) {
1395 flags &= ~@as(u64, elf.SHF_COMPRESSED | elf.SHF_GROUP | elf.SHF_GNU_RETAIN);
1396 }
1397 break :blk switch (@"type") {
1398 elf.SHT_INIT_ARRAY, elf.SHT_FINI_ARRAY => flags | elf.SHF_WRITE,
1399 else => flags,
1400 };
1401 };
1402 const out_shndx = self.sectionByName(name) orelse try self.addSection(.{
1403 .type = @"type",
1404 .flags = flags,
1405 .name = try self.insertShString(name),
1406 });
1407 return out_shndx;
1408}
1409
1410pub fn writeShdrTable(self: *Elf) !void {
1411 const gpa = self.base.comp.gpa;
1412 const target_endian = self.getTarget().cpu.arch.endian();
1413 const foreign_endian = target_endian != builtin.cpu.arch.endian();
1414 const shsize: u64 = switch (self.ptr_width) {
1415 .p32 => @sizeOf(elf.Elf32_Shdr),
1416 .p64 => @sizeOf(elf.Elf64_Shdr),
1417 };
1418 const shalign: u16 = switch (self.ptr_width) {
1419 .p32 => @alignOf(elf.Elf32_Shdr),
1420 .p64 => @alignOf(elf.Elf64_Shdr),
1421 };
1422
1423 const shoff = self.shdr_table_offset orelse 0;
1424 const needed_size = self.sections.items(.shdr).len * shsize;
1425
1426 if (needed_size > self.allocatedSize(shoff)) {
1427 self.shdr_table_offset = null;
1428 self.shdr_table_offset = try self.findFreeSpace(needed_size, shalign);
1429 }
1430
1431 log.debug("writing section headers from 0x{x} to 0x{x}", .{
1432 self.shdr_table_offset.?,
1433 self.shdr_table_offset.? + needed_size,
1434 });
1435
1436 switch (self.ptr_width) {
1437 .p32 => {
1438 const buf = try gpa.alloc(elf.Elf32_Shdr, self.sections.items(.shdr).len);
1439 defer gpa.free(buf);
1440
1441 for (buf, 0..) |*shdr, i| {
1442 assert(self.sections.items(.shdr)[i].sh_offset != math.maxInt(u64));
1443 shdr.* = shdrTo32(self.sections.items(.shdr)[i]);
1444 if (foreign_endian) {
1445 mem.byteSwapAllFields(elf.Elf32_Shdr, shdr);
1446 }
1447 }
1448 try self.pwriteAll(@ptrCast(buf), self.shdr_table_offset.?);
1449 },
1450 .p64 => {
1451 const buf = try gpa.alloc(elf.Elf64_Shdr, self.sections.items(.shdr).len);
1452 defer gpa.free(buf);
1453
1454 for (buf, 0..) |*shdr, i| {
1455 assert(self.sections.items(.shdr)[i].sh_offset != math.maxInt(u64));
1456 shdr.* = self.sections.items(.shdr)[i];
1457 if (foreign_endian) {
1458 mem.byteSwapAllFields(elf.Elf64_Shdr, shdr);
1459 }
1460 }
1461 try self.pwriteAll(@ptrCast(buf), self.shdr_table_offset.?);
1462 },
1463 }
1464}
1465
1466fn writePhdrTable(self: *Elf) !void {
1467 const gpa = self.base.comp.gpa;
1468 const target_endian = self.getTarget().cpu.arch.endian();
1469 const foreign_endian = target_endian != builtin.cpu.arch.endian();
1470 const phdr_table = &self.phdrs.items[self.phdr_indexes.table.int().?];
1471
1472 log.debug("writing program headers from 0x{x} to 0x{x}", .{
1473 phdr_table.offset,
1474 phdr_table.offset + phdr_table.filesz,
1475 });
1476
1477 switch (self.ptr_width) {
1478 .p32 => {
1479 const buf = try gpa.alloc(elf.Elf32.Phdr, self.phdrs.items.len);
1480 defer gpa.free(buf);
1481
1482 for (buf, 0..) |*phdr, i| {
1483 phdr.* = phdrTo32(self.phdrs.items[i]);
1484 if (foreign_endian) {
1485 mem.byteSwapAllFields(elf.Elf32.Phdr, phdr);
1486 }
1487 }
1488 try self.pwriteAll(@ptrCast(buf), phdr_table.offset);
1489 },
1490 .p64 => {
1491 const buf = try gpa.alloc(elf.Elf64.Phdr, self.phdrs.items.len);
1492 defer gpa.free(buf);
1493
1494 for (buf, 0..) |*phdr, i| {
1495 phdr.* = self.phdrs.items[i];
1496 if (foreign_endian) {
1497 mem.byteSwapAllFields(elf.Elf64.Phdr, phdr);
1498 }
1499 }
1500 try self.pwriteAll(@ptrCast(buf), phdr_table.offset);
1501 },
1502 }
1503}
1504
1505pub fn writeElfHeader(self: *Elf) !void {
1506 const diags = &self.base.comp.link_diags;
1507 if (diags.hasErrors()) return; // We had errors, so skip flushing to render the output unusable
1508
1509 const comp = self.base.comp;
1510 var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 = undefined;
1511
1512 var index: usize = 0;
1513 hdr_buf[0..4].* = elf.MAGIC.*;
1514 index += 4;
1515
1516 hdr_buf[index] = switch (self.ptr_width) {
1517 .p32 => elf.ELFCLASS32,
1518 .p64 => elf.ELFCLASS64,
1519 };
1520 index += 1;
1521
1522 const target = self.getTarget();
1523 const endian = target.cpu.arch.endian();
1524 hdr_buf[index] = switch (endian) {
1525 .little => elf.ELFDATA2LSB,
1526 .big => elf.ELFDATA2MSB,
1527 };
1528 index += 1;
1529
1530 hdr_buf[index] = 1; // ELF version
1531 index += 1;
1532
1533 hdr_buf[index] = @backingInt(@as(elf.OSABI, switch (target.cpu.arch) {
1534 .amdgcn => switch (target.os.tag) {
1535 .amdhsa => .AMDGPU_HSA,
1536 .amdpal => .AMDGPU_PAL,
1537 .mesa3d => .AMDGPU_MESA3D,
1538 else => .NONE,
1539 },
1540 .msp430 => .STANDALONE,
1541 else => switch (target.os.tag) {
1542 .freebsd, .ps4 => .FREEBSD,
1543 .hermit => .STANDALONE,
1544 .illumos => .SOLARIS,
1545 .openbsd => .OPENBSD,
1546 else => .NONE,
1547 },
1548 }));
1549 index += 1;
1550
1551 // ABI Version, possibly used by glibc but not by static executables
1552 // padding
1553 @memset(hdr_buf[index..][0..8], 0);
1554 index += 8;
1555
1556 assert(index == 16);
1557
1558 const output_mode = comp.config.output_mode;
1559 const link_mode = comp.config.link_mode;
1560 const elf_type: elf.ET = switch (output_mode) {
1561 .Exe => if (comp.config.pie or target.os.tag == .haiku) .DYN else .EXEC,
1562 .Obj => .REL,
1563 .Lib => switch (link_mode) {
1564 .static => @as(elf.ET, .REL),
1565 .dynamic => .DYN,
1566 },
1567 };
1568 mem.writeInt(u16, hdr_buf[index..][0..2], @backingInt(elf_type), endian);
1569 index += 2;
1570
1571 const machine = target.toElfMachine();
1572 mem.writeInt(u16, hdr_buf[index..][0..2], @backingInt(machine), endian);
1573 index += 2;
1574
1575 // ELF Version, again
1576 mem.writeInt(u32, hdr_buf[index..][0..4], 1, endian);
1577 index += 4;
1578
1579 const e_entry: u64 = if (self.linkerDefinedPtr()) |obj| blk: {
1580 const entry_sym = obj.entrySymbol(self) orelse break :blk 0;
1581 break :blk @intCast(entry_sym.address(.{}, self));
1582 } else 0;
1583 const phdr_table_offset = if (self.phdr_indexes.table.int()) |phndx| self.phdrs.items[phndx].offset else 0;
1584 switch (self.ptr_width) {
1585 .p32 => {
1586 mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(e_entry), endian);
1587 index += 4;
1588
1589 // e_phoff
1590 mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(phdr_table_offset), endian);
1591 index += 4;
1592
1593 // e_shoff
1594 mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(self.shdr_table_offset.?), endian);
1595 index += 4;
1596 },
1597 .p64 => {
1598 // e_entry
1599 mem.writeInt(u64, hdr_buf[index..][0..8], e_entry, endian);
1600 index += 8;
1601
1602 // e_phoff
1603 mem.writeInt(u64, hdr_buf[index..][0..8], phdr_table_offset, endian);
1604 index += 8;
1605
1606 // e_shoff
1607 mem.writeInt(u64, hdr_buf[index..][0..8], self.shdr_table_offset.?, endian);
1608 index += 8;
1609 },
1610 }
1611
1612 const e_flags = 0;
1613 mem.writeInt(u32, hdr_buf[index..][0..4], e_flags, endian);
1614 index += 4;
1615
1616 const e_ehsize: u16 = switch (self.ptr_width) {
1617 .p32 => @sizeOf(elf.Elf32_Ehdr),
1618 .p64 => @sizeOf(elf.Elf64_Ehdr),
1619 };
1620 mem.writeInt(u16, hdr_buf[index..][0..2], e_ehsize, endian);
1621 index += 2;
1622
1623 const e_phentsize: u16 = switch (self.ptr_width) {
1624 .p32 => @sizeOf(elf.Elf32.Phdr),
1625 .p64 => @sizeOf(elf.Elf64.Phdr),
1626 };
1627 mem.writeInt(u16, hdr_buf[index..][0..2], e_phentsize, endian);
1628 index += 2;
1629
1630 const e_phnum = @as(u16, @intCast(self.phdrs.items.len));
1631 mem.writeInt(u16, hdr_buf[index..][0..2], e_phnum, endian);
1632 index += 2;
1633
1634 const e_shentsize: u16 = switch (self.ptr_width) {
1635 .p32 => @sizeOf(elf.Elf32_Shdr),
1636 .p64 => @sizeOf(elf.Elf64_Shdr),
1637 };
1638 mem.writeInt(u16, hdr_buf[index..][0..2], e_shentsize, endian);
1639 index += 2;
1640
1641 const e_shnum: u16 = @intCast(self.sections.items(.shdr).len);
1642 mem.writeInt(u16, hdr_buf[index..][0..2], e_shnum, endian);
1643 index += 2;
1644
1645 mem.writeInt(u16, hdr_buf[index..][0..2], @intCast(self.section_indexes.shstrtab.?), endian);
1646 index += 2;
1647
1648 assert(index == e_ehsize);
1649
1650 try self.pwriteAll(hdr_buf[0..index], 0);
1651}
1652
1653pub fn freeNav(self: *Elf, nav: InternPool.Nav.Index) void {
1654 return self.zigObjectPtr().?.freeNav(self, nav);
1655}
1656
1657pub fn updateFunc(
1658 self: *Elf,
1659 pt: Zcu.PerThread,
1660 func_index: InternPool.Index,
1661 mir: *const codegen.AnyMir,
1662) link.Error!void {
1663 return self.zigObjectPtr().?.updateFunc(self, pt, func_index, mir);
1664}
1665
1666pub fn updateNav(
1667 self: *Elf,
1668 pt: Zcu.PerThread,
1669 nav: InternPool.Nav.Index,
1670) link.Error!void {
1671 return self.zigObjectPtr().?.updateNav(self, pt, nav);
1672}
1673
1674pub fn updateContainerType(
1675 self: *Elf,
1676 pt: Zcu.PerThread,
1677 ty: InternPool.Index,
1678 success: bool,
1679) link.Error!void {
1680 try self.zigObjectPtr().?.updateContainerType(pt, ty, success);
1681}
1682
1683pub fn updateExports(
1684 self: *Elf,
1685 pt: Zcu.PerThread,
1686 export_indices: []const Zcu.Export.Index,
1687) link.Error!void {
1688 return self.zigObjectPtr().?.updateExports(self, pt, export_indices);
1689}
1690
1691pub fn updateLineNumber(self: *Elf, pt: Zcu.PerThread, inst: InternPool.TrackedInst.Index, line: u32) link.Error!void {
1692 return self.zigObjectPtr().?.updateLineNumber(pt, inst, line);
1693}
1694
1695fn checkDuplicates(self: *Elf) !void {
1696 const gpa = self.base.comp.gpa;
1697
1698 var dupes: std.array_hash_map.Auto(SymbolResolver.Index, std.ArrayList(File.Index)) = .empty;
1699 defer {
1700 for (dupes.values()) |*list| {
1701 list.deinit(gpa);
1702 }
1703 dupes.deinit(gpa);
1704 }
1705
1706 if (self.zigObjectPtr()) |zig_object| {
1707 try zig_object.checkDuplicates(&dupes, self);
1708 }
1709 for (self.objects.items) |index| {
1710 try self.file(index).?.object.checkDuplicates(&dupes, self);
1711 }
1712
1713 try self.reportDuplicates(dupes);
1714}
1715
1716pub fn addCommentString(self: *Elf) !void {
1717 const gpa = self.base.comp.gpa;
1718 if (self.comment_merge_section_index != null) return;
1719 const msec_index = try self.getOrCreateMergeSection(".comment", elf.SHF_MERGE | elf.SHF_STRINGS, elf.SHT_PROGBITS);
1720 const msec = self.mergeSection(msec_index);
1721 const res = try msec.insertZ(gpa, "zig " ++ builtin.zig_version_string);
1722 if (res.found_existing) return;
1723 const msub_index = try msec.addMergeSubsection(gpa);
1724 const msub = msec.mergeSubsection(msub_index);
1725 msub.merge_section_index = msec_index;
1726 msub.string_index = res.key.pos;
1727 msub.alignment = .@"1";
1728 msub.size = res.key.len;
1729 msub.entsize = 1;
1730 msub.alive = true;
1731 res.sub.* = msub_index;
1732 self.comment_merge_section_index = msec_index;
1733}
1734
1735pub fn resolveMergeSections(self: *Elf) !void {
1736 const tracy = trace(@src());
1737 defer tracy.end();
1738
1739 var has_errors = false;
1740 for (self.objects.items) |index| {
1741 const object = self.file(index).?.object;
1742 if (!object.alive) continue;
1743 if (!object.dirty) continue;
1744 object.initInputMergeSections(self) catch |err| switch (err) {
1745 error.AlreadyReported => has_errors = true,
1746 else => |e| return e,
1747 };
1748 }
1749
1750 if (has_errors) return error.AlreadyReported;
1751
1752 for (self.objects.items) |index| {
1753 const object = self.file(index).?.object;
1754 if (!object.alive) continue;
1755 if (!object.dirty) continue;
1756 try object.initOutputMergeSections(self);
1757 }
1758
1759 for (self.objects.items) |index| {
1760 const object = self.file(index).?.object;
1761 if (!object.alive) continue;
1762 if (!object.dirty) continue;
1763 object.resolveMergeSubsections(self) catch |err| switch (err) {
1764 error.AlreadyReported => has_errors = true,
1765 else => |e| return e,
1766 };
1767 }
1768
1769 if (has_errors) return error.AlreadyReported;
1770}
1771
1772pub fn finalizeMergeSections(self: *Elf) !void {
1773 for (self.merge_sections.items) |*msec| {
1774 try msec.finalize(self.base.comp.gpa);
1775 }
1776}
1777
1778pub fn updateMergeSectionSizes(self: *Elf) !void {
1779 for (self.merge_sections.items) |*msec| {
1780 msec.updateSize();
1781 }
1782 for (self.merge_sections.items) |*msec| {
1783 const shdr = &self.sections.items(.shdr)[msec.output_section_index];
1784 const offset = msec.alignment.forward(shdr.sh_size);
1785 const padding = offset - shdr.sh_size;
1786 msec.value = @intCast(offset);
1787 shdr.sh_size += padding + msec.size;
1788 shdr.sh_addralign = @max(shdr.sh_addralign, msec.alignment.toByteUnits() orelse 1);
1789 shdr.sh_entsize = if (shdr.sh_entsize == 0) msec.entsize else @min(shdr.sh_entsize, msec.entsize);
1790 }
1791}
1792
1793pub fn writeMergeSections(self: *Elf) !void {
1794 const gpa = self.base.comp.gpa;
1795 var buffer = std.array_list.Managed(u8).init(gpa);
1796 defer buffer.deinit();
1797
1798 for (self.merge_sections.items) |*msec| {
1799 const shdr = self.sections.items(.shdr)[msec.output_section_index];
1800 const fileoff = try self.cast(usize, msec.value + shdr.sh_offset);
1801 const size = try self.cast(usize, msec.size);
1802 try buffer.ensureTotalCapacity(size);
1803 buffer.appendNTimesAssumeCapacity(0, size);
1804
1805 for (msec.finalized_subsections.items) |msub_index| {
1806 const msub = msec.mergeSubsection(msub_index);
1807 assert(msub.alive);
1808 const string = msub.getString(self);
1809 const off = try self.cast(usize, msub.value);
1810 @memcpy(buffer.items[off..][0..string.len], string);
1811 }
1812
1813 try self.pwriteAll(buffer.items, fileoff);
1814 buffer.clearRetainingCapacity();
1815 }
1816}
1817
1818fn initOutputSections(self: *Elf) !void {
1819 for (self.objects.items) |index| {
1820 try self.file(index).?.object.initOutputSections(self);
1821 }
1822 for (self.merge_sections.items) |*msec| {
1823 if (msec.finalized_subsections.items.len == 0) continue;
1824 try msec.initOutputSection(self);
1825 }
1826}
1827
1828fn initSyntheticSections(self: *Elf) !void {
1829 const comp = self.base.comp;
1830 const target = self.getTarget();
1831 const ptr_size = self.ptrWidthBytes();
1832
1833 const is_exe_or_dyn_lib = switch (comp.config.output_mode) {
1834 .Exe => true,
1835 .Lib => comp.config.link_mode == .dynamic,
1836 .Obj => false,
1837 };
1838 const have_dynamic_linker = comp.config.link_mode == .dynamic and is_exe_or_dyn_lib;
1839
1840 const needs_eh_frame = blk: {
1841 if (self.zigObjectPtr()) |zo|
1842 if (zo.eh_frame_index != null) break :blk true;
1843 break :blk for (self.objects.items) |index| {
1844 if (self.file(index).?.object.cies.items.len > 0) break true;
1845 } else false;
1846 };
1847
1848 if (needs_eh_frame) {
1849 if (self.section_indexes.eh_frame == null) {
1850 self.section_indexes.eh_frame = self.sectionByName(".eh_frame") orelse try self.addSection(.{
1851 .name = try self.insertShString(".eh_frame"),
1852 .type = if (target.cpu.arch == .x86_64)
1853 elf.SHT_X86_64_UNWIND
1854 else
1855 elf.SHT_PROGBITS,
1856 .flags = elf.SHF_ALLOC,
1857 .addralign = ptr_size,
1858 });
1859 }
1860 if (comp.link_eh_frame_hdr and self.section_indexes.eh_frame_hdr == null) {
1861 self.section_indexes.eh_frame_hdr = try self.addSection(.{
1862 .name = try self.insertShString(".eh_frame_hdr"),
1863 .type = elf.SHT_PROGBITS,
1864 .flags = elf.SHF_ALLOC,
1865 .addralign = 4,
1866 });
1867 }
1868 }
1869
1870 if (self.got.entries.items.len > 0 and self.section_indexes.got == null) {
1871 self.section_indexes.got = try self.addSection(.{
1872 .name = try self.insertShString(".got"),
1873 .type = elf.SHT_PROGBITS,
1874 .flags = elf.SHF_ALLOC | elf.SHF_WRITE,
1875 .addralign = ptr_size,
1876 });
1877 }
1878
1879 if (have_dynamic_linker) {
1880 if (self.section_indexes.got_plt == null) {
1881 self.section_indexes.got_plt = try self.addSection(.{
1882 .name = try self.insertShString(".got.plt"),
1883 .type = elf.SHT_PROGBITS,
1884 .flags = elf.SHF_ALLOC | elf.SHF_WRITE,
1885 .addralign = @alignOf(u64),
1886 });
1887 }
1888 } else {
1889 assert(self.plt.symbols.items.len == 0);
1890 }
1891
1892 const needs_rela_dyn = blk: {
1893 if (self.got.flags.needs_rela or self.got.flags.needs_tlsld or self.copy_rel.symbols.items.len > 0)
1894 break :blk true;
1895 if (self.zigObjectPtr()) |zig_object| {
1896 if (zig_object.num_dynrelocs > 0) break :blk true;
1897 }
1898 for (self.objects.items) |index| {
1899 if (self.file(index).?.object.num_dynrelocs > 0) break :blk true;
1900 }
1901 break :blk false;
1902 };
1903 if (needs_rela_dyn and self.section_indexes.rela_dyn == null) {
1904 self.section_indexes.rela_dyn = try self.addSection(.{
1905 .name = try self.insertShString(".rela.dyn"),
1906 .type = elf.SHT_RELA,
1907 .flags = elf.SHF_ALLOC,
1908 .addralign = @alignOf(elf.Elf64_Rela),
1909 .entsize = @sizeOf(elf.Elf64_Rela),
1910 });
1911 }
1912
1913 if (self.plt.symbols.items.len > 0) {
1914 if (self.section_indexes.plt == null) {
1915 self.section_indexes.plt = try self.addSection(.{
1916 .name = try self.insertShString(".plt"),
1917 .type = elf.SHT_PROGBITS,
1918 .flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR,
1919 .addralign = 16,
1920 });
1921 }
1922 if (self.section_indexes.rela_plt == null) {
1923 self.section_indexes.rela_plt = try self.addSection(.{
1924 .name = try self.insertShString(".rela.plt"),
1925 .type = elf.SHT_RELA,
1926 .flags = elf.SHF_ALLOC,
1927 .addralign = @alignOf(elf.Elf64_Rela),
1928 .entsize = @sizeOf(elf.Elf64_Rela),
1929 });
1930 }
1931 }
1932
1933 if (self.plt_got.symbols.items.len > 0 and self.section_indexes.plt_got == null) {
1934 self.section_indexes.plt_got = try self.addSection(.{
1935 .name = try self.insertShString(".plt.got"),
1936 .type = elf.SHT_PROGBITS,
1937 .flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR,
1938 .addralign = 16,
1939 });
1940 }
1941
1942 if (self.copy_rel.symbols.items.len > 0 and self.section_indexes.copy_rel == null) {
1943 self.section_indexes.copy_rel = try self.addSection(.{
1944 .name = try self.insertShString(".copyrel"),
1945 .type = elf.SHT_NOBITS,
1946 .flags = elf.SHF_ALLOC | elf.SHF_WRITE,
1947 });
1948 }
1949
1950 if (needs_interp: {
1951 if (comp.config.link_mode == .static) break :needs_interp false;
1952 if (target.dynamic_linker.get() == null) break :needs_interp false;
1953 break :needs_interp switch (comp.config.output_mode) {
1954 .Exe => true,
1955 .Lib => comp.root_mod.resolved_target.is_explicit_dynamic_linker,
1956 .Obj => false,
1957 };
1958 } and self.section_indexes.interp == null) {
1959 self.section_indexes.interp = try self.addSection(.{
1960 .name = try self.insertShString(".interp"),
1961 .type = elf.SHT_PROGBITS,
1962 .flags = elf.SHF_ALLOC,
1963 .addralign = 1,
1964 });
1965 }
1966
1967 if (have_dynamic_linker or comp.config.pie or self.isEffectivelyDynLib()) {
1968 if (self.section_indexes.dynstrtab == null) {
1969 self.section_indexes.dynstrtab = try self.addSection(.{
1970 .name = try self.insertShString(".dynstr"),
1971 .flags = elf.SHF_ALLOC,
1972 .type = elf.SHT_STRTAB,
1973 .entsize = 1,
1974 .addralign = 1,
1975 });
1976 }
1977 if (self.section_indexes.dynamic == null) {
1978 self.section_indexes.dynamic = try self.addSection(.{
1979 .name = try self.insertShString(".dynamic"),
1980 .flags = elf.SHF_ALLOC | elf.SHF_WRITE,
1981 .type = elf.SHT_DYNAMIC,
1982 .entsize = @sizeOf(elf.Elf64_Dyn),
1983 .addralign = @alignOf(elf.Elf64_Dyn),
1984 });
1985 }
1986 if (self.section_indexes.dynsymtab == null) {
1987 self.section_indexes.dynsymtab = try self.addSection(.{
1988 .name = try self.insertShString(".dynsym"),
1989 .flags = elf.SHF_ALLOC,
1990 .type = elf.SHT_DYNSYM,
1991 .addralign = @alignOf(elf.Elf64_Sym),
1992 .entsize = @sizeOf(elf.Elf64_Sym),
1993 .info = 1,
1994 });
1995 }
1996 if (self.section_indexes.hash == null) {
1997 self.section_indexes.hash = try self.addSection(.{
1998 .name = try self.insertShString(".hash"),
1999 .flags = elf.SHF_ALLOC,
2000 .type = elf.SHT_HASH,
2001 .addralign = 4,
2002 .entsize = 4,
2003 });
2004 }
2005 if (self.section_indexes.gnu_hash == null) {
2006 self.section_indexes.gnu_hash = try self.addSection(.{
2007 .name = try self.insertShString(".gnu.hash"),
2008 .flags = elf.SHF_ALLOC,
2009 .type = elf.SHT_GNU_HASH,
2010 .addralign = 8,
2011 });
2012 }
2013
2014 const needs_versions = for (self.dynsym.entries.items) |entry| {
2015 const sym = self.symbol(entry.ref).?;
2016 if (sym.flags.import and sym.version_index.VERSION > elf.Versym.GLOBAL.VERSION) break true;
2017 } else false;
2018 if (needs_versions) {
2019 if (self.section_indexes.versym == null) {
2020 self.section_indexes.versym = try self.addSection(.{
2021 .name = try self.insertShString(".gnu.version"),
2022 .flags = elf.SHF_ALLOC,
2023 .type = elf.SHT_GNU_VERSYM,
2024 .addralign = @alignOf(elf.Versym),
2025 .entsize = @sizeOf(elf.Versym),
2026 });
2027 }
2028 if (self.section_indexes.verneed == null) {
2029 self.section_indexes.verneed = try self.addSection(.{
2030 .name = try self.insertShString(".gnu.version_r"),
2031 .flags = elf.SHF_ALLOC,
2032 .type = elf.SHT_GNU_VERNEED,
2033 .addralign = @alignOf(elf.Elf64_Verneed),
2034 });
2035 }
2036 }
2037 }
2038
2039 try self.initSymtab();
2040 try self.initShStrtab();
2041}
2042
2043pub fn initSymtab(self: *Elf) !void {
2044 const small_ptr = switch (self.ptr_width) {
2045 .p32 => true,
2046 .p64 => false,
2047 };
2048 if (self.section_indexes.symtab == null) {
2049 self.section_indexes.symtab = try self.addSection(.{
2050 .name = try self.insertShString(".symtab"),
2051 .type = elf.SHT_SYMTAB,
2052 .addralign = if (small_ptr) @alignOf(elf.Elf32_Sym) else @alignOf(elf.Elf64_Sym),
2053 .entsize = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym),
2054 });
2055 }
2056 if (self.section_indexes.strtab == null) {
2057 self.section_indexes.strtab = try self.addSection(.{
2058 .name = try self.insertShString(".strtab"),
2059 .type = elf.SHT_STRTAB,
2060 .entsize = 1,
2061 .addralign = 1,
2062 });
2063 }
2064}
2065
2066pub fn initShStrtab(self: *Elf) !void {
2067 if (self.section_indexes.shstrtab == null) {
2068 self.section_indexes.shstrtab = try self.addSection(.{
2069 .name = try self.insertShString(".shstrtab"),
2070 .type = elf.SHT_STRTAB,
2071 .entsize = 1,
2072 .addralign = 1,
2073 });
2074 }
2075}
2076
2077fn initSpecialPhdrs(self: *Elf) !void {
2078 comptime assert(max_number_of_special_phdrs == 5);
2079
2080 if (self.section_indexes.interp != null and self.phdr_indexes.interp == .none) {
2081 self.phdr_indexes.interp = (try self.addPhdr(.{
2082 .type = @backingInt(elf.PT.INTERP),
2083 .flags = elf.PF_R,
2084 .@"align" = 1,
2085 })).toOptional();
2086 }
2087 if (self.section_indexes.dynamic != null and self.phdr_indexes.dynamic == .none) {
2088 self.phdr_indexes.dynamic = (try self.addPhdr(.{
2089 .type = @backingInt(elf.PT.DYNAMIC),
2090 .flags = elf.PF_R | elf.PF_W,
2091 })).toOptional();
2092 }
2093 if (self.section_indexes.eh_frame_hdr != null and self.phdr_indexes.gnu_eh_frame == .none) {
2094 self.phdr_indexes.gnu_eh_frame = (try self.addPhdr(.{
2095 .type = @backingInt(elf.PT.GNU_EH_FRAME),
2096 .flags = elf.PF_R,
2097 })).toOptional();
2098 }
2099 if (self.phdr_indexes.gnu_stack == .none) {
2100 self.phdr_indexes.gnu_stack = (try self.addPhdr(.{
2101 .type = @backingInt(elf.PT.GNU_STACK),
2102 .flags = elf.PF_W | elf.PF_R,
2103 .memsz = self.base.stack_size,
2104 .@"align" = 1,
2105 })).toOptional();
2106 }
2107
2108 const has_tls = for (self.sections.items(.shdr)) |shdr| {
2109 if (shdr.sh_flags & elf.SHF_TLS != 0) break true;
2110 } else false;
2111 if (has_tls and self.phdr_indexes.tls == .none) {
2112 self.phdr_indexes.tls = (try self.addPhdr(.{
2113 .type = @backingInt(elf.PT.TLS),
2114 .flags = elf.PF_R,
2115 .@"align" = 1,
2116 })).toOptional();
2117 }
2118}
2119
2120/// We need to sort constructors/destuctors in the following sections:
2121/// * .init_array
2122/// * .fini_array
2123/// * .preinit_array
2124/// * .ctors
2125/// * .dtors
2126/// The prority of inclusion is defined as part of the input section's name. For example, .init_array.10000.
2127/// If no priority value has been specified,
2128/// * for .init_array, .fini_array and .preinit_array, we automatically assign that section max value of maxInt(i32)
2129/// and push it to the back of the queue,
2130/// * for .ctors and .dtors, we automatically assign that section min value of -1
2131/// and push it to the front of the queue,
2132/// crtbegin and ctrend are assigned minInt(i32) and maxInt(i32) respectively.
2133/// Ties are broken by the file prority which corresponds to the inclusion of input sections in this output section
2134/// we are about to sort.
2135fn sortInitFini(self: *Elf) !void {
2136 const gpa = self.base.comp.gpa;
2137 const slice = self.sections.slice();
2138
2139 const Entry = struct {
2140 priority: i32,
2141 atom_ref: Ref,
2142
2143 pub fn lessThan(ctx: *Elf, lhs: @This(), rhs: @This()) bool {
2144 if (lhs.priority == rhs.priority) {
2145 return ctx.atom(lhs.atom_ref).?.priority(ctx) < ctx.atom(rhs.atom_ref).?.priority(ctx);
2146 }
2147 return lhs.priority < rhs.priority;
2148 }
2149 };
2150
2151 for (slice.items(.shdr), slice.items(.atom_list_2)) |shdr, *atom_list| {
2152 if (shdr.sh_flags & elf.SHF_ALLOC == 0) continue;
2153 if (atom_list.atoms.keys().len == 0) continue;
2154
2155 var is_init_fini = false;
2156 var is_ctor_dtor = false;
2157 switch (shdr.sh_type) {
2158 elf.SHT_PREINIT_ARRAY,
2159 elf.SHT_INIT_ARRAY,
2160 elf.SHT_FINI_ARRAY,
2161 => is_init_fini = true,
2162 else => {
2163 const name = self.getShString(shdr.sh_name);
2164 is_ctor_dtor = mem.find(u8, name, ".ctors") != null or mem.find(u8, name, ".dtors") != null;
2165 },
2166 }
2167 if (!is_init_fini and !is_ctor_dtor) continue;
2168
2169 var entries = std.array_list.Managed(Entry).init(gpa);
2170 try entries.ensureTotalCapacityPrecise(atom_list.atoms.keys().len);
2171 defer entries.deinit();
2172
2173 for (atom_list.atoms.keys()) |ref| {
2174 const atom_ptr = self.atom(ref).?;
2175 const object = atom_ptr.file(self).?.object;
2176 const priority = blk: {
2177 if (is_ctor_dtor) {
2178 const basename = object.path.basename();
2179 if (mem.eql(u8, basename, "crtbegin.o")) break :blk std.math.minInt(i32);
2180 if (mem.eql(u8, basename, "crtend.o")) break :blk std.math.maxInt(i32);
2181 }
2182 const default: i32 = if (is_ctor_dtor) -1 else std.math.maxInt(i32);
2183 const name = atom_ptr.name(self);
2184 var it = mem.splitBackwardsScalar(u8, name, '.');
2185 const priority = std.fmt.parseUnsigned(u16, it.first(), 10) catch default;
2186 break :blk priority;
2187 };
2188 entries.appendAssumeCapacity(.{ .priority = priority, .atom_ref = ref });
2189 }
2190
2191 mem.sort(Entry, entries.items, self, Entry.lessThan);
2192
2193 atom_list.atoms.clearRetainingCapacity();
2194 for (entries.items) |entry| {
2195 _ = atom_list.atoms.getOrPutAssumeCapacity(entry.atom_ref);
2196 }
2197 }
2198}
2199
2200fn setDynamicSection(self: *Elf, rpaths: []const []const u8) !void {
2201 if (self.section_indexes.dynamic == null) return;
2202
2203 const shared_objects = self.shared_objects.values();
2204
2205 for (shared_objects) |index| {
2206 const shared_object = self.file(index).?.shared_object;
2207 if (!shared_object.alive) continue;
2208 try self.dynamic.addNeeded(shared_object, self);
2209 }
2210
2211 if (self.isEffectivelyDynLib()) {
2212 if (self.soname) |soname| {
2213 try self.dynamic.setSoname(soname, self);
2214 }
2215 }
2216
2217 try self.dynamic.setRpath(rpaths, self);
2218}
2219
2220fn sortDynamicSymtab(self: *Elf) void {
2221 if (self.section_indexes.gnu_hash == null) return;
2222 self.dynsym.sort(self);
2223}
2224
2225fn setVersionSymtab(self: *Elf) !void {
2226 const gpa = self.base.comp.gpa;
2227 if (self.section_indexes.versym == null) return;
2228 try self.versym.resize(gpa, self.dynsym.count());
2229 self.versym.items[0] = .LOCAL;
2230 for (self.dynsym.entries.items, 1..) |entry, i| {
2231 const sym = self.symbol(entry.ref).?;
2232 self.versym.items[i] = sym.version_index;
2233 }
2234
2235 if (self.section_indexes.verneed) |shndx| {
2236 try self.verneed.generate(self);
2237 const shdr = &self.sections.items(.shdr)[shndx];
2238 shdr.sh_info = @as(u32, @intCast(self.verneed.verneed.items.len));
2239 }
2240}
2241
2242fn setHashSections(self: *Elf) !void {
2243 if (self.section_indexes.hash != null) {
2244 try self.hash.generate(self);
2245 }
2246 if (self.section_indexes.gnu_hash != null) {
2247 try self.gnu_hash.calcSize(self);
2248 }
2249}
2250
2251fn phdrRank(phdr: elf.Elf64.Phdr) u8 {
2252 return switch (phdr.type) {
2253 .NULL => 0,
2254 .PHDR => 1,
2255 .INTERP => 2,
2256 .LOAD => 3,
2257 .DYNAMIC, .TLS => 4,
2258 .GNU_EH_FRAME => 5,
2259 .GNU_STACK => 6,
2260 else => 7,
2261 };
2262}
2263
2264fn sortPhdrs(
2265 gpa: Allocator,
2266 phdrs: *ProgramHeaderList,
2267 special_indexes: *ProgramHeaderIndexes,
2268 section_indexes: []OptionalProgramHeaderIndex,
2269) error{OutOfMemory}!void {
2270 const Entry = struct {
2271 phndx: u16,
2272
2273 pub fn lessThan(program_headers: []const elf.Elf64.Phdr, lhs: @This(), rhs: @This()) bool {
2274 const lhs_phdr = program_headers[lhs.phndx];
2275 const rhs_phdr = program_headers[rhs.phndx];
2276 const lhs_rank = phdrRank(lhs_phdr);
2277 const rhs_rank = phdrRank(rhs_phdr);
2278 if (lhs_rank == rhs_rank) return lhs_phdr.vaddr < rhs_phdr.vaddr;
2279 return lhs_rank < rhs_rank;
2280 }
2281 };
2282
2283 const entries = try gpa.alloc(Entry, phdrs.items.len);
2284 defer gpa.free(entries);
2285 for (entries, 0..) |*entry, phndx| {
2286 entry.* = .{ .phndx = @intCast(phndx) };
2287 }
2288
2289 // The `@as` here works around a bug in the C backend.
2290 mem.sort(Entry, entries, @as([]const elf.Elf64.Phdr, phdrs.items), Entry.lessThan);
2291
2292 const backlinks = try gpa.alloc(u16, entries.len);
2293 defer gpa.free(backlinks);
2294 const slice = try phdrs.toOwnedSlice(gpa);
2295 defer gpa.free(slice);
2296 try phdrs.resize(gpa, slice.len);
2297
2298 for (entries, phdrs.items, 0..) |entry, *phdr, i| {
2299 backlinks[entry.phndx] = @intCast(i);
2300 phdr.* = slice[entry.phndx];
2301 }
2302
2303 inline for (@typeInfo(ProgramHeaderIndexes).@"struct".field_names) |field_name| {
2304 if (@field(special_indexes, field_name).int()) |special_index| {
2305 @field(special_indexes, field_name) = @fromBackingInt(@intCast(backlinks[special_index]));
2306 }
2307 }
2308
2309 for (section_indexes) |*opt_phndx| {
2310 if (opt_phndx.int()) |index| {
2311 opt_phndx.* = @fromBackingInt(@intCast(backlinks[index]));
2312 }
2313 }
2314}
2315
2316fn shdrRank(shdr: elf.Elf64_Shdr, shstrtab: []const u8) u8 {
2317 const name = shString(shstrtab, shdr.sh_name);
2318 const flags = shdr.sh_flags;
2319
2320 switch (shdr.sh_type) {
2321 elf.SHT_NULL => return 0,
2322 elf.SHT_DYNSYM => return 2,
2323 elf.SHT_HASH => return 3,
2324 elf.SHT_GNU_HASH => return 3,
2325 elf.SHT_GNU_VERSYM => return 4,
2326 elf.SHT_GNU_VERDEF => return 4,
2327 elf.SHT_GNU_VERNEED => return 4,
2328
2329 elf.SHT_PREINIT_ARRAY,
2330 elf.SHT_INIT_ARRAY,
2331 elf.SHT_FINI_ARRAY,
2332 => return 0xf1,
2333
2334 elf.SHT_DYNAMIC => return 0xf2,
2335
2336 elf.SHT_RELA, elf.SHT_GROUP => return 0xf,
2337
2338 elf.SHT_PROGBITS => if (flags & elf.SHF_ALLOC != 0) {
2339 if (flags & elf.SHF_EXECINSTR != 0) {
2340 return 0xf0;
2341 } else if (flags & elf.SHF_WRITE != 0) {
2342 return if (flags & elf.SHF_TLS != 0) 0xf3 else 0xf5;
2343 } else if (mem.eql(u8, name, ".interp")) {
2344 return 1;
2345 } else if (mem.startsWith(u8, name, ".eh_frame")) {
2346 return 0xe1;
2347 } else {
2348 return 0xe0;
2349 }
2350 } else {
2351 if (mem.startsWith(u8, name, ".debug")) {
2352 return 0xf7;
2353 } else {
2354 return 0xf8;
2355 }
2356 },
2357 elf.SHT_X86_64_UNWIND => return 0xe1,
2358
2359 elf.SHT_NOBITS => return if (flags & elf.SHF_TLS != 0) 0xf4 else 0xf6,
2360 elf.SHT_SYMTAB => return 0xf9,
2361 elf.SHT_STRTAB => return if (mem.eql(u8, name, ".dynstr")) 0x4 else 0xfa,
2362 else => return 0xff,
2363 }
2364}
2365
2366pub fn sortShdrs(
2367 gpa: Allocator,
2368 section_indexes: *SectionIndexes,
2369 sections: *std.MultiArrayList(Section),
2370 shstrtab: []const u8,
2371 merge_sections: []Merge.Section,
2372 comdat_group_sections: []GroupSection,
2373 zig_object_ptr: ?*ZigObject,
2374 files: std.MultiArrayList(File.Entry),
2375) !void {
2376 const Entry = struct {
2377 shndx: u32,
2378
2379 const Context = struct {
2380 shdrs: []const elf.Elf64_Shdr,
2381 shstrtab: []const u8,
2382 };
2383
2384 pub fn lessThan(ctx: Context, lhs: @This(), rhs: @This()) bool {
2385 const lhs_rank = shdrRank(ctx.shdrs[lhs.shndx], ctx.shstrtab);
2386 const rhs_rank = shdrRank(ctx.shdrs[rhs.shndx], ctx.shstrtab);
2387 if (lhs_rank == rhs_rank) {
2388 const lhs_name = shString(ctx.shstrtab, ctx.shdrs[lhs.shndx].sh_name);
2389 const rhs_name = shString(ctx.shstrtab, ctx.shdrs[rhs.shndx].sh_name);
2390 return std.mem.lessThan(u8, lhs_name, rhs_name);
2391 }
2392 return lhs_rank < rhs_rank;
2393 }
2394 };
2395
2396 const shdrs = sections.items(.shdr);
2397
2398 const entries = try gpa.alloc(Entry, shdrs.len);
2399 defer gpa.free(entries);
2400 for (entries, 0..shdrs.len) |*entry, shndx| {
2401 entry.* = .{ .shndx = @intCast(shndx) };
2402 }
2403
2404 const sort_context: Entry.Context = .{
2405 .shdrs = shdrs,
2406 .shstrtab = shstrtab,
2407 };
2408 mem.sortUnstable(Entry, entries, sort_context, Entry.lessThan);
2409
2410 const backlinks = try gpa.alloc(u32, entries.len);
2411 defer gpa.free(backlinks);
2412 {
2413 var slice = sections.toOwnedSlice();
2414 defer slice.deinit(gpa);
2415 try sections.resize(gpa, slice.len);
2416
2417 for (entries, 0..) |entry, i| {
2418 backlinks[entry.shndx] = @intCast(i);
2419 sections.set(i, slice.get(entry.shndx));
2420 }
2421 }
2422
2423 inline for (@typeInfo(SectionIndexes).@"struct".field_names) |field_name| {
2424 if (@field(section_indexes, field_name)) |special_index| {
2425 @field(section_indexes, field_name) = backlinks[special_index];
2426 }
2427 }
2428
2429 for (merge_sections) |*msec| {
2430 msec.output_section_index = backlinks[msec.output_section_index];
2431 }
2432
2433 const slice = sections.slice();
2434 for (slice.items(.shdr), slice.items(.atom_list_2)) |*shdr, *atom_list| {
2435 atom_list.output_section_index = backlinks[atom_list.output_section_index];
2436 for (atom_list.atoms.keys()) |ref| {
2437 fileLookup(files, ref.file, zig_object_ptr).?.atom(ref.index).?.output_section_index = atom_list.output_section_index;
2438 }
2439 if (shdr.sh_type == elf.SHT_RELA) {
2440 shdr.sh_link = section_indexes.symtab.?;
2441 shdr.sh_info = backlinks[shdr.sh_info];
2442 }
2443 }
2444
2445 if (zig_object_ptr) |zo| zo.resetShdrIndexes(backlinks);
2446
2447 for (comdat_group_sections) |*cg| {
2448 cg.shndx = backlinks[cg.shndx];
2449 }
2450
2451 if (section_indexes.symtab) |index| {
2452 const shdr = &slice.items(.shdr)[index];
2453 shdr.sh_link = section_indexes.strtab.?;
2454 }
2455
2456 if (section_indexes.dynamic) |index| {
2457 const shdr = &slice.items(.shdr)[index];
2458 shdr.sh_link = section_indexes.dynstrtab.?;
2459 }
2460
2461 if (section_indexes.dynsymtab) |index| {
2462 const shdr = &slice.items(.shdr)[index];
2463 shdr.sh_link = section_indexes.dynstrtab.?;
2464 }
2465
2466 if (section_indexes.hash) |index| {
2467 const shdr = &slice.items(.shdr)[index];
2468 shdr.sh_link = section_indexes.dynsymtab.?;
2469 }
2470
2471 if (section_indexes.gnu_hash) |index| {
2472 const shdr = &slice.items(.shdr)[index];
2473 shdr.sh_link = section_indexes.dynsymtab.?;
2474 }
2475
2476 if (section_indexes.versym) |index| {
2477 const shdr = &slice.items(.shdr)[index];
2478 shdr.sh_link = section_indexes.dynsymtab.?;
2479 }
2480
2481 if (section_indexes.verneed) |index| {
2482 const shdr = &slice.items(.shdr)[index];
2483 shdr.sh_link = section_indexes.dynstrtab.?;
2484 }
2485
2486 if (section_indexes.rela_dyn) |index| {
2487 const shdr = &slice.items(.shdr)[index];
2488 shdr.sh_link = section_indexes.dynsymtab orelse 0;
2489 }
2490
2491 if (section_indexes.rela_plt) |index| {
2492 const shdr = &slice.items(.shdr)[index];
2493 shdr.sh_link = section_indexes.dynsymtab.?;
2494 shdr.sh_info = section_indexes.plt.?;
2495 }
2496
2497 if (section_indexes.eh_frame_rela) |index| {
2498 const shdr = &slice.items(.shdr)[index];
2499 shdr.sh_link = section_indexes.symtab.?;
2500 shdr.sh_info = section_indexes.eh_frame.?;
2501 }
2502}
2503
2504fn updateSectionSizes(self: *Elf) !void {
2505 const slice = self.sections.slice();
2506 for (slice.items(.shdr), slice.items(.atom_list_2)) |shdr, *atom_list| {
2507 if (atom_list.atoms.keys().len == 0) continue;
2508 if (!atom_list.dirty) continue;
2509 if (self.requiresThunks() and shdr.sh_flags & elf.SHF_EXECINSTR != 0) continue;
2510 atom_list.updateSize(self);
2511 try atom_list.allocate(self);
2512 atom_list.dirty = false;
2513 }
2514
2515 if (self.requiresThunks()) {
2516 for (slice.items(.shdr), slice.items(.atom_list_2)) |shdr, *atom_list| {
2517 if (shdr.sh_flags & elf.SHF_EXECINSTR == 0) continue;
2518 if (atom_list.atoms.keys().len == 0) continue;
2519 if (!atom_list.dirty) continue;
2520
2521 // Create jump/branch range extenders if needed.
2522 try self.createThunks(atom_list);
2523 try atom_list.allocate(self);
2524 atom_list.dirty = false;
2525 }
2526
2527 // This might not be needed if there was a link from Atom/Thunk to AtomList.
2528 for (self.thunks.items) |*th| {
2529 th.value += slice.items(.atom_list_2)[th.output_section_index].value;
2530 }
2531 }
2532
2533 const shdrs = slice.items(.shdr);
2534 if (self.section_indexes.eh_frame) |index| {
2535 shdrs[index].sh_size = try eh_frame.calcEhFrameSize(self);
2536 }
2537
2538 if (self.section_indexes.eh_frame_hdr) |index| {
2539 shdrs[index].sh_size = eh_frame.calcEhFrameHdrSize(self);
2540 }
2541
2542 if (self.section_indexes.got) |index| {
2543 shdrs[index].sh_size = self.got.size(self);
2544 }
2545
2546 if (self.section_indexes.plt) |index| {
2547 shdrs[index].sh_size = self.plt.size(self);
2548 }
2549
2550 if (self.section_indexes.got_plt) |index| {
2551 shdrs[index].sh_size = self.got_plt.size(self);
2552 }
2553
2554 if (self.section_indexes.plt_got) |index| {
2555 shdrs[index].sh_size = self.plt_got.size(self);
2556 }
2557
2558 if (self.section_indexes.rela_dyn) |shndx| {
2559 var num = self.got.numRela(self) + self.copy_rel.numRela();
2560 if (self.zigObjectPtr()) |zig_object| {
2561 num += zig_object.num_dynrelocs;
2562 }
2563 for (self.objects.items) |index| {
2564 num += self.file(index).?.object.num_dynrelocs;
2565 }
2566 shdrs[shndx].sh_size = num * @sizeOf(elf.Elf64_Rela);
2567 }
2568
2569 if (self.section_indexes.rela_plt) |index| {
2570 shdrs[index].sh_size = self.plt.numRela() * @sizeOf(elf.Elf64_Rela);
2571 }
2572
2573 if (self.section_indexes.copy_rel) |index| {
2574 try self.copy_rel.updateSectionSize(index, self);
2575 }
2576
2577 if (self.section_indexes.interp) |index| {
2578 shdrs[index].sh_size = self.getTarget().dynamic_linker.get().?.len + 1;
2579 }
2580
2581 if (self.section_indexes.hash) |index| {
2582 shdrs[index].sh_size = self.hash.size();
2583 }
2584
2585 if (self.section_indexes.gnu_hash) |index| {
2586 shdrs[index].sh_size = self.gnu_hash.size();
2587 }
2588
2589 if (self.section_indexes.dynamic) |index| {
2590 shdrs[index].sh_size = self.dynamic.size(self);
2591 }
2592
2593 if (self.section_indexes.dynsymtab) |index| {
2594 shdrs[index].sh_size = self.dynsym.size();
2595 }
2596
2597 if (self.section_indexes.dynstrtab) |index| {
2598 shdrs[index].sh_size = self.dynstrtab.items.len;
2599 }
2600
2601 if (self.section_indexes.versym) |index| {
2602 shdrs[index].sh_size = self.versym.items.len * @sizeOf(elf.Versym);
2603 }
2604
2605 if (self.section_indexes.verneed) |index| {
2606 shdrs[index].sh_size = self.verneed.size();
2607 }
2608
2609 try self.updateSymtabSize();
2610 self.updateShStrtabSize();
2611}
2612
2613pub fn updateShStrtabSize(self: *Elf) void {
2614 if (self.section_indexes.shstrtab) |index| {
2615 self.sections.items(.shdr)[index].sh_size = self.shstrtab.items.len;
2616 }
2617}
2618
2619fn shdrToPhdrFlags(sh_flags: u64) u32 {
2620 const write = sh_flags & elf.SHF_WRITE != 0;
2621 const exec = sh_flags & elf.SHF_EXECINSTR != 0;
2622 var out_flags: u32 = elf.PF_R;
2623 if (write) out_flags |= elf.PF_W;
2624 if (exec) out_flags |= elf.PF_X;
2625 return out_flags;
2626}
2627
2628/// Returns maximum number of program headers that may be emitted by the linker.
2629/// (This is an upper bound so that we can reserve enough space for the header and progam header
2630/// table without running out of space and being forced to move things around.)
2631fn getMaxNumberOfPhdrs() u64 {
2632 // The estimated maximum number of segments the linker can emit for input sections are:
2633 var num: u64 = max_number_of_object_segments;
2634 // Any other non-loadable program headers, including TLS, DYNAMIC, GNU_STACK, GNU_EH_FRAME, INTERP:
2635 num += max_number_of_special_phdrs;
2636 // PHDR program header and corresponding read-only load segment:
2637 num += 2;
2638 return num;
2639}
2640
2641fn addLoadPhdrs(self: *Elf) error{OutOfMemory}!void {
2642 for (self.sections.items(.shdr)) |shdr| {
2643 if (shdr.sh_type == elf.SHT_NULL) continue;
2644 if (shdr.sh_flags & elf.SHF_ALLOC == 0) continue;
2645 const flags = shdrToPhdrFlags(shdr.sh_flags);
2646 if (self.getPhdr(.{ .flags = flags, .type = @backingInt(elf.PT.LOAD) }) == .none) {
2647 _ = try self.addPhdr(.{ .flags = flags, .type = @backingInt(elf.PT.LOAD) });
2648 }
2649 }
2650}
2651
2652/// Allocates PHDR table in virtual memory and in file.
2653fn allocatePhdrTable(self: *Elf) error{OutOfMemory}!void {
2654 const diags = &self.base.comp.link_diags;
2655 const phdr_table = &self.phdrs.items[self.phdr_indexes.table.int().?];
2656 const phdr_table_load = &self.phdrs.items[self.phdr_indexes.table_load.int().?];
2657
2658 const ehsize: u64 = switch (self.ptr_width) {
2659 .p32 => @sizeOf(elf.Elf32_Ehdr),
2660 .p64 => @sizeOf(elf.Elf64_Ehdr),
2661 };
2662 const phsize: u64 = switch (self.ptr_width) {
2663 .p32 => @sizeOf(elf.Elf32.Phdr),
2664 .p64 => @sizeOf(elf.Elf64.Phdr),
2665 };
2666 const needed_size = self.phdrs.items.len * phsize;
2667 const available_space = self.allocatedSize(phdr_table.offset);
2668
2669 if (needed_size > available_space) {
2670 // In this case, we have two options:
2671 // 1. increase the available padding for EHDR + PHDR table so that we don't overflow it
2672 // (revisit getMaxNumberOfPhdrs())
2673 // 2. shift everything in file to free more space for EHDR + PHDR table
2674 // TODO verify `getMaxNumberOfPhdrs()` is accurate and convert this into no-op
2675 var err = try diags.addErrorWithNotes(1);
2676 try err.addMsg("fatal linker error: not enough space reserved for EHDR and PHDR table", .{});
2677 err.addNote("required 0x{x}, available 0x{x}", .{ needed_size, available_space });
2678 }
2679
2680 phdr_table_load.filesz = needed_size + ehsize;
2681 phdr_table_load.memsz = needed_size + ehsize;
2682 phdr_table.filesz = needed_size;
2683 phdr_table.memsz = needed_size;
2684}
2685
2686/// Allocates alloc sections and creates load segments for sections
2687/// extracted from input object files.
2688pub fn allocateAllocSections(self: *Elf) !void {
2689 // We use this struct to track maximum alignment of all TLS sections.
2690 // According to https://github.com/rui314/mold/commit/bd46edf3f0fe9e1a787ea453c4657d535622e61f in mold,
2691 // in-file offsets have to be aligned against the start of TLS program header.
2692 // If that's not ensured, then in a multi-threaded context, TLS variables across a shared object
2693 // boundary may not get correctly loaded at an aligned address.
2694 const Align = struct {
2695 tls_start_align: u64 = 1,
2696 first_tls_index: ?usize = null,
2697
2698 fn isFirstTlsShdr(this: @This(), other: usize) bool {
2699 if (this.first_tls_index) |index| return index == other;
2700 return false;
2701 }
2702
2703 fn @"align"(this: @This(), index: usize, sh_addralign: u64, addr: u64) u64 {
2704 const alignment = if (this.isFirstTlsShdr(index)) this.tls_start_align else sh_addralign;
2705 return mem.alignForward(u64, addr, alignment);
2706 }
2707 };
2708
2709 const slice = self.sections.slice();
2710 var alignment = Align{};
2711 for (slice.items(.shdr), 0..) |shdr, i| {
2712 if (shdr.sh_type == elf.SHT_NULL) continue;
2713 if (shdr.sh_flags & elf.SHF_TLS == 0) continue;
2714 if (alignment.first_tls_index == null) alignment.first_tls_index = i;
2715 alignment.tls_start_align = @max(alignment.tls_start_align, shdr.sh_addralign);
2716 }
2717
2718 // Next, calculate segment covers by scanning all alloc sections.
2719 // If a section matches segment flags with the preceeding section,
2720 // we put it in the same segment. Otherwise, we create a new cover.
2721 // This algorithm is simple but suboptimal in terms of space re-use:
2722 // normally we would also take into account any gaps in allocated
2723 // virtual and file offsets. However, the simple one will do for one
2724 // as we are more interested in quick turnaround and compatibility
2725 // with `findFreeSpace` mechanics than anything else.
2726 const Cover = std.array_list.Managed(u32);
2727 const gpa = self.base.comp.gpa;
2728 var covers: [max_number_of_object_segments]Cover = undefined;
2729 for (&covers) |*cover| {
2730 cover.* = Cover.init(gpa);
2731 }
2732 defer for (&covers) |*cover| {
2733 cover.deinit();
2734 };
2735
2736 for (slice.items(.shdr), 0..) |shdr, shndx| {
2737 if (shdr.sh_type == elf.SHT_NULL) continue;
2738 if (shdr.sh_flags & elf.SHF_ALLOC == 0) continue;
2739 const flags = shdrToPhdrFlags(shdr.sh_flags);
2740 try covers[flags - 1].append(@intCast(shndx));
2741 }
2742
2743 // Now we can proceed with allocating the sections in virtual memory.
2744 // As the base address we take the end address of the PHDR table.
2745 // When allocating we first find the largest required alignment
2746 // of any section that is contained in a cover and use it to align
2747 // the start address of the segement (and first section).
2748 const phdr_table = &self.phdrs.items[self.phdr_indexes.table_load.int().?];
2749 var addr = phdr_table.vaddr + phdr_table.memsz;
2750
2751 for (covers) |cover| {
2752 if (cover.items.len == 0) continue;
2753
2754 var @"align": u64 = self.page_size;
2755 for (cover.items) |shndx| {
2756 const shdr = slice.items(.shdr)[shndx];
2757 if (shdr.sh_type == elf.SHT_NOBITS and shdr.sh_flags & elf.SHF_TLS != 0) continue;
2758 @"align" = @max(@"align", shdr.sh_addralign);
2759 }
2760
2761 addr = mem.alignForward(u64, addr, @"align");
2762
2763 var memsz: u64 = 0;
2764 var filesz: u64 = 0;
2765 var i: usize = 0;
2766 while (i < cover.items.len) : (i += 1) {
2767 const shndx = cover.items[i];
2768 const shdr = &slice.items(.shdr)[shndx];
2769 if (shdr.sh_type == elf.SHT_NOBITS and shdr.sh_flags & elf.SHF_TLS != 0) {
2770 // .tbss is a little special as it's used only by the loader meaning it doesn't
2771 // need to be actually mmap'ed at runtime. We still need to correctly increment
2772 // the addresses of every TLS zerofill section tho. Thus, we hack it so that
2773 // we increment the start address like normal, however, after we are done,
2774 // the next ALLOC section will get its start address allocated within the same
2775 // range as the .tbss sections. We will get something like this:
2776 //
2777 // ...
2778 // .tbss 0x10
2779 // .tcommon 0x20
2780 // .data 0x10
2781 // ...
2782 var tbss_addr = addr;
2783 while (i < cover.items.len and
2784 slice.items(.shdr)[cover.items[i]].sh_type == elf.SHT_NOBITS and
2785 slice.items(.shdr)[cover.items[i]].sh_flags & elf.SHF_TLS != 0) : (i += 1)
2786 {
2787 const tbss_shndx = cover.items[i];
2788 const tbss_shdr = &slice.items(.shdr)[tbss_shndx];
2789 tbss_addr = alignment.@"align"(tbss_shndx, tbss_shdr.sh_addralign, tbss_addr);
2790 tbss_shdr.sh_addr = tbss_addr;
2791 tbss_addr += tbss_shdr.sh_size;
2792 }
2793 i -= 1;
2794 continue;
2795 }
2796 const next = alignment.@"align"(shndx, shdr.sh_addralign, addr);
2797 const padding = next - addr;
2798 addr = next;
2799 shdr.sh_addr = addr;
2800 if (shdr.sh_type != elf.SHT_NOBITS) {
2801 filesz += padding + shdr.sh_size;
2802 }
2803 memsz += padding + shdr.sh_size;
2804 addr += shdr.sh_size;
2805 }
2806
2807 const first = slice.items(.shdr)[cover.items[0]];
2808 const phndx = self.getPhdr(.{ .type = @backingInt(elf.PT.LOAD), .flags = shdrToPhdrFlags(first.sh_flags) }).unwrap().?;
2809 const phdr = &self.phdrs.items[phndx.int()];
2810 const allocated_size = self.allocatedSize(phdr.offset);
2811 if (filesz > allocated_size) {
2812 const old_offset = phdr.offset;
2813 phdr.offset = 0;
2814 var new_offset = try self.findFreeSpace(filesz, @"align");
2815 phdr.offset = new_offset;
2816
2817 log.debug("moving phdr({d}) from 0x{x} to 0x{x}", .{ phndx, old_offset, new_offset });
2818
2819 for (cover.items) |shndx| {
2820 const shdr = &slice.items(.shdr)[shndx];
2821 slice.items(.phndx)[shndx] = phndx.toOptional();
2822 if (shdr.sh_type == elf.SHT_NOBITS) {
2823 shdr.sh_offset = 0;
2824 continue;
2825 }
2826 new_offset = alignment.@"align"(shndx, shdr.sh_addralign, new_offset);
2827
2828 log.debug("moving {s} from 0x{x} to 0x{x}", .{
2829 self.getShString(shdr.sh_name),
2830 shdr.sh_offset,
2831 new_offset,
2832 });
2833
2834 if (shdr.sh_offset > 0) {
2835 // Get size actually commited to the output file.
2836 const existing_size = self.sectionSize(shndx);
2837 try self.base.copyRangeAll(shdr.sh_offset, new_offset, existing_size);
2838 }
2839
2840 shdr.sh_offset = new_offset;
2841 new_offset += shdr.sh_size;
2842 }
2843 }
2844
2845 phdr.vaddr = first.sh_addr;
2846 phdr.paddr = first.sh_addr;
2847 phdr.memsz = memsz;
2848 phdr.filesz = filesz;
2849 phdr.@"align" = @"align";
2850
2851 addr = mem.alignForward(u64, addr, self.page_size);
2852 }
2853}
2854
2855/// Allocates non-alloc sections (debug info, symtabs, etc.).
2856pub fn allocateNonAllocSections(self: *Elf) !void {
2857 for (self.sections.items(.shdr), 0..) |*shdr, shndx| {
2858 if (shdr.sh_type == elf.SHT_NULL) continue;
2859 if (shdr.sh_flags & elf.SHF_ALLOC != 0) continue;
2860 const needed_size = shdr.sh_size;
2861 if (needed_size > self.allocatedSize(shdr.sh_offset)) {
2862 shdr.sh_size = 0;
2863 const new_offset = try self.findFreeSpace(needed_size, shdr.sh_addralign);
2864
2865 log.debug("moving {s} from 0x{x} to 0x{x}", .{
2866 self.getShString(shdr.sh_name),
2867 shdr.sh_offset,
2868 new_offset,
2869 });
2870
2871 if (shdr.sh_offset > 0) {
2872 const existing_size = self.sectionSize(@intCast(shndx));
2873 try self.base.copyRangeAll(shdr.sh_offset, new_offset, existing_size);
2874 }
2875
2876 shdr.sh_offset = new_offset;
2877 shdr.sh_size = needed_size;
2878 }
2879 }
2880}
2881
2882fn allocateSpecialPhdrs(self: *Elf) void {
2883 const slice = self.sections.slice();
2884
2885 for (&[_]struct { OptionalProgramHeaderIndex, ?u32 }{
2886 .{ self.phdr_indexes.interp, self.section_indexes.interp },
2887 .{ self.phdr_indexes.dynamic, self.section_indexes.dynamic },
2888 .{ self.phdr_indexes.gnu_eh_frame, self.section_indexes.eh_frame_hdr },
2889 }) |pair| {
2890 if (pair[0].int()) |index| {
2891 const shdr = slice.items(.shdr)[pair[1].?];
2892 const phdr = &self.phdrs.items[index];
2893 phdr.@"align" = shdr.sh_addralign;
2894 phdr.offset = shdr.sh_offset;
2895 phdr.vaddr = shdr.sh_addr;
2896 phdr.paddr = shdr.sh_addr;
2897 phdr.filesz = shdr.sh_size;
2898 phdr.memsz = shdr.sh_size;
2899 }
2900 }
2901
2902 // Set the TLS segment boundaries.
2903 // We assume TLS sections are laid out contiguously and that there is
2904 // a single TLS segment.
2905 if (self.phdr_indexes.tls.int()) |index| {
2906 const shdrs = slice.items(.shdr);
2907 const phdr = &self.phdrs.items[index];
2908 var shndx: u32 = 0;
2909 while (shndx < shdrs.len) {
2910 const shdr = shdrs[shndx];
2911 if (shdr.sh_flags & elf.SHF_TLS == 0) {
2912 shndx += 1;
2913 continue;
2914 }
2915 phdr.offset = shdr.sh_offset;
2916 phdr.vaddr = shdr.sh_addr;
2917 phdr.paddr = shdr.sh_addr;
2918 phdr.@"align" = shdr.sh_addralign;
2919 shndx += 1;
2920 phdr.@"align" = @max(phdr.@"align", shdr.sh_addralign);
2921 if (shdr.sh_type != elf.SHT_NOBITS) {
2922 phdr.filesz = shdr.sh_offset + shdr.sh_size - phdr.offset;
2923 }
2924 phdr.memsz = shdr.sh_addr + shdr.sh_size - phdr.vaddr;
2925
2926 while (shndx < shdrs.len) : (shndx += 1) {
2927 const next = shdrs[shndx];
2928 if (next.sh_flags & elf.SHF_TLS == 0) break;
2929 phdr.@"align" = @max(phdr.@"align", next.sh_addralign);
2930 if (next.sh_type != elf.SHT_NOBITS) {
2931 phdr.filesz = next.sh_offset + next.sh_size - phdr.offset;
2932 }
2933 phdr.memsz = next.sh_addr + next.sh_size - phdr.vaddr;
2934 }
2935 }
2936 }
2937}
2938
2939fn writeAtoms(self: *Elf) !void {
2940 const gpa = self.base.comp.gpa;
2941
2942 var undefs: std.array_hash_map.Auto(SymbolResolver.Index, std.array_list.Managed(Ref)) = .empty;
2943 defer {
2944 for (undefs.values()) |*refs| refs.deinit();
2945 undefs.deinit(gpa);
2946 }
2947
2948 var buffer: std.Io.Writer.Allocating = .init(gpa);
2949 defer buffer.deinit();
2950
2951 const slice = self.sections.slice();
2952 var has_reloc_errors = false;
2953 for (slice.items(.shdr), slice.items(.atom_list_2)) |shdr, atom_list| {
2954 if (shdr.sh_type == elf.SHT_NOBITS) continue;
2955 if (atom_list.atoms.keys().len == 0) continue;
2956 atom_list.write(&buffer, &undefs, self) catch |err| switch (err) {
2957 error.UnsupportedCpuArch => {
2958 try self.reportUnsupportedCpuArch();
2959 return error.AlreadyReported;
2960 },
2961 error.RelocFailure, error.RelaxFailure => has_reloc_errors = true,
2962 else => |e| return e,
2963 };
2964 }
2965
2966 try self.reportUndefinedSymbols(&undefs);
2967 if (has_reloc_errors) return error.AlreadyReported;
2968
2969 if (self.requiresThunks()) {
2970 for (self.thunks.items) |th| {
2971 const thunk_size = th.size(self);
2972 try buffer.ensureUnusedCapacity(thunk_size);
2973 const shdr = slice.items(.shdr)[th.output_section_index];
2974 const offset = @as(u64, @intCast(th.value)) + shdr.sh_offset;
2975 try th.write(self, &buffer.writer);
2976 assert(buffer.written().len == thunk_size);
2977 try self.pwriteAll(buffer.written(), offset);
2978 buffer.clearRetainingCapacity();
2979 }
2980 }
2981}
2982
2983pub fn updateSymtabSize(self: *Elf) !void {
2984 var nlocals: u32 = 0;
2985 var nglobals: u32 = 0;
2986 var strsize: u32 = 0;
2987
2988 const gpa = self.base.comp.gpa;
2989 const shared_objects = self.shared_objects.values();
2990
2991 var files = std.array_list.Managed(File.Index).init(gpa);
2992 defer files.deinit();
2993 try files.ensureTotalCapacityPrecise(self.objects.items.len + shared_objects.len + 2);
2994
2995 if (self.zig_object_index) |index| files.appendAssumeCapacity(index);
2996 for (self.objects.items) |index| files.appendAssumeCapacity(index);
2997 for (shared_objects) |index| files.appendAssumeCapacity(index);
2998 if (self.linker_defined_index) |index| files.appendAssumeCapacity(index);
2999
3000 // Section symbols
3001 nlocals += @intCast(self.sections.slice().len);
3002
3003 if (self.requiresThunks()) for (self.thunks.items) |*th| {
3004 th.output_symtab_ctx.reset();
3005 th.output_symtab_ctx.ilocal = nlocals;
3006 th.calcSymtabSize(self);
3007 nlocals += th.output_symtab_ctx.nlocals;
3008 strsize += th.output_symtab_ctx.strsize;
3009 };
3010
3011 for (files.items) |index| {
3012 const file_ptr = self.file(index).?;
3013 const ctx = switch (file_ptr) {
3014 inline else => |x| &x.output_symtab_ctx,
3015 };
3016 ctx.reset();
3017 ctx.ilocal = nlocals;
3018 ctx.iglobal = nglobals;
3019 try file_ptr.updateSymtabSize(self);
3020 nlocals += ctx.nlocals;
3021 nglobals += ctx.nglobals;
3022 strsize += ctx.strsize;
3023 }
3024
3025 if (self.section_indexes.got) |_| {
3026 self.got.output_symtab_ctx.reset();
3027 self.got.output_symtab_ctx.ilocal = nlocals;
3028 self.got.updateSymtabSize(self);
3029 nlocals += self.got.output_symtab_ctx.nlocals;
3030 strsize += self.got.output_symtab_ctx.strsize;
3031 }
3032
3033 if (self.section_indexes.plt) |_| {
3034 self.plt.output_symtab_ctx.reset();
3035 self.plt.output_symtab_ctx.ilocal = nlocals;
3036 self.plt.updateSymtabSize(self);
3037 nlocals += self.plt.output_symtab_ctx.nlocals;
3038 strsize += self.plt.output_symtab_ctx.strsize;
3039 }
3040
3041 if (self.section_indexes.plt_got) |_| {
3042 self.plt_got.output_symtab_ctx.reset();
3043 self.plt_got.output_symtab_ctx.ilocal = nlocals;
3044 self.plt_got.updateSymtabSize(self);
3045 nlocals += self.plt_got.output_symtab_ctx.nlocals;
3046 strsize += self.plt_got.output_symtab_ctx.strsize;
3047 }
3048
3049 for (files.items) |index| {
3050 const file_ptr = self.file(index).?;
3051 const ctx = switch (file_ptr) {
3052 inline else => |x| &x.output_symtab_ctx,
3053 };
3054 ctx.iglobal += nlocals;
3055 }
3056
3057 const slice = self.sections.slice();
3058 const symtab_shdr = &slice.items(.shdr)[self.section_indexes.symtab.?];
3059 symtab_shdr.sh_info = nlocals;
3060 symtab_shdr.sh_link = self.section_indexes.strtab.?;
3061
3062 const sym_size: u64 = switch (self.ptr_width) {
3063 .p32 => @sizeOf(elf.Elf32_Sym),
3064 .p64 => @sizeOf(elf.Elf64_Sym),
3065 };
3066 const needed_size = (nlocals + nglobals) * sym_size;
3067 symtab_shdr.sh_size = needed_size;
3068
3069 const strtab = &slice.items(.shdr)[self.section_indexes.strtab.?];
3070 strtab.sh_size = strsize + 1;
3071}
3072
3073fn writeSyntheticSections(self: *Elf) !void {
3074 const gpa = self.base.comp.gpa;
3075 const slice = self.sections.slice();
3076
3077 if (self.section_indexes.interp) |shndx| {
3078 var buffer: [256]u8 = undefined;
3079 const interp = self.getTarget().dynamic_linker.get().?;
3080 @memcpy(buffer[0..interp.len], interp);
3081 buffer[interp.len] = 0;
3082 const contents = buffer[0 .. interp.len + 1];
3083 const shdr = slice.items(.shdr)[shndx];
3084 assert(shdr.sh_size == contents.len);
3085 try self.pwriteAll(contents, shdr.sh_offset);
3086 }
3087
3088 if (self.section_indexes.hash) |shndx| {
3089 const shdr = slice.items(.shdr)[shndx];
3090 try self.pwriteAll(self.hash.buffer.items, shdr.sh_offset);
3091 }
3092
3093 if (self.section_indexes.gnu_hash) |shndx| {
3094 const shdr = slice.items(.shdr)[shndx];
3095 var aw: std.Io.Writer.Allocating = .init(gpa);
3096 try aw.ensureUnusedCapacity(self.gnu_hash.size());
3097 defer aw.deinit();
3098 try self.gnu_hash.write(self, &aw.writer);
3099 try self.pwriteAll(aw.written(), shdr.sh_offset);
3100 }
3101
3102 if (self.section_indexes.versym) |shndx| {
3103 const shdr = slice.items(.shdr)[shndx];
3104 try self.pwriteAll(@ptrCast(self.versym.items), shdr.sh_offset);
3105 }
3106
3107 if (self.section_indexes.verneed) |shndx| {
3108 const shdr = slice.items(.shdr)[shndx];
3109 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.verneed.size());
3110 defer buffer.deinit();
3111 try self.verneed.write(&buffer.writer);
3112 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3113 }
3114
3115 if (self.section_indexes.dynamic) |shndx| {
3116 const shdr = slice.items(.shdr)[shndx];
3117 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.dynamic.size(self));
3118 defer buffer.deinit();
3119 try self.dynamic.write(self, &buffer.writer);
3120 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3121 }
3122
3123 if (self.section_indexes.dynsymtab) |shndx| {
3124 const shdr = slice.items(.shdr)[shndx];
3125 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.dynsym.size());
3126 defer buffer.deinit();
3127 try self.dynsym.write(self, &buffer.writer);
3128 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3129 }
3130
3131 if (self.section_indexes.dynstrtab) |shndx| {
3132 const shdr = slice.items(.shdr)[shndx];
3133 try self.pwriteAll(self.dynstrtab.items, shdr.sh_offset);
3134 }
3135
3136 if (self.section_indexes.eh_frame) |shndx| {
3137 const existing_size = existing_size: {
3138 const zo = self.zigObjectPtr() orelse break :existing_size 0;
3139 const sym = zo.symbol(zo.eh_frame_index orelse break :existing_size 0);
3140 break :existing_size sym.atom(self).?.size;
3141 };
3142 const shdr = slice.items(.shdr)[shndx];
3143 const sh_size = try self.cast(usize, shdr.sh_size);
3144 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, @intCast(sh_size - existing_size));
3145 defer buffer.deinit();
3146 try eh_frame.writeEhFrame(self, &buffer.writer);
3147 assert(buffer.written().len == sh_size - existing_size);
3148 try self.pwriteAll(buffer.written(), shdr.sh_offset + existing_size);
3149 }
3150
3151 if (self.section_indexes.eh_frame_hdr) |shndx| {
3152 const shdr = slice.items(.shdr)[shndx];
3153 const sh_size = try self.cast(usize, shdr.sh_size);
3154 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, sh_size);
3155 defer buffer.deinit();
3156 try eh_frame.writeEhFrameHdr(self, &buffer.writer);
3157 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3158 }
3159
3160 if (self.section_indexes.got) |index| {
3161 const shdr = slice.items(.shdr)[index];
3162 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.got.size(self));
3163 defer buffer.deinit();
3164 try self.got.write(self, &buffer.writer);
3165 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3166 }
3167
3168 if (self.section_indexes.rela_dyn) |shndx| {
3169 const shdr = slice.items(.shdr)[shndx];
3170 try self.got.addRela(self);
3171 try self.copy_rel.addRela(self);
3172 self.sortRelaDyn();
3173 try self.pwriteAll(@ptrCast(self.rela_dyn.items), shdr.sh_offset);
3174 }
3175
3176 if (self.section_indexes.plt) |shndx| {
3177 const shdr = slice.items(.shdr)[shndx];
3178 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.plt.size(self));
3179 defer buffer.deinit();
3180 try self.plt.write(self, &buffer.writer);
3181 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3182 }
3183
3184 if (self.section_indexes.got_plt) |shndx| {
3185 const shdr = slice.items(.shdr)[shndx];
3186 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.got_plt.size(self));
3187 defer buffer.deinit();
3188 try self.got_plt.write(self, &buffer.writer);
3189 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3190 }
3191
3192 if (self.section_indexes.plt_got) |shndx| {
3193 const shdr = slice.items(.shdr)[shndx];
3194 var buffer = try std.Io.Writer.Allocating.initCapacity(gpa, self.plt_got.size(self));
3195 defer buffer.deinit();
3196 try self.plt_got.write(self, &buffer.writer);
3197 try self.pwriteAll(buffer.written(), shdr.sh_offset);
3198 }
3199
3200 if (self.section_indexes.rela_plt) |shndx| {
3201 const shdr = slice.items(.shdr)[shndx];
3202 try self.plt.addRela(self);
3203 try self.pwriteAll(@ptrCast(self.rela_plt.items), shdr.sh_offset);
3204 }
3205
3206 try self.writeSymtab();
3207 try self.writeShStrtab();
3208}
3209
3210pub fn writeShStrtab(self: *Elf) !void {
3211 if (self.section_indexes.shstrtab) |index| {
3212 const shdr = self.sections.items(.shdr)[index];
3213 log.debug("writing .shstrtab from 0x{x} to 0x{x}", .{ shdr.sh_offset, shdr.sh_offset + shdr.sh_size });
3214 try self.pwriteAll(self.shstrtab.items, shdr.sh_offset);
3215 }
3216}
3217
3218pub fn writeSymtab(self: *Elf) !void {
3219 const gpa = self.base.comp.gpa;
3220 const shared_objects = self.shared_objects.values();
3221
3222 const slice = self.sections.slice();
3223 const symtab_shdr = slice.items(.shdr)[self.section_indexes.symtab.?];
3224 const strtab_shdr = slice.items(.shdr)[self.section_indexes.strtab.?];
3225 const sym_size: u64 = switch (self.ptr_width) {
3226 .p32 => @sizeOf(elf.Elf32_Sym),
3227 .p64 => @sizeOf(elf.Elf64_Sym),
3228 };
3229 const nsyms = try self.cast(usize, @divExact(symtab_shdr.sh_size, sym_size));
3230
3231 log.debug("writing {d} symbols in .symtab from 0x{x} to 0x{x}", .{
3232 nsyms,
3233 symtab_shdr.sh_offset,
3234 symtab_shdr.sh_offset + symtab_shdr.sh_size,
3235 });
3236 log.debug("writing .strtab from 0x{x} to 0x{x}", .{
3237 strtab_shdr.sh_offset,
3238 strtab_shdr.sh_offset + strtab_shdr.sh_size,
3239 });
3240
3241 try self.symtab.resize(gpa, nsyms);
3242 const needed_strtab_size = try self.cast(usize, strtab_shdr.sh_size - 1);
3243 // TODO we could resize instead and in ZigObject/Object always access as slice
3244 self.strtab.clearRetainingCapacity();
3245 self.strtab.appendAssumeCapacity(0);
3246 try self.strtab.ensureUnusedCapacity(gpa, needed_strtab_size);
3247
3248 for (slice.items(.shdr), 0..) |shdr, shndx| {
3249 const out_sym = &self.symtab.items[shndx];
3250 out_sym.* = .{
3251 .st_name = 0,
3252 .st_value = shdr.sh_addr,
3253 .st_info = if (shdr.sh_type == elf.SHT_NULL) elf.STT_NOTYPE else elf.STT_SECTION,
3254 .st_shndx = @intCast(shndx),
3255 .st_size = 0,
3256 .st_other = 0,
3257 };
3258 }
3259
3260 if (self.requiresThunks()) for (self.thunks.items) |th| {
3261 th.writeSymtab(self);
3262 };
3263
3264 if (self.zigObjectPtr()) |zig_object| {
3265 zig_object.asFile().writeSymtab(self);
3266 }
3267
3268 for (self.objects.items) |index| {
3269 const file_ptr = self.file(index).?;
3270 file_ptr.writeSymtab(self);
3271 }
3272
3273 for (shared_objects) |index| {
3274 const file_ptr = self.file(index).?;
3275 file_ptr.writeSymtab(self);
3276 }
3277
3278 if (self.linkerDefinedPtr()) |obj| {
3279 obj.asFile().writeSymtab(self);
3280 }
3281
3282 if (self.section_indexes.got) |_| {
3283 self.got.writeSymtab(self);
3284 }
3285
3286 if (self.section_indexes.plt) |_| {
3287 self.plt.writeSymtab(self);
3288 }
3289
3290 if (self.section_indexes.plt_got) |_| {
3291 self.plt_got.writeSymtab(self);
3292 }
3293
3294 const foreign_endian = self.getTarget().cpu.arch.endian() != builtin.cpu.arch.endian();
3295 switch (self.ptr_width) {
3296 .p32 => {
3297 const buf = try gpa.alloc(elf.Elf32_Sym, self.symtab.items.len);
3298 defer gpa.free(buf);
3299
3300 for (buf, self.symtab.items) |*out, sym| {
3301 out.* = .{
3302 .st_name = sym.st_name,
3303 .st_info = sym.st_info,
3304 .st_other = sym.st_other,
3305 .st_shndx = sym.st_shndx,
3306 .st_value = @intCast(sym.st_value),
3307 .st_size = @intCast(sym.st_size),
3308 };
3309 if (foreign_endian) mem.byteSwapAllFields(elf.Elf32_Sym, out);
3310 }
3311 try self.pwriteAll(@ptrCast(buf), symtab_shdr.sh_offset);
3312 },
3313 .p64 => {
3314 if (foreign_endian) {
3315 for (self.symtab.items) |*sym| mem.byteSwapAllFields(elf.Elf64_Sym, sym);
3316 }
3317 try self.pwriteAll(@ptrCast(self.symtab.items), symtab_shdr.sh_offset);
3318 },
3319 }
3320
3321 try self.pwriteAll(self.strtab.items, strtab_shdr.sh_offset);
3322}
3323
3324/// Always 4 or 8 depending on whether this is 32-bit ELF or 64-bit ELF.
3325pub fn ptrWidthBytes(self: Elf) u8 {
3326 return switch (self.ptr_width) {
3327 .p32 => 4,
3328 .p64 => 8,
3329 };
3330}
3331
3332/// Does not necessarily match `ptrWidthBytes` for example can be 2 bytes
3333/// in a 32-bit ELF file.
3334pub fn archPtrWidthBytes(self: Elf) u8 {
3335 return @intCast(@divExact(self.getTarget().ptrBitWidth(), 8));
3336}
3337
3338fn phdrTo32(phdr: elf.Elf64.Phdr) elf.Elf32.Phdr {
3339 return .{
3340 .type = phdr.type,
3341 .flags = phdr.flags,
3342 .offset = @intCast(phdr.offset),
3343 .vaddr = @intCast(phdr.vaddr),
3344 .paddr = @intCast(phdr.paddr),
3345 .filesz = @intCast(phdr.filesz),
3346 .memsz = @intCast(phdr.memsz),
3347 .@"align" = @intCast(phdr.@"align"),
3348 };
3349}
3350
3351fn shdrTo32(shdr: elf.Elf64_Shdr) elf.Elf32_Shdr {
3352 return .{
3353 .sh_name = shdr.sh_name,
3354 .sh_type = shdr.sh_type,
3355 .sh_flags = @as(u32, @intCast(shdr.sh_flags)),
3356 .sh_addr = @as(u32, @intCast(shdr.sh_addr)),
3357 .sh_offset = @as(u32, @intCast(shdr.sh_offset)),
3358 .sh_size = @as(u32, @intCast(shdr.sh_size)),
3359 .sh_link = shdr.sh_link,
3360 .sh_info = shdr.sh_info,
3361 .sh_addralign = @as(u32, @intCast(shdr.sh_addralign)),
3362 .sh_entsize = @as(u32, @intCast(shdr.sh_entsize)),
3363 };
3364}
3365
3366pub fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
3367 return actual_size +| (actual_size / ideal_factor);
3368}
3369
3370/// If a target compiles other output modes as dynamic libraries,
3371/// this function returns true for those too.
3372pub fn isEffectivelyDynLib(self: Elf) bool {
3373 if (self.base.isDynLib()) return true;
3374 return switch (self.getTarget().os.tag) {
3375 .haiku => self.base.isExe(),
3376 else => false,
3377 };
3378}
3379
3380fn getPhdr(self: *Elf, opts: struct {
3381 type: u32 = 0,
3382 flags: u32 = 0,
3383}) OptionalProgramHeaderIndex {
3384 for (self.phdrs.items, 0..) |phdr, phndx| {
3385 if (self.phdr_indexes.table_load.int()) |index| {
3386 if (phndx == index) continue;
3387 }
3388 if (@backingInt(phdr.type) == opts.type and @backingInt(phdr.flags) == opts.flags)
3389 return @fromBackingInt(@intCast(phndx));
3390 }
3391 return .none;
3392}
3393
3394fn addPhdr(self: *Elf, opts: struct {
3395 type: u32 = 0,
3396 flags: u32 = 0,
3397 @"align": u64 = 0,
3398 offset: u64 = 0,
3399 addr: u64 = 0,
3400 filesz: u64 = 0,
3401 memsz: u64 = 0,
3402}) error{OutOfMemory}!ProgramHeaderIndex {
3403 const gpa = self.base.comp.gpa;
3404 const index: ProgramHeaderIndex = @fromBackingInt(@intCast(self.phdrs.items.len));
3405 try self.phdrs.append(gpa, .{
3406 .type = @fromBackingInt(opts.type),
3407 .flags = @fromBackingInt(opts.flags),
3408 .offset = opts.offset,
3409 .vaddr = opts.addr,
3410 .paddr = opts.addr,
3411 .filesz = opts.filesz,
3412 .memsz = opts.memsz,
3413 .@"align" = opts.@"align",
3414 });
3415 return index;
3416}
3417
3418pub fn addRelaShdr(self: *Elf, name: u32, shndx: u32) !u32 {
3419 const entsize: u64 = switch (self.ptr_width) {
3420 .p32 => @sizeOf(elf.Elf32_Rela),
3421 .p64 => @sizeOf(elf.Elf64_Rela),
3422 };
3423 const addralign: u64 = switch (self.ptr_width) {
3424 .p32 => @alignOf(elf.Elf32_Rela),
3425 .p64 => @alignOf(elf.Elf64_Rela),
3426 };
3427 return self.addSection(.{
3428 .name = name,
3429 .type = elf.SHT_RELA,
3430 .flags = elf.SHF_INFO_LINK,
3431 .entsize = entsize,
3432 .info = shndx,
3433 .addralign = addralign,
3434 });
3435}
3436
3437pub const AddSectionOpts = struct {
3438 name: u32 = 0,
3439 type: u32 = elf.SHT_NULL,
3440 flags: u64 = 0,
3441 link: u32 = 0,
3442 info: u32 = 0,
3443 addralign: u64 = 0,
3444 entsize: u64 = 0,
3445};
3446
3447pub fn addSection(self: *Elf, opts: AddSectionOpts) !u32 {
3448 const gpa = self.base.comp.gpa;
3449 const index: u32 = @intCast(try self.sections.addOne(gpa));
3450 self.sections.set(index, .{
3451 .shdr = .{
3452 .sh_name = opts.name,
3453 .sh_type = opts.type,
3454 .sh_flags = opts.flags,
3455 .sh_addr = 0,
3456 .sh_offset = 0,
3457 .sh_size = 0,
3458 .sh_link = opts.link,
3459 .sh_info = opts.info,
3460 .sh_addralign = opts.addralign,
3461 .sh_entsize = opts.entsize,
3462 },
3463 });
3464 return index;
3465}
3466
3467pub fn sectionByName(self: *Elf, name: [:0]const u8) ?u32 {
3468 for (self.sections.items(.shdr), 0..) |*shdr, i| {
3469 const this_name = self.getShString(shdr.sh_name);
3470 if (mem.eql(u8, this_name, name)) return @intCast(i);
3471 } else return null;
3472}
3473
3474const RelaDyn = struct {
3475 offset: u64,
3476 sym: u64 = 0,
3477 type: u32,
3478 addend: i64 = 0,
3479 target: ?*const Symbol = null,
3480};
3481
3482pub fn addRelaDyn(self: *Elf, opts: RelaDyn) !void {
3483 try self.rela_dyn.ensureUnusedCapacity(self.base.alloctor, 1);
3484 self.addRelaDynAssumeCapacity(opts);
3485}
3486
3487pub fn addRelaDynAssumeCapacity(self: *Elf, opts: RelaDyn) void {
3488 relocs_log.debug(" {f}: [{x} => {d}({s})] + {x}", .{
3489 relocation.fmtRelocType(opts.type, self.getTarget().cpu.arch),
3490 opts.offset,
3491 opts.sym,
3492 if (opts.target) |sym| sym.name(self) else "",
3493 opts.addend,
3494 });
3495 self.rela_dyn.appendAssumeCapacity(.{
3496 .r_offset = opts.offset,
3497 .r_info = (opts.sym << 32) | opts.type,
3498 .r_addend = opts.addend,
3499 });
3500}
3501
3502fn sortRelaDyn(self: *Elf) void {
3503 const Sort = struct {
3504 fn rank(rel: elf.Elf64_Rela, ctx: *Elf) u2 {
3505 const cpu_arch = ctx.getTarget().cpu.arch;
3506 const r_type = rel.r_type();
3507 const r_kind = relocation.decode(r_type, cpu_arch).?;
3508 return switch (r_kind) {
3509 .rel => 0,
3510 .irel => 2,
3511 else => 1,
3512 };
3513 }
3514
3515 pub fn lessThan(ctx: *Elf, lhs: elf.Elf64_Rela, rhs: elf.Elf64_Rela) bool {
3516 if (rank(lhs, ctx) == rank(rhs, ctx)) {
3517 if (lhs.r_sym() == rhs.r_sym()) return lhs.r_offset < rhs.r_offset;
3518 return lhs.r_sym() < rhs.r_sym();
3519 }
3520 return rank(lhs, ctx) < rank(rhs, ctx);
3521 }
3522 };
3523 mem.sort(elf.Elf64_Rela, self.rela_dyn.items, self, Sort.lessThan);
3524}
3525
3526pub fn calcNumIRelativeRelocs(self: *Elf) usize {
3527 var count: usize = self.num_ifunc_dynrelocs;
3528
3529 for (self.got.entries.items) |entry| {
3530 if (entry.tag != .got) continue;
3531 const sym = self.symbol(entry.ref).?;
3532 if (sym.isIFunc(self)) count += 1;
3533 }
3534
3535 return count;
3536}
3537
3538pub fn getStartStopBasename(self: Elf, shdr: elf.Elf64_Shdr) ?[]const u8 {
3539 const name = self.getShString(shdr.sh_name);
3540 if (shdr.sh_flags & elf.SHF_ALLOC != 0 and name.len > 0) {
3541 if (Elf.isCIdentifier(name)) return name;
3542 }
3543 return null;
3544}
3545
3546pub fn isCIdentifier(name: []const u8) bool {
3547 if (name.len == 0) return false;
3548 const first_c = name[0];
3549 if (!std.ascii.isAlphabetic(first_c) and first_c != '_') return false;
3550 for (name[1..]) |c| {
3551 if (!std.ascii.isAlphanumeric(c) and c != '_') return false;
3552 }
3553 return true;
3554}
3555
3556pub fn addThunk(self: *Elf) !Thunk.Index {
3557 const index = @as(Thunk.Index, @intCast(self.thunks.items.len));
3558 const th = try self.thunks.addOne(self.base.comp.gpa);
3559 th.* = .{};
3560 return index;
3561}
3562
3563pub fn thunk(self: *Elf, index: Thunk.Index) *Thunk {
3564 assert(index < self.thunks.items.len);
3565 return &self.thunks.items[index];
3566}
3567
3568pub fn file(self: *Elf, index: File.Index) ?File {
3569 return fileLookup(self.files, index, self.zig_object);
3570}
3571
3572fn fileLookup(files: std.MultiArrayList(File.Entry), index: File.Index, zig_object: ?*ZigObject) ?File {
3573 const tag = files.items(.tags)[index];
3574 return switch (tag) {
3575 .null => null,
3576 .linker_defined => .{ .linker_defined = &files.items(.data)[index].linker_defined },
3577 .zig_object => .{ .zig_object = zig_object.? },
3578 .object => .{ .object = &files.items(.data)[index].object },
3579 .shared_object => .{ .shared_object = &files.items(.data)[index].shared_object },
3580 };
3581}
3582
3583pub fn addFileHandle(
3584 gpa: Allocator,
3585 file_handles: *std.ArrayList(File.Handle),
3586 handle: Io.File,
3587) Allocator.Error!File.HandleIndex {
3588 try file_handles.append(gpa, handle);
3589 return @intCast(file_handles.items.len - 1);
3590}
3591
3592pub fn fileHandle(self: Elf, index: File.HandleIndex) File.Handle {
3593 return self.file_handles.items[index];
3594}
3595
3596pub fn atom(self: *Elf, ref: Ref) ?*Atom {
3597 const file_ptr = self.file(ref.file) orelse return null;
3598 return file_ptr.atom(ref.index);
3599}
3600
3601pub fn group(self: *Elf, ref: Ref) *Group {
3602 return self.file(ref.file).?.group(ref.index);
3603}
3604
3605pub fn symbol(self: *Elf, ref: Ref) ?*Symbol {
3606 const file_ptr = self.file(ref.file) orelse return null;
3607 return file_ptr.symbol(ref.index);
3608}
3609
3610pub fn getGlobalSymbol(self: *Elf, name: []const u8, lib_name: ?[]const u8) !u32 {
3611 return self.zigObjectPtr().?.getGlobalSymbol(self, name, lib_name);
3612}
3613
3614pub fn zigObjectPtr(self: *Elf) ?*ZigObject {
3615 return self.zig_object;
3616}
3617
3618pub fn linkerDefinedPtr(self: *Elf) ?*LinkerDefined {
3619 const index = self.linker_defined_index orelse return null;
3620 return self.file(index).?.linker_defined;
3621}
3622
3623pub fn getOrCreateMergeSection(self: *Elf, name: [:0]const u8, flags: u64, @"type": u32) !Merge.Section.Index {
3624 const gpa = self.base.comp.gpa;
3625 const out_name = name: {
3626 if (self.base.isRelocatable()) break :name name;
3627 if (mem.eql(u8, name, ".rodata") or mem.startsWith(u8, name, ".rodata"))
3628 break :name if (flags & elf.SHF_STRINGS != 0) ".rodata.str" else ".rodata.cst";
3629 break :name name;
3630 };
3631 for (self.merge_sections.items, 0..) |msec, index| {
3632 if (mem.eql(u8, msec.name(self), out_name)) return @intCast(index);
3633 }
3634 const out_off = try self.insertShString(out_name);
3635 const out_flags = flags & ~@as(u64, elf.SHF_COMPRESSED | elf.SHF_GROUP);
3636 const index: Merge.Section.Index = @intCast(self.merge_sections.items.len);
3637 const msec = try self.merge_sections.addOne(gpa);
3638 msec.* = .{
3639 .name_offset = out_off,
3640 .flags = out_flags,
3641 .type = @"type",
3642 };
3643 return index;
3644}
3645
3646pub fn mergeSection(self: *Elf, index: Merge.Section.Index) *Merge.Section {
3647 assert(index < self.merge_sections.items.len);
3648 return &self.merge_sections.items[index];
3649}
3650
3651pub fn gotAddress(self: *Elf) i64 {
3652 const shndx = blk: {
3653 if (self.getTarget().cpu.arch == .x86_64 and self.section_indexes.got_plt != null)
3654 break :blk self.section_indexes.got_plt.?;
3655 break :blk if (self.section_indexes.got) |shndx| shndx else null;
3656 };
3657 return if (shndx) |index| @intCast(self.sections.items(.shdr)[index].sh_addr) else 0;
3658}
3659
3660pub fn tpAddress(self: *Elf) i64 {
3661 const index = self.phdr_indexes.tls.int() orelse return 0;
3662 const phdr = self.phdrs.items[index];
3663 const addr = switch (self.getTarget().cpu.arch) {
3664 .x86_64 => mem.alignForward(u64, phdr.vaddr + phdr.memsz, phdr.@"align"),
3665 .aarch64, .aarch64_be => mem.alignBackward(u64, phdr.vaddr - 16, phdr.@"align"),
3666 .riscv64, .riscv64be => phdr.vaddr,
3667 else => |arch| std.debug.panic("TODO implement getTpAddress for {s}", .{@tagName(arch)}),
3668 };
3669 return @intCast(addr);
3670}
3671
3672pub fn dtpAddress(self: *Elf) i64 {
3673 const index = self.phdr_indexes.tls.int() orelse return 0;
3674 const phdr = self.phdrs.items[index];
3675 return @intCast(phdr.vaddr);
3676}
3677
3678pub fn tlsAddress(self: *Elf) i64 {
3679 const index = self.phdr_indexes.tls.int() orelse return 0;
3680 const phdr = self.phdrs.items[index];
3681 return @intCast(phdr.vaddr);
3682}
3683
3684pub fn getShString(self: Elf, off: u32) [:0]const u8 {
3685 return shString(self.shstrtab.items, off);
3686}
3687
3688fn shString(
3689 shstrtab: []const u8,
3690 off: u32,
3691) [:0]const u8 {
3692 const slice = shstrtab[off..];
3693 return slice[0..mem.findScalar(u8, slice, 0).? :0];
3694}
3695
3696pub fn insertShString(self: *Elf, name: [:0]const u8) error{OutOfMemory}!u32 {
3697 const gpa = self.base.comp.gpa;
3698 const off = @as(u32, @intCast(self.shstrtab.items.len));
3699 try self.shstrtab.ensureUnusedCapacity(gpa, name.len + 1);
3700 self.shstrtab.print(gpa, "{s}\x00", .{name}) catch unreachable;
3701 return off;
3702}
3703
3704pub fn getDynString(self: Elf, off: u32) [:0]const u8 {
3705 assert(off < self.dynstrtab.items.len);
3706 return mem.sliceTo(@as([*:0]const u8, @ptrCast(self.dynstrtab.items.ptr + off)), 0);
3707}
3708
3709pub fn insertDynString(self: *Elf, name: []const u8) error{OutOfMemory}!u32 {
3710 const gpa = self.base.comp.gpa;
3711 const off = @as(u32, @intCast(self.dynstrtab.items.len));
3712 try self.dynstrtab.ensureUnusedCapacity(gpa, name.len + 1);
3713 self.dynstrtab.print(gpa, "{s}\x00", .{name}) catch unreachable;
3714 return off;
3715}
3716
3717fn reportUndefinedSymbols(self: *Elf, undefs: anytype) !void {
3718 const gpa = self.base.comp.gpa;
3719 const diags = &self.base.comp.link_diags;
3720 const max_notes = 4;
3721
3722 try diags.msgs.ensureUnusedCapacity(gpa, undefs.count());
3723
3724 for (undefs.keys(), undefs.values()) |key, refs| {
3725 const undef_sym = self.resolver.keys.items[key - 1];
3726 const nrefs = @min(refs.items.len, max_notes);
3727 const nnotes = nrefs + @intFromBool(refs.items.len > max_notes);
3728
3729 var err = try diags.addErrorWithNotesAssumeCapacity(nnotes);
3730 try err.addMsg("undefined symbol: {s}", .{undef_sym.name(self)});
3731
3732 for (refs.items[0..nrefs]) |ref| {
3733 const atom_ptr = self.atom(ref).?;
3734 const file_ptr = atom_ptr.file(self).?;
3735 err.addNote("referenced by {f}:{s}", .{ file_ptr.fmtPath(), atom_ptr.name(self) });
3736 }
3737
3738 if (refs.items.len > max_notes) {
3739 const remaining = refs.items.len - max_notes;
3740 err.addNote("referenced {d} more times", .{remaining});
3741 }
3742 }
3743}
3744
3745fn reportDuplicates(self: *Elf, dupes: anytype) error{ HasDuplicates, OutOfMemory }!void {
3746 if (dupes.keys().len == 0) return; // Nothing to do
3747 const diags = &self.base.comp.link_diags;
3748
3749 const max_notes = 3;
3750
3751 for (dupes.keys(), dupes.values()) |key, notes| {
3752 const sym = self.resolver.keys.items[key - 1];
3753 const nnotes = @min(notes.items.len, max_notes) + @intFromBool(notes.items.len > max_notes);
3754
3755 var err = try diags.addErrorWithNotes(nnotes + 1);
3756 try err.addMsg("duplicate symbol definition: {s}", .{sym.name(self)});
3757 err.addNote("defined by {f}", .{sym.file(self).?.fmtPath()});
3758
3759 var inote: usize = 0;
3760 while (inote < @min(notes.items.len, max_notes)) : (inote += 1) {
3761 const file_ptr = self.file(notes.items[inote]).?;
3762 err.addNote("defined by {f}", .{file_ptr.fmtPath()});
3763 }
3764
3765 if (notes.items.len > max_notes) {
3766 const remaining = notes.items.len - max_notes;
3767 err.addNote("defined {d} more times", .{remaining});
3768 }
3769 }
3770
3771 return error.HasDuplicates;
3772}
3773
3774fn reportUnsupportedCpuArch(self: *Elf) error{OutOfMemory}!void {
3775 const diags = &self.base.comp.link_diags;
3776 var err = try diags.addErrorWithNotes(0);
3777 try err.addMsg("fatal linker error: unsupported CPU architecture {s}", .{
3778 @tagName(self.getTarget().cpu.arch),
3779 });
3780}
3781
3782pub fn addFileError(
3783 self: *Elf,
3784 file_index: File.Index,
3785 comptime format: []const u8,
3786 args: anytype,
3787) error{OutOfMemory}!void {
3788 const diags = &self.base.comp.link_diags;
3789 var err = try diags.addErrorWithNotes(1);
3790 try err.addMsg(format, args);
3791 err.addNote("while parsing {f}", .{self.file(file_index).?.fmtPath()});
3792}
3793
3794pub fn failFile(
3795 self: *Elf,
3796 file_index: File.Index,
3797 comptime format: []const u8,
3798 args: anytype,
3799) error{ OutOfMemory, AlreadyReported } {
3800 try addFileError(self, file_index, format, args);
3801 return error.AlreadyReported;
3802}
3803
3804const FormatShdr = struct {
3805 elf_file: *Elf,
3806 shdr: elf.Elf64_Shdr,
3807};
3808
3809fn fmtShdr(self: *Elf, shdr: elf.Elf64_Shdr) std.fmt.Alt(FormatShdr, formatShdr) {
3810 return .{ .data = .{
3811 .shdr = shdr,
3812 .elf_file = self,
3813 } };
3814}
3815
3816fn formatShdr(ctx: FormatShdr, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3817 const shdr = ctx.shdr;
3818 try writer.print("{s} : @{x} ({x}) : align({x}) : size({x}) : entsize({x}) : flags({f})", .{
3819 ctx.elf_file.getShString(shdr.sh_name), shdr.sh_offset,
3820 shdr.sh_addr, shdr.sh_addralign,
3821 shdr.sh_size, shdr.sh_entsize,
3822 fmtShdrFlags(shdr.sh_flags),
3823 });
3824}
3825
3826pub fn fmtShdrFlags(sh_flags: u64) std.fmt.Alt(u64, formatShdrFlags) {
3827 return .{ .data = sh_flags };
3828}
3829
3830fn formatShdrFlags(sh_flags: u64, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3831 if (elf.SHF_WRITE & sh_flags != 0) {
3832 try writer.writeAll("W");
3833 }
3834 if (elf.SHF_ALLOC & sh_flags != 0) {
3835 try writer.writeAll("A");
3836 }
3837 if (elf.SHF_EXECINSTR & sh_flags != 0) {
3838 try writer.writeAll("X");
3839 }
3840 if (elf.SHF_MERGE & sh_flags != 0) {
3841 try writer.writeAll("M");
3842 }
3843 if (elf.SHF_STRINGS & sh_flags != 0) {
3844 try writer.writeAll("S");
3845 }
3846 if (elf.SHF_INFO_LINK & sh_flags != 0) {
3847 try writer.writeAll("I");
3848 }
3849 if (elf.SHF_LINK_ORDER & sh_flags != 0) {
3850 try writer.writeAll("L");
3851 }
3852 if (elf.SHF_EXCLUDE & sh_flags != 0) {
3853 try writer.writeAll("E");
3854 }
3855 if (elf.SHF_COMPRESSED & sh_flags != 0) {
3856 try writer.writeAll("C");
3857 }
3858 if (elf.SHF_GROUP & sh_flags != 0) {
3859 try writer.writeAll("G");
3860 }
3861 if (elf.SHF_OS_NONCONFORMING & sh_flags != 0) {
3862 try writer.writeAll("O");
3863 }
3864 if (elf.SHF_TLS & sh_flags != 0) {
3865 try writer.writeAll("T");
3866 }
3867 if (elf.SHF_X86_64_LARGE & sh_flags != 0) {
3868 try writer.writeAll("l");
3869 }
3870 if (elf.SHF_MIPS_ADDR & sh_flags != 0 or elf.SHF_ARM_PURECODE & sh_flags != 0) {
3871 try writer.writeAll("p");
3872 }
3873}
3874
3875const FormatPhdr = struct {
3876 elf_file: *Elf,
3877 phdr: elf.Elf64.Phdr,
3878};
3879
3880fn fmtPhdr(self: *Elf, phdr: elf.Elf64.Phdr) std.fmt.Alt(FormatPhdr, formatPhdr) {
3881 return .{ .data = .{
3882 .phdr = phdr,
3883 .elf_file = self,
3884 } };
3885}
3886
3887fn formatPhdr(ctx: FormatPhdr, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3888 const phdr = ctx.phdr;
3889 const write = phdr.flags.W;
3890 const read = phdr.flags.R;
3891 const exec = phdr.flags.X;
3892 var flags: [3]u8 = @splat('_');
3893 if (exec) flags[0] = 'X';
3894 if (write) flags[1] = 'W';
3895 if (read) flags[2] = 'R';
3896 const p_type = switch (phdr.type) {
3897 .LOAD => "LOAD",
3898 .TLS => "TLS",
3899 .GNU_EH_FRAME => "GNU_EH_FRAME",
3900 .GNU_STACK => "GNU_STACK",
3901 .DYNAMIC => "DYNAMIC",
3902 .INTERP => "INTERP",
3903 .NULL => "NULL",
3904 .PHDR => "PHDR",
3905 .NOTE => "NOTE",
3906 else => "UNKNOWN",
3907 };
3908 try writer.print("{s} : {s} : @{x} ({x}) : align({x}) : filesz({x}) : memsz({x})", .{
3909 p_type, flags, phdr.offset, phdr.vaddr,
3910 phdr.@"align", phdr.filesz, phdr.memsz,
3911 });
3912}
3913
3914pub fn dumpState(self: *Elf) std.fmt.Alt(*Elf, fmtDumpState) {
3915 return .{ .data = self };
3916}
3917
3918fn fmtDumpState(self: *Elf, writer: *std.Io.Writer) std.Io.Writer.Error!void {
3919 const shared_objects = self.shared_objects.values();
3920
3921 if (self.zigObjectPtr()) |zig_object| {
3922 try writer.print("zig_object({d}) : {s}\n", .{ zig_object.index, zig_object.basename });
3923 try writer.print("{f}{f}", .{
3924 zig_object.fmtAtoms(self),
3925 zig_object.fmtSymtab(self),
3926 });
3927 try writer.writeByte('\n');
3928 }
3929
3930 for (self.objects.items) |index| {
3931 const object = self.file(index).?.object;
3932 try writer.print("object({d}) : {f}", .{ index, object.fmtPath() });
3933 if (!object.alive) try writer.writeAll(" : [*]");
3934 try writer.writeByte('\n');
3935 try writer.print("{f}{f}{f}{f}{f}\n", .{
3936 object.fmtAtoms(self),
3937 object.fmtCies(self),
3938 object.fmtFdes(self),
3939 object.fmtSymtab(self),
3940 object.fmtGroups(self),
3941 });
3942 }
3943
3944 for (shared_objects) |index| {
3945 const shared_object = self.file(index).?.shared_object;
3946 try writer.print("shared_object({d}) : {f} : needed({})", .{
3947 index, shared_object.path, shared_object.needed,
3948 });
3949 if (!shared_object.alive) try writer.writeAll(" : [*]");
3950 try writer.writeByte('\n');
3951 try writer.print("{f}\n", .{shared_object.fmtSymtab(self)});
3952 }
3953
3954 if (self.linker_defined_index) |index| {
3955 const linker_defined = self.file(index).?.linker_defined;
3956 try writer.print("linker_defined({d}) : (linker defined)\n", .{index});
3957 try writer.print("{f}\n", .{linker_defined.fmtSymtab(self)});
3958 }
3959
3960 const slice = self.sections.slice();
3961 {
3962 try writer.writeAll("atom lists\n");
3963 for (slice.items(.shdr), slice.items(.atom_list_2), 0..) |shdr, atom_list, shndx| {
3964 try writer.print("shdr({d}) : {s} : {f}\n", .{ shndx, self.getShString(shdr.sh_name), atom_list.fmt(self) });
3965 }
3966 }
3967
3968 if (self.requiresThunks()) {
3969 try writer.writeAll("thunks\n");
3970 for (self.thunks.items, 0..) |th, index| {
3971 try writer.print("thunk({d}) : {f}\n", .{ index, th.fmt(self) });
3972 }
3973 }
3974
3975 try writer.print("{f}\n", .{self.got.fmt(self)});
3976 try writer.print("{f}\n", .{self.plt.fmt(self)});
3977
3978 try writer.writeAll("Output groups\n");
3979 for (self.group_sections.items) |cg| {
3980 try writer.print(" shdr({d}) : GROUP({f})\n", .{ cg.shndx, cg.cg_ref });
3981 }
3982
3983 try writer.writeAll("\nOutput merge sections\n");
3984 for (self.merge_sections.items) |msec| {
3985 try writer.print(" shdr({d}) : {f}\n", .{ msec.output_section_index, msec.fmt(self) });
3986 }
3987
3988 try writer.writeAll("\nOutput shdrs\n");
3989 for (slice.items(.shdr), slice.items(.phndx), 0..) |shdr, phndx, shndx| {
3990 try writer.print(" shdr({d}) : phdr({d}) : {f}\n", .{
3991 shndx,
3992 phndx,
3993 self.fmtShdr(shdr),
3994 });
3995 }
3996 try writer.writeAll("\nOutput phdrs\n");
3997 for (self.phdrs.items, 0..) |phdr, phndx| {
3998 try writer.print(" phdr({d}) : {f}\n", .{ phndx, self.fmtPhdr(phdr) });
3999 }
4000}
4001
4002/// Caller owns the memory.
4003pub fn preadAllAlloc(allocator: Allocator, io: Io, io_file: Io.File, offset: u64, size: u64) ![]u8 {
4004 const buffer = try allocator.alloc(u8, math.cast(usize, size) orelse return error.Overflow);
4005 errdefer allocator.free(buffer);
4006 const amt = try io_file.readPositionalAll(io, buffer, offset);
4007 if (amt != size) return error.InputOutput;
4008 return buffer;
4009}
4010
4011/// Binary search
4012pub fn bsearch(comptime T: type, haystack: []const T, predicate: anytype) usize {
4013 var min: usize = 0;
4014 var max: usize = haystack.len;
4015 while (min < max) {
4016 const index = (min + max) / 2;
4017 const curr = haystack[index];
4018 if (predicate.predicate(curr)) {
4019 min = index + 1;
4020 } else {
4021 max = index;
4022 }
4023 }
4024 return min;
4025}
4026
4027/// Linear search
4028pub fn lsearch(comptime T: type, haystack: []const T, predicate: anytype) usize {
4029 var i: usize = 0;
4030 while (i < haystack.len) : (i += 1) {
4031 if (predicate.predicate(haystack[i])) break;
4032 }
4033 return i;
4034}
4035
4036pub fn getTarget(self: *const Elf) *const std.Target {
4037 return &self.base.comp.root_mod.resolved_target.result;
4038}
4039
4040fn requiresThunks(self: Elf) bool {
4041 return switch (self.getTarget().cpu.arch) {
4042 .aarch64, .aarch64_be => true,
4043 .x86_64, .riscv64, .riscv64be => false,
4044 else => @panic("TODO unimplemented architecture"),
4045 };
4046}
4047
4048/// The following three values are only observed at compile-time and used to emit a compile error
4049/// to remind the programmer to update expected maximum numbers of different program header types
4050/// so that we reserve enough space for the program header table up-front.
4051/// Bump these numbers when adding or deleting a Zig specific pre-allocated segment, or adding
4052/// more special-purpose program headers.
4053const max_number_of_object_segments = 9;
4054const max_number_of_special_phdrs = 5;
4055
4056const default_entry_addr = 0x8000000;
4057
4058pub const base_tag: link.File.Tag = .elf;
4059
4060pub const Group = struct {
4061 signature_off: u32,
4062 file_index: File.Index,
4063 shndx: u32,
4064 members_start: u32,
4065 members_len: u32,
4066 is_comdat: bool,
4067 alive: bool = true,
4068
4069 pub fn file(cg: Group, elf_file: *Elf) File {
4070 return elf_file.file(cg.file_index).?;
4071 }
4072
4073 pub fn signature(cg: Group, elf_file: *Elf) [:0]const u8 {
4074 return cg.file(elf_file).object.getString(cg.signature_off);
4075 }
4076
4077 pub fn members(cg: Group, elf_file: *Elf) []const u32 {
4078 const object = cg.file(elf_file).object;
4079 return object.group_data.items[cg.members_start..][0..cg.members_len];
4080 }
4081
4082 pub const Index = u32;
4083};
4084
4085pub const SymtabCtx = struct {
4086 ilocal: u32 = 0,
4087 iglobal: u32 = 0,
4088 nlocals: u32 = 0,
4089 nglobals: u32 = 0,
4090 strsize: u32 = 0,
4091
4092 pub fn reset(ctx: *SymtabCtx) void {
4093 ctx.ilocal = 0;
4094 ctx.iglobal = 0;
4095 ctx.nlocals = 0;
4096 ctx.nglobals = 0;
4097 ctx.strsize = 0;
4098 }
4099};
4100
4101pub const null_sym = elf.Elf64_Sym{
4102 .st_name = 0,
4103 .st_info = 0,
4104 .st_other = 0,
4105 .st_shndx = 0,
4106 .st_value = 0,
4107 .st_size = 0,
4108};
4109
4110pub const null_shdr = elf.Elf64_Shdr{
4111 .sh_name = 0,
4112 .sh_type = 0,
4113 .sh_flags = 0,
4114 .sh_addr = 0,
4115 .sh_offset = 0,
4116 .sh_size = 0,
4117 .sh_link = 0,
4118 .sh_info = 0,
4119 .sh_addralign = 0,
4120 .sh_entsize = 0,
4121};
4122
4123pub const SystemLib = struct {
4124 needed: bool = false,
4125 path: Path,
4126};
4127
4128pub const Ref = struct {
4129 index: u32 = 0,
4130 file: u32 = 0,
4131
4132 pub fn eql(ref: Ref, other: Ref) bool {
4133 return ref.index == other.index and ref.file == other.file;
4134 }
4135
4136 pub fn format(ref: Ref, writer: *std.Io.Writer) std.Io.Writer.Error!void {
4137 try writer.print("ref({d},{d})", .{ ref.index, ref.file });
4138 }
4139};
4140
4141pub const SymbolResolver = struct {
4142 keys: std.ArrayList(Key) = .empty,
4143 values: std.ArrayList(Ref) = .empty,
4144 table: std.array_hash_map.Auto(void, void) = .empty,
4145
4146 const Result = struct {
4147 found_existing: bool,
4148 index: Index,
4149 ref: *Ref,
4150 };
4151
4152 pub fn deinit(resolver: *SymbolResolver, allocator: Allocator) void {
4153 resolver.keys.deinit(allocator);
4154 resolver.values.deinit(allocator);
4155 resolver.table.deinit(allocator);
4156 }
4157
4158 pub fn getOrPut(
4159 resolver: *SymbolResolver,
4160 allocator: Allocator,
4161 ref: Ref,
4162 elf_file: *Elf,
4163 ) !Result {
4164 const adapter = Adapter{ .keys = resolver.keys.items, .elf_file = elf_file };
4165 const key = Key{ .index = ref.index, .file_index = ref.file };
4166 const gop = try resolver.table.getOrPutAdapted(allocator, key, adapter);
4167 if (!gop.found_existing) {
4168 try resolver.keys.append(allocator, key);
4169 _ = try resolver.values.addOne(allocator);
4170 }
4171 return .{
4172 .found_existing = gop.found_existing,
4173 .index = @intCast(gop.index + 1),
4174 .ref = &resolver.values.items[gop.index],
4175 };
4176 }
4177
4178 pub fn get(resolver: SymbolResolver, index: Index) ?Ref {
4179 if (index == 0) return null;
4180 return resolver.values.items[index - 1];
4181 }
4182
4183 pub fn reset(resolver: *SymbolResolver) void {
4184 resolver.keys.clearRetainingCapacity();
4185 resolver.values.clearRetainingCapacity();
4186 resolver.table.clearRetainingCapacity();
4187 }
4188
4189 const Key = struct {
4190 index: Symbol.Index,
4191 file_index: File.Index,
4192
4193 fn name(key: Key, elf_file: *Elf) [:0]const u8 {
4194 const ref = Ref{ .index = key.index, .file = key.file_index };
4195 return elf_file.symbol(ref).?.name(elf_file);
4196 }
4197
4198 fn file(key: Key, elf_file: *Elf) ?File {
4199 return elf_file.file(key.file_index);
4200 }
4201
4202 fn eql(key: Key, other: Key, elf_file: *Elf) bool {
4203 const key_name = key.name(elf_file);
4204 const other_name = other.name(elf_file);
4205 return mem.eql(u8, key_name, other_name);
4206 }
4207
4208 fn hash(key: Key, elf_file: *Elf) u32 {
4209 return @truncate(Hash.hash(0, key.name(elf_file)));
4210 }
4211 };
4212
4213 const Adapter = struct {
4214 keys: []const Key,
4215 elf_file: *Elf,
4216
4217 pub fn eql(ctx: @This(), key: Key, b_void: void, b_map_index: usize) bool {
4218 _ = b_void;
4219 const other = ctx.keys[b_map_index];
4220 return key.eql(other, ctx.elf_file);
4221 }
4222
4223 pub fn hash(ctx: @This(), key: Key) u32 {
4224 return key.hash(ctx.elf_file);
4225 }
4226 };
4227
4228 pub const Index = u32;
4229};
4230
4231const Section = struct {
4232 /// Section header.
4233 shdr: elf.Elf64_Shdr,
4234
4235 /// Assigned program header index if any.
4236 phndx: OptionalProgramHeaderIndex = .none,
4237
4238 /// List of atoms contributing to this section.
4239 /// TODO currently this is only used for relocations tracking in relocatable mode
4240 /// but will be merged with atom_list_2.
4241 atom_list: std.ArrayList(Ref) = .empty,
4242
4243 /// List of atoms contributing to this section.
4244 /// This can be used by sections that require special handling such as init/fini array, etc.
4245 atom_list_2: AtomList = .{},
4246
4247 /// Index of the last allocated atom in this section.
4248 last_atom: Ref = .{ .index = 0, .file = 0 },
4249
4250 /// A list of atoms that have surplus capacity. This list can have false
4251 /// positives, as functions grow and shrink over time, only sometimes being added
4252 /// or removed from the freelist.
4253 ///
4254 /// An atom has surplus capacity when its overcapacity value is greater than
4255 /// padToIdeal(minimum_atom_size). That is, when it has so
4256 /// much extra capacity, that we could fit a small new symbol in it, itself with
4257 /// ideal_capacity or more.
4258 ///
4259 /// Ideal capacity is defined by size + (size / ideal_factor)
4260 ///
4261 /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that
4262 /// overcapacity can be negative. A simple way to have negative overcapacity is to
4263 /// allocate a fresh text block, which will have ideal capacity, and then grow it
4264 /// by 1 byte. It will then have -1 overcapacity.
4265 free_list: std.ArrayList(Ref) = .empty,
4266};
4267
4268pub fn sectionSize(self: *Elf, shndx: u32) u64 {
4269 const last_atom_ref = self.sections.items(.last_atom)[shndx];
4270 const atom_ptr = self.atom(last_atom_ref) orelse return 0;
4271 return @as(u64, @intCast(atom_ptr.value)) + atom_ptr.size;
4272}
4273
4274fn defaultEntrySymbolName(cpu_arch: std.Target.Cpu.Arch) []const u8 {
4275 return switch (cpu_arch) {
4276 .mips, .mipsel, .mips64, .mips64el => "__start",
4277 else => "_start",
4278 };
4279}
4280
4281fn createThunks(elf_file: *Elf, atom_list: *AtomList) !void {
4282 const gpa = elf_file.base.comp.gpa;
4283 const cpu_arch = elf_file.getTarget().cpu.arch;
4284
4285 // A branch will need an extender if its target is larger than
4286 // `2^(jump_bits - 1) - margin` where margin is some arbitrary number.
4287 const max_distance = switch (cpu_arch) {
4288 .aarch64, .aarch64_be => 0x500_000,
4289 .x86_64, .riscv64, .riscv64be => unreachable,
4290 else => @panic("unhandled arch"),
4291 };
4292
4293 const advance = struct {
4294 fn advance(list: *AtomList, size: u64, alignment: Atom.Alignment) !i64 {
4295 const offset = alignment.forward(list.size);
4296 const padding = offset - list.size;
4297 list.size += padding + size;
4298 list.alignment = list.alignment.max(alignment);
4299 return @intCast(offset);
4300 }
4301 }.advance;
4302
4303 for (atom_list.atoms.keys()) |ref| {
4304 elf_file.atom(ref).?.value = -1;
4305 }
4306
4307 var i: usize = 0;
4308 while (i < atom_list.atoms.keys().len) {
4309 const start = i;
4310 const start_atom = elf_file.atom(atom_list.atoms.keys()[start]).?;
4311 assert(start_atom.alive);
4312 start_atom.value = try advance(atom_list, start_atom.size, start_atom.alignment);
4313 i += 1;
4314
4315 while (i < atom_list.atoms.keys().len) : (i += 1) {
4316 const atom_ptr = elf_file.atom(atom_list.atoms.keys()[i]).?;
4317 assert(atom_ptr.alive);
4318 if (@as(i64, @intCast(atom_ptr.alignment.forward(atom_list.size))) - start_atom.value >= max_distance)
4319 break;
4320 atom_ptr.value = try advance(atom_list, atom_ptr.size, atom_ptr.alignment);
4321 }
4322
4323 // Insert a thunk at the group end
4324 const thunk_index = try elf_file.addThunk();
4325 const thunk_ptr = elf_file.thunk(thunk_index);
4326 thunk_ptr.output_section_index = atom_list.output_section_index;
4327
4328 // Scan relocs in the group and create trampolines for any unreachable callsite
4329 for (atom_list.atoms.keys()[start..i]) |ref| {
4330 const atom_ptr = elf_file.atom(ref).?;
4331 const file_ptr = atom_ptr.file(elf_file).?;
4332 log.debug("atom({f}) {s}", .{ ref, atom_ptr.name(elf_file) });
4333 for (atom_ptr.relocs(elf_file)) |rel| {
4334 const is_reachable = switch (cpu_arch) {
4335 .aarch64, .aarch64_be => r: {
4336 const r_type: elf.R_AARCH64 = @fromBackingInt(@intCast(rel.r_type()));
4337 if (r_type != .CALL26 and r_type != .JUMP26) break :r true;
4338 const target_ref = file_ptr.resolveSymbol(rel.r_sym(), elf_file);
4339 const target = elf_file.symbol(target_ref).?;
4340 if (target.flags.has_plt) break :r false;
4341 if (atom_ptr.output_section_index != target.output_section_index) break :r false;
4342 const target_atom = target.atom(elf_file).?;
4343 if (target_atom.value == -1) break :r false;
4344 const saddr = atom_ptr.address(elf_file) + @as(i64, @intCast(rel.r_offset));
4345 const taddr = target.address(.{}, elf_file);
4346 _ = math.cast(i28, taddr + rel.r_addend - saddr) orelse break :r false;
4347 break :r true;
4348 },
4349 .x86_64, .riscv64, .riscv64be => unreachable,
4350 else => @panic("unsupported arch"),
4351 };
4352 if (is_reachable) continue;
4353 const target = file_ptr.resolveSymbol(rel.r_sym(), elf_file);
4354 try thunk_ptr.symbols.put(gpa, target, {});
4355 }
4356 atom_ptr.addExtra(.{ .thunk = thunk_index }, elf_file);
4357 }
4358
4359 thunk_ptr.value = try advance(atom_list, thunk_ptr.size(elf_file), Atom.Alignment.fromNonzeroByteUnits(2));
4360
4361 log.debug("thunk({d}) : {f}", .{ thunk_index, thunk_ptr.fmt(elf_file) });
4362 }
4363}
4364
4365pub fn stringTableLookup(strtab: []const u8, off: u32) [:0]const u8 {
4366 const slice = strtab[off..];
4367 return slice[0..mem.findScalar(u8, slice, 0).? :0];
4368}
4369
4370pub fn pwriteAll(elf_file: *Elf, bytes: []const u8, offset: u64) error{AlreadyReported}!void {
4371 const comp = elf_file.base.comp;
4372 const io = comp.io;
4373 const diags = &comp.link_diags;
4374 elf_file.base.file.?.writePositionalAll(io, bytes, offset) catch |err|
4375 return diags.fail("failed to write: {t}", .{err});
4376}
4377
4378pub fn setLength(elf_file: *Elf, length: u64) error{AlreadyReported}!void {
4379 const comp = elf_file.base.comp;
4380 const io = comp.i;
4381 const diags = &comp.link_diags;
4382 elf_file.base.file.?.setLength(io, length) catch |err| {
4383 return diags.fail("failed to set file end pos: {s}", .{@errorName(err)});
4384 };
4385}
4386
4387pub fn cast(elf_file: *Elf, comptime T: type, x: anytype) error{AlreadyReported}!T {
4388 return std.math.cast(T, x) orelse {
4389 const comp = elf_file.base.comp;
4390 const diags = &comp.link_diags;
4391 return diags.fail("encountered {d}, overflowing {d}-bit value", .{ x, @bitSizeOf(T) });
4392 };
4393}
4394
4395const std = @import("std");
4396const Io = std.Io;
4397const build_options = @import("build_options");
4398const builtin = @import("builtin");
4399const assert = std.debug.assert;
4400const elf = std.elf;
4401const fs = std.fs;
4402const log = std.log.scoped(.link);
4403const relocs_log = std.log.scoped(.link_relocs);
4404const state_log = std.log.scoped(.link_state);
4405const math = std.math;
4406const mem = std.mem;
4407const Allocator = std.mem.Allocator;
4408const Hash = std.hash.Wyhash;
4409const Path = std.Build.Cache.Path;
4410const Stat = std.Build.Cache.File.Stat;
4411
4412const codegen = @import("../codegen.zig");
4413const eh_frame = @import("Elf/eh_frame.zig");
4414const gc = @import("Elf/gc.zig");
4415const musl = @import("../libs/musl.zig");
4416const link = @import("../link.zig");
4417const relocatable = @import("Elf/relocatable.zig");
4418const relocation = @import("Elf/relocation.zig");
4419const target_util = @import("../target.zig");
4420const trace = @import("../tracy.zig").trace;
4421const synthetic_sections = @import("Elf/synthetic_sections.zig");
4422
4423const Merge = @import("Elf/Merge.zig");
4424const Archive = @import("Elf/Archive.zig");
4425const AtomList = @import("Elf/AtomList.zig");
4426const Compilation = @import("../Compilation.zig");
4427const GroupSection = synthetic_sections.GroupSection;
4428const CopyRelSection = synthetic_sections.CopyRelSection;
4429const Diags = @import("../link.zig").Diags;
4430const DynamicSection = synthetic_sections.DynamicSection;
4431const DynsymSection = synthetic_sections.DynsymSection;
4432const Dwarf = @import("Dwarf.zig");
4433const Elf = @This();
4434const File = @import("Elf/file.zig").File;
4435const GnuHashSection = synthetic_sections.GnuHashSection;
4436const GotSection = synthetic_sections.GotSection;
4437const GotPltSection = synthetic_sections.GotPltSection;
4438const HashSection = synthetic_sections.HashSection;
4439const LinkerDefined = @import("Elf/LinkerDefined.zig");
4440const Zcu = @import("../Zcu.zig");
4441const Object = @import("Elf/Object.zig");
4442const InternPool = @import("../InternPool.zig");
4443const PltSection = synthetic_sections.PltSection;
4444const PltGotSection = synthetic_sections.PltGotSection;
4445const SharedObject = @import("Elf/SharedObject.zig");
4446const Symbol = @import("Elf/Symbol.zig");
4447const StringTable = @import("StringTable.zig");
4448const Thunk = @import("Elf/Thunk.zig");
4449const Value = @import("../Value.zig");
4450const VerneedSection = synthetic_sections.VerneedSection;
4451const ZigObject = @import("Elf/ZigObject.zig");