Commit acb91f4b30

Jakub Konka <kubkon@jakubkonka.com>
2024-08-29 23:23:39
elf: fix emitting correct .rela. sections in -r mode
1 parent 25fa092
Changed files (1)
src
link
src/link/Elf/ZigObject.zig
@@ -494,14 +494,6 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf, tid: Zcu.PerThread.Id) !voi
                     }
                 }
             }
-
-            if (elf_file.base.isRelocatable() and relocs.items.len > 0) {
-                const rela_sect_name = try std.fmt.allocPrintZ(gpa, ".rela{s}", .{elf_file.getShString(shdr.sh_name)});
-                defer gpa.free(rela_sect_name);
-                if (elf_file.sectionByName(rela_sect_name) == null) {
-                    _ = try elf_file.addRelaShdr(try elf_file.insertShString(rela_sect_name), shndx);
-                }
-            }
         }
 
         self.debug_abbrev_section_dirty = false;
@@ -820,6 +812,7 @@ pub fn writeAr(self: ZigObject, writer: anytype) !void {
 }
 
 pub fn addAtomsToRelaSections(self: *ZigObject, elf_file: *Elf) !void {
+    const gpa = elf_file.base.comp.gpa;
     for (self.atoms_indexes.items) |atom_index| {
         const atom_ptr = self.atom(atom_index) orelse continue;
         if (!atom_ptr.alive) continue;
@@ -829,11 +822,18 @@ pub fn addAtomsToRelaSections(self: *ZigObject, elf_file: *Elf) !void {
         const out_shndx = atom_ptr.output_section_index;
         const out_shdr = elf_file.sections.items(.shdr)[out_shndx];
         if (out_shdr.sh_type == elf.SHT_NOBITS) continue;
-        const out_rela_shndx = for (elf_file.sections.items(.shdr), 0..) |out_rela_shdr, out_rela_shndx| {
-            if (out_rela_shdr.sh_type == elf.SHT_RELA and out_rela_shdr.sh_info == out_shndx) break out_rela_shndx;
-        } else unreachable;
+        const rela_sect_name = try std.fmt.allocPrintZ(gpa, ".rela{s}", .{
+            elf_file.getShString(out_shdr.sh_name),
+        });
+        defer gpa.free(rela_sect_name);
+        const out_rela_shndx = if (elf_file.sectionByName(rela_sect_name)) |out_rela_shndx|
+            out_rela_shndx
+        else
+            try elf_file.addRelaShdr(try elf_file.insertShString(rela_sect_name), out_shndx);
+        const out_rela_shdr = &elf_file.sections.items(.shdr)[out_rela_shndx];
+        out_rela_shdr.sh_info = out_shndx;
+        out_rela_shdr.sh_link = elf_file.symtab_section_index.?;
         const atom_list = &elf_file.sections.items(.atom_list)[out_rela_shndx];
-        const gpa = elf_file.base.comp.gpa;
         try atom_list.append(gpa, .{ .index = atom_index, .file = self.index });
     }
 }