google / sanitizers

AddressSanitizer, ThreadSanitizer, MemorySanitizer
Other
11.56k stars 1.04k forks source link

Down-Upcast for CRTP during construction incorrectly (?) flagged as UB #1773

Open upsj opened 3 months ago

upsj commented 3 months ago

Take the following piece of code

#include <iostream>

struct A {
  virtual ~A() = default;
  void foo() { std::cout << "foo"; }
};

template <typename Derived> struct EnableA : A {};

struct B {
  virtual ~B() = default;
  void bar() { std::cout << "bar"; }
};

template <typename Derived> struct EnableB : B {
  EnableB() { static_cast<Derived *>(this)->foo(); }
};

struct C : EnableA<C>, EnableB<C> {};

int main() { C c; }

compiled with UBSAN. We get the following warning:

ubsan-test.cpp:16:15: runtime error: downcast of address 0x7ffc23c64be0 which does not point to an object of type 'C'
0x7ffc23c64be0: note: object is of type 'EnableA<C>'
 00 00 00 00  90 30 40 00 00 00 00 00  70 30 40 00 00 00 00 00  01 00 00 00 00 00 00 00  90 95 c2 51
              ^~~~~~~~~~~~~~~~~~~~~~~
              vptr for 'EnableA<C>'

The static_cast gets flagged as an invalid down-cast, since this has not finished construction. But we are not accessing the Derived object at all, only using it to access the already initialized A class (internally this is static_cast<A*>(static_cast<C*>(this))->foo();)

There has also been a similar discussion on StackOverflow, which sounds like the specification is unclear here, but since we are not calling any virtual functions or using any RTTI, it is not immediately clear why the standard should be interpreted so strictly here.

Related issue: https://github.com/ginkgo-project/ginkgo/issues/1655