authorgravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2023-10-13 14:54:52+02:00
committergravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2023-10-16 19:33:05+02:00
log7be983ac9217a596b7f35e7ef4c49fda0270e10b
tree358dd3cf5de8c7c412febd9d77c487f9d7c3114e
parent9b6337ab06e90b23c7d494b49fb8a728ac9d75e2

elf: create new synthetic section ZigGotSection


10 files changed, 341 insertions(+), 122 deletions(-)

src/arch/aarch64/CodeGen.zig+2-2
......@@ -4318,8 +4318,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
43184318 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
43194319 const sym_index = try elf_file.getOrCreateMetadataForDecl(func.owner_decl);
43204320 const sym = elf_file.symbol(sym_index);
4321 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
4322 const got_addr = @as(u32, @intCast(sym.gotAddress(elf_file)));
4321 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
4322 const got_addr = @as(u32, @intCast(sym.zigGotAddress(elf_file)));
43234323 try self.genSetReg(Type.usize, .x30, .{ .memory = got_addr });
43244324 } else if (self.bin_file.cast(link.File.MachO)) |macho_file| {
43254325 const atom = try macho_file.getOrCreateAtomForDecl(func.owner_decl);
src/arch/arm/CodeGen.zig+2-2
......@@ -4304,8 +4304,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
43044304 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
43054305 const sym_index = try elf_file.getOrCreateMetadataForDecl(func.owner_decl);
43064306 const sym = elf_file.symbol(sym_index);
4307 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
4308 const got_addr = @as(u32, @intCast(sym.gotAddress(elf_file)));
4307 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
4308 const got_addr = @as(u32, @intCast(sym.zigGotAddress(elf_file)));
43094309 try self.genSetReg(Type.usize, .lr, .{ .memory = got_addr });
43104310 } else if (self.bin_file.cast(link.File.MachO)) |_| {
43114311 unreachable; // unsupported architecture for MachO
src/arch/riscv64/CodeGen.zig+2-2
......@@ -1754,8 +1754,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
17541754 .func => |func| {
17551755 const sym_index = try elf_file.getOrCreateMetadataForDecl(func.owner_decl);
17561756 const sym = elf_file.symbol(sym_index);
1757 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
1758 const got_addr = @as(u32, @intCast(sym.gotAddress(elf_file)));
1757 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
1758 const got_addr = @as(u32, @intCast(sym.zigGotAddress(elf_file)));
17591759 try self.genSetReg(Type.usize, .ra, .{ .memory = got_addr });
17601760 _ = try self.addInst(.{
17611761 .tag = .jalr,
src/arch/sparc64/CodeGen.zig+2-2
......@@ -1349,8 +1349,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
13491349 const got_addr = if (self.bin_file.cast(link.File.Elf)) |elf_file| blk: {
13501350 const sym_index = try elf_file.getOrCreateMetadataForDecl(func.owner_decl);
13511351 const sym = elf_file.symbol(sym_index);
1352 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
1353 break :blk @as(u32, @intCast(sym.gotAddress(elf_file)));
1352 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
1353 break :blk @as(u32, @intCast(sym.zigGotAddress(elf_file)));
13541354 } else unreachable;
13551355
13561356 try self.genSetReg(Type.usize, .o7, .{ .memory = got_addr });
src/arch/x86_64/CodeGen.zig+2-4
......@@ -9189,8 +9189,7 @@ fn genCall(self: *Self, info: union(enum) {
91899189 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
91909190 const sym_index = try elf_file.getOrCreateMetadataForDecl(owner_decl);
91919191 const sym = elf_file.symbol(sym_index);
9192 sym.flags.needs_got = true;
9193 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
9192 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
91949193 _ = try self.addInst(.{
91959194 .tag = .call,
91969195 .ops = .direct_got_reloc,
......@@ -11637,8 +11636,7 @@ fn genLazySymbolRef(
1163711636 const sym_index = elf_file.getOrCreateMetadataForLazySymbol(lazy_sym) catch |err|
1163811637 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1163911638 const sym = elf_file.symbol(sym_index);
11640 sym.flags.needs_got = true;
11641 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
11639 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
1164211640 const reloc = Mir.Reloc{
1164311641 .atom_index = try self.owner.getSymbolIndex(self),
1164411642 .sym_index = sym.esym_index,
src/codegen.zig+2-3
......@@ -889,9 +889,8 @@ fn genDeclRef(
889889 if (bin_file.cast(link.File.Elf)) |elf_file| {
890890 const sym_index = try elf_file.getOrCreateMetadataForDecl(decl_index);
891891 const sym = elf_file.symbol(sym_index);
892 sym.flags.needs_got = true;
893 _ = try sym.getOrCreateGotEntry(sym_index, elf_file);
894 return GenResult.mcv(.{ .memory = sym.gotAddress(elf_file) });
892 _ = try sym.getOrCreateZigGotEntry(sym_index, elf_file);
893 return GenResult.mcv(.{ .memory = sym.zigGotAddress(elf_file) });
895894 } else if (bin_file.cast(link.File.MachO)) |macho_file| {
896895 const atom_index = try macho_file.getOrCreateAtomForDecl(decl_index);
897896 const sym_index = macho_file.getAtom(atom_index).getSymbolIndex().?;
src/link/Elf.zig+95-81
......@@ -33,16 +33,16 @@ phdrs: std.ArrayListUnmanaged(elf.Elf64_Phdr) = .{},
3333
3434/// Tracked loadable segments during incremental linking.
3535/// The index into the program headers of a PT_LOAD program header with Read and Execute flags
36phdr_load_re_zig_index: ?u16 = null,
36phdr_zig_load_re_index: ?u16 = null,
3737/// The index into the program headers of the global offset table.
3838/// It needs PT_LOAD and Read flags.
39phdr_got_zig_index: ?u16 = null,
39phdr_zig_got_index: ?u16 = null,
4040/// The index into the program headers of a PT_LOAD program header with Read flag
41phdr_load_ro_zig_index: ?u16 = null,
41phdr_zig_load_ro_index: ?u16 = null,
4242/// The index into the program headers of a PT_LOAD program header with Write flag
43phdr_load_rw_zig_index: ?u16 = null,
43phdr_zig_load_rw_index: ?u16 = null,
4444/// The index into the program headers of a PT_LOAD program header with zerofill data.
45phdr_load_zerofill_zig_index: ?u16 = null,
45phdr_zig_load_zerofill_index: ?u16 = null,
4646
4747/// Special program headers
4848/// PT_PHDR
......@@ -99,13 +99,15 @@ plt_got: PltGotSection = .{},
9999copy_rel: CopyRelSection = .{},
100100/// .rela.plt section
101101rela_plt: std.ArrayListUnmanaged(elf.Elf64_Rela) = .{},
102/// .zig.got section
103zig_got: ZigGotSection = .{},
102104
103105/// Tracked section headers with incremental updates to Zig module
104text_zig_section_index: ?u16 = null,
105rodata_zig_section_index: ?u16 = null,
106data_zig_section_index: ?u16 = null,
107bss_zig_section_index: ?u16 = null,
108got_zig_section_index: ?u16 = null,
106zig_text_section_index: ?u16 = null,
107zig_rodata_section_index: ?u16 = null,
108zig_data_section_index: ?u16 = null,
109zig_bss_section_index: ?u16 = null,
110zig_got_section_index: ?u16 = null,
109111debug_info_section_index: ?u16 = null,
110112debug_abbrev_section_index: ?u16 = null,
111113debug_str_section_index: ?u16 = null,
......@@ -479,7 +481,7 @@ pub fn lowerAnonDecl(self: *Elf, decl_val: InternPool.Index, src_loc: Module.Src
479481 const tv = TypedValue{ .ty = ty, .val = val };
480482 const name = try std.fmt.allocPrint(gpa, "__anon_{d}", .{@intFromEnum(decl_val)});
481483 defer gpa.free(name);
482 const res = self.lowerConst(name, tv, self.rodata_zig_section_index.?, src_loc) catch |err| switch (err) {
484 const res = self.lowerConst(name, tv, self.zig_rodata_section_index.?, src_loc) catch |err| switch (err) {
483485 else => {
484486 // TODO improve error message
485487 const em = try Module.ErrorMsg.create(gpa, src_loc, "lowerAnonDecl failed with error: {s}", .{
......@@ -687,8 +689,8 @@ pub fn initMetadata(self: *Elf) !void {
687689 const ptr_bit_width = self.base.options.target.ptrBitWidth();
688690 const is_linux = self.base.options.target.os.tag == .linux;
689691
690 if (self.phdr_load_re_zig_index == null) {
691 self.phdr_load_re_zig_index = try self.allocateSegment(.{
692 if (self.phdr_zig_load_re_index == null) {
693 self.phdr_zig_load_re_index = try self.allocateSegment(.{
692694 .addr = if (ptr_bit_width >= 32) 0x8000000 else 0x8000,
693695 .memsz = self.base.options.program_code_size_hint,
694696 .filesz = self.base.options.program_code_size_hint,
......@@ -697,11 +699,11 @@ pub fn initMetadata(self: *Elf) !void {
697699 });
698700 }
699701
700 if (self.phdr_got_zig_index == null) {
702 if (self.phdr_zig_got_index == null) {
701703 // We really only need ptr alignment but since we are using PROGBITS, linux requires
702704 // page align.
703705 const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
704 self.phdr_got_zig_index = try self.allocateSegment(.{
706 self.phdr_zig_got_index = try self.allocateSegment(.{
705707 .addr = if (ptr_bit_width >= 32) 0x4000000 else 0x4000,
706708 .memsz = @as(u64, ptr_size) * self.base.options.symbol_count_hint,
707709 .filesz = @as(u64, ptr_size) * self.base.options.symbol_count_hint,
......@@ -710,9 +712,9 @@ pub fn initMetadata(self: *Elf) !void {
710712 });
711713 }
712714
713 if (self.phdr_load_ro_zig_index == null) {
715 if (self.phdr_zig_load_ro_index == null) {
714716 const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
715 self.phdr_load_ro_zig_index = try self.allocateSegment(.{
717 self.phdr_zig_load_ro_index = try self.allocateSegment(.{
716718 .addr = if (ptr_bit_width >= 32) 0xc000000 else 0xa000,
717719 .memsz = 1024,
718720 .filesz = 1024,
......@@ -721,9 +723,9 @@ pub fn initMetadata(self: *Elf) !void {
721723 });
722724 }
723725
724 if (self.phdr_load_rw_zig_index == null) {
726 if (self.phdr_zig_load_rw_index == null) {
725727 const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
726 self.phdr_load_rw_zig_index = try self.allocateSegment(.{
728 self.phdr_zig_load_rw_index = try self.allocateSegment(.{
727729 .addr = if (ptr_bit_width >= 32) 0x10000000 else 0xc000,
728730 .memsz = 1024,
729731 .filesz = 1024,
......@@ -732,64 +734,64 @@ pub fn initMetadata(self: *Elf) !void {
732734 });
733735 }
734736
735 if (self.phdr_load_zerofill_zig_index == null) {
737 if (self.phdr_zig_load_zerofill_index == null) {
736738 const alignment = if (is_linux) self.page_size else @as(u16, ptr_size);
737 self.phdr_load_zerofill_zig_index = try self.allocateSegment(.{
739 self.phdr_zig_load_zerofill_index = try self.allocateSegment(.{
738740 .addr = if (ptr_bit_width >= 32) 0x14000000 else 0xf000,
739741 .memsz = 0,
740742 .filesz = 0,
741743 .alignment = alignment,
742744 .flags = elf.PF_R | elf.PF_W,
743745 });
744 const phdr = &self.phdrs.items[self.phdr_load_zerofill_zig_index.?];
745 phdr.p_offset = self.phdrs.items[self.phdr_load_rw_zig_index.?].p_offset; // .bss overlaps .data
746 const phdr = &self.phdrs.items[self.phdr_zig_load_zerofill_index.?];
747 phdr.p_offset = self.phdrs.items[self.phdr_zig_load_rw_index.?].p_offset; // .bss overlaps .data
746748 phdr.p_memsz = 1024;
747749 }
748750
749 if (self.text_zig_section_index == null) {
750 self.text_zig_section_index = try self.allocateAllocSection(.{
751 .name = ".text.zig",
752 .phdr_index = self.phdr_load_re_zig_index.?,
751 if (self.zig_text_section_index == null) {
752 self.zig_text_section_index = try self.allocateAllocSection(.{
753 .name = ".zig.text",
754 .phdr_index = self.phdr_zig_load_re_index.?,
753755 .flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR,
754756 });
755 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.text_zig_section_index.?, .{});
757 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_text_section_index.?, .{});
756758 }
757759
758 if (self.got_zig_section_index == null) {
759 self.got_zig_section_index = try self.allocateAllocSection(.{
760 .name = ".got.zig",
761 .phdr_index = self.phdr_got_zig_index.?,
760 if (self.zig_got_section_index == null) {
761 self.zig_got_section_index = try self.allocateAllocSection(.{
762 .name = ".zig.got",
763 .phdr_index = self.phdr_zig_got_index.?,
762764 .alignment = ptr_size,
763765 });
764766 }
765767
766 if (self.rodata_zig_section_index == null) {
767 self.rodata_zig_section_index = try self.allocateAllocSection(.{
768 .name = ".rodata.zig",
769 .phdr_index = self.phdr_load_ro_zig_index.?,
768 if (self.zig_rodata_section_index == null) {
769 self.zig_rodata_section_index = try self.allocateAllocSection(.{
770 .name = ".zig.rodata",
771 .phdr_index = self.phdr_zig_load_ro_index.?,
770772 });
771 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.rodata_zig_section_index.?, .{});
773 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_rodata_section_index.?, .{});
772774 }
773775
774 if (self.data_zig_section_index == null) {
775 self.data_zig_section_index = try self.allocateAllocSection(.{
776 .name = ".data.zig",
777 .phdr_index = self.phdr_load_rw_zig_index.?,
776 if (self.zig_data_section_index == null) {
777 self.zig_data_section_index = try self.allocateAllocSection(.{
778 .name = ".zig.data",
779 .phdr_index = self.phdr_zig_load_rw_index.?,
778780 .alignment = ptr_size,
779781 .flags = elf.SHF_ALLOC | elf.SHF_WRITE,
780782 });
781 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.data_zig_section_index.?, .{});
783 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_data_section_index.?, .{});
782784 }
783785
784 if (self.bss_zig_section_index == null) {
785 self.bss_zig_section_index = try self.allocateAllocSection(.{
786 if (self.zig_bss_section_index == null) {
787 self.zig_bss_section_index = try self.allocateAllocSection(.{
786788 .name = ".bss.zig",
787 .phdr_index = self.phdr_load_zerofill_zig_index.?,
789 .phdr_index = self.phdr_zig_load_zerofill_index.?,
788790 .alignment = ptr_size,
789791 .flags = elf.SHF_ALLOC | elf.SHF_WRITE,
790792 .type = elf.SHT_NOBITS,
791793 });
792 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.bss_zig_section_index.?, .{});
794 try self.last_atom_and_free_list_table.putNoClobber(gpa, self.zig_bss_section_index.?, .{});
793795 }
794796
795797 if (self.dwarf) |*dw| {
......@@ -875,7 +877,7 @@ pub fn growAllocSection(self: *Elf, shdr_index: u16, needed_size: u64) !void {
875877 }
876878
877879 const mem_capacity = self.allocatedVirtualSize(phdr.p_vaddr);
878 if (needed_size <= mem_capacity) {
880 if (needed_size > mem_capacity) {
879881 var err = try self.addErrorWithNotes(2);
880882 try err.addMsg(self, "fatal linker error: cannot expand load segment phdr({d}) in virtual memory", .{
881883 phdr_index,
......@@ -1544,8 +1546,8 @@ pub fn flushModule(self: *Elf, comp: *Compilation, prog_node: *std.Progress.Node
15441546 if (self.zig_module_index) |index| {
15451547 // .bss.zig always overlaps .data.zig in file offset, but is zero-sized in file so it doesn't
15461548 // get mapped by the loader
1547 if (self.data_zig_section_index) |data_shndx| blk: {
1548 const bss_shndx = self.bss_zig_section_index orelse break :blk;
1549 if (self.zig_data_section_index) |data_shndx| blk: {
1550 const bss_shndx = self.zig_bss_section_index orelse break :blk;
15491551 const data_phndx = self.phdr_to_shdr_table.get(data_shndx).?;
15501552 const bss_phndx = self.phdr_to_shdr_table.get(bss_shndx).?;
15511553 self.shdrs.items[bss_shndx].sh_offset = self.shdrs.items[data_shndx].sh_offset;
......@@ -1580,7 +1582,7 @@ pub fn flushModule(self: *Elf, comp: *Compilation, prog_node: *std.Progress.Node
15801582 if (self.debug_info_header_dirty) {
15811583 // Currently only one compilation unit is supported, so the address range is simply
15821584 // identical to the main program header virtual address and memory size.
1583 const text_phdr = &self.phdrs.items[self.phdr_load_re_zig_index.?];
1585 const text_phdr = &self.phdrs.items[self.phdr_zig_load_re_index.?];
15841586 const low_pc = text_phdr.p_vaddr;
15851587 const high_pc = text_phdr.p_vaddr + text_phdr.p_memsz;
15861588 try dw.writeDbgInfoHeader(self.base.options.module.?, low_pc, high_pc);
......@@ -1590,7 +1592,7 @@ pub fn flushModule(self: *Elf, comp: *Compilation, prog_node: *std.Progress.Node
15901592 if (self.debug_aranges_section_dirty) {
15911593 // Currently only one compilation unit is supported, so the address range is simply
15921594 // identical to the main program header virtual address and memory size.
1593 const text_phdr = &self.phdrs.items[self.phdr_load_re_zig_index.?];
1595 const text_phdr = &self.phdrs.items[self.phdr_zig_load_re_index.?];
15941596 try dw.writeDbgAranges(text_phdr.p_vaddr, text_phdr.p_memsz);
15951597 self.debug_aranges_section_dirty = false;
15961598 }
......@@ -2999,24 +3001,24 @@ fn getDeclShdrIndex(self: *Elf, decl_index: Module.Decl.Index, code: []const u8)
29993001 const decl = mod.declPtr(decl_index);
30003002 const shdr_index = switch (decl.ty.zigTypeTag(mod)) {
30013003 // TODO: what if this is a function pointer?
3002 .Fn => self.text_zig_section_index.?,
3004 .Fn => self.zig_text_section_index.?,
30033005 else => blk: {
30043006 if (decl.getOwnedVariable(mod)) |variable| {
3005 if (variable.is_const) break :blk self.rodata_zig_section_index.?;
3007 if (variable.is_const) break :blk self.zig_rodata_section_index.?;
30063008 if (variable.init.toValue().isUndefDeep(mod)) {
30073009 const mode = self.base.options.optimize_mode;
3008 if (mode == .Debug or mode == .ReleaseSafe) break :blk self.data_zig_section_index.?;
3009 break :blk self.bss_zig_section_index.?;
3010 if (mode == .Debug or mode == .ReleaseSafe) break :blk self.zig_data_section_index.?;
3011 break :blk self.zig_bss_section_index.?;
30103012 }
30113013 // TODO I blatantly copied the logic from the Wasm linker, but is there a less
30123014 // intrusive check for all zeroes than this?
30133015 const is_all_zeroes = for (code) |byte| {
30143016 if (byte != 0) break false;
30153017 } else true;
3016 if (is_all_zeroes) break :blk self.bss_zig_section_index.?;
3017 break :blk self.data_zig_section_index.?;
3018 if (is_all_zeroes) break :blk self.zig_bss_section_index.?;
3019 break :blk self.zig_data_section_index.?;
30183020 }
3019 break :blk self.rodata_zig_section_index.?;
3021 break :blk self.zig_rodata_section_index.?;
30203022 },
30213023 };
30223024 return shdr_index;
......@@ -3070,8 +3072,9 @@ fn updateDeclCode(
30703072 esym.st_value = atom_ptr.value;
30713073
30723074 log.debug(" (writing new offset table entry)", .{});
3073 // const extra = sym.extra(self).?;
3074 // try self.got.writeEntry(self, extra.got);
3075 assert(sym.flags.has_zig_got);
3076 const extra = sym.extra(self).?;
3077 try self.zig_got.writeOne(self, extra.zig_got);
30753078 }
30763079 } else if (code.len < old_size) {
30773080 atom_ptr.shrink(self);
......@@ -3083,10 +3086,8 @@ fn updateDeclCode(
30833086 sym.value = atom_ptr.value;
30843087 esym.st_value = atom_ptr.value;
30853088
3086 sym.flags.needs_got = true;
3087 const gop = try sym.getOrCreateGotEntry(sym_index, self);
3088 _ = gop;
3089 // try self.got.writeEntry(self, gop.index);
3089 const gop = try sym.getOrCreateZigGotEntry(sym_index, self);
3090 try self.zig_got.writeOne(self, gop.index);
30903091 }
30913092
30923093 if (self.base.child_pid) |pid| {
......@@ -3296,8 +3297,8 @@ fn updateLazySymbol(self: *Elf, sym: link.File.LazySymbol, symbol_index: Symbol.
32963297 };
32973298
32983299 const output_section_index = switch (sym.kind) {
3299 .code => self.text_zig_section_index.?,
3300 .const_data => self.rodata_zig_section_index.?,
3300 .code => self.zig_text_section_index.?,
3301 .const_data => self.zig_rodata_section_index.?,
33013302 };
33023303 const local_sym = self.symbol(symbol_index);
33033304 const phdr_index = self.phdr_to_shdr_table.get(output_section_index).?;
......@@ -3320,10 +3321,8 @@ fn updateLazySymbol(self: *Elf, sym: link.File.LazySymbol, symbol_index: Symbol.
33203321 local_sym.value = atom_ptr.value;
33213322 local_esym.st_value = atom_ptr.value;
33223323
3323 local_sym.flags.needs_got = true;
3324 const gop = try local_sym.getOrCreateGotEntry(symbol_index, self);
3325 _ = gop;
3326 // try self.got.writeEntry(self, gop.index);
3324 const gop = try local_sym.getOrCreateZigGotEntry(symbol_index, self);
3325 try self.zig_got.writeOne(self, gop.index);
33273326
33283327 const section_offset = atom_ptr.value - self.phdrs.items[phdr_index].p_vaddr;
33293328 const file_offset = self.shdrs.items[output_section_index].sh_offset + section_offset;
......@@ -3343,7 +3342,7 @@ pub fn lowerUnnamedConst(self: *Elf, typed_value: TypedValue, decl_index: Module
33433342 const index = unnamed_consts.items.len;
33443343 const name = try std.fmt.allocPrint(gpa, "__unnamed_{s}_{d}", .{ decl_name, index });
33453344 defer gpa.free(name);
3346 const sym_index = switch (try self.lowerConst(name, typed_value, self.rodata_zig_section_index.?, decl.srcLoc(mod))) {
3345 const sym_index = switch (try self.lowerConst(name, typed_value, self.zig_rodata_section_index.?, decl.srcLoc(mod))) {
33473346 .ok => |sym_index| sym_index,
33483347 .fail => |em| {
33493348 decl.analysis = .codegen_failure;
......@@ -4183,11 +4182,11 @@ fn sortSections(self: *Elf) !void {
41834182 &self.copy_rel_section_index,
41844183 &self.versym_section_index,
41854184 &self.verneed_section_index,
4186 &self.text_zig_section_index,
4187 &self.got_zig_section_index,
4188 &self.rodata_zig_section_index,
4189 &self.data_zig_section_index,
4190 &self.bss_zig_section_index,
4185 &self.zig_text_section_index,
4186 &self.zig_got_section_index,
4187 &self.zig_rodata_section_index,
4188 &self.zig_data_section_index,
4189 &self.zig_bss_section_index,
41914190 &self.debug_str_section_index,
41924191 &self.debug_info_section_index,
41934192 &self.debug_abbrev_section_index,
......@@ -4340,6 +4339,9 @@ fn updateSectionSizes(self: *Elf) !void {
43404339 if (self.strtab_section_index) |index| {
43414340 // TODO I don't really this here but we need it to add symbol names from GOT and other synthetic
43424341 // sections into .strtab for easier debugging.
4342 if (self.zig_got_section_index) |_| {
4343 try self.zig_got.updateStrtab(self);
4344 }
43434345 if (self.got_section_index) |_| {
43444346 try self.got.updateStrtab(self);
43454347 }
......@@ -4719,6 +4721,11 @@ fn updateSymtabSize(self: *Elf) !void {
47194721 sizes.nglobals += shared_object.output_symtab_size.nglobals;
47204722 }
47214723
4724 if (self.zig_got_section_index) |_| {
4725 self.zig_got.updateSymtabSize(self);
4726 sizes.nlocals += self.zig_got.output_symtab_size.nlocals;
4727 }
4728
47224729 if (self.got_section_index) |_| {
47234730 self.got.updateSymtabSize(self);
47244731 sizes.nlocals += self.got.output_symtab_size.nlocals;
......@@ -4930,6 +4937,11 @@ fn writeSymtab(self: *Elf) !void {
49304937 ctx.iglobal += shared_object.output_symtab_size.nglobals;
49314938 }
49324939
4940 if (self.zig_got_section_index) |_| {
4941 try self.zig_got.writeSymtab(self, ctx);
4942 ctx.ilocal += self.zig_got.output_symtab_size.nlocals;
4943 }
4944
49334945 if (self.got_section_index) |_| {
49344946 try self.got.writeSymtab(self, ctx);
49354947 ctx.ilocal += self.got.output_symtab_size.nlocals;
......@@ -5289,11 +5301,11 @@ pub fn isDynLib(self: Elf) bool {
52895301
52905302pub fn isZigSection(self: Elf, shndx: u16) bool {
52915303 inline for (&[_]?u16{
5292 self.text_zig_section_index,
5293 self.rodata_zig_section_index,
5294 self.data_zig_section_index,
5295 self.bss_zig_section_index,
5296 self.got_zig_section_index,
5304 self.zig_text_section_index,
5305 self.zig_rodata_section_index,
5306 self.zig_data_section_index,
5307 self.zig_bss_section_index,
5308 self.zig_got_section_index,
52975309 }) |maybe_index| {
52985310 if (maybe_index) |index| {
52995311 if (index == shndx) return true;
......@@ -5851,6 +5863,7 @@ fn fmtDumpState(
58515863 try writer.print("{}\n", .{linker_defined.fmtSymtab(self)});
58525864 }
58535865 try writer.print("{}\n", .{self.got.fmt(self)});
5866 try writer.print("{}\n", .{self.zig_got.fmt(self)});
58545867 try writer.writeAll("Output shdrs\n");
58555868 for (self.shdrs.items, 0..) |shdr, shndx| {
58565869 try writer.print("shdr({d}) : phdr({?d}) : {}\n", .{
......@@ -6030,4 +6043,5 @@ const Type = @import("../type.zig").Type;
60306043const TypedValue = @import("../TypedValue.zig");
60316044const Value = @import("../value.zig").Value;
60326045const VerneedSection = synthetic_sections.VerneedSection;
6046const ZigGotSection = synthetic_sections.ZigGotSection;
60336047const ZigModule = @import("Elf/ZigModule.zig");
src/link/Elf/Atom.zig+16-2
......@@ -367,8 +367,16 @@ pub fn scanRelocs(self: Atom, elf_file: *Elf, code: ?[]const u8, undefs: anytype
367367 try self.scanReloc(symbol, rel, dynAbsRelocAction(symbol, elf_file), elf_file);
368368 },
369369
370 // TODO I have temporarily repurposed those for handling .zig.got indirection
371 // but we should probably claim unused custom values for incremental linking
372 // that get rewritten to standard relocs when lowering to a relocatable object
373 // file.
370374 elf.R_X86_64_GOT32,
371375 elf.R_X86_64_GOT64,
376 => {
377 assert(symbol.flags.has_zig_got);
378 },
379
372380 elf.R_X86_64_GOTPC32,
373381 elf.R_X86_64_GOTPC64,
374382 elf.R_X86_64_GOTPCREL,
......@@ -736,6 +744,8 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) !void {
736744 null;
737745 break :blk if (shndx) |index| @as(i64, @intCast(elf_file.shdrs.items[index].sh_addr)) else 0;
738746 };
747 // Address of the .zig.got table entry if any.
748 const ZIG_GOT = @as(i64, @intCast(target.zigGotAddress(elf_file)));
739749 // Relative offset to the start of the global offset table.
740750 const G = @as(i64, @intCast(target.gotAddress(elf_file))) - GOT;
741751 // // Address of the thread pointer.
......@@ -796,8 +806,12 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) !void {
796806 elf.R_X86_64_32 => try cwriter.writeIntLittle(u32, @as(u32, @truncate(@as(u64, @intCast(S + A))))),
797807 elf.R_X86_64_32S => try cwriter.writeIntLittle(i32, @as(i32, @truncate(S + A))),
798808
799 elf.R_X86_64_GOT32 => try cwriter.writeIntLittle(u32, @as(u32, @intCast(G + GOT + A))),
800 elf.R_X86_64_GOT64 => try cwriter.writeIntLittle(u64, @as(u64, @intCast(G + GOT + A))),
809 // TODO I have temporarily repurposed those for handling .zig.got indirection
810 // but we should probably claim unused custom values for incremental linking
811 // that get rewritten to standard relocs when lowering to a relocatable object
812 // file.
813 elf.R_X86_64_GOT32 => try cwriter.writeIntLittle(u32, @as(u32, @intCast(ZIG_GOT + A))),
814 elf.R_X86_64_GOT64 => try cwriter.writeIntLittle(u64, @as(u64, @intCast(ZIG_GOT + A))),
801815
802816 elf.R_X86_64_TPOFF32 => try cwriter.writeIntLittle(i32, @as(i32, @truncate(S + A - TP))),
803817 elf.R_X86_64_TPOFF64 => try cwriter.writeIntLittle(i64, S + A - TP),
src/link/Elf/Symbol.zig+22-13
......@@ -137,19 +137,6 @@ pub fn copyRelAddress(symbol: Symbol, elf_file: *Elf) u64 {
137137 return shdr.sh_addr + symbol.value;
138138}
139139
140const GetOrCreateGotEntryResult = struct {
141 found_existing: bool,
142 index: GotSection.Index,
143};
144
145pub fn getOrCreateGotEntry(symbol: *Symbol, symbol_index: Index, elf_file: *Elf) !GetOrCreateGotEntryResult {
146 assert(symbol.flags.needs_got);
147 if (symbol.flags.has_got) return .{ .found_existing = true, .index = symbol.extra(elf_file).?.got };
148 const index = try elf_file.got.addGotSymbol(symbol_index, elf_file);
149 symbol.flags.has_got = true;
150 return .{ .found_existing = false, .index = index };
151}
152
153140pub fn tlsGdAddress(symbol: Symbol, elf_file: *Elf) u64 {
154141 if (!symbol.flags.has_tlsgd) return 0;
155142 const extras = symbol.extra(elf_file).?;
......@@ -171,6 +158,23 @@ pub fn tlsDescAddress(symbol: Symbol, elf_file: *Elf) u64 {
171158 return entry.address(elf_file);
172159}
173160
161const GetOrCreateZigGotEntryResult = struct {
162 found_existing: bool,
163 index: ZigGotSection.Index,
164};
165
166pub fn getOrCreateZigGotEntry(symbol: *Symbol, symbol_index: Index, elf_file: *Elf) !GetOrCreateZigGotEntryResult {
167 if (symbol.flags.has_zig_got) return .{ .found_existing = true, .index = symbol.extra(elf_file).?.zig_got };
168 const index = try elf_file.zig_got.addSymbol(symbol_index, elf_file);
169 return .{ .found_existing = false, .index = index };
170}
171
172pub fn zigGotAddress(symbol: Symbol, elf_file: *Elf) u64 {
173 if (!symbol.flags.has_zig_got) return 0;
174 const extras = symbol.extra(elf_file).?;
175 return elf_file.zig_got.entryAddress(extras.zig_got, elf_file);
176}
177
174178pub fn dsoAlignment(symbol: Symbol, elf_file: *Elf) !u64 {
175179 const file_ptr = symbol.file(elf_file) orelse return 0;
176180 assert(file_ptr == .shared_object);
......@@ -367,6 +371,9 @@ pub const Flags = packed struct {
367371 /// Whether the symbol contains TLSDESC indirection.
368372 needs_tlsdesc: bool = false,
369373 has_tlsdesc: bool = false,
374
375 /// Whether the symbol contains .zig.got indirection.
376 has_zig_got: bool = false,
370377};
371378
372379pub const Extra = struct {
......@@ -378,6 +385,7 @@ pub const Extra = struct {
378385 tlsgd: u32 = 0,
379386 gottp: u32 = 0,
380387 tlsdesc: u32 = 0,
388 zig_got: u32 = 0,
381389};
382390
383391pub const Index = u32;
......@@ -397,4 +405,5 @@ const Object = @import("Object.zig");
397405const PltSection = synthetic_sections.PltSection;
398406const SharedObject = @import("SharedObject.zig");
399407const Symbol = @This();
408const ZigGotSection = synthetic_sections.ZigGotSection;
400409const ZigModule = @import("ZigModule.zig");
src/link/Elf/synthetic_sections.zig+196-11
......@@ -220,6 +220,191 @@ pub const DynamicSection = struct {
220220 }
221221};
222222
223pub const ZigGotSection = struct {
224 entries: std.ArrayListUnmanaged(Symbol.Index) = .{},
225 output_symtab_size: Elf.SymtabSize = .{},
226 flags: Flags = .{},
227
228 const Flags = packed struct {
229 needs_rela: bool = false, // TODO in prep for PIC/PIE and base relocations
230 dirty: bool = false,
231 };
232
233 pub const Index = u32;
234
235 pub fn deinit(zig_got: *ZigGotSection, allocator: Allocator) void {
236 zig_got.entries.deinit(allocator);
237 }
238
239 fn allocateEntry(zig_got: *ZigGotSection, allocator: Allocator) !Index {
240 try zig_got.entries.ensureUnusedCapacity(allocator, 1);
241 // TODO add free list
242 const index = @as(Index, @intCast(zig_got.entries.items.len));
243 _ = zig_got.entries.addOneAssumeCapacity();
244 zig_got.flags.dirty = true;
245 return index;
246 }
247
248 pub fn addSymbol(zig_got: *ZigGotSection, sym_index: Symbol.Index, elf_file: *Elf) !Index {
249 const index = try zig_got.allocateEntry(elf_file.base.allocator);
250 const entry = &zig_got.entries.items[index];
251 entry.* = sym_index;
252 const symbol = elf_file.symbol(sym_index);
253 symbol.flags.has_zig_got = true;
254 if (symbol.extra(elf_file)) |extra| {
255 var new_extra = extra;
256 new_extra.zig_got = index;
257 symbol.setExtra(new_extra, elf_file);
258 } else try symbol.addExtra(.{ .zig_got = index }, elf_file);
259 return index;
260 }
261
262 pub fn entryOffset(zig_got: ZigGotSection, index: Index, elf_file: *Elf) u64 {
263 _ = zig_got;
264 const entry_size = elf_file.archPtrWidthBytes();
265 const shdr = elf_file.shdrs.items[elf_file.zig_got_section_index.?];
266 return shdr.sh_offset + @as(u64, entry_size) * index;
267 }
268
269 pub fn entryAddress(zig_got: ZigGotSection, index: Index, elf_file: *Elf) u64 {
270 _ = zig_got;
271 const entry_size = elf_file.archPtrWidthBytes();
272 const shdr = elf_file.shdrs.items[elf_file.zig_got_section_index.?];
273 return shdr.sh_addr + @as(u64, entry_size) * index;
274 }
275
276 pub fn size(zig_got: ZigGotSection, elf_file: *Elf) usize {
277 return elf_file.archPtrWidthBytes() * zig_got.entries.items.len;
278 }
279
280 pub fn writeOne(zig_got: *ZigGotSection, elf_file: *Elf, index: Index) !void {
281 if (zig_got.flags.dirty) {
282 const needed_size = zig_got.size(elf_file);
283 try elf_file.growAllocSection(elf_file.zig_got_section_index.?, needed_size);
284 zig_got.flags.dirty = false;
285 }
286 const entry_size: u16 = elf_file.archPtrWidthBytes();
287 const endian = elf_file.base.options.target.cpu.arch.endian();
288 const off = zig_got.entryOffset(index, elf_file);
289 const vaddr = zig_got.entryAddress(index, elf_file);
290 const entry = zig_got.entries.items[index];
291 const value = elf_file.symbol(entry).value;
292 switch (entry_size) {
293 2 => {
294 var buf: [2]u8 = undefined;
295 std.mem.writeInt(u16, &buf, @as(u16, @intCast(value)), endian);
296 try elf_file.base.file.?.pwriteAll(&buf, off);
297 },
298 4 => {
299 var buf: [4]u8 = undefined;
300 std.mem.writeInt(u32, &buf, @as(u32, @intCast(value)), endian);
301 try elf_file.base.file.?.pwriteAll(&buf, off);
302 },
303 8 => {
304 var buf: [8]u8 = undefined;
305 std.mem.writeInt(u64, &buf, value, endian);
306 try elf_file.base.file.?.pwriteAll(&buf, off);
307
308 if (elf_file.base.child_pid) |pid| {
309 switch (builtin.os.tag) {
310 .linux => {
311 var local_vec: [1]std.os.iovec_const = .{.{
312 .iov_base = &buf,
313 .iov_len = buf.len,
314 }};
315 var remote_vec: [1]std.os.iovec_const = .{.{
316 .iov_base = @as([*]u8, @ptrFromInt(@as(usize, @intCast(vaddr)))),
317 .iov_len = buf.len,
318 }};
319 const rc = std.os.linux.process_vm_writev(pid, &local_vec, &remote_vec, 0);
320 switch (std.os.errno(rc)) {
321 .SUCCESS => assert(rc == buf.len),
322 else => |errno| log.warn("process_vm_writev failure: {s}", .{@tagName(errno)}),
323 }
324 },
325 else => return error.HotSwapUnavailableOnHostOperatingSystem,
326 }
327 }
328 },
329 else => unreachable,
330 }
331 }
332
333 pub fn writeAll(zig_got: ZigGotSection, elf_file: *Elf, writer: anytype) !void {
334 for (zig_got.entries.items) |entry| {
335 const symbol = elf_file.symbol(entry);
336 const value = symbol.address(.{ .plt = false }, elf_file);
337 try writeInt(value, elf_file, writer);
338 }
339 }
340
341 pub fn updateSymtabSize(zig_got: *ZigGotSection, elf_file: *Elf) void {
342 _ = elf_file;
343 zig_got.output_symtab_size.nlocals = @as(u32, @intCast(zig_got.entries.items.len));
344 }
345
346 pub fn updateStrtab(zig_got: ZigGotSection, elf_file: *Elf) !void {
347 const gpa = elf_file.base.allocator;
348 for (zig_got.entries.items) |entry| {
349 const symbol_name = elf_file.symbol(entry).name(elf_file);
350 const name = try std.fmt.allocPrint(gpa, "{s}$ziggot", .{symbol_name});
351 defer gpa.free(name);
352 _ = try elf_file.strtab.insert(gpa, name);
353 }
354 }
355
356 pub fn writeSymtab(zig_got: ZigGotSection, elf_file: *Elf, ctx: anytype) !void {
357 const gpa = elf_file.base.allocator;
358 for (zig_got.entries.items, ctx.ilocal.., 0..) |entry, ilocal, index| {
359 const symbol = elf_file.symbol(entry);
360 const symbol_name = symbol.name(elf_file);
361 const name = try std.fmt.allocPrint(gpa, "{s}$ziggot", .{symbol_name});
362 defer gpa.free(name);
363 const st_name = try elf_file.strtab.insert(gpa, name);
364 const st_value = zig_got.entryAddress(@intCast(index), elf_file);
365 const st_size = elf_file.archPtrWidthBytes();
366 ctx.symtab[ilocal] = .{
367 .st_name = st_name,
368 .st_info = elf.STT_OBJECT,
369 .st_other = 0,
370 .st_shndx = elf_file.zig_got_section_index.?,
371 .st_value = st_value,
372 .st_size = st_size,
373 };
374 }
375 }
376
377 const FormatCtx = struct {
378 zig_got: ZigGotSection,
379 elf_file: *Elf,
380 };
381
382 pub fn fmt(zig_got: ZigGotSection, elf_file: *Elf) std.fmt.Formatter(format2) {
383 return .{ .data = .{ .zig_got = zig_got, .elf_file = elf_file } };
384 }
385
386 pub fn format2(
387 ctx: FormatCtx,
388 comptime unused_fmt_string: []const u8,
389 options: std.fmt.FormatOptions,
390 writer: anytype,
391 ) !void {
392 _ = options;
393 _ = unused_fmt_string;
394 try writer.writeAll(".zig.got\n");
395 for (ctx.zig_got.entries.items, 0..) |entry, index| {
396 const symbol = ctx.elf_file.symbol(entry);
397 try writer.print(" {d}@0x{x} => {d}@0x{x} ({s})\n", .{
398 index,
399 ctx.zig_got.entryAddress(@intCast(index), ctx.elf_file),
400 entry,
401 symbol.address(.{}, ctx.elf_file),
402 symbol.name(ctx.elf_file),
403 });
404 }
405 }
406};
407
223408pub const GotSection = struct {
224409 entries: std.ArrayListUnmanaged(Entry) = .{},
225410 output_symtab_size: Elf.SymtabSize = .{},
......@@ -420,17 +605,6 @@ pub const GotSection = struct {
420605 }
421606 }
422607
423 fn writeInt(value: anytype, elf_file: *Elf, writer: anytype) !void {
424 const entry_size = elf_file.archPtrWidthBytes();
425 const endian = elf_file.base.options.target.cpu.arch.endian();
426 switch (entry_size) {
427 2 => try writer.writeInt(u16, @intCast(value), endian),
428 4 => try writer.writeInt(u32, @intCast(value), endian),
429 8 => try writer.writeInt(u64, @intCast(value), endian),
430 else => unreachable,
431 }
432 }
433
434608 pub fn addRela(got: GotSection, elf_file: *Elf) !void {
435609 const is_dyn_lib = elf_file.isDynLib();
436610 try elf_file.rela_dyn.ensureUnusedCapacity(elf_file.base.allocator, got.numRela(elf_file));
......@@ -1327,6 +1501,17 @@ pub const VerneedSection = struct {
13271501 }
13281502};
13291503
1504fn writeInt(value: anytype, elf_file: *Elf, writer: anytype) !void {
1505 const entry_size = elf_file.archPtrWidthBytes();
1506 const endian = elf_file.base.options.target.cpu.arch.endian();
1507 switch (entry_size) {
1508 2 => try writer.writeInt(u16, @intCast(value), endian),
1509 4 => try writer.writeInt(u32, @intCast(value), endian),
1510 8 => try writer.writeInt(u64, @intCast(value), endian),
1511 else => unreachable,
1512 }
1513}
1514
13301515const assert = std.debug.assert;
13311516const builtin = @import("builtin");
13321517const elf = std.elf;