[PATCH v3 03/11] objtool: Keep the layout of linked objects when writing them back

From: Shivang Upadhyay

Date: Wed Dec 02 2026 - 02:42:13 EST


When objtool modifies a file, libelf recomputes section offsets and
rewrites it. That is fine for a relocatable object, but a linked object
has a layout already fixed by the linker: program headers refer to file
offsets, and section contents are what gets loaded. Letting libelf
rearrange that layout corrupts the file.

Set ELF_F_LAYOUT for anything that is not ET_REL so libelf preserves the
existing layout. Objtool only patches bytes in place in that case.

Signed-off-by: Shivang Upadhyay <shivangu@xxxxxxxxxxxxx>
---
tools/objtool/elf.c | 7 +++++++
1 file changed, 7 insertions(+)

diff --git a/tools/objtool/elf.c b/tools/objtool/elf.c
index 493cb9f21dde..cb5e9f75a16e 100644
--- a/tools/objtool/elf.c
+++ b/tools/objtool/elf.c
@@ -1250,6 +1250,13 @@ struct elf *elf_open_read(const char *name, int flags)
goto err;
}

+ /*
+ * A linked object has a layout fixed by the linker (segments etc.);
+ * don't let libelf rearrange it when writing back.
+ */
+ if (elf->ehdr.e_type != ET_REL)
+ elf_flagelf(elf->elf, ELF_C_SET, ELF_F_LAYOUT);
+
if (read_sections(elf))
goto err;

--
2.56.1