gdbsupport: add checked_static_cast
authorAndrew Burgess <aburgess@redhat.com>
Mon, 27 Jun 2022 12:29:06 +0000 (13:29 +0100)
committerAndrew Burgess <aburgess@redhat.com>
Thu, 21 Jul 2022 14:19:43 +0000 (15:19 +0100)
commit11da1b13b313ae46c84008ebf096ffed1701e3c1
treee33bbfa15ff289c9ee5b486cc420940917bf8e16
parent08106042d9f5fdff60c129bf33190639f1a98b2a
gdbsupport: add checked_static_cast

This commit was inspired by these mailing list posts:

  https://sourceware.org/pipermail/gdb-patches/2022-June/190323.html
  https://sourceware.org/pipermail/gdb-patches/2022-April/188098.html

The idea is to add a new function gdb::checked_static_cast, which can,
in some cases, be used as a drop-in replacement for static_cast.  And
so, if I previously wrote this:

  BaseClass *base = get_base_class_pointer ();
  DerivedClass *derived = static_cast<DerivedClass *> (base);

I can now write:

  BaseClass *base = get_base_class_pointer ();
  DerivedClass *derived = gdb::checked_static_cast<DerivedClass *> (base);

The requirement is that BaseClass and DerivedClass must be
polymorphic.

The benefit of making this change is that, when GDB is built in
developer mode, a run-time check will be made to ensure that `base`
really is of type DerivedClass before the cast is performed.  If
`base` is not of type DerivedClass then GDB will assert.

In a non-developer build gdb::checked_static_cast is equivalent to a
static_cast, and there should be no performance difference.

This commit adds the support function, but does not make use of this
function, a use will be added in the next commit.

Co-Authored-By: Pedro Alves <pedro@palves.net>
Co-Authored-By: Tom Tromey <tom@tromey.com>
gdbsupport/gdb-checked-static-cast.h [new file with mode: 0644]