[PATCH] debugedit: Update section headers if section headers are not at end of ELF

Mark Wielaard mark@klomp.org
Mon Oct 26 16:44:24 GMT 2026


elfutils libelf elf_update might overwrite the section headers if the
section headers are in the middle of the file (between sections)
instead of at the end. So trigger an section layout update, which will
put the section headers at the end, if we detect the shdrs not being
at the end.

https://sourceware.org/bugzilla/show_bug.cgi?id=34468

	* tools/debugedit.c (struct DSO): Remove (unused) lastscn
	field. Add end_offset field.
	(fdopen_dso): Track and set DSO end_offset.
	(main): Set need_update if phnum != 0 and e_shoff < end_offset.

Signed-off-by: Mark Wielaard <mark@klomp.org>
---
 tools/debugedit.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/tools/debugedit.c b/tools/debugedit.c
index 510c0d7b3f29..785fe991f466 100644
--- a/tools/debugedit.c
+++ b/tools/debugedit.c
@@ -234,7 +234,7 @@ typedef struct
   GElf_Ehdr ehdr;
   Elf_Scn **scn;
   const char *filename;
-  int lastscn;
+  uint64_t end_offset;
   size_t phnum;
   size_t shnum;
   size_t shstrndx;
@@ -3666,6 +3666,7 @@ fdopen_dso (int fd, const char *name)
   int i;
   DSO *dso = NULL;
   size_t phnum, shnum, shstrndx;
+  uint64_t end_offset = 0;
 
   if (dest_dir == NULL && (!do_build_id || no_recompute_build_id))
     elf = elf_begin (fd, ELF_C_READ, NULL);
@@ -3750,7 +3751,10 @@ fdopen_dso (int fd, const char *name)
     {
       dso->scn[i] = elf_getscn (elf, i);
       gelf_getshdr (dso->scn[i], dso->shdr + i);
+      if (dso->shdr[i].sh_offset + dso->shdr[i].sh_size > end_offset)
+       end_offset = dso->shdr[i].sh_offset + dso->shdr[i].sh_size;
     }
+  dso->end_offset = end_offset;
 
   dso->filename = (const char *) strdup (name);
   setup_strings (&dso->debug_str);
@@ -4138,6 +4142,13 @@ main (int argc, char *argv[])
 		 || (do_build_id && build_id != NULL));
 #endif
 
+  /* If the shdrs are not at the and there are phdrs then we do need
+     to update the offsets so that the shdrs come last.
+     https://sourceware.org/bugzilla/show_bug.cgi?id=34468  */
+  need_update = (need_update
+                || (dso->phnum != 0
+                    && (dso->ehdr.e_shoff < dso->end_offset)));
+
   /* We might have changed the size of some debug sections. If so make
      sure the section headers are updated and the data offsets are
      correct. We set ELF_F_LAYOUT above because we don't want libelf
-- 
2.56.0



More information about the Debugedit mailing list