authorgravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2023-04-13 22:54:55+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-04-13 22:54:55+02:00
log5e19250a1251e7857b5679949085fa1fb3f9bdcd
tree0aae5737ccb62456fcb4b099a07ff015a82c1989
parent25e3851fe0f7fe254b48c2242ab8d4ef89165fd5
parenta34752c941c81e600c56670abb612fc86d0a2b73
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #15185 from ziglang/macho-tls

macho: add TLS support

18 files changed, 878 insertions(+), 530 deletions(-)

ci/x86_64-macos-debug.sh-1
......@@ -51,7 +51,6 @@ stage3/bin/zig build test docs \
5151 --zig-lib-dir "$(pwd)/../lib" \
5252 -Denable-macos-sdk \
5353 -Dstatic-llvm \
54 -Dskip-non-native \
5554 --search-prefix "$PREFIX"
5655
5756# Produce the experimental std lib documentation.
ci/x86_64-macos-release.sh-1
......@@ -51,7 +51,6 @@ stage3/bin/zig build test docs \
5151 --zig-lib-dir "$(pwd)/../lib" \
5252 -Denable-macos-sdk \
5353 -Dstatic-llvm \
54 -Dskip-non-native \
5554 --search-prefix "$PREFIX"
5655
5756# Produce the experimental std lib documentation.
src/arch/aarch64/CodeGen.zig+1
......@@ -6171,6 +6171,7 @@ fn genTypedValue(self: *Self, arg_tv: TypedValue) InnerError!MCValue {
61716171 .linker_load => |ll| .{ .linker_load = ll },
61726172 .immediate => |imm| .{ .immediate = imm },
61736173 .memory => |addr| .{ .memory = addr },
6174 .tlv_reloc => unreachable, // TODO
61746175 },
61756176 .fail => |msg| {
61766177 self.err_msg = msg;
src/arch/aarch64/Emit.zig+10-19
......@@ -673,7 +673,7 @@ fn mirCallExtern(emit: *Emit, inst: Mir.Inst.Index) !void {
673673 const atom_index = macho_file.getAtomIndexForSymbol(.{ .sym_index = relocation.atom_index, .file = null }).?;
674674 const target = macho_file.getGlobalByIndex(relocation.sym_index);
675675 try link.File.MachO.Atom.addRelocation(macho_file, atom_index, .{
676 .type = @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_BRANCH26),
676 .type = .branch,
677677 .target = target,
678678 .offset = offset,
679679 .addend = 0,
......@@ -883,41 +883,32 @@ fn mirLoadMemoryPie(emit: *Emit, inst: Mir.Inst.Index) !void {
883883 }
884884
885885 if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
886 const Atom = link.File.MachO.Atom;
887 const Relocation = Atom.Relocation;
886888 const atom_index = macho_file.getAtomIndexForSymbol(.{ .sym_index = data.atom_index, .file = null }).?;
887 // TODO this causes segfault in stage1
888 // try atom.addRelocations(macho_file, 2, .{
889 try link.File.MachO.Atom.addRelocation(macho_file, atom_index, .{
889 try Atom.addRelocations(macho_file, atom_index, &[_]Relocation{ .{
890890 .target = .{ .sym_index = data.sym_index, .file = null },
891891 .offset = offset,
892892 .addend = 0,
893893 .pcrel = true,
894894 .length = 2,
895895 .type = switch (tag) {
896 .load_memory_got,
897 .load_memory_ptr_got,
898 => @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGE21),
899 .load_memory_direct,
900 .load_memory_ptr_direct,
901 => @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_PAGE21),
896 .load_memory_got, .load_memory_ptr_got => Relocation.Type.got_page,
897 .load_memory_direct, .load_memory_ptr_direct => Relocation.Type.page,
902898 else => unreachable,
903899 },
904 });
905 try link.File.MachO.Atom.addRelocation(macho_file, atom_index, .{
900 }, .{
906901 .target = .{ .sym_index = data.sym_index, .file = null },
907902 .offset = offset + 4,
908903 .addend = 0,
909904 .pcrel = false,
910905 .length = 2,
911906 .type = switch (tag) {
912 .load_memory_got,
913 .load_memory_ptr_got,
914 => @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGEOFF12),
915 .load_memory_direct,
916 .load_memory_ptr_direct,
917 => @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_PAGEOFF12),
907 .load_memory_got, .load_memory_ptr_got => Relocation.Type.got_pageoff,
908 .load_memory_direct, .load_memory_ptr_direct => Relocation.Type.pageoff,
918909 else => unreachable,
919910 },
920 });
911 } });
921912 } else if (emit.bin_file.cast(link.File.Coff)) |coff_file| {
922913 const atom_index = coff_file.getAtomIndexForSymbol(.{ .sym_index = data.atom_index, .file = null }).?;
923914 const target = switch (tag) {
src/arch/arm/CodeGen.zig+1-1
......@@ -6114,7 +6114,7 @@ fn genTypedValue(self: *Self, arg_tv: TypedValue) InnerError!MCValue {
61146114 .mcv => |mcv| switch (mcv) {
61156115 .none => .none,
61166116 .undef => .undef,
6117 .linker_load => unreachable, // TODO
6117 .tlv_reloc, .linker_load => unreachable, // TODO
61186118 .immediate => |imm| .{ .immediate = @truncate(u32, imm) },
61196119 .memory => |addr| .{ .memory = addr },
61206120 },
src/arch/riscv64/CodeGen.zig+1-1
......@@ -2572,7 +2572,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
25722572 .mcv => |mcv| switch (mcv) {
25732573 .none => .none,
25742574 .undef => .undef,
2575 .linker_load => unreachable, // TODO
2575 .tlv_reloc, .linker_load => unreachable, // TODO
25762576 .immediate => |imm| .{ .immediate = imm },
25772577 .memory => |addr| .{ .memory = addr },
25782578 },
src/arch/sparc64/CodeGen.zig+1-1
......@@ -3931,7 +3931,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
39313931 .mcv => |mcv| switch (mcv) {
39323932 .none => .none,
39333933 .undef => .undef,
3934 .linker_load => unreachable, // TODO
3934 .tlv_reloc, .linker_load => unreachable, // TODO
39353935 .immediate => |imm| .{ .immediate = imm },
39363936 .memory => |addr| .{ .memory = addr },
39373937 },
src/arch/x86_64/CodeGen.zig+406-94
......@@ -132,6 +132,10 @@ pub const MCValue = union(enum) {
132132 memory: u64,
133133 /// The value is in memory but requires a linker relocation fixup.
134134 linker_load: codegen.LinkerLoad,
135 /// Pointer to a threadlocal variable.
136 /// The address resolution will be deferred until the linker allocates everything in virtual memory.
137 /// Payload is a symbol index.
138 tlv_reloc: u32,
135139 /// The value is one of the stack variables.
136140 /// If the type is a pointer, it means the pointer address is in the stack at this offset.
137141 stack_offset: i32,
......@@ -146,6 +150,7 @@ pub const MCValue = union(enum) {
146150 .stack_offset,
147151 .ptr_stack_offset,
148152 .linker_load,
153 .tlv_reloc,
149154 => true,
150155 else => false,
151156 };
......@@ -731,6 +736,40 @@ fn asmMemoryRegisterImmediate(
731736 });
732737}
733738
739fn asmMovLinker(self: *Self, reg: Register, atom_index: u32, linker_load: codegen.LinkerLoad) !void {
740 const ops: Mir.Inst.Ops = switch (linker_load.type) {
741 .got => .got_reloc,
742 .direct => .direct_reloc,
743 .import => .import_reloc,
744 };
745 _ = try self.addInst(.{
746 .tag = .mov_linker,
747 .ops = ops,
748 .data = .{ .payload = try self.addExtra(Mir.LeaRegisterReloc{
749 .reg = @enumToInt(reg),
750 .atom_index = atom_index,
751 .sym_index = linker_load.sym_index,
752 }) },
753 });
754}
755
756fn asmLeaLinker(self: *Self, reg: Register, atom_index: u32, linker_load: codegen.LinkerLoad) !void {
757 const ops: Mir.Inst.Ops = switch (linker_load.type) {
758 .got => .got_reloc,
759 .direct => .direct_reloc,
760 .import => .import_reloc,
761 };
762 _ = try self.addInst(.{
763 .tag = .lea_linker,
764 .ops = ops,
765 .data = .{ .payload = try self.addExtra(Mir.LeaRegisterReloc{
766 .reg = @enumToInt(reg),
767 .atom_index = atom_index,
768 .sym_index = linker_load.sym_index,
769 }) },
770 });
771}
772
734773fn gen(self: *Self) InnerError!void {
735774 const cc = self.fn_type.fnCallingConvention();
736775 if (cc != .Naked) {
......@@ -2863,7 +2902,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
28632902 const offset_reg_lock = self.register_manager.lockRegAssumeUnused(offset_reg);
28642903 defer self.register_manager.unlockReg(offset_reg_lock);
28652904
2866 const addr_reg = try self.register_manager.allocReg(null, gp);
2905 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
28672906 switch (array) {
28682907 .register => {
28692908 const off = @intCast(i32, try self.allocMem(
......@@ -2872,19 +2911,33 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
28722911 array_ty.abiAlignment(self.target.*),
28732912 ));
28742913 try self.genSetStack(array_ty, off, array, .{});
2875 try self.asmRegisterMemory(.lea, addr_reg.to64(), Memory.sib(.qword, .{
2914 try self.asmRegisterMemory(.lea, addr_reg, Memory.sib(.qword, .{
28762915 .base = .rbp,
28772916 .disp = -off,
28782917 }));
28792918 },
28802919 .stack_offset => |off| {
2881 try self.asmRegisterMemory(.lea, addr_reg.to64(), Memory.sib(.qword, .{
2920 try self.asmRegisterMemory(.lea, addr_reg, Memory.sib(.qword, .{
28822921 .base = .rbp,
28832922 .disp = -off,
28842923 }));
28852924 },
2886 .memory, .linker_load => {
2887 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, array);
2925 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
2926 .tlv_reloc => try self.genSetReg(array_ty, addr_reg, array),
2927 .linker_load => |load_struct| {
2928 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
2929 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
2930 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
2931 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
2932 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
2933 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
2934 } else unreachable;
2935
2936 switch (load_struct.type) {
2937 .import => unreachable,
2938 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
2939 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
2940 }
28882941 },
28892942 else => return self.fail("TODO implement array_elem_val when array is {}", .{array}),
28902943 }
......@@ -3597,10 +3650,30 @@ fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!vo
35973650 else => return self.fail("TODO implement loading from register into {}", .{dst_mcv}),
35983651 }
35993652 },
3600 .memory, .linker_load => {
3653 .memory, .tlv_reloc => {
36013654 const reg = try self.copyToTmpRegister(ptr_ty, ptr);
36023655 try self.load(dst_mcv, .{ .register = reg }, ptr_ty);
36033656 },
3657 .linker_load => |load_struct| {
3658 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
3659 const addr_reg_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
3660 defer self.register_manager.unlockReg(addr_reg_lock);
3661
3662 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
3663 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3664 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
3665 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
3666 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3667 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
3668 } else unreachable;
3669
3670 switch (load_struct.type) {
3671 .import => unreachable,
3672 .got, .direct => try self.asmMovLinker(addr_reg, atom_index, load_struct),
3673 }
3674
3675 try self.load(dst_mcv, .{ .register = addr_reg }, ptr_ty);
3676 },
36043677 }
36053678}
36063679
......@@ -3630,41 +3703,6 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
36303703 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
36313704}
36323705
3633fn loadMemPtrIntoRegister(self: *Self, reg: Register, ptr_ty: Type, ptr: MCValue) InnerError!void {
3634 switch (ptr) {
3635 .linker_load => |load_struct| {
3636 const abi_size = @intCast(u32, ptr_ty.abiSize(self.target.*));
3637 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
3638 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3639 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
3640 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
3641 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3642 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
3643 } else unreachable;
3644 const ops: Mir.Inst.Ops = switch (load_struct.type) {
3645 .got => .got_reloc,
3646 .direct => .direct_reloc,
3647 .import => .import_reloc,
3648 };
3649 _ = try self.addInst(.{
3650 .tag = .lea_linker,
3651 .ops = ops,
3652 .data = .{ .payload = try self.addExtra(Mir.LeaRegisterReloc{
3653 .reg = @enumToInt(registerAlias(reg, abi_size)),
3654 .atom_index = atom_index,
3655 .sym_index = load_struct.sym_index,
3656 }) },
3657 });
3658 },
3659 .memory => |addr| {
3660 // TODO: in case the address fits in an imm32 we can use [ds:imm32]
3661 // instead of wasting an instruction copying the address to a register
3662 try self.genSetReg(ptr_ty, reg, .{ .immediate = addr });
3663 },
3664 else => unreachable,
3665 }
3666}
3667
36683706fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
36693707 const abi_size = @intCast(u32, value_ty.abiSize(self.target.*));
36703708 switch (ptr) {
......@@ -3775,11 +3813,29 @@ fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type
37753813
37763814 try self.store(ptr, .{ .register = tmp_reg }, ptr_ty, value_ty);
37773815 } else {
3778 const addr_reg = try self.register_manager.allocReg(null, gp);
3816 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
37793817 const addr_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
37803818 defer self.register_manager.unlockReg(addr_lock);
37813819
3782 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, value);
3820 switch (value) {
3821 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
3822 .linker_load => |load_struct| {
3823 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
3824 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3825 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
3826 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
3827 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3828 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
3829 } else unreachable;
3830 switch (load_struct.type) {
3831 .import => unreachable,
3832 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
3833 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
3834 }
3835 },
3836 else => unreachable,
3837 }
3838
37833839 try self.genInlineMemcpy(
37843840 ptr,
37853841 .{ .register = addr_reg },
......@@ -3799,7 +3855,7 @@ fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type
37993855 .{ .immediate = abi_size },
38003856 .{},
38013857 ),
3802 .ptr_stack_offset => {
3858 .ptr_stack_offset, .tlv_reloc => {
38033859 const tmp_reg = try self.copyToTmpRegister(value_ty, value);
38043860 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
38053861 defer self.register_manager.unlockReg(tmp_lock);
......@@ -3815,19 +3871,41 @@ fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type
38153871 };
38163872 defer if (value_lock) |lock| self.register_manager.unlockReg(lock);
38173873
3818 const addr_reg = try self.register_manager.allocReg(null, gp);
3874 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
38193875 const addr_reg_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
38203876 defer self.register_manager.unlockReg(addr_reg_lock);
38213877
3822 try self.loadMemPtrIntoRegister(addr_reg, ptr_ty, ptr);
3823 // Load the pointer, which is stored in memory
3824 try self.asmRegisterMemory(
3825 .mov,
3826 addr_reg.to64(),
3827 Memory.sib(.qword, .{ .base = addr_reg.to64() }),
3828 );
3878 switch (ptr) {
3879 .memory => |addr| {
3880 try self.genSetReg(ptr_ty, addr_reg, .{ .immediate = addr });
3881 // Load the pointer, which is stored in memory
3882 try self.asmRegisterMemory(.mov, addr_reg, Memory.sib(.qword, .{ .base = addr_reg }));
3883 },
3884 .linker_load => |load_struct| {
3885 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
3886 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3887 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
3888 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
3889 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
3890 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
3891 } else unreachable;
3892 switch (load_struct.type) {
3893 .import => unreachable,
3894 .got, .direct => try self.asmMovLinker(addr_reg, atom_index, load_struct),
3895 }
3896 },
3897 else => unreachable,
3898 }
38293899
3830 const new_ptr = MCValue{ .register = addr_reg.to64() };
3900 const new_ptr = MCValue{ .register = addr_reg };
3901 try self.store(new_ptr, value, ptr_ty, value_ty);
3902 },
3903 .tlv_reloc => {
3904 const addr_reg = try self.copyToTmpRegister(Type.usize, ptr);
3905 const addr_reg_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
3906 defer self.register_manager.unlockReg(addr_reg_lock);
3907
3908 const new_ptr = MCValue{ .register = addr_reg };
38313909 try self.store(new_ptr, value, ptr_ty, value_ty);
38323910 },
38333911 }
......@@ -3875,7 +3953,7 @@ fn fieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32
38753953
38763954 const dst_mcv: MCValue = result: {
38773955 switch (mcv) {
3878 .stack_offset => {
3956 .stack_offset, .tlv_reloc => {
38793957 const offset_reg = try self.copyToTmpRegister(ptr_ty, .{
38803958 .immediate = field_offset,
38813959 });
......@@ -4157,12 +4235,31 @@ fn genUnOpMir(self: *Self, mir_tag: Mir.Inst.Tag, dst_ty: Type, dst_mcv: MCValue
41574235 }));
41584236 },
41594237 .ptr_stack_offset => unreachable,
4238 .tlv_reloc => unreachable,
41604239 .memory, .linker_load => {
41614240 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
41624241 const addr_reg_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
41634242 defer self.register_manager.unlockReg(addr_reg_lock);
41644243
4165 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, dst_mcv);
4244 switch (dst_mcv) {
4245 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
4246 .linker_load => |load_struct| {
4247 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
4248 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
4249 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
4250 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
4251 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
4252 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
4253 } else unreachable;
4254
4255 switch (load_struct.type) {
4256 .import => unreachable,
4257 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
4258 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
4259 }
4260 },
4261 else => unreachable,
4262 }
41664263 try self.asmMemory(
41674264 mir_tag,
41684265 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{ .base = addr_reg }),
......@@ -4800,6 +4897,7 @@ fn genBinOp(
48004897 .eflags,
48014898 .register_overflow,
48024899 .ptr_stack_offset,
4900 .tlv_reloc,
48034901 => unreachable,
48044902 .register => |src_reg| try self.asmCmovccRegisterRegister(
48054903 registerAlias(tmp_reg, cmov_abi_size),
......@@ -4819,7 +4917,26 @@ fn genBinOp(
48194917 const addr_reg_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
48204918 defer self.register_manager.unlockReg(addr_reg_lock);
48214919
4822 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, mat_src_mcv);
4920 switch (mat_src_mcv) {
4921 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
4922 .linker_load => |load_struct| {
4923 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
4924 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
4925 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
4926 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
4927 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
4928 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
4929 } else unreachable;
4930
4931 switch (load_struct.type) {
4932 .import => unreachable,
4933 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
4934 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
4935 }
4936 },
4937 else => unreachable,
4938 }
4939
48234940 try self.asmCmovccRegisterMemory(
48244941 registerAlias(tmp_reg, cmov_abi_size),
48254942 Memory.sib(Memory.PtrSize.fromSize(cmov_abi_size), .{ .base = addr_reg }),
......@@ -4865,7 +4982,7 @@ fn genBinOpMir(self: *Self, mir_tag: Mir.Inst.Tag, ty: Type, dst_mcv: MCValue, s
48654982 .undef => unreachable,
48664983 .dead, .unreach => unreachable,
48674984 .register_overflow => unreachable,
4868 .ptr_stack_offset => {
4985 .ptr_stack_offset, .tlv_reloc => {
48694986 const dst_reg_lock = self.register_manager.lockReg(dst_reg);
48704987 defer if (dst_reg_lock) |lock| self.register_manager.unlockReg(lock);
48714988
......@@ -4942,11 +5059,30 @@ fn genBinOpMir(self: *Self, mir_tag: Mir.Inst.Tag, ty: Type, dst_mcv: MCValue, s
49425059 } = switch (dst_mcv) {
49435060 else => unreachable,
49445061 .memory, .linker_load => dst: {
4945 const dst_addr_reg = try self.register_manager.allocReg(null, gp);
5062 const dst_addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
49465063 const dst_addr_lock = self.register_manager.lockRegAssumeUnused(dst_addr_reg);
49475064 errdefer self.register_manager.unlockReg(dst_addr_lock);
49485065
4949 try self.loadMemPtrIntoRegister(dst_addr_reg, Type.usize, dst_mcv);
5066 switch (dst_mcv) {
5067 .memory => |addr| try self.genSetReg(Type.usize, dst_addr_reg, .{ .immediate = addr }),
5068 .linker_load => |load_struct| {
5069 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
5070 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
5071 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
5072 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
5073 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
5074 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
5075 } else unreachable;
5076
5077 switch (load_struct.type) {
5078 .import => unreachable,
5079 .got => try self.asmMovLinker(dst_addr_reg, atom_index, load_struct),
5080 .direct => try self.asmLeaLinker(dst_addr_reg, atom_index, load_struct),
5081 }
5082 },
5083 else => unreachable,
5084 }
5085
49505086 break :dst .{
49515087 .addr_reg = dst_addr_reg,
49525088 .addr_lock = dst_addr_lock,
......@@ -4968,11 +5104,30 @@ fn genBinOpMir(self: *Self, mir_tag: Mir.Inst.Tag, ty: Type, dst_mcv: MCValue, s
49685104 const src_limb_lock = self.register_manager.lockRegAssumeUnused(src_limb_reg);
49695105 errdefer self.register_manager.unlockReg(src_limb_lock);
49705106
4971 const src_addr_reg = try self.register_manager.allocReg(null, gp);
5107 const src_addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
49725108 const src_addr_lock = self.register_manager.lockRegAssumeUnused(src_addr_reg);
49735109 errdefer self.register_manager.unlockReg(src_addr_lock);
49745110
4975 try self.loadMemPtrIntoRegister(src_addr_reg, Type.usize, src_mcv);
5111 switch (src_mcv) {
5112 .memory => |addr| try self.genSetReg(Type.usize, src_addr_reg, .{ .immediate = addr }),
5113 .linker_load => |load_struct| {
5114 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
5115 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
5116 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
5117 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
5118 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
5119 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
5120 } else unreachable;
5121
5122 switch (load_struct.type) {
5123 .import => unreachable,
5124 .got => try self.asmMovLinker(src_addr_reg, atom_index, load_struct),
5125 .direct => try self.asmLeaLinker(src_addr_reg, atom_index, load_struct),
5126 }
5127 },
5128 else => unreachable,
5129 }
5130
49765131 break :src .{
49775132 .addr_reg = src_addr_reg,
49785133 .addr_lock = src_addr_lock,
......@@ -5078,7 +5233,7 @@ fn genBinOpMir(self: *Self, mir_tag: Mir.Inst.Tag, ty: Type, dst_mcv: MCValue, s
50785233 else => unreachable,
50795234 }
50805235 },
5081 .memory, .linker_load => {
5236 .memory, .linker_load, .tlv_reloc => {
50825237 try self.asmRegisterMemory(
50835238 .mov,
50845239 registerAlias(src.?.limb_reg, limb_abi_size),
......@@ -5117,6 +5272,7 @@ fn genBinOpMir(self: *Self, mir_tag: Mir.Inst.Tag, ty: Type, dst_mcv: MCValue, s
51175272 }
51185273 },
51195274 .ptr_stack_offset => unreachable,
5275 .tlv_reloc => unreachable,
51205276 }
51215277}
51225278
......@@ -5130,6 +5286,7 @@ fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: M
51305286 .dead, .unreach, .immediate => unreachable,
51315287 .eflags => unreachable,
51325288 .ptr_stack_offset => unreachable,
5289 .tlv_reloc => unreachable,
51335290 .register_overflow => unreachable,
51345291 .register => |dst_reg| {
51355292 const dst_alias = registerAlias(dst_reg, abi_size);
......@@ -5141,6 +5298,7 @@ fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: M
51415298 .undef => try self.genSetReg(dst_ty, dst_reg, .undef),
51425299 .dead, .unreach => unreachable,
51435300 .ptr_stack_offset => unreachable,
5301 .tlv_reloc => unreachable,
51445302 .register_overflow => unreachable,
51455303 .register => |src_reg| try self.asmRegisterRegister(
51465304 .imul,
......@@ -5184,6 +5342,7 @@ fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: M
51845342 .undef => return self.genSetStack(dst_ty, off, .undef, .{}),
51855343 .dead, .unreach => unreachable,
51865344 .ptr_stack_offset => unreachable,
5345 .tlv_reloc => unreachable,
51875346 .register_overflow => unreachable,
51885347 .register => |src_reg| {
51895348 // copy dst to a register
......@@ -5406,6 +5565,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
54065565 .linker_load => unreachable,
54075566 .eflags => unreachable,
54085567 .register_overflow => unreachable,
5568 .tlv_reloc => unreachable,
54095569 }
54105570 }
54115571
......@@ -5444,6 +5604,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
54445604 .linker_load => unreachable,
54455605 .eflags => unreachable,
54465606 .register_overflow => unreachable,
5607 .tlv_reloc => unreachable,
54475608 }
54485609 }
54495610
......@@ -5965,6 +6126,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
59656126 .register_overflow,
59666127 .ptr_stack_offset,
59676128 .eflags,
6129 .tlv_reloc,
59686130 => unreachable,
59696131
59706132 .register => |opt_reg| {
......@@ -5990,7 +6152,25 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
59906152 const addr_reg_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
59916153 defer self.register_manager.unlockReg(addr_reg_lock);
59926154
5993 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, opt_mcv);
6155 switch (opt_mcv) {
6156 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
6157 .linker_load => |load_struct| {
6158 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
6159 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
6160 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
6161 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
6162 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
6163 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
6164 } else unreachable;
6165
6166 switch (load_struct.type) {
6167 .import => unreachable,
6168 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
6169 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
6170 }
6171 },
6172 else => unreachable,
6173 }
59946174
59956175 const some_abi_size = @intCast(u32, some_info.ty.abiSize(self.target.*));
59966176 try self.asmMemoryImmediate(.cmp, Memory.sib(
......@@ -6925,11 +7105,30 @@ fn genSetStackArg(self: *Self, ty: Type, stack_offset: i32, mcv: MCValue) InnerE
69257105 return self.genSetStackArg(ty, stack_offset, MCValue{ .register = reg });
69267106 }
69277107
6928 const addr_reg = try self.register_manager.allocReg(null, gp);
7108 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
69297109 const addr_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
69307110 defer self.register_manager.unlockReg(addr_lock);
69317111
6932 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, mcv);
7112 switch (mcv) {
7113 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
7114 .linker_load => |load_struct| {
7115 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7116 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7117 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7118 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7119 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7120 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7121 } else unreachable;
7122
7123 switch (load_struct.type) {
7124 .import => unreachable,
7125 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
7126 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
7127 }
7128 },
7129 else => unreachable,
7130 }
7131
69337132 try self.genInlineMemcpy(
69347133 .{ .ptr_stack_offset = stack_offset },
69357134 .{ .register = addr_reg },
......@@ -6971,7 +7170,7 @@ fn genSetStackArg(self: *Self, ty: Type, stack_offset: i32, mcv: MCValue) InnerE
69717170 },
69727171 }
69737172 },
6974 .ptr_stack_offset => {
7173 .ptr_stack_offset, .tlv_reloc => {
69757174 const reg = try self.copyToTmpRegister(ty, mcv);
69767175 return self.genSetStackArg(ty, stack_offset, MCValue{ .register = reg });
69777176 },
......@@ -7133,11 +7332,30 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: i32, mcv: MCValue, opts: Inl
71337332 const reg = try self.copyToTmpRegister(ty, mcv);
71347333 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg }, opts);
71357334 } else {
7136 const addr_reg = try self.register_manager.allocReg(null, gp);
7335 const addr_reg = (try self.register_manager.allocReg(null, gp)).to64();
71377336 const addr_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
71387337 defer self.register_manager.unlockReg(addr_lock);
71397338
7140 try self.loadMemPtrIntoRegister(addr_reg, Type.usize, mcv);
7339 switch (mcv) {
7340 .memory => |addr| try self.genSetReg(Type.usize, addr_reg, .{ .immediate = addr }),
7341 .linker_load => |load_struct| {
7342 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7343 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7344 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7345 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7346 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7347 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7348 } else unreachable;
7349
7350 switch (load_struct.type) {
7351 .import => unreachable,
7352 .got => try self.asmMovLinker(addr_reg, atom_index, load_struct),
7353 .direct => try self.asmLeaLinker(addr_reg, atom_index, load_struct),
7354 }
7355 },
7356 else => unreachable,
7357 }
7358
71417359 try self.genInlineMemcpy(
71427360 .{ .ptr_stack_offset = stack_offset },
71437361 .{ .register = addr_reg },
......@@ -7157,7 +7375,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: i32, mcv: MCValue, opts: Inl
71577375 .{ .immediate = abi_size },
71587376 .{},
71597377 ),
7160 .ptr_stack_offset => {
7378 .ptr_stack_offset, .tlv_reloc => {
71617379 const tmp_reg = try self.copyToTmpRegister(ty, mcv);
71627380 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
71637381 defer self.register_manager.unlockReg(tmp_lock);
......@@ -7247,11 +7465,26 @@ fn genInlineMemcpy(
72477465 try self.spillRegisters(&.{ .rdi, .rsi, .rcx });
72487466
72497467 switch (dst_ptr) {
7250 .memory, .linker_load => {
7251 try self.loadMemPtrIntoRegister(.rdi, Type.usize, dst_ptr);
7468 .memory => |addr| {
7469 try self.genSetReg(Type.usize, .rdi, .{ .immediate = addr });
72527470 // Load the pointer, which is stored in memory
72537471 try self.asmRegisterMemory(.mov, .rdi, Memory.sib(.qword, .{ .base = .rdi }));
72547472 },
7473 .linker_load => |load_struct| {
7474 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7475 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7476 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7477 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7478 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7479 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7480 } else unreachable;
7481
7482 switch (load_struct.type) {
7483 .import => unreachable,
7484 .got, .direct => try self.asmMovLinker(.rdi, atom_index, load_struct),
7485 }
7486 },
7487 .tlv_reloc => try self.genSetReg(Type.usize, .rdi, dst_ptr),
72557488 .stack_offset, .ptr_stack_offset => |off| {
72567489 try self.asmRegisterMemory(switch (dst_ptr) {
72577490 .stack_offset => .mov,
......@@ -7275,11 +7508,26 @@ fn genInlineMemcpy(
72757508 }
72767509
72777510 switch (src_ptr) {
7278 .memory, .linker_load => {
7279 try self.loadMemPtrIntoRegister(.rsi, Type.usize, src_ptr);
7511 .memory => |addr| {
7512 try self.genSetReg(Type.usize, .rsi, .{ .immediate = addr });
72807513 // Load the pointer, which is stored in memory
72817514 try self.asmRegisterMemory(.mov, .rsi, Memory.sib(.qword, .{ .base = .rsi }));
72827515 },
7516 .linker_load => |load_struct| {
7517 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7518 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7519 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7520 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7521 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7522 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7523 } else unreachable;
7524
7525 switch (load_struct.type) {
7526 .import => unreachable,
7527 .got, .direct => try self.asmMovLinker(.rsi, atom_index, load_struct),
7528 }
7529 },
7530 .tlv_reloc => try self.genSetReg(Type.usize, .rsi, src_ptr),
72837531 .stack_offset, .ptr_stack_offset => |off| {
72847532 try self.asmRegisterMemory(switch (src_ptr) {
72857533 .stack_offset => .mov,
......@@ -7326,11 +7574,26 @@ fn genInlineMemset(
73267574 try self.spillRegisters(&.{ .rdi, .al, .rcx });
73277575
73287576 switch (dst_ptr) {
7329 .memory, .linker_load => {
7330 try self.loadMemPtrIntoRegister(.rdi, Type.usize, dst_ptr);
7577 .memory => |addr| {
7578 try self.genSetReg(Type.usize, .rdi, .{ .immediate = addr });
73317579 // Load the pointer, which is stored in memory
73327580 try self.asmRegisterMemory(.mov, .rdi, Memory.sib(.qword, .{ .base = .rdi }));
73337581 },
7582 .linker_load => |load_struct| {
7583 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7584 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7585 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7586 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7587 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7588 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7589 } else unreachable;
7590
7591 switch (load_struct.type) {
7592 .import => unreachable,
7593 .got, .direct => try self.asmMovLinker(.rdi, atom_index, load_struct),
7594 }
7595 },
7596 .tlv_reloc => try self.genSetReg(Type.usize, .rdi, dst_ptr),
73347597 .stack_offset, .ptr_stack_offset => |off| {
73357598 try self.asmRegisterMemory(switch (dst_ptr) {
73367599 .stack_offset => .mov,
......@@ -7454,10 +7717,10 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
74547717
74557718 try self.asmRegisterRegister(.mov, registerAlias(reg, abi_size), registerAlias(src_reg, abi_size));
74567719 },
7457 .memory, .linker_load => switch (ty.zigTypeTag()) {
7720 .memory => |addr| switch (ty.zigTypeTag()) {
74587721 .Float => {
7459 const base_reg = try self.register_manager.allocReg(null, gp);
7460 try self.loadMemPtrIntoRegister(base_reg, Type.usize, mcv);
7722 const base_reg = (try self.register_manager.allocReg(null, gp)).to64();
7723 try self.genSetReg(Type.usize, base_reg, .{ .immediate = addr });
74617724
74627725 if (intrinsicsAllowed(self.target.*, ty)) {
74637726 return self.asmRegisterMemory(
......@@ -7469,29 +7732,20 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
74697732 }),
74707733 },
74717734 reg.to128(),
7472 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{ .base = base_reg.to64() }),
7735 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{ .base = base_reg }),
74737736 );
74747737 }
74757738
74767739 return self.fail("TODO genSetReg from memory for float with no intrinsics", .{});
74777740 },
7478 else => switch (mcv) {
7479 else => unreachable,
7480 .linker_load => {
7481 try self.loadMemPtrIntoRegister(reg, Type.usize, mcv);
7482 try self.asmRegisterMemory(
7483 .mov,
7484 registerAlias(reg, abi_size),
7485 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{ .base = reg.to64() }),
7486 );
7487 },
7488 .memory => |x| if (x <= math.maxInt(i32)) {
7741 else => {
7742 if (addr <= math.maxInt(i32)) {
74897743 try self.asmRegisterMemory(
74907744 .mov,
74917745 registerAlias(reg, abi_size),
74927746 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{
74937747 .base = .ds,
7494 .disp = @intCast(i32, x),
7748 .disp = @intCast(i32, addr),
74957749 }),
74967750 );
74977751 } else {
......@@ -7501,20 +7755,77 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
75017755 _ = try self.addInst(.{
75027756 .tag = .mov_moffs,
75037757 .ops = .rax_moffs,
7504 .data = .{ .payload = try self.addExtra(Mir.MemoryMoffs.encode(.ds, x)) },
7758 .data = .{ .payload = try self.addExtra(Mir.MemoryMoffs.encode(.ds, addr)) },
75057759 });
75067760 } else {
75077761 // Rather than duplicate the logic used for the move, we just use a self-call with a new MCValue.
7508 try self.genSetReg(ty, reg, MCValue{ .immediate = x });
7762 try self.genSetReg(Type.usize, reg, MCValue{ .immediate = addr });
75097763 try self.asmRegisterMemory(
75107764 .mov,
75117765 registerAlias(reg, abi_size),
75127766 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{ .base = reg.to64() }),
75137767 );
75147768 }
7515 },
7769 }
75167770 },
75177771 },
7772 .tlv_reloc => |sym_index| {
7773 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7774 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7775 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7776 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7777 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7778 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7779 } else unreachable;
7780
7781 if (self.bin_file.cast(link.File.MachO)) |_| {
7782 _ = try self.addInst(.{
7783 .tag = .mov_linker,
7784 .ops = .tlv_reloc,
7785 .data = .{ .payload = try self.addExtra(Mir.LeaRegisterReloc{
7786 .reg = @enumToInt(Register.rdi),
7787 .atom_index = atom_index,
7788 .sym_index = sym_index,
7789 }) },
7790 });
7791 // TODO: spill registers before calling
7792 try self.asmMemory(.call, Memory.sib(.qword, .{ .base = .rdi }));
7793 try self.genSetReg(Type.usize, reg, .{ .register = .rax });
7794 } else return self.fail("TODO emit ptr to TLV sequence on {s}", .{@tagName(self.bin_file.tag)});
7795 },
7796 .linker_load => |load_struct| {
7797 const atom_index = if (self.bin_file.cast(link.File.MachO)) |macho_file| blk: {
7798 const atom = try macho_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7799 break :blk macho_file.getAtom(atom).getSymbolIndex().?;
7800 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| blk: {
7801 const atom = try coff_file.getOrCreateAtomForDecl(self.mod_fn.owner_decl);
7802 break :blk coff_file.getAtom(atom).getSymbolIndex().?;
7803 } else unreachable;
7804
7805 switch (ty.zigTypeTag()) {
7806 .Float => {
7807 const base_reg = (try self.register_manager.allocReg(null, gp)).to64();
7808 try self.asmLeaLinker(base_reg, atom_index, load_struct);
7809
7810 if (intrinsicsAllowed(self.target.*, ty)) {
7811 return self.asmRegisterMemory(
7812 switch (ty.tag()) {
7813 .f32 => .movss,
7814 .f64 => .movsd,
7815 else => return self.fail("TODO genSetReg from memory for {}", .{
7816 ty.fmt(self.bin_file.options.module.?),
7817 }),
7818 },
7819 reg.to128(),
7820 Memory.sib(Memory.PtrSize.fromSize(abi_size), .{ .base = base_reg.to64() }),
7821 );
7822 }
7823
7824 return self.fail("TODO genSetReg from memory for float with no intrinsics", .{});
7825 },
7826 else => try self.asmMovLinker(registerAlias(reg, abi_size), atom_index, load_struct),
7827 }
7828 },
75187829 .stack_offset => |off| {
75197830 switch (ty.zigTypeTag()) {
75207831 .Int => switch (ty.intInfo(self.target.*).signedness) {
......@@ -8468,6 +8779,7 @@ fn genTypedValue(self: *Self, arg_tv: TypedValue) InnerError!MCValue {
84688779 .linker_load => |ll| .{ .linker_load = ll },
84698780 .immediate => |imm| .{ .immediate = imm },
84708781 .memory => |addr| .{ .memory = addr },
8782 .tlv_reloc => |sym_index| .{ .tlv_reloc = sym_index },
84718783 },
84728784 .fail => |msg| {
84738785 self.err_msg = msg;
src/arch/x86_64/Emit.zig+8-8
......@@ -42,7 +42,7 @@ pub fn emitMir(emit: *Emit) Error!void {
4242 ).?;
4343 const target = macho_file.getGlobalByIndex(inst.data.relocation.sym_index);
4444 try link.File.MachO.Atom.addRelocation(macho_file, atom_index, .{
45 .type = @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_BRANCH),
45 .type = .branch,
4646 .target = target,
4747 .offset = end_offset - 4,
4848 .addend = 0,
......@@ -65,20 +65,20 @@ pub fn emitMir(emit: *Emit) Error!void {
6565 });
6666 } else return emit.fail("TODO implement {} for {}", .{ inst.tag, emit.bin_file.tag }),
6767
68 .lea_linker => if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
68 .mov_linker, .lea_linker => if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
6969 const metadata =
7070 emit.lower.mir.extraData(Mir.LeaRegisterReloc, inst.data.payload).data;
71 const reloc_type = switch (inst.ops) {
72 .got_reloc => @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_GOT),
73 .direct_reloc => @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_SIGNED),
74 else => unreachable,
75 };
7671 const atom_index = macho_file.getAtomIndexForSymbol(.{
7772 .sym_index = metadata.atom_index,
7873 .file = null,
7974 }).?;
8075 try link.File.MachO.Atom.addRelocation(macho_file, atom_index, .{
81 .type = reloc_type,
76 .type = switch (inst.ops) {
77 .got_reloc => .got,
78 .direct_reloc => .signed,
79 .tlv_reloc => .tlv,
80 else => unreachable,
81 },
8282 .target = .{ .sym_index = metadata.sym_index, .file = null },
8383 .offset = @intCast(u32, end_offset - 4),
8484 .addend = 0,
src/arch/x86_64/Lower.zig+10
......@@ -127,6 +127,7 @@ pub fn lowerMir(lower: *Lower, inst: Mir.Inst) Error![]const Instruction {
127127 .call_extern => try lower.emit(.none, .call, &.{.{ .imm = Immediate.s(0) }}),
128128
129129 .lea_linker => try lower.mirLeaLinker(inst),
130 .mov_linker => try lower.mirMovLinker(inst),
130131
131132 .mov_moffs => try lower.mirMovMoffs(inst),
132133
......@@ -444,6 +445,15 @@ fn mirLeaLinker(lower: *Lower, inst: Mir.Inst) Error!void {
444445 });
445446}
446447
448fn mirMovLinker(lower: *Lower, inst: Mir.Inst) Error!void {
449 const metadata = lower.mir.extraData(Mir.LeaRegisterReloc, inst.data.payload).data;
450 const reg = @intToEnum(Register, metadata.reg);
451 try lower.emit(.none, .mov, &.{
452 .{ .reg = reg },
453 .{ .mem = Memory.rip(Memory.PtrSize.fromBitSize(reg.bitSize()), 0) },
454 });
455}
456
447457const abi = @import("abi.zig");
448458const assert = std.debug.assert;
449459const bits = @import("bits.zig");
src/arch/x86_64/Mir.zig+5
......@@ -233,6 +233,8 @@ pub const Inst = struct {
233233
234234 /// Load effective address of a symbol not yet allocated in VM.
235235 lea_linker,
236 /// Move address of a symbol not yet allocated in VM.
237 mov_linker,
236238
237239 /// End of prologue
238240 dbg_prologue_end,
......@@ -402,6 +404,9 @@ pub const Inst = struct {
402404 /// Linker relocation - imports table indirection (binding).
403405 /// Uses `payload` payload with extra data of type `LeaRegisterReloc`.
404406 import_reloc,
407 /// Linker relocation - threadlocal variable via GOT indirection.
408 /// Uses `payload` payload with extra data of type `LeaRegisterReloc`.
409 tlv_reloc,
405410 };
406411
407412 pub const Data = union {
src/codegen.zig+19-5
......@@ -493,7 +493,7 @@ pub fn generateSymbol(
493493 bin_file.allocator,
494494 src_loc,
495495 "TODO implement generateSymbol for big int enums ('{}')",
496 .{typed_value.ty.fmtDebug()},
496 .{typed_value.ty.fmt(mod)},
497497 ),
498498 };
499499 }
......@@ -932,6 +932,10 @@ pub const GenResult = union(enum) {
932932 /// such as ARM, the immediate will never exceed 32-bits.
933933 immediate: u64,
934934 linker_load: LinkerLoad,
935 /// Pointer to a threadlocal variable.
936 /// The address resolution will be deferred until the linker allocates everything in virtual memory.
937 /// Payload is a symbol index.
938 tlv_reloc: u32,
935939 /// Direct by-address reference to memory location.
936940 memory: u64,
937941 };
......@@ -957,13 +961,13 @@ fn genDeclRef(
957961 tv: TypedValue,
958962 decl_index: Module.Decl.Index,
959963) CodeGenError!GenResult {
960 log.debug("genDeclRef: ty = {}, val = {}", .{ tv.ty.fmtDebug(), tv.val.fmtDebug() });
964 const module = bin_file.options.module.?;
965 log.debug("genDeclRef: ty = {}, val = {}", .{ tv.ty.fmt(module), tv.val.fmtValue(tv.ty, module) });
961966
962967 const target = bin_file.options.target;
963968 const ptr_bits = target.cpu.arch.ptrBitWidth();
964969 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
965970
966 const module = bin_file.options.module.?;
967971 const decl = module.declPtr(decl_index);
968972
969973 if (!decl.ty.isFnOrHasRuntimeBitsIgnoreComptime()) {
......@@ -991,6 +995,8 @@ fn genDeclRef(
991995
992996 module.markDeclAlive(decl);
993997
998 const is_threadlocal = tv.val.isPtrToThreadLocal(module) and !bin_file.options.single_threaded;
999
9941000 if (bin_file.cast(link.File.Elf)) |elf_file| {
9951001 const atom_index = try elf_file.getOrCreateAtomForDecl(decl_index);
9961002 const atom = elf_file.getAtom(atom_index);
......@@ -998,6 +1004,9 @@ fn genDeclRef(
9981004 } else if (bin_file.cast(link.File.MachO)) |macho_file| {
9991005 const atom_index = try macho_file.getOrCreateAtomForDecl(decl_index);
10001006 const sym_index = macho_file.getAtom(atom_index).getSymbolIndex().?;
1007 if (is_threadlocal) {
1008 return GenResult.mcv(.{ .tlv_reloc = sym_index });
1009 }
10011010 return GenResult.mcv(.{ .linker_load = .{
10021011 .type = .got,
10031012 .sym_index = sym_index,
......@@ -1025,7 +1034,8 @@ fn genUnnamedConst(
10251034 tv: TypedValue,
10261035 owner_decl_index: Module.Decl.Index,
10271036) CodeGenError!GenResult {
1028 log.debug("genUnnamedConst: ty = {}, val = {}", .{ tv.ty.fmtDebug(), tv.val.fmtDebug() });
1037 const mod = bin_file.options.module.?;
1038 log.debug("genUnnamedConst: ty = {}, val = {}", .{ tv.ty.fmt(mod), tv.val.fmtValue(tv.ty, mod) });
10291039
10301040 const target = bin_file.options.target;
10311041 const local_sym_index = bin_file.lowerUnnamedConst(tv, owner_decl_index) catch |err| {
......@@ -1065,7 +1075,11 @@ pub fn genTypedValue(
10651075 typed_value.val = rt.data;
10661076 }
10671077
1068 log.debug("genTypedValue: ty = {}, val = {}", .{ typed_value.ty.fmtDebug(), typed_value.val.fmtDebug() });
1078 const mod = bin_file.options.module.?;
1079 log.debug("genTypedValue: ty = {}, val = {}", .{
1080 typed_value.ty.fmt(mod),
1081 typed_value.val.fmtValue(typed_value.ty, mod),
1082 });
10691083
10701084 if (typed_value.val.isUndef())
10711085 return GenResult.mcv(.undef);
src/link.zig+2-2
......@@ -540,7 +540,7 @@ pub const File = struct {
540540 /// May be called before or after updateDeclExports for any given Decl.
541541 pub fn updateDecl(base: *File, module: *Module, decl_index: Module.Decl.Index) UpdateDeclError!void {
542542 const decl = module.declPtr(decl_index);
543 log.debug("updateDecl {*} ({s}), type={}", .{ decl, decl.name, decl.ty.fmtDebug() });
543 log.debug("updateDecl {*} ({s}), type={}", .{ decl, decl.name, decl.ty.fmt(module) });
544544 assert(decl.has_tv);
545545 if (build_options.only_c) {
546546 assert(base.tag == .c);
......@@ -564,7 +564,7 @@ pub const File = struct {
564564 pub fn updateFunc(base: *File, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) UpdateDeclError!void {
565565 const owner_decl = module.declPtr(func.owner_decl);
566566 log.debug("updateFunc {*} ({s}), type={}", .{
567 owner_decl, owner_decl.name, owner_decl.ty.fmtDebug(),
567 owner_decl, owner_decl.name, owner_decl.ty.fmt(module),
568568 });
569569 if (build_options.only_c) {
570570 assert(base.tag == .c);
src/link/Dwarf.zig+12-3
......@@ -150,7 +150,7 @@ pub const DeclState = struct {
150150 .type = ty,
151151 .offset = undefined,
152152 });
153 log.debug("%{d}: {}", .{ sym_index, ty.fmtDebug() });
153 log.debug("%{d}: {}", .{ sym_index, ty.fmt(self.mod) });
154154 try self.abbrev_resolver.putNoClobberContext(self.gpa, ty, sym_index, .{
155155 .mod = self.mod,
156156 });
......@@ -570,7 +570,7 @@ pub const DeclState = struct {
570570 try dbg_info_buffer.append(0);
571571 },
572572 else => {
573 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmtDebug()});
573 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmt(self.mod)});
574574 try dbg_info_buffer.append(@enumToInt(AbbrevKind.pad1));
575575 },
576576 }
......@@ -1055,6 +1055,10 @@ pub fn commitDeclState(
10551055 },
10561056 }
10571057 {
1058 log.debug("relocating subprogram high PC value: {x} => {x}", .{
1059 self.getRelocDbgInfoSubprogramHighPC(),
1060 sym_size,
1061 });
10581062 const ptr = dbg_info_buffer.items[self.getRelocDbgInfoSubprogramHighPC()..][0..4];
10591063 mem.writeInt(u32, ptr, @intCast(u32, sym_size), target_endian);
10601064 }
......@@ -1263,7 +1267,12 @@ pub fn commitDeclState(
12631267 } else {
12641268 const atom = self.getAtom(.di_atom, symbol.atom_index);
12651269 const value = atom.off + symbol.offset + reloc.addend;
1266 log.debug("{x}: [() => {x}] (%{d}, '{}')", .{ reloc.offset, value, target, ty.fmtDebug() });
1270 log.debug("{x}: [() => {x}] (%{d}, '{}')", .{
1271 reloc.offset,
1272 value,
1273 target,
1274 ty.fmt(module),
1275 });
12671276 mem.writeInt(
12681277 u32,
12691278 dbg_info_buffer.items[reloc.offset..][0..@sizeOf(u32)],
src/link/MachO.zig+298-228
......@@ -5,7 +5,6 @@ const build_options = @import("build_options");
55const builtin = @import("builtin");
66const assert = std.debug.assert;
77const dwarf = std.dwarf;
8const fmt = std.fmt;
98const fs = std.fs;
109const log = std.log.scoped(.link);
1110const macho = std.macho;
......@@ -138,6 +137,8 @@ got_section_index: ?u8 = null,
138137data_const_section_index: ?u8 = null,
139138la_symbol_ptr_section_index: ?u8 = null,
140139data_section_index: ?u8 = null,
140thread_vars_section_index: ?u8 = null,
141thread_data_section_index: ?u8 = null,
141142
142143locals: std.ArrayListUnmanaged(macho.nlist_64) = .{},
143144globals: std.ArrayListUnmanaged(SymbolWithLoc) = .{},
......@@ -153,13 +154,9 @@ stub_helper_preamble_atom_index: ?Atom.Index = null,
153154
154155strtab: StringTable(.strtab) = .{},
155156
156got_entries: std.ArrayListUnmanaged(Entry) = .{},
157got_entries_free_list: std.ArrayListUnmanaged(u32) = .{},
158got_entries_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{},
159
160stubs: std.ArrayListUnmanaged(Entry) = .{},
161stubs_free_list: std.ArrayListUnmanaged(u32) = .{},
162stubs_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{},
157got_table: SectionTable = .{},
158stubs_table: SectionTable = .{},
159tlv_table: SectionTable = .{},
163160
164161error_flags: File.ErrorFlags = File.ErrorFlags{},
165162
......@@ -268,26 +265,120 @@ const DeclMetadata = struct {
268265 }
269266};
270267
271const Entry = struct {
272 target: SymbolWithLoc,
273 // Index into the synthetic symbol table (i.e., file == null).
274 sym_index: u32,
268const SectionTable = struct {
269 entries: std.ArrayListUnmanaged(Entry) = .{},
270 free_list: std.ArrayListUnmanaged(u32) = .{},
271 lookup: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{},
272
273 pub fn deinit(st: *ST, allocator: Allocator) void {
274 st.entries.deinit(allocator);
275 st.free_list.deinit(allocator);
276 st.lookup.deinit(allocator);
277 }
278
279 pub fn allocateEntry(st: *ST, allocator: Allocator, target: SymbolWithLoc) !u32 {
280 try st.entries.ensureUnusedCapacity(allocator, 1);
281 const index = blk: {
282 if (st.free_list.popOrNull()) |index| {
283 log.debug(" (reusing entry index {d})", .{index});
284 break :blk index;
285 } else {
286 log.debug(" (allocating entry at index {d})", .{st.entries.items.len});
287 const index = @intCast(u32, st.entries.items.len);
288 _ = st.entries.addOneAssumeCapacity();
289 break :blk index;
290 }
291 };
292 st.entries.items[index] = .{ .target = target, .sym_index = 0 };
293 try st.lookup.putNoClobber(allocator, target, index);
294 return index;
295 }
296
297 pub fn freeEntry(st: *ST, allocator: Allocator, target: SymbolWithLoc) void {
298 const index = st.lookup.get(target) orelse return;
299 st.free_list.append(allocator, index) catch {};
300 st.entries.items[index] = .{
301 .target = .{ .sym_index = 0 },
302 .sym_index = 0,
303 };
304 _ = st.lookup.remove(target);
305 }
275306
276 pub fn getSymbol(entry: Entry, macho_file: *MachO) macho.nlist_64 {
277 return macho_file.getSymbol(.{ .sym_index = entry.sym_index, .file = null });
307 pub fn getAtomIndex(st: *const ST, macho_file: *MachO, target: SymbolWithLoc) ?Atom.Index {
308 const index = st.lookup.get(target) orelse return null;
309 return st.entries.items[index].getAtomIndex(macho_file);
278310 }
279311
280 pub fn getSymbolPtr(entry: Entry, macho_file: *MachO) *macho.nlist_64 {
281 return macho_file.getSymbolPtr(.{ .sym_index = entry.sym_index, .file = null });
312 const FormatContext = struct {
313 macho_file: *MachO,
314 st: *const ST,
315 };
316
317 fn fmt(
318 ctx: FormatContext,
319 comptime unused_format_string: []const u8,
320 options: std.fmt.FormatOptions,
321 writer: anytype,
322 ) @TypeOf(writer).Error!void {
323 _ = options;
324 comptime assert(unused_format_string.len == 0);
325 try writer.writeAll("SectionTable:\n");
326 for (ctx.st.entries.items, 0..) |entry, i| {
327 const atom_sym = entry.getSymbol(ctx.macho_file);
328 const target_sym = ctx.macho_file.getSymbol(entry.target);
329 try writer.print(" {d}@{x} => ", .{ i, atom_sym.n_value });
330 if (target_sym.undf()) {
331 try writer.print("import('{s}')", .{
332 ctx.macho_file.getSymbolName(entry.target),
333 });
334 } else {
335 try writer.print("local(%{d}) in object({?d})", .{
336 entry.target.sym_index,
337 entry.target.file,
338 });
339 }
340 try writer.writeByte('\n');
341 }
282342 }
283343
284 pub fn getAtomIndex(entry: Entry, macho_file: *MachO) ?Atom.Index {
285 return macho_file.getAtomIndexForSymbol(.{ .sym_index = entry.sym_index, .file = null });
344 fn format(st: *const ST, comptime unused_format_string: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
345 _ = st;
346 _ = unused_format_string;
347 _ = options;
348 _ = writer;
349 @compileError("do not format SectionTable directly; use st.fmtDebug()");
286350 }
287351
288 pub fn getName(entry: Entry, macho_file: *MachO) []const u8 {
289 return macho_file.getSymbolName(.{ .sym_index = entry.sym_index, .file = null });
352 pub fn fmtDebug(st: *const ST, macho_file: *MachO) std.fmt.Formatter(fmt) {
353 return .{ .data = .{
354 .macho_file = macho_file,
355 .st = st,
356 } };
290357 }
358
359 const ST = @This();
360
361 const Entry = struct {
362 target: SymbolWithLoc,
363 // Index into the synthetic symbol table (i.e., file == null).
364 sym_index: u32,
365
366 pub fn getSymbol(entry: Entry, macho_file: *MachO) macho.nlist_64 {
367 return macho_file.getSymbol(.{ .sym_index = entry.sym_index });
368 }
369
370 pub fn getSymbolPtr(entry: Entry, macho_file: *MachO) *macho.nlist_64 {
371 return macho_file.getSymbolPtr(.{ .sym_index = entry.sym_index });
372 }
373
374 pub fn getAtomIndex(entry: Entry, macho_file: *MachO) ?Atom.Index {
375 return macho_file.getAtomIndexForSymbol(.{ .sym_index = entry.sym_index });
376 }
377
378 pub fn getName(entry: Entry, macho_file: *MachO) []const u8 {
379 return macho_file.getSymbolName(.{ .sym_index = entry.sym_index });
380 }
381 };
291382};
292383
293384const BindingTable = std.AutoArrayHashMapUnmanaged(Atom.Index, std.ArrayListUnmanaged(Atom.Binding));
......@@ -397,7 +488,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO {
397488 // Create dSYM bundle.
398489 log.debug("creating {s}.dSYM bundle", .{sub_path});
399490
400 const d_sym_path = try fmt.allocPrint(
491 const d_sym_path = try std.fmt.allocPrint(
401492 allocator,
402493 "{s}.dSYM" ++ fs.path.sep_str ++ "Contents" ++ fs.path.sep_str ++ "Resources" ++ fs.path.sep_str ++ "DWARF",
403494 .{sub_path},
......@@ -611,6 +702,9 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
611702 if (self.dyld_stub_binder_index == null) {
612703 self.dyld_stub_binder_index = try self.addUndefined("dyld_stub_binder", .add_got);
613704 }
705 if (!self.base.options.single_threaded) {
706 _ = try self.addUndefined("__tlv_bootstrap", .none);
707 }
614708
615709 try self.createMhExecuteHeaderSymbol();
616710
......@@ -619,6 +713,12 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
619713 try self.resolveSymbolsInDylibs(&actions);
620714
621715 if (self.unresolved.count() > 0) {
716 for (self.unresolved.keys()) |index| {
717 // TODO: convert into compiler errors.
718 const global = self.globals.items[index];
719 const sym_name = self.getSymbolName(global);
720 log.err("undefined symbol reference '{s}'", .{sym_name});
721 }
622722 return error.UndefinedSymbolReference;
623723 }
624724
......@@ -1237,22 +1337,17 @@ pub fn createAtom(self: *MachO) !Atom.Index {
12371337
12381338pub fn createGotAtom(self: *MachO, target: SymbolWithLoc) !Atom.Index {
12391339 const atom_index = try self.createAtom();
1240 const atom = self.getAtomPtr(atom_index);
1241 atom.size = @sizeOf(u64);
1340 self.getAtomPtr(atom_index).size = @sizeOf(u64);
12421341
1243 const sym = atom.getSymbolPtr(self);
1342 const sym = self.getAtom(atom_index).getSymbolPtr(self);
12441343 sym.n_type = macho.N_SECT;
12451344 sym.n_sect = self.got_section_index.? + 1;
1246 sym.n_value = try self.allocateAtom(atom_index, atom.size, @alignOf(u64));
1345 sym.n_value = try self.allocateAtom(atom_index, @sizeOf(u64), @alignOf(u64));
12471346
12481347 log.debug("allocated GOT atom at 0x{x}", .{sym.n_value});
12491348
12501349 try Atom.addRelocation(self, atom_index, .{
1251 .type = switch (self.base.options.target.cpu.arch) {
1252 .aarch64 => @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_UNSIGNED),
1253 .x86_64 => @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_UNSIGNED),
1254 else => unreachable,
1255 },
1350 .type = .unsigned,
12561351 .target = target,
12571352 .offset = 0,
12581353 .addend = 0,
......@@ -1269,6 +1364,7 @@ pub fn createGotAtom(self: *MachO, target: SymbolWithLoc) !Atom.Index {
12691364 } else {
12701365 try Atom.addRebase(self, atom_index, 0);
12711366 }
1367 try self.writePtrWidthAtom(atom_index);
12721368
12731369 return atom_index;
12741370}
......@@ -1334,15 +1430,15 @@ fn createStubHelperPreambleAtom(self: *MachO) !void {
13341430 code[9] = 0xff;
13351431 code[10] = 0x25;
13361432
1337 try Atom.addRelocations(self, atom_index, 2, .{ .{
1338 .type = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_SIGNED),
1433 try Atom.addRelocations(self, atom_index, &[_]Relocation{ .{
1434 .type = .signed,
13391435 .target = dyld_private,
13401436 .offset = 3,
13411437 .addend = 0,
13421438 .pcrel = true,
13431439 .length = 2,
13441440 }, .{
1345 .type = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_GOT),
1441 .type = .got,
13461442 .target = dyld_stub_binder,
13471443 .offset = 11,
13481444 .addend = 0,
......@@ -1374,29 +1470,29 @@ fn createStubHelperPreambleAtom(self: *MachO) !void {
13741470 // br x16
13751471 mem.writeIntLittle(u32, code[20..][0..4], aarch64.Instruction.br(.x16).toU32());
13761472
1377 try Atom.addRelocations(self, atom_index, 4, .{ .{
1378 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGE21),
1473 try Atom.addRelocations(self, atom_index, &[_]Relocation{ .{
1474 .type = .page,
13791475 .target = dyld_private,
13801476 .offset = 0,
13811477 .addend = 0,
13821478 .pcrel = true,
13831479 .length = 2,
13841480 }, .{
1385 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGEOFF12),
1481 .type = .pageoff,
13861482 .target = dyld_private,
13871483 .offset = 4,
13881484 .addend = 0,
13891485 .pcrel = false,
13901486 .length = 2,
13911487 }, .{
1392 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGE21),
1488 .type = .got_page,
13931489 .target = dyld_stub_binder,
13941490 .offset = 12,
13951491 .addend = 0,
13961492 .pcrel = true,
13971493 .length = 2,
13981494 }, .{
1399 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGEOFF12),
1495 .type = .got_pageoff,
14001496 .target = dyld_stub_binder,
14011497 .offset = 16,
14021498 .addend = 0,
......@@ -1454,8 +1550,8 @@ fn createStubHelperAtom(self: *MachO) !Atom.Index {
14541550 code[5] = 0xe9;
14551551
14561552 try Atom.addRelocation(self, atom_index, .{
1457 .type = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_BRANCH),
1458 .target = .{ .sym_index = stub_helper_preamble_atom_sym_index, .file = null },
1553 .type = .branch,
1554 .target = .{ .sym_index = stub_helper_preamble_atom_sym_index },
14591555 .offset = 6,
14601556 .addend = 0,
14611557 .pcrel = true,
......@@ -1477,8 +1573,8 @@ fn createStubHelperAtom(self: *MachO) !Atom.Index {
14771573 // Next 4 bytes 8..12 are just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
14781574
14791575 try Atom.addRelocation(self, atom_index, .{
1480 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_BRANCH26),
1481 .target = .{ .sym_index = stub_helper_preamble_atom_sym_index, .file = null },
1576 .type = .branch,
1577 .target = .{ .sym_index = stub_helper_preamble_atom_sym_index },
14821578 .offset = 4,
14831579 .addend = 0,
14841580 .pcrel = true,
......@@ -1505,12 +1601,8 @@ fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, target: SymbolWithLo
15051601 sym.n_sect = self.la_symbol_ptr_section_index.? + 1;
15061602
15071603 try Atom.addRelocation(self, atom_index, .{
1508 .type = switch (self.base.options.target.cpu.arch) {
1509 .aarch64 => @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_UNSIGNED),
1510 .x86_64 => @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_UNSIGNED),
1511 else => unreachable,
1512 },
1513 .target = .{ .sym_index = stub_sym_index, .file = null },
1604 .type = .unsigned,
1605 .target = .{ .sym_index = stub_sym_index },
15141606 .offset = 0,
15151607 .addend = 0,
15161608 .pcrel = false,
......@@ -1563,8 +1655,8 @@ fn createStubAtom(self: *MachO, laptr_sym_index: u32) !Atom.Index {
15631655 code[1] = 0x25;
15641656
15651657 try Atom.addRelocation(self, atom_index, .{
1566 .type = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_BRANCH),
1567 .target = .{ .sym_index = laptr_sym_index, .file = null },
1658 .type = .branch,
1659 .target = .{ .sym_index = laptr_sym_index },
15681660 .offset = 2,
15691661 .addend = 0,
15701662 .pcrel = true,
......@@ -1583,18 +1675,18 @@ fn createStubAtom(self: *MachO, laptr_sym_index: u32) !Atom.Index {
15831675 // br x16
15841676 mem.writeIntLittle(u32, code[8..12], aarch64.Instruction.br(.x16).toU32());
15851677
1586 try Atom.addRelocations(self, atom_index, 2, .{
1678 try Atom.addRelocations(self, atom_index, &[_]Relocation{
15871679 .{
1588 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGE21),
1589 .target = .{ .sym_index = laptr_sym_index, .file = null },
1680 .type = .page,
1681 .target = .{ .sym_index = laptr_sym_index },
15901682 .offset = 0,
15911683 .addend = 0,
15921684 .pcrel = true,
15931685 .length = 2,
15941686 },
15951687 .{
1596 .type = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGEOFF12),
1597 .target = .{ .sym_index = laptr_sym_index, .file = null },
1688 .type = .pageoff,
1689 .target = .{ .sym_index = laptr_sym_index },
15981690 .offset = 4,
15991691 .addend = 0,
16001692 .pcrel = false,
......@@ -1612,6 +1704,42 @@ fn createStubAtom(self: *MachO, laptr_sym_index: u32) !Atom.Index {
16121704 return atom_index;
16131705}
16141706
1707fn createThreadLocalDescriptorAtom(self: *MachO, target: SymbolWithLoc) !Atom.Index {
1708 const gpa = self.base.allocator;
1709 const size = 3 * @sizeOf(u64);
1710 const required_alignment: u32 = 1;
1711 const atom_index = try self.createAtom();
1712 self.getAtomPtr(atom_index).size = size;
1713
1714 const target_sym_name = self.getSymbolName(target);
1715 const name_delimiter = mem.indexOf(u8, target_sym_name, "$").?;
1716 const sym_name = try gpa.dupe(u8, target_sym_name[0..name_delimiter]);
1717 defer gpa.free(sym_name);
1718
1719 const sym = self.getAtom(atom_index).getSymbolPtr(self);
1720 sym.n_type = macho.N_SECT;
1721 sym.n_sect = self.thread_vars_section_index.? + 1;
1722 sym.n_strx = try self.strtab.insert(gpa, sym_name);
1723 sym.n_value = try self.allocateAtom(atom_index, size, required_alignment);
1724
1725 log.debug("allocated threadlocal descriptor atom '{s}' at 0x{x}", .{ sym_name, sym.n_value });
1726
1727 try Atom.addRelocation(self, atom_index, .{
1728 .type = .tlv_initializer,
1729 .target = target,
1730 .offset = 0x10,
1731 .addend = 0,
1732 .pcrel = false,
1733 .length = 3,
1734 });
1735
1736 var code: [size]u8 = undefined;
1737 mem.set(u8, &code, 0);
1738 try self.writeAtom(atom_index, &code);
1739
1740 return atom_index;
1741}
1742
16151743fn createMhExecuteHeaderSymbol(self: *MachO) !void {
16161744 if (self.base.options.output_mode != .Exe) return;
16171745 if (self.getGlobal("__mh_execute_header")) |global| {
......@@ -1760,12 +1888,9 @@ pub fn deinit(self: *MachO) void {
17601888 d_sym.deinit();
17611889 }
17621890
1763 self.got_entries.deinit(gpa);
1764 self.got_entries_free_list.deinit(gpa);
1765 self.got_entries_table.deinit(gpa);
1766 self.stubs.deinit(gpa);
1767 self.stubs_free_list.deinit(gpa);
1891 self.got_table.deinit(gpa);
17681892 self.stubs_table.deinit(gpa);
1893 self.tlv_table.deinit(gpa);
17691894 self.strtab.deinit(gpa);
17701895
17711896 self.locals.deinit(gpa);
......@@ -1898,20 +2023,10 @@ fn freeAtom(self: *MachO, atom_index: Atom.Index) void {
18982023 self.locals_free_list.append(gpa, sym_index) catch {};
18992024
19002025 // Try freeing GOT atom if this decl had one
1901 const got_target = SymbolWithLoc{ .sym_index = sym_index, .file = null };
1902 if (self.got_entries_table.get(got_target)) |got_index| {
1903 self.got_entries_free_list.append(gpa, @intCast(u32, got_index)) catch {};
1904 self.got_entries.items[got_index] = .{
1905 .target = .{ .sym_index = 0, .file = null },
1906 .sym_index = 0,
1907 };
1908 _ = self.got_entries_table.remove(got_target);
1909
1910 if (self.d_sym) |*d_sym| {
1911 d_sym.swapRemoveRelocs(sym_index);
1912 }
2026 self.got_table.freeEntry(gpa, .{ .sym_index = sym_index });
19132027
1914 log.debug(" adding GOT index {d} to free list (target local@{d})", .{ got_index, sym_index });
2028 if (self.d_sym) |*d_sym| {
2029 d_sym.swapRemoveRelocs(sym_index);
19152030 }
19162031
19172032 self.locals.items[sym_index].n_type = 0;
......@@ -1986,70 +2101,34 @@ fn allocateGlobal(self: *MachO) !u32 {
19862101 return index;
19872102}
19882103
1989fn allocateGotEntry(self: *MachO, target: SymbolWithLoc) !u32 {
1990 const gpa = self.base.allocator;
1991 try self.got_entries.ensureUnusedCapacity(gpa, 1);
1992
1993 const index = blk: {
1994 if (self.got_entries_free_list.popOrNull()) |index| {
1995 log.debug(" (reusing GOT entry index {d})", .{index});
1996 break :blk index;
1997 } else {
1998 log.debug(" (allocating GOT entry at index {d})", .{self.got_entries.items.len});
1999 const index = @intCast(u32, self.got_entries.items.len);
2000 _ = self.got_entries.addOneAssumeCapacity();
2001 break :blk index;
2002 }
2003 };
2004
2005 self.got_entries.items[index] = .{ .target = target, .sym_index = 0 };
2006 try self.got_entries_table.putNoClobber(gpa, target, index);
2007
2008 return index;
2009}
2010
20112104fn addGotEntry(self: *MachO, target: SymbolWithLoc) !void {
2012 if (self.got_entries_table.contains(target)) return;
2013
2014 const got_index = try self.allocateGotEntry(target);
2105 if (self.got_table.lookup.contains(target)) return;
2106 const got_index = try self.got_table.allocateEntry(self.base.allocator, target);
20152107 const got_atom_index = try self.createGotAtom(target);
20162108 const got_atom = self.getAtom(got_atom_index);
2017 self.got_entries.items[got_index].sym_index = got_atom.getSymbolIndex().?;
2018 try self.writePtrWidthAtom(got_atom_index);
2019}
2020
2021fn allocateStubEntry(self: *MachO, target: SymbolWithLoc) !u32 {
2022 try self.stubs.ensureUnusedCapacity(self.base.allocator, 1);
2023
2024 const index = blk: {
2025 if (self.stubs_free_list.popOrNull()) |index| {
2026 log.debug(" (reusing stub entry index {d})", .{index});
2027 break :blk index;
2028 } else {
2029 log.debug(" (allocating stub entry at index {d})", .{self.stubs.items.len});
2030 const index = @intCast(u32, self.stubs.items.len);
2031 _ = self.stubs.addOneAssumeCapacity();
2032 break :blk index;
2033 }
2034 };
2035
2036 self.stubs.items[index] = .{ .target = target, .sym_index = 0 };
2037 try self.stubs_table.putNoClobber(self.base.allocator, target, index);
2038
2039 return index;
2109 self.got_table.entries.items[got_index].sym_index = got_atom.getSymbolIndex().?;
2110 self.markRelocsDirtyByTarget(target);
20402111}
20412112
20422113fn addStubEntry(self: *MachO, target: SymbolWithLoc) !void {
2043 if (self.stubs_table.contains(target)) return;
2044
2045 const stub_index = try self.allocateStubEntry(target);
2114 if (self.stubs_table.lookup.contains(target)) return;
2115 const stub_index = try self.stubs_table.allocateEntry(self.base.allocator, target);
20462116 const stub_helper_atom_index = try self.createStubHelperAtom();
20472117 const stub_helper_atom = self.getAtom(stub_helper_atom_index);
20482118 const laptr_atom_index = try self.createLazyPointerAtom(stub_helper_atom.getSymbolIndex().?, target);
20492119 const laptr_atom = self.getAtom(laptr_atom_index);
20502120 const stub_atom_index = try self.createStubAtom(laptr_atom.getSymbolIndex().?);
20512121 const stub_atom = self.getAtom(stub_atom_index);
2052 self.stubs.items[stub_index].sym_index = stub_atom.getSymbolIndex().?;
2122 self.stubs_table.entries.items[stub_index].sym_index = stub_atom.getSymbolIndex().?;
2123 self.markRelocsDirtyByTarget(target);
2124}
2125
2126fn addTlvEntry(self: *MachO, target: SymbolWithLoc) !void {
2127 if (self.tlv_table.lookup.contains(target)) return;
2128 const tlv_index = try self.tlv_table.allocateEntry(self.base.allocator, target);
2129 const tlv_atom_index = try self.createThreadLocalDescriptorAtom(target);
2130 const tlv_atom = self.getAtom(tlv_atom_index);
2131 self.tlv_table.entries.items[tlv_index].sym_index = tlv_atom.getSymbolIndex().?;
20532132 self.markRelocsDirtyByTarget(target);
20542133}
20552134
......@@ -2070,8 +2149,6 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv
20702149 self.freeUnnamedConsts(decl_index);
20712150 Atom.freeRelocations(self, atom_index);
20722151
2073 const atom = self.getAtom(atom_index);
2074
20752152 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
20762153 defer code_buffer.deinit();
20772154
......@@ -2100,7 +2177,13 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv
21002177 const addr = try self.updateDeclCode(decl_index, code);
21012178
21022179 if (decl_state) |*ds| {
2103 try self.d_sym.?.dwarf.commitDeclState(module, decl_index, addr, atom.size, ds);
2180 try self.d_sym.?.dwarf.commitDeclState(
2181 module,
2182 decl_index,
2183 addr,
2184 self.getAtom(atom_index).size,
2185 ds,
2186 );
21042187 }
21052188
21062189 // Since we updated the vaddr and the size, each corresponding export symbol also
......@@ -2196,8 +2279,8 @@ pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index)
21962279 }
21972280
21982281 const atom_index = try self.getOrCreateAtomForDecl(decl_index);
2282 const sym_index = self.getAtom(atom_index).getSymbolIndex().?;
21992283 Atom.freeRelocations(self, atom_index);
2200 const atom = self.getAtom(atom_index);
22012284
22022285 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
22032286 defer code_buffer.deinit();
......@@ -2216,14 +2299,14 @@ pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index)
22162299 }, &code_buffer, .{
22172300 .dwarf = ds,
22182301 }, .{
2219 .parent_atom_index = atom.getSymbolIndex().?,
2302 .parent_atom_index = sym_index,
22202303 })
22212304 else
22222305 try codegen.generateSymbol(&self.base, decl.srcLoc(), .{
22232306 .ty = decl.ty,
22242307 .val = decl_val,
22252308 }, &code_buffer, .none, .{
2226 .parent_atom_index = atom.getSymbolIndex().?,
2309 .parent_atom_index = sym_index,
22272310 });
22282311
22292312 var code = switch (res) {
......@@ -2237,7 +2320,13 @@ pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index)
22372320 const addr = try self.updateDeclCode(decl_index, code);
22382321
22392322 if (decl_state) |*ds| {
2240 try self.d_sym.?.dwarf.commitDeclState(module, decl_index, addr, atom.size, ds);
2323 try self.d_sym.?.dwarf.commitDeclState(
2324 module,
2325 decl_index,
2326 addr,
2327 self.getAtom(atom_index).size,
2328 ds,
2329 );
22412330 }
22422331
22432332 // Since we updated the vaddr and the size, each corresponding export symbol also
......@@ -2322,7 +2411,6 @@ fn updateLazySymbolAtom(
23222411 symbol.n_value = vaddr;
23232412
23242413 try self.addGotEntry(.{ .sym_index = local_sym_index });
2325 self.markRelocsDirtyByTarget(atom.getSymbolWithLoc());
23262414 try self.writeAtom(atom_index, code);
23272415}
23282416
......@@ -2356,6 +2444,7 @@ fn getDeclOutputSection(self: *MachO, decl_index: Module.Decl.Index) u8 {
23562444 const val = decl.val;
23572445 const zig_ty = ty.zigTypeTag();
23582446 const mode = self.base.options.optimize_mode;
2447 const single_threaded = self.base.options.single_threaded;
23592448 const sect_id: u8 = blk: {
23602449 // TODO finish and audit this function
23612450 if (val.isUndefDeep()) {
......@@ -2366,7 +2455,10 @@ fn getDeclOutputSection(self: *MachO, decl_index: Module.Decl.Index) u8 {
23662455 }
23672456 }
23682457
2369 if (val.castTag(.variable)) |_| {
2458 if (val.castTag(.variable)) |variable| {
2459 if (variable.data.is_threadlocal and !single_threaded) {
2460 break :blk self.thread_data_section_index.?;
2461 }
23702462 break :blk self.data_section_index.?;
23712463 }
23722464
......@@ -2391,16 +2483,28 @@ fn updateDeclCode(self: *MachO, decl_index: Module.Decl.Index, code: []u8) !u64
23912483
23922484 const required_alignment = decl.getAlignment(self.base.options.target);
23932485
2394 const sym_name = try decl.getFullyQualifiedName(mod);
2395 defer self.base.allocator.free(sym_name);
2486 const decl_name = try decl.getFullyQualifiedName(mod);
2487 defer gpa.free(decl_name);
23962488
23972489 const decl_metadata = self.decls.get(decl_index).?;
23982490 const atom_index = decl_metadata.atom;
23992491 const atom = self.getAtom(atom_index);
24002492 const sym_index = atom.getSymbolIndex().?;
24012493 const sect_id = decl_metadata.section;
2494 const header = &self.sections.items(.header)[sect_id];
2495 const segment = self.getSegment(sect_id);
2496 const is_threadlocal = if (!self.base.options.single_threaded)
2497 header.flags == macho.S_THREAD_LOCAL_REGULAR or header.flags == macho.S_THREAD_LOCAL_ZEROFILL
2498 else
2499 false;
24022500 const code_len = code.len;
24032501
2502 const sym_name = if (is_threadlocal)
2503 try std.fmt.allocPrint(gpa, "{s}$tlv$init", .{decl_name})
2504 else
2505 decl_name;
2506 defer if (is_threadlocal) gpa.free(sym_name);
2507
24042508 if (atom.size != 0) {
24052509 const sym = atom.getSymbolPtr(self);
24062510 sym.n_strx = try self.strtab.insert(gpa, sym_name);
......@@ -2418,25 +2522,29 @@ fn updateDeclCode(self: *MachO, decl_index: Module.Decl.Index, code: []u8) !u64
24182522
24192523 if (vaddr != sym.n_value) {
24202524 sym.n_value = vaddr;
2525 // TODO: I think we should update the offset to the initializer here too.
2526 const target: SymbolWithLoc = if (is_threadlocal) blk: {
2527 const tlv_atom_index = self.tlv_table.getAtomIndex(self, .{
2528 .sym_index = sym_index,
2529 }).?;
2530 const tlv_atom = self.getAtom(tlv_atom_index);
2531 break :blk tlv_atom.getSymbolWithLoc();
2532 } else .{ .sym_index = sym_index };
2533 self.markRelocsDirtyByTarget(target);
24212534 log.debug(" (updating GOT entry)", .{});
2422 const got_target = SymbolWithLoc{ .sym_index = sym_index, .file = null };
2423 const got_atom_index = self.getGotAtomIndexForSymbol(got_target).?;
2424 self.markRelocsDirtyByTarget(got_target);
2535 const got_atom_index = self.got_table.getAtomIndex(self, target).?;
24252536 try self.writePtrWidthAtom(got_atom_index);
24262537 }
24272538 } else if (code_len < atom.size) {
24282539 self.shrinkAtom(atom_index, code_len);
24292540 } else if (atom.next_index == null) {
2430 const header = &self.sections.items(.header)[sect_id];
2431 const segment = self.getSegment(sect_id);
24322541 const needed_size = (sym.n_value + code_len) - segment.vmaddr;
24332542 header.size = needed_size;
24342543 }
24352544 self.getAtomPtr(atom_index).size = code_len;
24362545 } else {
2437 const name_str_index = try self.strtab.insert(gpa, sym_name);
24382546 const sym = atom.getSymbolPtr(self);
2439 sym.n_strx = name_str_index;
2547 sym.n_strx = try self.strtab.insert(gpa, sym_name);
24402548 sym.n_type = macho.N_SECT;
24412549 sym.n_sect = sect_id + 1;
24422550 sym.n_desc = 0;
......@@ -2450,10 +2558,17 @@ fn updateDeclCode(self: *MachO, decl_index: Module.Decl.Index, code: []u8) !u64
24502558 self.getAtomPtr(atom_index).size = code_len;
24512559 sym.n_value = vaddr;
24522560
2453 try self.addGotEntry(.{ .sym_index = sym_index });
2561 if (is_threadlocal) {
2562 try self.addTlvEntry(.{ .sym_index = sym_index });
2563 }
2564 const target: SymbolWithLoc = if (is_threadlocal) blk: {
2565 const tlv_atom_index = self.tlv_table.getAtomIndex(self, .{ .sym_index = sym_index }).?;
2566 const tlv_atom = self.getAtom(tlv_atom_index);
2567 break :blk tlv_atom.getSymbolWithLoc();
2568 } else .{ .sym_index = sym_index };
2569 try self.addGotEntry(target);
24542570 }
24552571
2456 self.markRelocsDirtyByTarget(atom.getSymbolWithLoc());
24572572 try self.writeAtom(atom_index, code);
24582573
24592574 return atom.getSymbol(self).n_value;
......@@ -2647,11 +2762,7 @@ pub fn getDeclVAddr(self: *MachO, decl_index: Module.Decl.Index, reloc_info: Fil
26472762 const sym_index = self.getAtom(this_atom_index).getSymbolIndex().?;
26482763 const atom_index = self.getAtomIndexForSymbol(.{ .sym_index = reloc_info.parent_atom_index, .file = null }).?;
26492764 try Atom.addRelocation(self, atom_index, .{
2650 .type = switch (self.base.options.target.cpu.arch) {
2651 .aarch64 => @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_UNSIGNED),
2652 .x86_64 => @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_UNSIGNED),
2653 else => unreachable,
2654 },
2765 .type = .unsigned,
26552766 .target = .{ .sym_index = sym_index, .file = null },
26562767 .offset = @intCast(u32, reloc_info.offset),
26572768 .addend = reloc_info.addend,
......@@ -2790,6 +2901,28 @@ fn populateMissingMetadata(self: *MachO) !void {
27902901 self.segment_table_dirty = true;
27912902 }
27922903
2904 if (!self.base.options.single_threaded) {
2905 if (self.thread_vars_section_index == null) {
2906 self.thread_vars_section_index = try self.allocateSection("__DATA2", "__thread_vars", .{
2907 .size = @sizeOf(u64) * 3,
2908 .alignment = @sizeOf(u64),
2909 .flags = macho.S_THREAD_LOCAL_VARIABLES,
2910 .prot = macho.PROT.READ | macho.PROT.WRITE,
2911 });
2912 self.segment_table_dirty = true;
2913 }
2914
2915 if (self.thread_data_section_index == null) {
2916 self.thread_data_section_index = try self.allocateSection("__DATA3", "__thread_data", .{
2917 .size = @sizeOf(u64),
2918 .alignment = @alignOf(u64),
2919 .flags = macho.S_THREAD_LOCAL_REGULAR,
2920 .prot = macho.PROT.READ | macho.PROT.WRITE,
2921 });
2922 self.segment_table_dirty = true;
2923 }
2924 }
2925
27932926 if (self.linkedit_segment_cmd_index == null) {
27942927 self.linkedit_segment_cmd_index = @intCast(u8, self.segments.items.len);
27952928
......@@ -3077,28 +3210,6 @@ fn allocateAtom(self: *MachO, atom_index: Atom.Index, new_atom_size: u64, alignm
30773210 return vaddr;
30783211}
30793212
3080fn getSectionPrecedence(header: macho.section_64) u4 {
3081 if (header.isCode()) {
3082 if (mem.eql(u8, "__text", header.sectName())) return 0x0;
3083 if (header.type() == macho.S_SYMBOL_STUBS) return 0x1;
3084 return 0x2;
3085 }
3086 switch (header.type()) {
3087 macho.S_NON_LAZY_SYMBOL_POINTERS,
3088 macho.S_LAZY_SYMBOL_POINTERS,
3089 => return 0x0,
3090 macho.S_MOD_INIT_FUNC_POINTERS => return 0x1,
3091 macho.S_MOD_TERM_FUNC_POINTERS => return 0x2,
3092 macho.S_ZEROFILL => return 0xf,
3093 macho.S_THREAD_LOCAL_REGULAR => return 0xd,
3094 macho.S_THREAD_LOCAL_ZEROFILL => return 0xe,
3095 else => if (mem.eql(u8, "__eh_frame", header.sectName()))
3096 return 0xf
3097 else
3098 return 0x3,
3099 }
3100}
3101
31023213pub fn getGlobalSymbol(self: *MachO, name: []const u8, lib_name: ?[]const u8) !u32 {
31033214 _ = lib_name;
31043215 const gpa = self.base.allocator;
......@@ -3474,8 +3585,8 @@ const SymtabCtx = struct {
34743585
34753586fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void {
34763587 const gpa = self.base.allocator;
3477 const nstubs = @intCast(u32, self.stubs_table.count());
3478 const ngot_entries = @intCast(u32, self.got_entries_table.count());
3588 const nstubs = @intCast(u32, self.stubs_table.lookup.count());
3589 const ngot_entries = @intCast(u32, self.got_table.lookup.count());
34793590 const nindirectsyms = nstubs * 2 + ngot_entries;
34803591 const iextdefsym = ctx.nlocalsym;
34813592 const iundefsym = iextdefsym + ctx.nextdefsym;
......@@ -3497,7 +3608,7 @@ fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void {
34973608 if (self.stubs_section_index) |sect_id| {
34983609 const stubs = &self.sections.items(.header)[sect_id];
34993610 stubs.reserved1 = 0;
3500 for (self.stubs.items) |entry| {
3611 for (self.stubs_table.entries.items) |entry| {
35013612 if (entry.sym_index == 0) continue;
35023613 const target_sym = self.getSymbol(entry.target);
35033614 assert(target_sym.undf());
......@@ -3508,7 +3619,7 @@ fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void {
35083619 if (self.got_section_index) |sect_id| {
35093620 const got = &self.sections.items(.header)[sect_id];
35103621 got.reserved1 = nstubs;
3511 for (self.got_entries.items) |entry| {
3622 for (self.got_table.entries.items) |entry| {
35123623 if (entry.sym_index == 0) continue;
35133624 const target_sym = self.getSymbol(entry.target);
35143625 if (target_sym.undf()) {
......@@ -3522,7 +3633,7 @@ fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void {
35223633 if (self.la_symbol_ptr_section_index) |sect_id| {
35233634 const la_symbol_ptr = &self.sections.items(.header)[sect_id];
35243635 la_symbol_ptr.reserved1 = nstubs + ngot_entries;
3525 for (self.stubs.items) |entry| {
3636 for (self.stubs_table.entries.items) |entry| {
35263637 if (entry.sym_index == 0) continue;
35273638 const target_sym = self.getSymbol(entry.target);
35283639 assert(target_sym.undf());
......@@ -3593,6 +3704,10 @@ fn writeHeader(self: *MachO, ncmds: u32, sizeofcmds: u32) !void {
35933704 var header: macho.mach_header_64 = .{};
35943705 header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL;
35953706
3707 if (!self.base.options.single_threaded) {
3708 header.flags |= macho.MH_HAS_TLV_DESCRIPTORS;
3709 }
3710
35963711 switch (self.base.options.target.cpu.arch) {
35973712 .aarch64 => {
35983713 header.cputype = macho.CPU_TYPE_ARM64;
......@@ -3617,12 +3732,6 @@ fn writeHeader(self: *MachO, ncmds: u32, sizeofcmds: u32) !void {
36173732 else => unreachable,
36183733 }
36193734
3620 if (self.getSectionByName("__DATA", "__thread_vars")) |sect_id| {
3621 if (self.sections.items(.header)[sect_id].size > 0) {
3622 header.flags |= macho.MH_HAS_TLV_DESCRIPTORS;
3623 }
3624 }
3625
36263735 header.ncmds = ncmds;
36273736 header.sizeofcmds = sizeofcmds;
36283737
......@@ -3802,8 +3911,7 @@ pub fn getSymbol(self: *const MachO, sym_with_loc: SymbolWithLoc) macho.nlist_64
38023911
38033912/// Returns name of the symbol described by `sym_with_loc` descriptor.
38043913pub fn getSymbolName(self: *const MachO, sym_with_loc: SymbolWithLoc) []const u8 {
3805 assert(sym_with_loc.file == null);
3806 const sym = self.locals.items[sym_with_loc.sym_index];
3914 const sym = self.getSymbol(sym_with_loc);
38073915 return self.strtab.get(sym.n_strx).?;
38083916}
38093917
......@@ -3867,20 +3975,6 @@ pub fn getAtomIndexForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?Atom.In
38673975 return self.atom_by_index_table.get(sym_with_loc.sym_index);
38683976}
38693977
3870/// Returns GOT atom that references `sym_with_loc` if one exists.
3871/// Returns null otherwise.
3872pub fn getGotAtomIndexForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?Atom.Index {
3873 const got_index = self.got_entries_table.get(sym_with_loc) orelse return null;
3874 return self.got_entries.items[got_index].getAtomIndex(self);
3875}
3876
3877/// Returns stubs atom that references `sym_with_loc` if one exists.
3878/// Returns null otherwise.
3879pub fn getStubsAtomIndexForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?Atom.Index {
3880 const stubs_index = self.stubs_table.get(sym_with_loc) orelse return null;
3881 return self.stubs.items[stubs_index].getAtomIndex(self);
3882}
3883
38843978/// Returns symbol location corresponding to the set entrypoint.
38853979/// Asserts output mode is executable.
38863980pub fn getEntryPoint(self: MachO) error{MissingMainEntrypoint}!SymbolWithLoc {
......@@ -4227,37 +4321,13 @@ pub fn logSymtab(self: *MachO) void {
42274321 }
42284322
42294323 log.debug("GOT entries:", .{});
4230 for (self.got_entries.items, 0..) |entry, i| {
4231 const atom_sym = entry.getSymbol(self);
4232 const target_sym = self.getSymbol(entry.target);
4233 if (target_sym.undf()) {
4234 log.debug(" {d}@{x} => import('{s}')", .{
4235 i,
4236 atom_sym.n_value,
4237 self.getSymbolName(entry.target),
4238 });
4239 } else {
4240 log.debug(" {d}@{x} => local(%{d}) in object({?d}) {s}", .{
4241 i,
4242 atom_sym.n_value,
4243 entry.target.sym_index,
4244 entry.target.file,
4245 logSymAttributes(target_sym, &buf),
4246 });
4247 }
4248 }
4324 log.debug("{}", .{self.got_table.fmtDebug(self)});
42494325
42504326 log.debug("stubs entries:", .{});
4251 for (self.stubs.items, 0..) |entry, i| {
4252 const target_sym = self.getSymbol(entry.target);
4253 const atom_sym = entry.getSymbol(self);
4254 assert(target_sym.undf());
4255 log.debug(" {d}@{x} => import('{s}')", .{
4256 i,
4257 atom_sym.n_value,
4258 self.getSymbolName(entry.target),
4259 });
4260 }
4327 log.debug("{}", .{self.stubs_table.fmtDebug(self)});
4328
4329 log.debug("threadlocal entries:", .{});
4330 log.debug("{}", .{self.tlv_table.fmtDebug(self)});
42614331}
42624332
42634333pub fn logAtoms(self: *MachO) void {
src/link/MachO/Atom.zig+5-11
......@@ -14,7 +14,7 @@ const trace = @import("../../tracy.zig").trace;
1414const Allocator = mem.Allocator;
1515const Arch = std.Target.Cpu.Arch;
1616const MachO = @import("../MachO.zig");
17const Relocation = @import("Relocation.zig");
17pub const Relocation = @import("Relocation.zig");
1818const SymbolWithLoc = MachO.SymbolWithLoc;
1919
2020/// Each decl always gets a local symbol with the fully qualified name.
......@@ -113,25 +113,19 @@ pub fn freeListEligible(self: Atom, macho_file: *MachO) bool {
113113}
114114
115115pub fn addRelocation(macho_file: *MachO, atom_index: Index, reloc: Relocation) !void {
116 return addRelocations(macho_file, atom_index, 1, .{reloc});
116 return addRelocations(macho_file, atom_index, &[_]Relocation{reloc});
117117}
118118
119pub fn addRelocations(
120 macho_file: *MachO,
121 atom_index: Index,
122 comptime count: comptime_int,
123 relocs: [count]Relocation,
124) !void {
119pub fn addRelocations(macho_file: *MachO, atom_index: Index, relocs: []Relocation) !void {
125120 const gpa = macho_file.base.allocator;
126 const target = macho_file.base.options.target;
127121 const gop = try macho_file.relocs.getOrPut(gpa, atom_index);
128122 if (!gop.found_existing) {
129123 gop.value_ptr.* = .{};
130124 }
131 try gop.value_ptr.ensureUnusedCapacity(gpa, count);
125 try gop.value_ptr.ensureUnusedCapacity(gpa, relocs.len);
132126 for (relocs) |reloc| {
133127 log.debug(" (adding reloc of type {s} to target %{d})", .{
134 reloc.fmtType(target),
128 @tagName(reloc.type),
135129 reloc.target.sym_index,
136130 });
137131 gop.value_ptr.appendAssumeCapacity(reloc);
src/link/MachO/DebugSymbols.zig+6-12
......@@ -226,26 +226,20 @@ pub fn flushModule(self: *DebugSymbols, macho_file: *MachO) !void {
226226
227227 for (self.relocs.items) |*reloc| {
228228 const sym = switch (reloc.type) {
229 .direct_load => macho_file.getSymbol(.{ .sym_index = reloc.target, .file = null }),
229 .direct_load => macho_file.getSymbol(.{ .sym_index = reloc.target }),
230230 .got_load => blk: {
231 const got_index = macho_file.got_entries_table.get(.{
232 .sym_index = reloc.target,
233 .file = null,
234 }).?;
235 const got_entry = macho_file.got_entries.items[got_index];
231 const got_index = macho_file.got_table.lookup.get(.{ .sym_index = reloc.target }).?;
232 const got_entry = macho_file.got_table.entries.items[got_index];
236233 break :blk got_entry.getSymbol(macho_file);
237234 },
238235 };
239236 if (sym.n_value == reloc.prev_vaddr) continue;
240237
241238 const sym_name = switch (reloc.type) {
242 .direct_load => macho_file.getSymbolName(.{ .sym_index = reloc.target, .file = null }),
239 .direct_load => macho_file.getSymbolName(.{ .sym_index = reloc.target }),
243240 .got_load => blk: {
244 const got_index = macho_file.got_entries_table.get(.{
245 .sym_index = reloc.target,
246 .file = null,
247 }).?;
248 const got_entry = macho_file.got_entries.items[got_index];
241 const got_index = macho_file.got_table.lookup.get(.{ .sym_index = reloc.target }).?;
242 const got_entry = macho_file.got_table.entries.items[got_index];
249243 break :blk got_entry.getName(macho_file);
250244 },
251245 };
src/link/MachO/Relocation.zig+93-143
......@@ -1,19 +1,7 @@
1const Relocation = @This();
1//! Relocation used by the self-hosted backends to instruct the linker where and how to
2//! fixup the values when flushing the contents to file and/or memory.
23
3const std = @import("std");
4const aarch64 = @import("../../arch/aarch64/bits.zig");
5const assert = std.debug.assert;
6const log = std.log.scoped(.link);
7const macho = std.macho;
8const math = std.math;
9const mem = std.mem;
10const meta = std.meta;
11
12const Atom = @import("Atom.zig");
13const MachO = @import("../MachO.zig");
14const SymbolWithLoc = MachO.SymbolWithLoc;
15
16type: u4,
4type: Type,
175target: SymbolWithLoc,
186offset: u32,
197addend: i64,
......@@ -21,39 +9,55 @@ pcrel: bool,
219length: u2,
2210dirty: bool = true,
2311
12pub const Type = enum {
13 // x86, x86_64
14 /// RIP-relative displacement to a GOT pointer
15 got,
16 /// RIP-relative displacement
17 signed,
18 /// RIP-relative displacement to GOT pointer to TLV thunk
19 tlv,
20
21 // aarch64
22 /// PC-relative distance to target page in GOT section
23 got_page,
24 /// Offset to a GOT pointer relative to the start of a page in GOT section
25 got_pageoff,
26 /// PC-relative distance to target page in a section
27 page,
28 /// Offset to a pointer relative to the start of a page in a section
29 pageoff,
30
31 // common
32 /// PC/RIP-relative displacement B/BL/CALL
33 branch,
34 /// Absolute pointer value
35 unsigned,
36 /// Relative offset to TLV initializer
37 tlv_initializer,
38};
39
2440/// Returns true if and only if the reloc is dirty AND the target address is available.
2541pub fn isResolvable(self: Relocation, macho_file: *MachO) bool {
2642 _ = self.getTargetAtomIndex(macho_file) orelse return false;
2743 return self.dirty;
2844}
2945
30pub fn fmtType(self: Relocation, target: std.Target) []const u8 {
31 switch (target.cpu.arch) {
32 .aarch64 => return @tagName(@intToEnum(macho.reloc_type_arm64, self.type)),
33 .x86_64 => return @tagName(@intToEnum(macho.reloc_type_x86_64, self.type)),
34 else => unreachable,
35 }
36}
37
3846pub fn getTargetAtomIndex(self: Relocation, macho_file: *MachO) ?Atom.Index {
39 switch (macho_file.base.options.target.cpu.arch) {
40 .aarch64 => switch (@intToEnum(macho.reloc_type_arm64, self.type)) {
41 .ARM64_RELOC_GOT_LOAD_PAGE21,
42 .ARM64_RELOC_GOT_LOAD_PAGEOFF12,
43 .ARM64_RELOC_POINTER_TO_GOT,
44 => return macho_file.getGotAtomIndexForSymbol(self.target),
45 else => {},
47 return switch (self.type) {
48 .got, .got_page, .got_pageoff => macho_file.got_table.getAtomIndex(macho_file, self.target),
49 .tlv => {
50 const thunk_atom_index = macho_file.tlv_table.getAtomIndex(macho_file, self.target) orelse
51 return null;
52 const thunk_atom = macho_file.getAtom(thunk_atom_index);
53 return macho_file.got_table.getAtomIndex(macho_file, thunk_atom.getSymbolWithLoc());
4654 },
47 .x86_64 => switch (@intToEnum(macho.reloc_type_x86_64, self.type)) {
48 .X86_64_RELOC_GOT,
49 .X86_64_RELOC_GOT_LOAD,
50 => return macho_file.getGotAtomIndexForSymbol(self.target),
51 else => {},
52 },
53 else => unreachable,
54 }
55 if (macho_file.getStubsAtomIndexForSymbol(self.target)) |stubs_atom| return stubs_atom;
56 return macho_file.getAtomIndexForSymbol(self.target);
55 .branch => if (macho_file.stubs_table.getAtomIndex(macho_file, self.target)) |index|
56 index
57 else
58 macho_file.getAtomIndexForSymbol(self.target),
59 else => macho_file.getAtomIndexForSymbol(self.target),
60 };
5761}
5862
5963pub fn resolve(self: Relocation, macho_file: *MachO, atom_index: Atom.Index, code: []u8) void {
......@@ -64,13 +68,22 @@ pub fn resolve(self: Relocation, macho_file: *MachO, atom_index: Atom.Index, cod
6468
6569 const target_atom_index = self.getTargetAtomIndex(macho_file).?; // Oops, you didn't check if the relocation can be resolved with isResolvable().
6670 const target_atom = macho_file.getAtom(target_atom_index);
67 const target_addr = @intCast(i64, target_atom.getSymbol(macho_file).n_value) + self.addend;
71
72 const target_addr: i64 = switch (self.type) {
73 .tlv_initializer => blk: {
74 assert(self.addend == 0); // Addend here makes no sense.
75 const header = macho_file.sections.items(.header)[macho_file.thread_data_section_index.?];
76 const target_sym = target_atom.getSymbol(macho_file);
77 break :blk @intCast(i64, target_sym.n_value - header.addr);
78 },
79 else => @intCast(i64, target_atom.getSymbol(macho_file).n_value) + self.addend,
80 };
6881
6982 log.debug(" ({x}: [() => 0x{x} ({s})) ({s})", .{
7083 source_addr,
7184 target_addr,
7285 macho_file.getSymbolName(self.target),
73 self.fmtType(macho_file.base.options.target),
86 @tagName(self.type),
7487 });
7588
7689 switch (arch) {
......@@ -81,18 +94,9 @@ pub fn resolve(self: Relocation, macho_file: *MachO, atom_index: Atom.Index, cod
8194}
8295
8396fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: []u8) void {
84 const rel_type = @intToEnum(macho.reloc_type_arm64, self.type);
85 if (rel_type == .ARM64_RELOC_UNSIGNED) {
86 return switch (self.length) {
87 2 => mem.writeIntLittle(u32, code[self.offset..][0..4], @truncate(u32, @bitCast(u64, target_addr))),
88 3 => mem.writeIntLittle(u64, code[self.offset..][0..8], @bitCast(u64, target_addr)),
89 else => unreachable,
90 };
91 }
92
93 var buffer = code[self.offset..][0..4];
94 switch (rel_type) {
95 .ARM64_RELOC_BRANCH26 => {
97 var buffer = code[self.offset..];
98 switch (self.type) {
99 .branch => {
96100 const displacement = math.cast(
97101 i28,
98102 @intCast(i64, target_addr) - @intCast(i64, source_addr),
......@@ -101,15 +105,12 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: []
101105 .unconditional_branch_immediate = mem.bytesToValue(meta.TagPayload(
102106 aarch64.Instruction,
103107 aarch64.Instruction.unconditional_branch_immediate,
104 ), buffer),
108 ), buffer[0..4]),
105109 };
106110 inst.unconditional_branch_immediate.imm26 = @truncate(u26, @bitCast(u28, displacement >> 2));
107 mem.writeIntLittle(u32, buffer, inst.toU32());
111 mem.writeIntLittle(u32, buffer[0..4], inst.toU32());
108112 },
109 .ARM64_RELOC_PAGE21,
110 .ARM64_RELOC_GOT_LOAD_PAGE21,
111 .ARM64_RELOC_TLVP_LOAD_PAGE21,
112 => {
113 .page, .got_page => {
113114 const source_page = @intCast(i32, source_addr >> 12);
114115 const target_page = @intCast(i32, target_addr >> 12);
115116 const pages = @bitCast(u21, @intCast(i21, target_page - source_page));
......@@ -117,31 +118,29 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: []
117118 .pc_relative_address = mem.bytesToValue(meta.TagPayload(
118119 aarch64.Instruction,
119120 aarch64.Instruction.pc_relative_address,
120 ), buffer),
121 ), buffer[0..4]),
121122 };
122123 inst.pc_relative_address.immhi = @truncate(u19, pages >> 2);
123124 inst.pc_relative_address.immlo = @truncate(u2, pages);
124 mem.writeIntLittle(u32, buffer, inst.toU32());
125 mem.writeIntLittle(u32, buffer[0..4], inst.toU32());
125126 },
126 .ARM64_RELOC_PAGEOFF12,
127 .ARM64_RELOC_GOT_LOAD_PAGEOFF12,
128 => {
127 .pageoff, .got_pageoff => {
129128 const narrowed = @truncate(u12, @intCast(u64, target_addr));
130 if (isArithmeticOp(buffer)) {
129 if (isArithmeticOp(buffer[0..4])) {
131130 var inst = aarch64.Instruction{
132131 .add_subtract_immediate = mem.bytesToValue(meta.TagPayload(
133132 aarch64.Instruction,
134133 aarch64.Instruction.add_subtract_immediate,
135 ), buffer),
134 ), buffer[0..4]),
136135 };
137136 inst.add_subtract_immediate.imm12 = narrowed;
138 mem.writeIntLittle(u32, buffer, inst.toU32());
137 mem.writeIntLittle(u32, buffer[0..4], inst.toU32());
139138 } else {
140139 var inst = aarch64.Instruction{
141140 .load_store_register = mem.bytesToValue(meta.TagPayload(
142141 aarch64.Instruction,
143142 aarch64.Instruction.load_store_register,
144 ), buffer),
143 ), buffer[0..4]),
145144 };
146145 const offset: u12 = blk: {
147146 if (inst.load_store_register.size == 0) {
......@@ -157,89 +156,25 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: []
157156 }
158157 };
159158 inst.load_store_register.offset = offset;
160 mem.writeIntLittle(u32, buffer, inst.toU32());
159 mem.writeIntLittle(u32, buffer[0..4], inst.toU32());
161160 }
162161 },
163 .ARM64_RELOC_TLVP_LOAD_PAGEOFF12 => {
164 const RegInfo = struct {
165 rd: u5,
166 rn: u5,
167 size: u2,
168 };
169 const reg_info: RegInfo = blk: {
170 if (isArithmeticOp(buffer)) {
171 const inst = mem.bytesToValue(meta.TagPayload(
172 aarch64.Instruction,
173 aarch64.Instruction.add_subtract_immediate,
174 ), buffer);
175 break :blk .{
176 .rd = inst.rd,
177 .rn = inst.rn,
178 .size = inst.sf,
179 };
180 } else {
181 const inst = mem.bytesToValue(meta.TagPayload(
182 aarch64.Instruction,
183 aarch64.Instruction.load_store_register,
184 ), buffer);
185 break :blk .{
186 .rd = inst.rt,
187 .rn = inst.rn,
188 .size = inst.size,
189 };
190 }
191 };
192 const narrowed = @truncate(u12, @intCast(u64, target_addr));
193 var inst = aarch64.Instruction{
194 .add_subtract_immediate = .{
195 .rd = reg_info.rd,
196 .rn = reg_info.rn,
197 .imm12 = narrowed,
198 .sh = 0,
199 .s = 0,
200 .op = 0,
201 .sf = @truncate(u1, reg_info.size),
202 },
203 };
204 mem.writeIntLittle(u32, buffer, inst.toU32());
205 },
206 .ARM64_RELOC_POINTER_TO_GOT => {
207 const result = @intCast(i32, @intCast(i64, target_addr) - @intCast(i64, source_addr));
208 mem.writeIntLittle(i32, buffer, result);
162 .tlv_initializer, .unsigned => switch (self.length) {
163 2 => mem.writeIntLittle(u32, buffer[0..4], @truncate(u32, @bitCast(u64, target_addr))),
164 3 => mem.writeIntLittle(u64, buffer[0..8], @bitCast(u64, target_addr)),
165 else => unreachable,
209166 },
210 .ARM64_RELOC_SUBTRACTOR => unreachable,
211 .ARM64_RELOC_ADDEND => unreachable,
212 .ARM64_RELOC_UNSIGNED => unreachable,
167 .got, .signed, .tlv => unreachable, // Invalid target architecture.
213168 }
214169}
215170
216171fn resolveX8664(self: Relocation, source_addr: u64, target_addr: i64, code: []u8) void {
217 const rel_type = @intToEnum(macho.reloc_type_x86_64, self.type);
218 switch (rel_type) {
219 .X86_64_RELOC_BRANCH,
220 .X86_64_RELOC_GOT,
221 .X86_64_RELOC_GOT_LOAD,
222 .X86_64_RELOC_TLV,
223 => {
172 switch (self.type) {
173 .branch, .got, .tlv, .signed => {
224174 const displacement = @intCast(i32, @intCast(i64, target_addr) - @intCast(i64, source_addr) - 4);
225175 mem.writeIntLittle(u32, code[self.offset..][0..4], @bitCast(u32, displacement));
226176 },
227 .X86_64_RELOC_SIGNED,
228 .X86_64_RELOC_SIGNED_1,
229 .X86_64_RELOC_SIGNED_2,
230 .X86_64_RELOC_SIGNED_4,
231 => {
232 const correction: u3 = switch (rel_type) {
233 .X86_64_RELOC_SIGNED => 0,
234 .X86_64_RELOC_SIGNED_1 => 1,
235 .X86_64_RELOC_SIGNED_2 => 2,
236 .X86_64_RELOC_SIGNED_4 => 4,
237 else => unreachable,
238 };
239 const displacement = @intCast(i32, target_addr - @intCast(i64, source_addr + correction + 4));
240 mem.writeIntLittle(u32, code[self.offset..][0..4], @bitCast(u32, displacement));
241 },
242 .X86_64_RELOC_UNSIGNED => {
177 .tlv_initializer, .unsigned => {
243178 switch (self.length) {
244179 2 => {
245180 mem.writeIntLittle(u32, code[self.offset..][0..4], @truncate(u32, @bitCast(u64, target_addr)));
......@@ -250,7 +185,7 @@ fn resolveX8664(self: Relocation, source_addr: u64, target_addr: i64, code: []u8
250185 else => unreachable,
251186 }
252187 },
253 .X86_64_RELOC_SUBTRACTOR => unreachable,
188 .got_page, .got_pageoff, .page, .pageoff => unreachable, // Invalid target architecture.
254189 }
255190}
256191
......@@ -258,3 +193,18 @@ inline fn isArithmeticOp(inst: *const [4]u8) bool {
258193 const group_decode = @truncate(u5, inst[3]);
259194 return ((group_decode >> 2) == 4);
260195}
196
197const Relocation = @This();
198
199const std = @import("std");
200const aarch64 = @import("../../arch/aarch64/bits.zig");
201const assert = std.debug.assert;
202const log = std.log.scoped(.link);
203const macho = std.macho;
204const math = std.math;
205const mem = std.mem;
206const meta = std.meta;
207
208const Atom = @import("Atom.zig");
209const MachO = @import("../MachO.zig");
210const SymbolWithLoc = MachO.SymbolWithLoc;