[v2] bfd: xcofflink: validate line-number offsets

Message ID 20261103160737.2401392-1-harshit7kr@gmail.com
State New
Headers
Series [v2] bfd: xcofflink: validate line-number offsets |

Checks

Context Check Description
linaro-tcwg-bot/tcwg_binutils_build--master-aarch64 success Build passed
linaro-tcwg-bot/tcwg_binutils_build--master-arm success Build passed
linaro-tcwg-bot/tcwg_binutils_check--master-aarch64 success Test passed
linaro-tcwg-bot/tcwg_binutils_check--master-arm success Test passed

Commit Message

Harshit Kumar Nov. 3, 2026, 4:07 p.m. UTC
  xcoff_link_add_symbols (Pass 1) and xcoff_link_input_bfd (Pass 2)
compute linoff as the function's x_lnnoptr minus
enclosing->line_filepos.  x_lnnoptr is uint64_t, so a corrupt value
below line_filepos produces a large unsigned linoff.  A corrupt
x_lnnoptr can also place linoff past the end of the enclosing
line-number table, or leave it misaligned, meaning not a multiple of the
record size.

In the old signed variable, a value below line_filepos became negative.
Pass 1 accepted a negative linoff.  Pass 1 then read the first record
before the start of the table.  The read is a heap-buffer-overflow.  A
misaligned linoff can make the scan read a record that starts inside the
table and ends past it.  Pass 2 had no bounds check.

Pass 1 now rejects a linoff that wraps below the table start, is
misaligned, or lies outside the table.  The rejection reports an error
and sets bfd_error_bad_value.  Pass 2 checks the first record and all
*lineno_counts records against amt, the table size in bytes.  Pass 2
also checks that linoff is a multiple of linesz.  The Pass 2 check is
defensive.  Pass 1 already guarantees these bounds and alignment.

Behaviour change: Pass 1 used to skip an out-of-table linoff silently.
The function then lost its line numbers.  Pass 1 also accepted a
misaligned linoff.  Both cases now fail the link.  This includes the case
where the enclosing section has no line numbers but the function still
carries an x_lnnoptr.

Valid input gives the same result with and without this patch.

Extend ld/testsuite/ld-powerpc/xcoff-aux.exp.  The new tests use a valid
216-byte XCOFF32 input with one line-numbered function.  The tests cover
a positive control, a negative offset, an inflated offset, and a
misaligned offset.  Each malformed input must exit with status 1.  Each
malformed input must print the diagnostic "invalid line number offset".
Each malformed input must leave no output file and no crash output.  The
test deletes its inputs and outputs.

On an unpatched linker, the negative and misaligned inputs cause
heap-buffer-overflow reads under AddressSanitizer.  On an unpatched
linker, the inflated input exits with status 0.

No test covers the Pass 2 check.

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

bfd/
	PR ld/34883
	* xcofflink.c (xcoff_link_add_symbols): Validate line-number offset
	bounds and record alignment.
	(xcoff_link_input_bfd): Check line-number offset bounds and record
	alignment defensively.

ld/
	PR ld/34883
	* testsuite/ld-powerpc/xcoff-aux.exp (expect_lineno_rejection): New
	procedure.
	(xcoff_aux_test): Add tests for positive control, negative,
	inflated, and misaligned line-number offsets.

Signed-off-by: Harshit Kumar <harshit7kr@gmail.com>
---
v2: make linoff bfd_size_type and simplify the checks (Alan);
    add the alignment check in Pass 2; drop the bfd_zmalloc change;
    rejecting x_lnnoptr != 0 with lineno_count == 0 is intentional
    (none of the 52 function line tables in the corpus hit it).

Verification notes (below the commit message, not part of it):

- The new rejection is only reachable for functions with x_lnnoptr != 0.
  Functions without line info are skipped by the existing guard in both
  passes, so valid objects containing such functions are unaffected.
- Pass 1 sets linpend to the end of the enclosing table and scans only while
  linp < linpend, so *lineno_counts cannot exceed the table size.
- Corpus: 105 XCOFF objects, 49 of them XCOFF32. Of the XCOFF32 objects, 21
  have function line tables, holding 52 function line tables in total. All
  52 start on a record boundary inside their table. The Pass 2 bounds and
  alignment check accepts all 52.
- Each object links twice: relocatable (-r) and full link (-e .f0). The
  status matches. The only diagnostic difference is the source line number
  in the three pre-existing glink assertions, shifted by the added lines.
- Relocatable output is byte-identical with and without the patch, after
  masking the header timestamp. Full-link output differs only in the high byte
  of n_type in the symbol table. The byte also varies between runs of the
  unpatched linker, so this patch does not cause it.
- 49 single-member archives: the status matches. 46 links succeed, and their
  output is byte-identical after masking the timestamp.
- aix52.exp and powerpc.exp: 82 pass with and without the patch.
- The negative, inflated, and misaligned inputs used by the new tests exit
  with status 1 under ASan, print "invalid line number offset", and produce
  no ASan report. With leak detection enabled, the malformed inputs
  themselves produce no report.
- ASan xcoff-aux.exp: 11 of 11 pass with ASAN_OPTIONS=detect_leaks=0. The
  setting is needed because an unrelated 62-byte leak in ld, reproduced with
  both the patched and unpatched linkers, makes the positive control fail.

 bfd/xcofflink.c                       |  37 ++++++--
 ld/testsuite/ld-powerpc/xcoff-aux.exp | 128 ++++++++++++++++++++++++++
 2 files changed, 158 insertions(+), 7 deletions(-)
  

Patch

diff --git a/bfd/xcofflink.c b/bfd/xcofflink.c
index f155d1c3..b80a0905 100644
--- a/bfd/xcofflink.c
+++ b/bfd/xcofflink.c
@@ -1533,7 +1533,7 @@  xcoff_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
 	  if (auxlin.x_sym.x_fcnary.x_fcn.x_lnnoptr != 0)
 	    {
 	      asection *enclosing;
-	      bfd_signed_vma linoff;
+	      bfd_size_type linoff;
 
 	      enclosing = xcoff_section_data (abfd, csect)->enclosing;
 	      if (enclosing == NULL)
@@ -1547,8 +1547,10 @@  xcoff_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
 		}
 	      linoff = (auxlin.x_sym.x_fcnary.x_fcn.x_lnnoptr
 			- enclosing->line_filepos);
-	      /* Explicit cast to bfd_signed_vma for compiler.  */
-	      if (linoff < (bfd_signed_vma) (enclosing->lineno_count * linesz))
+	      /* A negative difference wraps to a large unsigned value,
+		 which the upper-bound check rejects.  */
+	      if (linoff < enclosing->lineno_count * linesz
+		  && linoff % linesz == 0)
 		{
 		  struct internal_lineno lin;
 		  bfd_byte *linpstart;
@@ -1584,6 +1586,15 @@  xcoff_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
 			  auxlin.x_sym.x_fcnary.x_fcn.x_lnnoptr;
 		    }
 		}
+	      else
+		{
+		  _bfd_error_handler
+		    /* xgettext:c-format */
+		    (_("%pB: `%s' has invalid line number offset"),
+		     abfd, name);
+		  bfd_set_error (bfd_error_bad_value);
+		  goto error_return;
+		}
 	    }
 	}
 
@@ -5718,7 +5729,7 @@  xcoff_link_input_bfd (struct xcoff_final_link_info *flinfo,
 		    {
 		      asection *enclosing;
 		      unsigned int enc_count;
-		      bfd_signed_vma linoff;
+		      bfd_size_type linoff;
 		      struct internal_lineno lin;
 		      bfd_byte *linp;
 		      bfd_byte *linpend;
@@ -5731,10 +5742,10 @@  xcoff_link_input_bfd (struct xcoff_final_link_info *flinfo,
 		      o = *csectpp;
 		      enclosing = xcoff_section_data (abfd, o)->enclosing;
 		      enc_count = xcoff_section_data (abfd, o)->lineno_count;
+		      amt = linesz * enc_count;
 		      if (oline != enclosing)
 			{
 			  pos = enclosing->line_filepos;
-			  amt = linesz * enc_count;
 			  if (bfd_seek (input_bfd, pos, SEEK_SET) != 0
 			      || (bfd_read (flinfo->linenos, amt, input_bfd)
 				  != amt))
@@ -5742,10 +5753,22 @@  xcoff_link_input_bfd (struct xcoff_final_link_info *flinfo,
 			  oline = enclosing;
 			}
 
-		      /* Copy across the first entry, adjusting its
-			 symbol index.  */
+		      /* Copy across the first record, adjusting its
+			 symbol index.  Check that the first record lies
+			 within the table.  Check that all *lineno_counts
+			 records lie within the table.  */
 		      linoff = (aux.x_sym.x_fcnary.x_fcn.x_lnnoptr
 				- enclosing->line_filepos);
+		      if (linoff >= amt
+			  || linoff % linesz != 0
+			  || *lineno_counts > (amt - linoff) / linesz)
+			{
+			  _bfd_error_handler
+			    /* xgettext:c-format */
+			    (_("%pB: invalid line number offset"), input_bfd);
+			  bfd_set_error (bfd_error_bad_value);
+			  return false;
+			}
 		      linp = flinfo->linenos + linoff;
 		      bfd_coff_swap_lineno_in (input_bfd, linp, &lin);
 		      lin.l_addr.l_symndx = *indexp;
diff --git a/ld/testsuite/ld-powerpc/xcoff-aux.exp b/ld/testsuite/ld-powerpc/xcoff-aux.exp
index 63118668..ef1256cd 100644
--- a/ld/testsuite/ld-powerpc/xcoff-aux.exp
+++ b/ld/testsuite/ld-powerpc/xcoff-aux.exp
@@ -124,6 +124,29 @@  proc expect_clean_rejection { ld opts obj bin what } {
     file delete -force $bin
 }
 
+# Link OBJ and require LD to reject it cleanly.  The link must exit with
+# status 1, print "invalid line number offset", and leave no output file
+# named by BIN.  Crash output fails the test.
+proc expect_lineno_rejection { ld opts obj bin what } {
+    file delete -force $bin
+    set result [run_ld_capture $ld $opts $obj $bin]
+    set status [lindex $result 0]
+    set out [lindex $result 1]
+    if { $status == 1
+	 && ![file exists $bin]
+	 && ! [crashed $out]
+	 && [string match "*invalid line number offset*" $out] } {
+	pass "XCOFF lineno $what: rejected cleanly"
+    } else {
+	set state [expr {[file exists $bin] ? "exists" : "absent"}]
+	fail "XCOFF lineno $what: LD must exit with status 1, print no crash\
+	      output, and leave no output file.  Got status $status, output\
+	      file $state: $out"
+    }
+    file delete -force $bin
+    file delete -force $obj
+}
+
 proc xcoff_aux_test {} {
     global ld tmpdir
 
@@ -367,6 +390,111 @@  proc xcoff_aux_test {} {
 	"$tmpdir/xcoff-aux-ar-overrun" \
 	"archive member inflated overrun, 238 slots past table end (.file n_numaux = 255)"
 
+    # Line-number offset tests.  The seed is a valid 216-byte XCOFF32
+    # input with one line-numbered function.
+    #   Header: magic 0x01df, 2 sections (.text, .text2), f_nsyms = 5,
+    #           f_symptr = 126 (0x007e).
+    #   Section 1 (.text): s_size = 4, s_scnptr = 100, s_lnnoptr = 104,
+    #           s_nlnno = 3.  The big-endian u32 s_lnnoptr sits at byte
+    #           offset 48, so byte 51 holds its least-significant byte.
+    #   Section 2 (.text2): s_size = 4, s_scnptr = 122, s_lnnoptr = 104,
+    #           s_nlnno = 0.  The section has no line-number records.
+    #   Symbols:
+    #     Slot 0..1: '.dummy' (class 107 C_HIDEXT, numaux 1) in .text
+    #     Slot 2..4: '.func'  (class 2 C_EXT, numaux 2) in .text.  The
+    #                function aux at slot 3 holds x_lnnoptr = 104.
+    #   The line-number table at byte offset 104 holds three 6-byte
+    #   records.  The first record is (symndx 2, line 0).
+    #   .text encloses .func.  Each test changes only the s_lnnoptr of
+    #   .text, so linoff = 104 - s_lnnoptr.
+    set lineno_hex {
+	01df0002000000000000007e00000005000000002e7465787400000000000000
+	000000000000000400000064000000000000006800000003000000202e746578
+	743200000000000000000000000000040000007a000000000000006800000000
+	0000002000000000000000020000000000100005000000140006000000002e64
+	756d6d79000000000000000100006b0100000000000000000000010500000000
+	00002e66756e6300000000000000000100200202000000000000000000000068
+	000000050000000000040000000000000100000000000000
+    }
+
+    regsub -all {\s+} $lineno_hex "" clean_lineno_hex
+    set lineno_seed "$tmpdir/xcoff-lineno-seed.o"
+    set f [open $lineno_seed "wb"]
+    fconfigure $f -translation binary
+    puts -nonewline $f [binary format H* $clean_lineno_hex]
+    close $f
+
+    if { [file size $lineno_seed] != 216 } {
+	unresolved "XCOFF lineno test: seed size is [file size $lineno_seed]\
+		    bytes, not 216"
+	file delete -force $lineno_seed
+	return
+    }
+
+    # 8. Positive control: the unmutated seed links without error.
+    set lineno_ctrl_bin "$tmpdir/xcoff-lineno-control"
+    file delete -force $lineno_ctrl_bin
+    set result [run_ld_capture $ld "$emul -e .func" $lineno_seed \
+		  $lineno_ctrl_bin]
+    set status [lindex $result 0]
+    set out [lindex $result 1]
+    if { $status != 0 || [crashed $out] || ![file exists $lineno_ctrl_bin] } {
+	fail "XCOFF lineno positive control: the unmutated input did not link\
+	      cleanly (status $status): $out"
+	file delete -force $lineno_ctrl_bin $lineno_seed
+	return
+    }
+    pass "XCOFF lineno positive control: unmutated object links cleanly"
+    file delete -force $lineno_ctrl_bin
+
+    # 9. Negative offset: s_lnnoptr = 110 gives linoff = 104 - 110 = -6.
+    # The patched linker computes linoff as an unsigned value, so the
+    # difference wraps to a large value and the upper-bound check rejects
+    # it.  On an unpatched linker, Pass 1 reads the first record before
+    # the start of the enclosing table.  The read is a
+    # heap-buffer-overflow.
+    set bad_lineno_neg "$tmpdir/xcoff-lineno-neg.o"
+    if { [catch {mutate_byte $lineno_seed $bad_lineno_neg 51 110} err] } {
+	fail "XCOFF lineno negative offset: mutation failed: $err"
+	file delete -force $lineno_seed $bad_lineno_neg
+	return
+    }
+    expect_lineno_rejection $ld "$emul -e .func" $bad_lineno_neg \
+	"$tmpdir/xcoff-lineno-neg" \
+	"negative line-number offset (linoff = -6)"
+
+    # 10. Inflated offset: s_lnnoptr = 0 gives linoff = 104, which is past
+    # the 18-byte table.  An unpatched linker skips the function in Pass 1.
+    # The function then has no line numbers, and the link exits with
+    # status 0.
+    set bad_lineno_inf "$tmpdir/xcoff-lineno-inf.o"
+    if { [catch {mutate_byte $lineno_seed $bad_lineno_inf 51 0} err] } {
+	fail "XCOFF lineno inflated offset: mutation failed: $err"
+	file delete -force $lineno_seed $bad_lineno_inf
+	return
+    }
+    expect_lineno_rejection $ld "$emul -e .func" $bad_lineno_inf \
+	"$tmpdir/xcoff-lineno-inf" \
+	"inflated line-number offset (linoff = 104 > table size)"
+
+    # 11. Misaligned offset: s_lnnoptr = 101 gives linoff = 3.  The value 3
+    # is not a multiple of the 6-byte record size.  s_lnnoptr = 101 also
+    # moves the start of the table the linker reads, so buffer byte 3 is
+    # file byte 104.  On an unpatched linker, Pass 1 reads the record at
+    # buffer byte 3 first.  Its scan then reads the records at buffer bytes
+    # 9 and 15.  The record at buffer byte 15 occupies buffer bytes 15 to
+    # 20.  Buffer bytes 18 to 20 lie past the 18-byte table.
+    set bad_lineno_mis "$tmpdir/xcoff-lineno-mis.o"
+    if { [catch {mutate_byte $lineno_seed $bad_lineno_mis 51 101} err] } {
+	fail "XCOFF lineno misaligned offset: mutation failed: $err"
+	file delete -force $lineno_seed $bad_lineno_mis
+	return
+    }
+    expect_lineno_rejection $ld "$emul -e .func" $bad_lineno_mis \
+	"$tmpdir/xcoff-lineno-mis" \
+	"misaligned line-number offset (linoff = 3)"
+    file delete -force $lineno_seed
+
 }
 
 xcoff_aux_test