[PATCH v2] objcopy: Fix --only-keep-debug

Peilin Ye yepeilin.cs@gmail.com
Fri Jan 28 23:00:30 GMT 2022


From: Peilin Ye <peilin.ye@bytedance.com>

objcopy's --only-keep-debug option has been broken for ELF files since
commit 8c803a2dd7d3 ("elf_backend_section_flags and
_bfd_elf_init_private_section_data"):

  1. binutils/objcopy.c:setup_section() marks non-debug OSECs as
     SHT_NOBITS, then calls bfd_copy_private_section_data(), see
     "mark_nobits";
  2. If ISEC and OSEC share the same section flags,
     bfd/elf.c:_bfd_elf_init_private_section_data() restores OSEC's
     section type back to ISEC's section type, effectively undoing
     "mark_nobits".

This makes objcopy's --only-keep-debug a no-op.  As an example, Linux's
scripts/package/builddeb script depends on this option to generate
debug-info-only kernel modules.

As suggested by Nick and Alan, fix --only-keep-debug by marking
non-debug OSECs as SHT_NOBITS after calling
bfd_copy_private_section_data() in setup_section().

binutils/ChangeLog:
	* objcopy.c (setup_section): For --only-keep-debug, mark
	  non-debug output sections as SHT_NOBITS after calling
	  bfd_copy_private_section_data()

Reported-by: Omar Sandoval <osandov@osandov.com>
Fixes: 8c803a2dd7d3 ("elf_backend_section_flags and _bfd_elf_init_private_section_data")
Suggested-by: Alan Modra <amodra@gmail.com>
Signed-off-by: Peilin Ye <peilin.ye@bytedance.com>
---
change since v1:
	- fix objcopy instead of touching _bfd_elf_init_private_section_data()
	  (suggested by Nick and Alan)

 binutils/objcopy.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/binutils/objcopy.c b/binutils/objcopy.c
index d16d8ee67e4d..d53aa5c6000f 100644
--- a/binutils/objcopy.c
+++ b/binutils/objcopy.c
@@ -4085,9 +4085,6 @@ setup_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
       goto loser;
     }
 
-  if (make_nobits)
-    elf_section_type (osection) = SHT_NOBITS;
-
   size = bfd_section_size (isection);
   size = bfd_convert_section_size (ibfd, isection, obfd, size);
   if (copy_byte >= 0)
@@ -4181,6 +4178,9 @@ setup_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
       goto loser;
     }
 
+  if (make_nobits)
+    elf_section_type (osection) = SHT_NOBITS;
+
   /* All went well.  */
   return;
 
-- 
2.20.1



More information about the Binutils mailing list