]> git.ipfire.org Git - thirdparty/binutils-gdb.git/commitdiff
Fix C++ cast of derived class to base class
authorTom Tromey <tom@tromey.com>
Sat, 2 Apr 2022 15:54:40 +0000 (09:54 -0600)
committerTom Tromey <tom@tromey.com>
Mon, 18 Apr 2022 15:34:55 +0000 (09:34 -0600)
PR c++/28907 points out that casting from a derived class to a base
class fails in some situations.  The problem turned out to be a
missing use of value_embedded_offset.  One peculiarity here is that,
if you managed to construct a pointer-to-derived with an embedded
offset of 0, the cast would work -- for example, one of the two new
tests here passes without the patch.

This embedded offset stuff is an endless source of bugs.  I wonder if
it's possible to get rid of it somehow.

Regression tested on x86-64 Fedora 34.

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

gdb/testsuite/gdb.cp/casts.cc
gdb/testsuite/gdb.cp/casts.exp
gdb/valops.c

index 543db896d3de9080882f2b5498b53146490a2a36..ea4dc96179353d3d8d6c3e65ea54cdacfe6e6d7a 100644 (file)
@@ -34,6 +34,20 @@ struct DoublyDerived : public VirtuallyDerived,
 {
 };
 
+struct Left
+{
+  int left;
+};
+
+struct Right
+{
+  int right;
+};
+
+struct LeftRight : public Left, public Right
+{
+};
+
 int
 main (int argc, char **argv)
 {
@@ -48,5 +62,11 @@ main (int argc, char **argv)
   Alpha *ad = &derived;
   Alpha *add = &doublyderived;
 
+  LeftRight gd;
+  gd.left = 23;
+  gd.right = 27;
+  unsigned long long gd_value = (unsigned long long) &gd;
+  unsigned long long r_value = (unsigned long long) (Right *) &gd;
+
   return 0;  /* breakpoint spot: casts.exp: 1 */
 }
index cda870f77a4dbd024b7917d08c9a82b3245dc558..5d0a52401a860264a2dc7573cc73b23c7fbdce0b 100644 (file)
@@ -174,6 +174,12 @@ gdb_test "print dynamic_cast<Gamma *> (add)" \
     " = \\(Gamma \\*\\) $nonzero_hex" \
     "dynamic_cast to sibling"
 
+gdb_test "print (unsigned long long) &gd == gd_value" " = true"
+gdb_test "print (unsigned long long) (LeftRight *) (Right *) &gd == gd_value" \
+    " = true"
+gdb_test "print (unsigned long long) (LeftRight *) (Right *) r_value == gd_value" \
+    " = true"
+
 if {[prepare_for_testing "failed to prepare" ${testfile}03 $srcfile2 \
                         {debug c++ additional_flags=-std=c++03}]} {
     return -1
index 42a1213b0c55323892c7bd771309756bec722123..e84cabf8f14c06e6cc398f44b9a9903827461900 100644 (file)
@@ -274,7 +274,7 @@ value_cast_structs (struct type *type, struct value *v2)
       if (v)
        {
          /* Downcasting is possible (t1 is superclass of v2).  */
-         CORE_ADDR addr2 = value_address (v2);
+         CORE_ADDR addr2 = value_address (v2) + value_embedded_offset (v2);
 
          addr2 -= value_address (v) + value_embedded_offset (v);
          return value_at (type, addr2);