From 7e27ab09476870e4b37a04172043c66b4bd77c20 Mon Sep 17 00:00:00 2001 From: Jakub Konka Date: Sun, 28 Nov 2021 20:35:00 +0100 Subject: [PATCH 1/2] macho: fix parsing addend for non-extern SIGNED_X reloc If `r_extern == 0` (the relocation is non-extern, meaning it targets a specific memory offset within the object's section) and if the relocation type signifies that the relocation requires correction for RIP such as SIGNED_1, then we need to subtract the correction, here 1 for SIGNED_1, from the calculated addend value as it's implicitly included. --- src/link/MachO/Atom.zig | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/link/MachO/Atom.zig b/src/link/MachO/Atom.zig index b189cc7eea..3fbb26d79f 100644 --- a/src/link/MachO/Atom.zig +++ b/src/link/MachO/Atom.zig @@ -437,9 +437,11 @@ pub fn parseRelocs(self: *Atom, relocs: []macho.relocation_info, context: RelocC }; addend = mem.readIntLittle(i32, self.code.items[offset..][0..4]) + correction; if (rel.r_extern == 0) { + // Note for the future self: when r_extern == 0, we should subtract correction from the + // addend. const seg = context.object.load_commands.items[context.object.segment_cmd_index.?].Segment; const target_sect_base_addr = seg.sections.items[rel.r_symbolnum - 1].addr; - addend += @intCast(i64, context.base_addr + offset + correction + 4) - + addend += @intCast(i64, context.base_addr + offset + 4) - @intCast(i64, target_sect_base_addr); } }, From 58a552aaf99f518d3f347c074d20a25c5223404b Mon Sep 17 00:00:00 2001 From: Jakub Konka Date: Sun, 28 Nov 2021 20:48:54 +0100 Subject: [PATCH 2/2] macho: save all undef symbols even if null --- src/link/MachO.zig | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/link/MachO.zig b/src/link/MachO.zig index 37f905cdd4..2508b61a38 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -4996,17 +4996,9 @@ fn writeSymbolTable(self: *MachO) !void { } } - var undefs = std.ArrayList(macho.nlist_64).init(self.base.allocator); - defer undefs.deinit(); - - for (self.undefs.items) |sym| { - if (sym.n_strx == 0) continue; - try undefs.append(sym); - } - const nlocals = locals.items.len; const nexports = self.globals.items.len; - const nundefs = undefs.items.len; + const nundefs = self.undefs.items.len; const locals_off = symtab.symoff; const locals_size = nlocals * @sizeOf(macho.nlist_64); @@ -5021,7 +5013,7 @@ fn writeSymbolTable(self: *MachO) !void { const undefs_off = exports_off + exports_size; const undefs_size = nundefs * @sizeOf(macho.nlist_64); log.debug("writing undefined symbols from 0x{x} to 0x{x}", .{ undefs_off, undefs_size + undefs_off }); - try self.base.file.?.pwriteAll(mem.sliceAsBytes(undefs.items), undefs_off); + try self.base.file.?.pwriteAll(mem.sliceAsBytes(self.undefs.items), undefs_off); symtab.nsyms = @intCast(u32, nlocals + nexports + nundefs); seg.inner.filesize += locals_size + exports_size + undefs_size;