In a relocatable object, a relocation's r_offset is an offset into
the section being relocated. In a linked object whose relocations
were preserved by the linker (--emit-relocs), it is a virtual address
instead.

Make reloc_offset() and set_reloc_offset() convert between the two,
using the base section's sh_addr. For a relocatable object sh_addr is 0,
so their behavior doesn't change.

Signed-off-by: Shivang Upadhyay <[email protected]>
---
 tools/objtool/include/objtool/elf.h | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/tools/objtool/include/objtool/elf.h 
b/tools/objtool/include/objtool/elf.h
index a82517a76a0f..e12fca2cc33b 100644
--- a/tools/objtool/include/objtool/elf.h
+++ b/tools/objtool/include/objtool/elf.h
@@ -396,14 +396,24 @@ static inline unsigned long sec_size(struct section *sec)
                ((Elf64_Rela *)reloc_rel(reloc))->field = val;          \
 })
 
+/*
+ * Relocation offsets in linked objects are absolute addresses; present them
+ * as offsets into the relocated section like in relocatable objects (where
+ * sh_addr is 0).
+ */
+static inline u64 reloc_base_addr(struct reloc *reloc)
+{
+       return reloc->sec->base ? reloc->sec->base->sh.sh_addr : 0;
+}
+
 static inline u64 reloc_offset(struct reloc *reloc)
 {
-       return __get_reloc_field(reloc, r_offset);
+       return __get_reloc_field(reloc, r_offset) - reloc_base_addr(reloc);
 }
 
 static inline void set_reloc_offset(struct elf *elf, struct reloc *reloc, u64 
offset)
 {
-       __set_reloc_field(reloc, r_offset, offset);
+       __set_reloc_field(reloc, r_offset, offset + reloc_base_addr(reloc));
        mark_sec_changed(elf, reloc->sec, true);
 }
 
-- 
2.56.1


Reply via email to