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

            Bug ID: 33676
           Summary: ld segfaults when using binary inside NOLOAD section
           Product: binutils
           Version: 2.46 (HEAD)
            Status: UNCONFIRMED
          Severity: normal
          Priority: P2
         Component: ld
          Assignee: unassigned at sourceware dot org
          Reporter: magnus at tagpad dot net
  Target Milestone: ---

Created attachment 16491
  --> https://sourceware.org/bugzilla/attachment.cgi?id=16491&action=edit
Reproduce ld segfault in NOLOAD section

Description:
============
ld crashes with segmentation fault when linking binary format files with ELF
output. This is a regression introduced after binutils 2.44.

Steps to Reproduce:
===================
Extract the attached ld_noload_segfault.zip and run:
  chmod +x build.sh
  ./build.sh

The reproducer includes:
- main.c: minimal C source
- test.bin: binary input file
- linker.ld: linker script with INPUT(test.bin) directive
- build.sh: script to compile and link

Expected Result:
================
Link completes successfully, creates test.elf (works in binutils 2.44)

Actual Result:
==============
Segmentation fault at ld/ldlang.c:2841

Root Cause:
===========
The code at ldlang.c:2840-2841 checks if the output BFD is ELF format, then
unconditionally calls elf_section_type() on the input section without verifying
the input section is also ELF format.

When linking binary format files, section->owner has bfd_target_binary flavour,
causing elf_section_type() to crash.

This was introduced in commit d87be451e (PR ld/32787) which added special
handling for NOLOAD note sections.

Backtrace:
==========
#0  lang_add_section () at ld/ldlang.c:2841
#1  output_section_callback_nosort () at ld/ldlang.c:2945
#2  walk_wild () at ld/ldlang.c:1081
#3  wild () at ld/ldlang.c:3276
#4  map_input_to_output_sections () at ld/ldlang.c:4320
#5  lang_process () at ld/ldlang.c:8565
#6  main () at ld/ldmain.c:882

Proposed Fix:
=============
Check section owner's BFD flavour before calling elf_section_type():

--- ld/ldlang.c.orig
+++ ld/ldlang.c
@@ -2838,7 +2838,8 @@
         section.  Unlike a .bss style section, if a note section is
         marked as NOLOAD, also clear SEC_ALLOC.  */
       if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
+         && bfd_get_flavour (section->owner) == bfd_target_elf_flavour
          && elf_section_type (section) != SHT_NOTE)
        flags &= ~SEC_HAS_CONTENTS;
       else
        flags &= ~SEC_ALLOC;

Tested with binutils 2.45.1 and current master (as of 2025-11-26).

-- 
You are receiving this mail because:
You are on the CC list for the bug.

Reply via email to