[cfe-dev] UB in TypeLoc casting

David Blaikie dblaikie at gmail.com
Sun Nov 18 17:05:32 PST 2012

TypeLoc casting looks bogus.

TypeLoc derived types return true from classof when the dynamic type
is not actually an instance of the derived type. The TypeLoc is then
(erroneously) cast to the derived type and the derived type's implicit
copy ctor is executed (so long as you remember to assign the result of
cast<SpecificTypeLoc>), if you copy, otherwise the SpecificTypeLoc's
member functions are actually invoked on a TypeLoc object - bogas, but
it works (because there's no other members in the SpecificTypeLoc

Richard / Kostya: what's the word on catching this kind of UB
(essentially: calling member functions of one type on an instance not
of that type)? (in the specific case mentioned below, as discussed in
the original thread, ASan or MSan might be able to help)

Clang Dev: what should we do to fix this? I don't think it's helpful
to add machinery to llvm::cast to handle concrete type conversion, so
I think we should consider a non-llvm::cast solution for this
hierarchy. Replace the llvm::isa calls with getTypeLocClass calls (or
a separate wrapper for that) & add a SpecificTypeLoc(const TypeLoc&)
ctor for every specific TypeLoc that has an appropriate assert & calls
up through to the base copy ctor. It'll be a fair bit of code to add
to TypeLoc, but nothing complicated.

Any other ideas?


In a previous thread/bug fix, there was an issue related to casting TypeLocs:

TemplateSpecializationTypeLoc &TSTL =

should've been:

TemplateSpecializationTypeLoc TSTL =

(in case you don't see the difference immediately: TSTL should've been
a value rather than a reference)]

More information about the cfe-dev mailing list