[v2] Fix an out of bounds array access in find_epilogue_using_linetable

Message ID AS8P193MB128510EEA4D953C321043BC7E43C2@AS8P193MB1285.EURP193.PROD.OUTLOOK.COM
State New
Headers
Series [v2] Fix an out of bounds array access in find_epilogue_using_linetable |

Checks

Context Check Description
linaro-tcwg-bot/tcwg_gdb_build--master-aarch64 success Testing passed
linaro-tcwg-bot/tcwg_gdb_build--master-arm success Testing passed
linaro-tcwg-bot/tcwg_gdb_check--master-arm success Testing passed
linaro-tcwg-bot/tcwg_gdb_check--master-aarch64 success Testing passed

Commit Message

Bernd Edlinger April 4, 2024, 3:34 p.m. UTC
  There is an out-of bounds array access in
find_epilogue_using_linetable.

This causes random test failures like these:

FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: $fba_value == $fn_fba
FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: check frame-id matches
FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: bt 2
FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: up
FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: $sp_value == $::main_sp
FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: $fba_value == $::main_fba
FAIL: gdb.base/unwind-on-each-insn-amd64.exp: foo: instruction 6: [string equal $fid $::main_fid]

Here the read happens below the first element of the line
table, and the test failure depends on the value that is
read from there.

Theoretically it is also possible that std::lower_bound
returns a pointer exactly at the upper bound of the line table,
also here the read value is undefined, that happens in this test:

FAIL: gdb.dwarf2/dw2-epilogue-begin.exp: confirm watchpoint doesn't trigger

Fixes: 528b729be1a2 ("gdb/dwarf2: Add support for DW_LNS_set_epilogue_begin in line-table")
---
 gdb/symtab.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

v2: Address review comments -- improved patch description, and added a comment.
  

Patch

diff --git a/gdb/symtab.c b/gdb/symtab.c
index 86603dfebc3..be646a7a353 100644
--- a/gdb/symtab.c
+++ b/gdb/symtab.c
@@ -4177,11 +4177,17 @@  find_epilogue_using_linetable (CORE_ADDR func_addr)
 	   return lte.unrelocated_pc () < pc;
 	 });
 
-      while (it->unrelocated_pc () >= unrel_start)
+      /* Note: Here IT points either to a linetable entry at or above unrel_end,
+	 or to the linetable entry after the last linetable array element.
+	 This means, it belongs either to the next function or is undefined.
+	 Therefore it must always be decremented first, before de-referencing.
+	 However it can also point to the beginning of the linetable array,
+	 if the array happens to be empty.  Decrementing below the first
+	 element of an array is undefined behaviour and must be avoided too.  */
+      while (it > linetable->item && (--it)->unrelocated_pc () >= unrel_start)
       {
 	if (it->epilogue_begin)
 	  return {it->pc (objfile)};
-	it --;
       }
     }
   return {};