gdb: use static_cast in gdb::checked_static_cast
This commit:
commit 6fe4779ac4b1874c995345e3eabd89cb1a05fbdf
Date: Sat Feb 24 11:00:20 2024 +0100
[gdb/build] Fix static cast of virtual base
addressed an issue where GDB would not compile in production mode due
to a use of gdb::checked_static_cast. The problem was that we were
asking GDB to cast from a virtual base class to a sub-class, this
works fine when using dynamic_cast, but does not work with
static_cast.
The gdb::checked_static_cast actually uses dynamic_cast under the hood
in development mode in order to ensure that the cast is valid, while
in a production build we use static_cast as this is more efficient.
What this meant however, was that when gdb::checked_static_cast was
used to cast from a virtual base class, the dynamic_cast of a
non-production build worked fine, while the production build's
static_cast caused a build failure.
However, the gdb::checked_static_cast function already contains some
static_assert calls that are intended to catch any issues with invalid
type casting, the goal of these asserts was to prevent issues like
this: the build only failing in production mode. Clearly the current
asserts are not enough.
I don't think there is a std::is_virtual_base type trait check, so
what I propose instead is that in non-production mode we also make use
of static_cast. This will ensure that any errors that crop up in
production mode should also be revealed in non-production mode, and
should catch issues like this in the future.
There should be no user visible changes after this commit.
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=31399
Co-Authored-By: Simon Marchi <simon.marchi@polymtl.ca>
diff --git a/gdbsupport/gdb-checked-static-cast.h b/gdbsupport/gdb-checked-static-cast.h
index 227010e..24fa7a4 100644
--- a/gdbsupport/gdb-checked-static-cast.h
+++ b/gdbsupport/gdb-checked-static-cast.h
@@ -54,16 +54,12 @@ checked_static_cast (V *v)
"types must be related");
#ifdef DEVELOPMENT
- if (v == nullptr)
- return nullptr;
-
- T result = dynamic_cast<T> (v);
- gdb_assert (result != nullptr);
-#else
- T result = static_cast<T> (v);
+ gdb_assert (v == nullptr || dynamic_cast<T> (v) != nullptr);
#endif
- return result;
+ /* If a base class of V is virtual then the dynamic_cast above will
+ succeed, but this static_cast will fail. */
+ return static_cast<T> (v);
}
/* Same as the above, but to cast from a reference type to another. */