[gdb] Fix heap-buffer-overflow in completion_tracker::build_completion_result
authorTom de Vries <tdevries@suse.de>
Fri, 4 Dec 2020 21:35:07 +0000 (22:35 +0100)
committerTom de Vries <tdevries@suse.de>
Fri, 4 Dec 2020 21:35:07 +0000 (22:35 +0100)
When building gdb with address sanitizer and running test-case
gdb.base/completion.exp, we run into:
...
==5743==ERROR: AddressSanitizer: heap-buffer-overflow on address \
  0x60200025c02f at pc 0x000000cd9d64 bp 0x7fff3297da30 sp 0x7fff3297da28
READ of size 1 at 0x60200025c02f thread T0
    #0 0xcd9d63 in completion_tracker::build_completion_result(char const*, \
                     int, int) gdb/completer.c:2258
  ...
0x60200025c02f is located 1 bytes to the left of 1-byte region \
  [0x60200025c030,0x60200025c031)
...

This can be reproduced using just:
...
$ gdb
(gdb) p/d[TAB]
...

The problem is in this code in completion_tracker::build_completion_result:
...
      bool completion_suppress_append
        = (suppress_append_ws ()
           || match_list[0][strlen (match_list[0]) - 1] == ' ');
...
If strlen (match_list[0]) == 0, then we access match_list[0][-1].

Fix this by testing if the memory access is in bounds before doing the memory
access.

Tested on x86_64-linux.

gdb/ChangeLog:

2020-12-04  Tom de Vries  <tdevries@suse.de>

PR gdb/27003
* completer.c (completion_tracker::build_completion_result): Don't
access match_list[0][-1].

gdb/ChangeLog
gdb/completer.c

index eae761b7f129965e59be39a2825a0bee94f78d45..b0c3bd62d0152dfdf64e68b43cba90a30b1c4158 100644 (file)
@@ -1,3 +1,9 @@
+2020-12-04  Tom de Vries  <tdevries@suse.de>
+
+       PR gdb/27003
+       * completer.c (completion_tracker::build_completion_result): Don't
+       access match_list[0][-1].
+
 2020-12-04  Tom Tromey  <tromey@adacore.com>
 
        * linespec.c (struct linespec_token): Rename; remove typedef.
index 262c8556bf6c9cf339fce4ba175c3c4a8d83003a..83b46a0e4d89f1c805bdf13d06fedc730736478c 100644 (file)
@@ -2253,9 +2253,11 @@ completion_tracker::build_completion_result (const char *text,
       /* If the tracker wants to, or we already have a space at the
         end of the match, tell readline to skip appending
         another.  */
+      char *match = match_list[0];
       bool completion_suppress_append
        = (suppress_append_ws ()
-          || match_list[0][strlen (match_list[0]) - 1] == ' ');
+          || (match[0] != '\0'
+              && match[strlen (match) - 1] == ' '));
 
       return completion_result (match_list, 1, completion_suppress_append);
     }