[2/2] gdb: safety checks in skip_prologue_using_sal

Message ID 74b814d3c7621df2d09945579829194e33a4ccf4.1684398918.git.aburgess@redhat.com
State New
Headers
Series New test for find_pc_sect_line |

Commit Message

Andrew Burgess May 18, 2023, 8:37 a.m. UTC
  While working on the previous patch I reverted this commit:

  commit e86e87f77fd5d8afb3e714f1d9e09e0ff5b4e6ff
  Date:   Tue Nov 28 16:23:32 2006 +0000

          * symtab.c (find_pc_sect_line): Do not return a line before
            the start of a symtab.

When I re-ran the testsuite I saw some GDB crashes in the tests:

  gdb.dwarf2/dw2-line-number-zero.exp
  gdb.dwarf2/dw2-lines.exp
  gdb.dwarf2/dw2-vendor-extended-opcode.exp

GDB was reading beyond the end of an array in the function
skip_prologue_using_sal.

Now, without the above commit reverted I don't believe that this
should ever happen.  Reverting the above commit effectively breaks
GDB's symtab_and_line lookup, we try to find a result for an address,
and return the wrong symtab and line-table.  In
skip_prologue_using_sal we then walk the line table looking for an
appropriate entry, except we never find one, and GDB just keeps going,
wandering off the end of the array.

However, I think adding extra protection to prevent walking off the
end of the array is pretty cheap, and if something does go wrong in
the future then this should prevent a random crash.

Obviously, I have no reproducer for this, as I said, I don't think
this should impact GDB at all, this is just adding a little extra
caution.
---
 gdb/symtab.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
  

Patch

diff --git a/gdb/symtab.c b/gdb/symtab.c
index 4f28667b1b3..5e1b9d91879 100644
--- a/gdb/symtab.c
+++ b/gdb/symtab.c
@@ -3953,15 +3953,17 @@  skip_prologue_using_sal (struct gdbarch *gdbarch, CORE_ADDR func_addr)
 	  struct objfile *objfile
 	    = prologue_sal.symtab->compunit ()->objfile ();
 	  const linetable *linetable = prologue_sal.symtab->linetable ();
+	  gdb_assert (linetable->nitems > 0);
 	  int idx = 0;
 
 	  /* Skip any earlier lines, and any end-of-sequence marker
 	     from a previous function.  */
-	  while (linetable->item[idx].pc (objfile) != prologue_sal.pc
-		 || linetable->item[idx].line == 0)
+	  while (idx + 1 < linetable->nitems
+		 && (linetable->item[idx].pc (objfile) != prologue_sal.pc
+		     || linetable->item[idx].line == 0))
 	    idx++;
 
-	  if (idx+1 < linetable->nitems
+	  if (idx + 1 < linetable->nitems
 	      && linetable->item[idx+1].line != 0
 	      && linetable->item[idx+1].pc (objfile) == start_pc)
 	    return start_pc;