public inbox for gdb-cvs@sourceware.org
help / color / mirror / Atom feed
* [binutils-gdb] [gdbsupport] Fix UB in print-utils.cc:int_string
@ 2022-05-23 12:50 Tom de Vries
  0 siblings, 0 replies; only message in thread
From: Tom de Vries @ 2022-05-23 12:50 UTC (permalink / raw)
  To: gdb-cvs

https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=735dfe028c93f20026339f3eeeadacac82fe7963

commit 735dfe028c93f20026339f3eeeadacac82fe7963
Author: Tom de Vries <tdevries@suse.de>
Date:   Mon May 23 14:50:02 2022 +0200

    [gdbsupport] Fix UB in print-utils.cc:int_string
    
    When building gdb with -fsanitize=undefined, I run into:
    ...
    (gdb) PASS: gdb.ada/access_to_packed_array.exp: set logging enabled on
    maint print symbols^M
    print-utils.cc:281:29:runtime error: negation of -9223372036854775808 cannot \
      be represented in type 'long int'; cast to an unsigned type to negate this \
      value to itself
    (gdb) FAIL: gdb.ada/access_to_packed_array.exp: maint print symbols
    ...
    
    By running in a debug session, we find that this happens during printing of:
    ...
       typedef system.storage_elements.storage_offset: \
         range -9223372036854775808 .. 9223372036854775807;
    ...
    Possibly, an ada test-case could be created that exercises this in isolation.
    
    The problem is here in int_string, where we negate a val with type LONGEST:
    ...
             return decimal2str ("-", -val, width);
    ...
    
    Fix this by, as recommend, using "-(ULONGEST)val" instead.
    
    Tested on x86_64-linux.

Diff:
---
 gdbsupport/print-utils.cc | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/gdbsupport/print-utils.cc b/gdbsupport/print-utils.cc
index 73ff1afda30..7bbb6deea74 100644
--- a/gdbsupport/print-utils.cc
+++ b/gdbsupport/print-utils.cc
@@ -278,7 +278,11 @@ int_string (LONGEST val, int radix, int is_signed, int width,
     case 10:
       {
 	if (is_signed && val < 0)
-	  return decimal2str ("-", -val, width);
+	  /* Cast to unsigned before negating, to prevent runtime error:
+	     negation of -9223372036854775808 cannot be represented in type
+	     'long int'; cast to an unsigned type to negate this value to
+	     itself.  */
+	  return decimal2str ("-", -(ULONGEST)val, width);
 	else
 	  return decimal2str ("", val, width);
       }


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2022-05-23 12:50 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-05-23 12:50 [binutils-gdb] [gdbsupport] Fix UB in print-utils.cc:int_string Tom de Vries

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).