authorgravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2023-09-02 17:23:49+02:00
committergravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2023-09-03 08:32:28+02:00
log009a349779186548480823140dd1f8758d600221
tree10a79ff337318e726608f611360fee1b040400f8
parente265dc61e651d67bbfb3be675ff132df865902ef

elf: add global symbol resolver


2 files changed, 262 insertions(+), 204 deletions(-)

src/link/Elf.zig+251-193
......@@ -1,99 +1,3 @@
1const Elf = @This();
2
3const std = @import("std");
4const build_options = @import("build_options");
5const builtin = @import("builtin");
6const assert = std.debug.assert;
7const elf = std.elf;
8const fs = std.fs;
9const log = std.log.scoped(.link);
10const math = std.math;
11const mem = std.mem;
12
13const codegen = @import("../codegen.zig");
14const glibc = @import("../glibc.zig");
15const link = @import("../link.zig");
16const lldMain = @import("../main.zig").lldMain;
17const musl = @import("../musl.zig");
18const target_util = @import("../target.zig");
19const trace = @import("../tracy.zig").trace;
20
21const Air = @import("../Air.zig");
22const Allocator = std.mem.Allocator;
23pub const Atom = @import("Elf/Atom.zig");
24const Cache = std.Build.Cache;
25const Compilation = @import("../Compilation.zig");
26const Dwarf = @import("Dwarf.zig");
27const File = link.File;
28const Liveness = @import("../Liveness.zig");
29const LlvmObject = @import("../codegen/llvm.zig").Object;
30const Module = @import("../Module.zig");
31const InternPool = @import("../InternPool.zig");
32const Package = @import("../Package.zig");
33const StringTable = @import("strtab.zig").StringTable;
34const TableSection = @import("table_section.zig").TableSection;
35const Type = @import("../type.zig").Type;
36const TypedValue = @import("../TypedValue.zig");
37const Value = @import("../value.zig").Value;
38
39const default_entry_addr = 0x8000000;
40
41pub const base_tag: File.Tag = .elf;
42
43const Section = struct {
44 shdr: elf.Elf64_Shdr,
45 phdr_index: u16,
46
47 /// Index of the last allocated atom in this section.
48 last_atom_index: ?Atom.Index = null,
49
50 /// A list of atoms that have surplus capacity. This list can have false
51 /// positives, as functions grow and shrink over time, only sometimes being added
52 /// or removed from the freelist.
53 ///
54 /// An atom has surplus capacity when its overcapacity value is greater than
55 /// padToIdeal(minimum_atom_size). That is, when it has so
56 /// much extra capacity, that we could fit a small new symbol in it, itself with
57 /// ideal_capacity or more.
58 ///
59 /// Ideal capacity is defined by size + (size / ideal_factor)
60 ///
61 /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that
62 /// overcapacity can be negative. A simple way to have negative overcapacity is to
63 /// allocate a fresh text block, which will have ideal capacity, and then grow it
64 /// by 1 byte. It will then have -1 overcapacity.
65 free_list: std.ArrayListUnmanaged(Atom.Index) = .{},
66};
67
68const LazySymbolMetadata = struct {
69 const State = enum { unused, pending_flush, flushed };
70 text_atom: Atom.Index = undefined,
71 rodata_atom: Atom.Index = undefined,
72 text_state: State = .unused,
73 rodata_state: State = .unused,
74};
75
76const DeclMetadata = struct {
77 atom: Atom.Index,
78 shdr: u16,
79 /// A list of all exports aliases of this Decl.
80 exports: std.ArrayListUnmanaged(u32) = .{},
81
82 fn getExport(m: DeclMetadata, elf_file: *const Elf, name: []const u8) ?u32 {
83 for (m.exports.items) |exp| {
84 if (mem.eql(u8, name, elf_file.getGlobalName(exp))) return exp;
85 }
86 return null;
87 }
88
89 fn getExportPtr(m: *DeclMetadata, elf_file: *Elf, name: []const u8) ?*u32 {
90 for (m.exports.items) |*exp| {
91 if (mem.eql(u8, name, elf_file.getGlobalName(exp.*))) return exp;
92 }
93 return null;
94 }
95};
96
971base: File,
982dwarf: ?Dwarf = null,
993
......@@ -151,11 +55,13 @@ strtab_section_index: ?u16 = null,
15155/// local symbols, they cannot be mixed. So we must buffer all the global symbols and
15256/// write them at the end. These are only the local symbols. The length of this array
15357/// is the value used for sh_info in the .symtab section.
154local_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = .{},
155global_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = .{},
58locals: std.ArrayListUnmanaged(elf.Elf64_Sym) = .{},
59globals: std.ArrayListUnmanaged(u32) = .{},
60resolver: std.StringHashMapUnmanaged(u32) = .{},
61unresolved: std.AutoArrayHashMapUnmanaged(u32, void) = .{},
15662
157local_symbol_free_list: std.ArrayListUnmanaged(u32) = .{},
158global_symbol_free_list: std.ArrayListUnmanaged(u32) = .{},
63locals_free_list: std.ArrayListUnmanaged(u32) = .{},
64globals_free_list: std.ArrayListUnmanaged(u32) = .{},
15965
16066got_table: TableSection(u32) = .{},
16167
......@@ -247,14 +153,7 @@ pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Option
247153 self.shdr_table_dirty = true;
248154
249155 // Index 0 is always a null symbol.
250 try self.local_symbols.append(allocator, .{
251 .st_name = 0,
252 .st_info = 0,
253 .st_other = 0,
254 .st_shndx = 0,
255 .st_value = 0,
256 .st_size = 0,
257 });
156 try self.locals.append(allocator, null_sym);
258157
259158 // There must always be a null section in index 0
260159 try self.sections.append(allocator, .{
......@@ -329,11 +228,20 @@ pub fn deinit(self: *Elf) void {
329228 self.program_headers.deinit(gpa);
330229 self.shstrtab.deinit(gpa);
331230 self.strtab.deinit(gpa);
332 self.local_symbols.deinit(gpa);
333 self.global_symbols.deinit(gpa);
334 self.global_symbol_free_list.deinit(gpa);
335 self.local_symbol_free_list.deinit(gpa);
231 self.locals.deinit(gpa);
232 self.globals.deinit(gpa);
233 self.globals_free_list.deinit(gpa);
234 self.locals_free_list.deinit(gpa);
336235 self.got_table.deinit(gpa);
236 self.unresolved.deinit(gpa);
237
238 {
239 var it = self.resolver.keyIterator();
240 while (it.next()) |key_ptr| {
241 gpa.free(key_ptr.*);
242 }
243 self.resolver.deinit(gpa);
244 }
337245
338246 {
339247 var it = self.decls.iterator();
......@@ -743,7 +651,7 @@ pub fn populateMissingMetadata(self: *Elf) !void {
743651 .sh_size = file_size,
744652 // The section header index of the associated string table.
745653 .sh_link = self.strtab_section_index.?,
746 .sh_info = @as(u32, @intCast(self.local_symbols.items.len)),
654 .sh_info = @as(u32, @intCast(self.locals.items.len)),
747655 .sh_addralign = min_align,
748656 .sh_entsize = each_size,
749657 },
......@@ -908,7 +816,7 @@ pub fn populateMissingMetadata(self: *Elf) !void {
908816
909817 {
910818 // Iterate over symbols, populating free_list and last_text_block.
911 if (self.local_symbols.items.len != 1) {
819 if (self.locals.items.len != 1) {
912820 @panic("TODO implement setting up free_list and last_text_block from existing ELF file");
913821 }
914822 // We are starting with an empty file. The default values are correct, null and empty list.
......@@ -1109,7 +1017,7 @@ pub fn flushModule(self: *Elf, comp: *Compilation, prog_node: *std.Progress.Node
11091017 log.debug("relocating '{?s}'", .{self.strtab.get(source_sym.st_name)});
11101018
11111019 for (relocs.items) |*reloc| {
1112 const target_sym = self.local_symbols.items[reloc.target];
1020 const target_sym = self.locals.items[reloc.target];
11131021 const target_vaddr = target_sym.st_value + reloc.addend;
11141022
11151023 if (target_vaddr == reloc.prev_vaddr) continue;
......@@ -2219,22 +2127,14 @@ fn freeAtom(self: *Elf, atom_index: Atom.Index) void {
22192127 }
22202128
22212129 // Appending to free lists is allowed to fail because the free lists are heuristics based anyway.
2222 const local_sym_index = atom.getSymbolIndex().?;
2223
2224 log.debug("adding %{d} to local symbols free list", .{local_sym_index});
2225 self.local_symbol_free_list.append(gpa, local_sym_index) catch {};
2226 self.local_symbols.items[local_sym_index] = .{
2227 .st_name = 0,
2228 .st_info = 0,
2229 .st_other = 0,
2230 .st_shndx = 0,
2231 .st_value = 0,
2232 .st_size = 0,
2233 };
2234 _ = self.atom_by_index_table.remove(local_sym_index);
2235 self.getAtomPtr(atom_index).local_sym_index = 0;
2236
2237 self.got_table.freeEntry(gpa, local_sym_index);
2130 const sym_index = atom.getSymbolIndex().?;
2131
2132 log.debug("adding %{d} to local symbols free list", .{sym_index});
2133 self.locals_free_list.append(gpa, sym_index) catch {};
2134 self.locals.items[sym_index] = null_sym;
2135 _ = self.atom_by_index_table.remove(sym_index);
2136 self.getAtomPtr(atom_index).sym_index = 0;
2137 self.got_table.freeEntry(gpa, sym_index);
22382138}
22392139
22402140fn shrinkAtom(self: *Elf, atom_index: Atom.Index, new_block_size: u64) void {
......@@ -2256,14 +2156,14 @@ pub fn createAtom(self: *Elf) !Atom.Index {
22562156 const gpa = self.base.allocator;
22572157 const atom_index = @as(Atom.Index, @intCast(self.atoms.items.len));
22582158 const atom = try self.atoms.addOne(gpa);
2259 const local_sym_index = try self.allocateLocalSymbol();
2260 try self.atom_by_index_table.putNoClobber(gpa, local_sym_index, atom_index);
2159 const sym_index = try self.allocateSymbol();
2160 try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom_index);
22612161 atom.* = .{
2262 .local_sym_index = local_sym_index,
2162 .sym_index = sym_index,
22632163 .prev_index = null,
22642164 .next_index = null,
22652165 };
2266 log.debug("creating ATOM(%{d}) at index {d}", .{ local_sym_index, atom_index });
2166 log.debug("creating ATOM(%{d}) at index {d}", .{ sym_index, atom_index });
22672167 return atom_index;
22682168}
22692169
......@@ -2389,22 +2289,20 @@ fn allocateAtom(self: *Elf, atom_index: Atom.Index, new_block_size: u64, alignme
23892289 return vaddr;
23902290}
23912291
2392pub fn allocateLocalSymbol(self: *Elf) !u32 {
2393 try self.local_symbols.ensureUnusedCapacity(self.base.allocator, 1);
2394
2292pub fn allocateSymbol(self: *Elf) !u32 {
2293 try self.locals.ensureUnusedCapacity(self.base.allocator, 1);
23952294 const index = blk: {
2396 if (self.local_symbol_free_list.popOrNull()) |index| {
2295 if (self.locals_free_list.popOrNull()) |index| {
23972296 log.debug(" (reusing symbol index {d})", .{index});
23982297 break :blk index;
23992298 } else {
2400 log.debug(" (allocating symbol index {d})", .{self.local_symbols.items.len});
2401 const index = @as(u32, @intCast(self.local_symbols.items.len));
2402 _ = self.local_symbols.addOneAssumeCapacity();
2299 log.debug(" (allocating symbol index {d})", .{self.locals.items.len});
2300 const index = @as(u32, @intCast(self.locals.items.len));
2301 _ = self.locals.addOneAssumeCapacity();
24032302 break :blk index;
24042303 }
24052304 };
2406
2407 self.local_symbols.items[index] = .{
2305 self.locals.items[index] = .{
24082306 .st_name = 0,
24092307 .st_info = 0,
24102308 .st_other = 0,
......@@ -2412,7 +2310,23 @@ pub fn allocateLocalSymbol(self: *Elf) !u32 {
24122310 .st_value = 0,
24132311 .st_size = 0,
24142312 };
2313 return index;
2314}
24152315
2316fn allocateGlobal(self: *Elf) !u32 {
2317 try self.globals.ensureUnusedCapacity(self.base.allocator, 1);
2318 const index = blk: {
2319 if (self.globals_free_list.popOrNull()) |index| {
2320 log.debug(" (reusing global index {d})", .{index});
2321 break :blk index;
2322 } else {
2323 log.debug(" (allocating symbol index {d})", .{self.globals.items.len});
2324 const index = @as(u32, @intCast(self.globals.items.len));
2325 _ = self.globals.addOneAssumeCapacity();
2326 break :blk index;
2327 }
2328 };
2329 self.globals.items[index] = 0;
24162330 return index;
24172331}
24182332
......@@ -2896,8 +2810,6 @@ pub fn updateDeclExports(
28962810 const decl_metadata = self.decls.getPtr(decl_index).?;
28972811 const shdr_index = decl_metadata.shdr;
28982812
2899 try self.global_symbols.ensureUnusedCapacity(gpa, exports.len);
2900
29012813 for (exports) |exp| {
29022814 const exp_name = mod.intern_pool.stringToSlice(exp.opts.name);
29032815 if (exp.opts.section.unwrap()) |section_name| {
......@@ -2905,7 +2817,7 @@ pub fn updateDeclExports(
29052817 try mod.failed_exports.ensureUnusedCapacity(mod.gpa, 1);
29062818 mod.failed_exports.putAssumeCapacityNoClobber(
29072819 exp,
2908 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(mod), "Unimplemented: ExportOptions.section", .{}),
2820 try Module.ErrorMsg.create(gpa, decl.srcLoc(mod), "Unimplemented: ExportOptions.section", .{}),
29092821 );
29102822 continue;
29112823 }
......@@ -2924,37 +2836,30 @@ pub fn updateDeclExports(
29242836 try mod.failed_exports.ensureUnusedCapacity(mod.gpa, 1);
29252837 mod.failed_exports.putAssumeCapacityNoClobber(
29262838 exp,
2927 try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(mod), "Unimplemented: GlobalLinkage.LinkOnce", .{}),
2839 try Module.ErrorMsg.create(gpa, decl.srcLoc(mod), "Unimplemented: GlobalLinkage.LinkOnce", .{}),
29282840 );
29292841 continue;
29302842 },
29312843 };
29322844 const stt_bits: u8 = @as(u4, @truncate(decl_sym.st_info));
2933 if (decl_metadata.getExport(self, exp_name)) |i| {
2934 const sym = &self.global_symbols.items[i];
2935 sym.* = .{
2936 .st_name = try self.strtab.insert(gpa, exp_name),
2937 .st_info = (stb_bits << 4) | stt_bits,
2938 .st_other = 0,
2939 .st_shndx = shdr_index,
2940 .st_value = decl_sym.st_value,
2941 .st_size = decl_sym.st_size,
2942 };
2943 } else {
2944 const i = if (self.global_symbol_free_list.popOrNull()) |i| i else blk: {
2945 _ = self.global_symbols.addOneAssumeCapacity();
2946 break :blk self.global_symbols.items.len - 1;
2947 };
2948 try decl_metadata.exports.append(gpa, @as(u32, @intCast(i)));
2949 self.global_symbols.items[i] = .{
2950 .st_name = try self.strtab.insert(gpa, exp_name),
2951 .st_info = (stb_bits << 4) | stt_bits,
2952 .st_other = 0,
2953 .st_shndx = shdr_index,
2954 .st_value = decl_sym.st_value,
2955 .st_size = decl_sym.st_size,
2956 };
2957 }
2845
2846 const sym_index = decl_metadata.getExport(self, exp_name) orelse blk: {
2847 const sym_index = try self.allocateSymbol();
2848 try decl_metadata.exports.append(gpa, sym_index);
2849 break :blk sym_index;
2850 };
2851 const sym = self.getSymbolPtr(sym_index);
2852 sym.* = .{
2853 .st_name = try self.strtab.insert(gpa, exp_name),
2854 .st_info = (stb_bits << 4) | stt_bits,
2855 .st_other = 0,
2856 .st_shndx = shdr_index,
2857 .st_value = decl_sym.st_value,
2858 .st_size = decl_sym.st_size,
2859 };
2860 const sym_name = self.getSymbolName(sym_index);
2861 const gop = try self.getOrPutGlobalPtr(sym_name);
2862 gop.value_ptr.* = sym_index;
29582863 }
29592864}
29602865
......@@ -2981,10 +2886,20 @@ pub fn deleteDeclExport(
29812886) void {
29822887 if (self.llvm_object) |_| return;
29832888 const metadata = self.decls.getPtr(decl_index) orelse return;
2889 const gpa = self.base.allocator;
29842890 const mod = self.base.options.module.?;
2985 const sym_index = metadata.getExportPtr(self, mod.intern_pool.stringToSlice(name)) orelse return;
2986 self.global_symbol_free_list.append(self.base.allocator, sym_index.*) catch {};
2987 self.global_symbols.items[sym_index.*].st_info = 0;
2891 const exp_name = mod.intern_pool.stringToSlice(name);
2892 const sym_index = metadata.getExportPtr(self, exp_name) orelse return;
2893 const sym = self.getSymbolPtr(sym_index.*);
2894 log.debug("deleting export '{s}'", .{exp_name});
2895 sym.* = null_sym;
2896 self.locals_free_list.append(gpa, sym_index.*) catch {};
2897
2898 if (self.resolver.fetchRemove(exp_name)) |entry| {
2899 self.globals_free_list.append(gpa, entry.value) catch {};
2900 self.globals.items[entry.value] = 0;
2901 }
2902
29882903 sym_index.* = 0;
29892904}
29902905
......@@ -3110,10 +3025,10 @@ fn writeSymbols(self: *Elf) !void {
31103025 };
31113026
31123027 const shdr = &self.sections.items(.shdr)[self.symtab_section_index.?];
3113 shdr.sh_info = @intCast(self.local_symbols.items.len);
3028 shdr.sh_info = @intCast(self.locals.items.len);
31143029 self.markDirty(self.symtab_section_index.?, null);
31153030
3116 const nsyms = self.local_symbols.items.len + self.global_symbols.items.len;
3031 const nsyms = self.locals.items.len + self.globals.items.len;
31173032 const needed_size = nsyms * sym_size;
31183033 try self.growNonAllocSection(self.symtab_section_index.?, needed_size, sym_align, true);
31193034
......@@ -3124,15 +3039,15 @@ fn writeSymbols(self: *Elf) !void {
31243039 const buf = try gpa.alloc(elf.Elf32_Sym, nsyms);
31253040 defer gpa.free(buf);
31263041
3127 for (buf[0..self.local_symbols.items.len], self.local_symbols.items) |*sym, local| {
3042 for (buf[0..self.locals.items.len], self.locals.items) |*sym, local| {
31283043 elf32SymFromSym(local, sym);
31293044 if (foreign_endian) {
31303045 mem.byteSwapAllFields(elf.Elf32_Sym, sym);
31313046 }
31323047 }
31333048
3134 for (buf[self.local_symbols.items.len..], self.global_symbols.items) |*sym, global| {
3135 elf32SymFromSym(global, sym);
3049 for (buf[self.locals.items.len..], self.globals.items) |*sym, global| {
3050 elf32SymFromSym(self.getSymbol(global), sym);
31363051 if (foreign_endian) {
31373052 mem.byteSwapAllFields(elf.Elf32_Sym, sym);
31383053 }
......@@ -3142,15 +3057,15 @@ fn writeSymbols(self: *Elf) !void {
31423057 .p64 => {
31433058 const buf = try gpa.alloc(elf.Elf64_Sym, nsyms);
31443059 defer gpa.free(buf);
3145 for (buf[0..self.local_symbols.items.len], self.local_symbols.items) |*sym, local| {
3060 for (buf[0..self.locals.items.len], self.locals.items) |*sym, local| {
31463061 sym.* = local;
31473062 if (foreign_endian) {
31483063 mem.byteSwapAllFields(elf.Elf64_Sym, sym);
31493064 }
31503065 }
31513066
3152 for (buf[self.local_symbols.items.len..], self.global_symbols.items) |*sym, global| {
3153 sym.* = global;
3067 for (buf[self.locals.items.len..], self.globals.items) |*sym, global| {
3068 sym.* = self.getSymbol(global);
31543069 if (foreign_endian) {
31553070 mem.byteSwapAllFields(elf.Elf64_Sym, sym);
31563071 }
......@@ -3450,11 +3365,12 @@ const CsuObjects = struct {
34503365
34513366fn logSymtab(self: Elf) void {
34523367 log.debug("locals:", .{});
3453 for (self.local_symbols.items, 0..) |sym, id| {
3368 for (self.locals.items, 0..) |sym, id| {
34543369 log.debug(" {d}: {?s}: @{x} in {d}", .{ id, self.strtab.get(sym.st_name), sym.st_value, sym.st_shndx });
34553370 }
34563371 log.debug("globals:", .{});
3457 for (self.global_symbols.items, 0..) |sym, id| {
3372 for (self.globals.items, 0..) |global, id| {
3373 const sym = self.getSymbol(global);
34583374 log.debug(" {d}: {?s}: @{x} in {d}", .{ id, self.strtab.get(sym.st_name), sym.st_value, sym.st_shndx });
34593375 }
34603376}
......@@ -3471,24 +3387,61 @@ pub fn getProgramHeaderPtr(self: *Elf, shdr_index: u16) *elf.Elf64_Phdr {
34713387
34723388/// Returns pointer-to-symbol described at sym_index.
34733389pub fn getSymbolPtr(self: *Elf, sym_index: u32) *elf.Elf64_Sym {
3474 return &self.local_symbols.items[sym_index];
3390 return &self.locals.items[sym_index];
34753391}
34763392
34773393/// Returns symbol at sym_index.
34783394pub fn getSymbol(self: *const Elf, sym_index: u32) elf.Elf64_Sym {
3479 return self.local_symbols.items[sym_index];
3395 return self.locals.items[sym_index];
34803396}
34813397
34823398/// Returns name of the symbol at sym_index.
34833399pub fn getSymbolName(self: *const Elf, sym_index: u32) []const u8 {
3484 const sym = self.local_symbols.items[sym_index];
3400 const sym = self.locals.items[sym_index];
34853401 return self.strtab.get(sym.st_name).?;
34863402}
34873403
3488/// Returns name of the global symbol at index.
3489pub fn getGlobalName(self: *const Elf, index: u32) []const u8 {
3490 const sym = self.global_symbols.items[index];
3491 return self.strtab.get(sym.st_name).?;
3404/// Returns pointer to the global entry for `name` if one exists.
3405pub fn getGlobalPtr(self: *Elf, name: []const u8) ?*u32 {
3406 const global_index = self.resolver.get(name) orelse return null;
3407 return &self.globals.items[global_index];
3408}
3409
3410/// Returns the global entry for `name` if one exists.
3411pub fn getGlobal(self: *const Elf, name: []const u8) ?u32 {
3412 const global_index = self.resolver.get(name) orelse return null;
3413 return self.globals.items[global_index];
3414}
3415
3416/// Returns the index of the global entry for `name` if one exists.
3417pub fn getGlobalIndex(self: *const Elf, name: []const u8) ?u32 {
3418 return self.resolver.get(name);
3419}
3420
3421/// Returns global entry at `index`.
3422pub fn getGlobalByIndex(self: *const Elf, index: u32) u32 {
3423 assert(index < self.globals.items.len);
3424 return self.globals.items[index];
3425}
3426
3427const GetOrPutGlobalPtrResult = struct {
3428 found_existing: bool,
3429 value_ptr: *u32,
3430};
3431
3432/// Return pointer to the global entry for `name` if one exists.
3433/// Puts a new global entry for `name` if one doesn't exist, and
3434/// returns a pointer to it.
3435pub fn getOrPutGlobalPtr(self: *Elf, name: []const u8) !GetOrPutGlobalPtrResult {
3436 if (self.getGlobalPtr(name)) |ptr| {
3437 return GetOrPutGlobalPtrResult{ .found_existing = true, .value_ptr = ptr };
3438 }
3439 const gpa = self.base.allocator;
3440 const global_index = try self.allocateGlobal();
3441 const global_name = try gpa.dupe(u8, name);
3442 _ = try self.resolver.put(gpa, global_name, global_index);
3443 const ptr = &self.globals.items[global_index];
3444 return GetOrPutGlobalPtrResult{ .found_existing = false, .value_ptr = ptr };
34923445}
34933446
34943447pub fn getAtom(self: *const Elf, atom_index: Atom.Index) Atom {
......@@ -3506,3 +3459,108 @@ pub fn getAtomPtr(self: *Elf, atom_index: Atom.Index) *Atom {
35063459pub fn getAtomIndexForSymbol(self: *Elf, sym_index: u32) ?Atom.Index {
35073460 return self.atom_by_index_table.get(sym_index);
35083461}
3462
3463pub const null_sym = elf.Elf64_Sym{
3464 .st_name = 0,
3465 .st_info = 0,
3466 .st_other = 0,
3467 .st_shndx = 0,
3468 .st_value = 0,
3469 .st_size = 0,
3470};
3471
3472const default_entry_addr = 0x8000000;
3473
3474pub const base_tag: File.Tag = .elf;
3475
3476const Section = struct {
3477 shdr: elf.Elf64_Shdr,
3478 phdr_index: u16,
3479
3480 /// Index of the last allocated atom in this section.
3481 last_atom_index: ?Atom.Index = null,
3482
3483 /// A list of atoms that have surplus capacity. This list can have false
3484 /// positives, as functions grow and shrink over time, only sometimes being added
3485 /// or removed from the freelist.
3486 ///
3487 /// An atom has surplus capacity when its overcapacity value is greater than
3488 /// padToIdeal(minimum_atom_size). That is, when it has so
3489 /// much extra capacity, that we could fit a small new symbol in it, itself with
3490 /// ideal_capacity or more.
3491 ///
3492 /// Ideal capacity is defined by size + (size / ideal_factor)
3493 ///
3494 /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that
3495 /// overcapacity can be negative. A simple way to have negative overcapacity is to
3496 /// allocate a fresh text block, which will have ideal capacity, and then grow it
3497 /// by 1 byte. It will then have -1 overcapacity.
3498 free_list: std.ArrayListUnmanaged(Atom.Index) = .{},
3499};
3500
3501const LazySymbolMetadata = struct {
3502 const State = enum { unused, pending_flush, flushed };
3503 text_atom: Atom.Index = undefined,
3504 rodata_atom: Atom.Index = undefined,
3505 text_state: State = .unused,
3506 rodata_state: State = .unused,
3507};
3508
3509const DeclMetadata = struct {
3510 atom: Atom.Index,
3511 shdr: u16,
3512 /// A list of all exports aliases of this Decl.
3513 exports: std.ArrayListUnmanaged(u32) = .{},
3514
3515 fn getExport(m: DeclMetadata, elf_file: *const Elf, name: []const u8) ?u32 {
3516 for (m.exports.items) |exp| {
3517 if (mem.eql(u8, name, elf_file.getSymbolName(exp))) return exp;
3518 }
3519 return null;
3520 }
3521
3522 fn getExportPtr(m: *DeclMetadata, elf_file: *Elf, name: []const u8) ?*u32 {
3523 for (m.exports.items) |*exp| {
3524 if (mem.eql(u8, name, elf_file.getSymbolName(exp.*))) return exp;
3525 }
3526 return null;
3527 }
3528};
3529
3530const Elf = @This();
3531
3532const std = @import("std");
3533const build_options = @import("build_options");
3534const builtin = @import("builtin");
3535const assert = std.debug.assert;
3536const elf = std.elf;
3537const fs = std.fs;
3538const log = std.log.scoped(.link);
3539const math = std.math;
3540const mem = std.mem;
3541
3542const codegen = @import("../codegen.zig");
3543const glibc = @import("../glibc.zig");
3544const link = @import("../link.zig");
3545const lldMain = @import("../main.zig").lldMain;
3546const musl = @import("../musl.zig");
3547const target_util = @import("../target.zig");
3548const trace = @import("../tracy.zig").trace;
3549
3550const Air = @import("../Air.zig");
3551const Allocator = std.mem.Allocator;
3552pub const Atom = @import("Elf/Atom.zig");
3553const Cache = std.Build.Cache;
3554const Compilation = @import("../Compilation.zig");
3555const Dwarf = @import("Dwarf.zig");
3556const File = link.File;
3557const Liveness = @import("../Liveness.zig");
3558const LlvmObject = @import("../codegen/llvm.zig").Object;
3559const Module = @import("../Module.zig");
3560const InternPool = @import("../InternPool.zig");
3561const Package = @import("../Package.zig");
3562const StringTable = @import("strtab.zig").StringTable;
3563const TableSection = @import("table_section.zig").TableSection;
3564const Type = @import("../type.zig").Type;
3565const TypedValue = @import("../TypedValue.zig");
3566const Value = @import("../value.zig").Value;
src/link/Elf/Atom.zig+11-11
......@@ -1,18 +1,10 @@
1const Atom = @This();
2
3const std = @import("std");
4const assert = std.debug.assert;
5const elf = std.elf;
6
7const Elf = @import("../Elf.zig");
8
91/// Each decl always gets a local symbol with the fully qualified name.
102/// The vaddr and size are found here directly.
113/// The file offset is found by computing the vaddr offset from the section vaddr
124/// the symbol references, and adding that to the file offset of the section.
135/// If this field is 0, it means the codegen size = 0 and there is no symbol or
146/// offset table entry.
15local_sym_index: u32,
7sym_index: u32,
168
179/// Points to the previous and next neighbors, based on the `text_offset`.
1810/// This can be used to find, for example, the capacity of this `TextBlock`.
......@@ -29,8 +21,8 @@ pub const Reloc = struct {
2921};
3022
3123pub fn getSymbolIndex(self: Atom) ?u32 {
32 if (self.local_sym_index == 0) return null;
33 return self.local_sym_index;
24 if (self.sym_index == 0) return null;
25 return self.sym_index;
3426}
3527
3628pub fn getSymbol(self: Atom, elf_file: *const Elf) elf.Elf64_Sym {
......@@ -106,3 +98,11 @@ pub fn freeRelocations(elf_file: *Elf, atom_index: Index) void {
10698 var removed_relocs = elf_file.relocs.fetchRemove(atom_index);
10799 if (removed_relocs) |*relocs| relocs.value.deinit(elf_file.base.allocator);
108100}
101
102const Atom = @This();
103
104const std = @import("std");
105const assert = std.debug.assert;
106const elf = std.elf;
107
108const Elf = @import("../Elf.zig");