From 316669967e3e6cf6b8e093c98e270c994de37268 Mon Sep 17 00:00:00 2001 From: Devin Coughlin Date: Sat, 5 Dec 2015 00:22:36 +0000 Subject: [PATCH] [analyzer] Fix MemRegion crash casting non-struct to derived struct (PR25426). This commit prevents MemRegion::getAsOffset() from crashing when the analyzed program casts a symbolic region of a non-record type to some derived type and then attempts to access a field of the base type. rdar://problem/23458069 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@254806 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/StaticAnalyzer/Core/MemRegion.cpp | 25 +++++++++++++------------ test/Analysis/reinterpret-cast.cpp | 15 ++++++++++++++- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/lib/StaticAnalyzer/Core/MemRegion.cpp b/lib/StaticAnalyzer/Core/MemRegion.cpp index 632a381a39..ad3f396e39 100644 --- a/lib/StaticAnalyzer/Core/MemRegion.cpp +++ b/lib/StaticAnalyzer/Core/MemRegion.cpp @@ -1177,6 +1177,7 @@ RegionRawOffset ElementRegion::getAsArrayOffset() const { /// Returns true if \p Base is an immediate base class of \p Child static bool isImmediateBase(const CXXRecordDecl *Child, const CXXRecordDecl *Base) { + assert(Child && "Child must not be null"); // Note that we do NOT canonicalize the base class here, because // ASTRecordLayout doesn't either. If that leads us down the wrong path, // so be it; at least we won't crash. @@ -1256,18 +1257,18 @@ RegionOffset MemRegion::getAsOffset() const { if (!Child) { // We cannot compute the offset of the base class. SymbolicOffsetBase = R; - } - - if (RootIsSymbolic) { - // Base layers on symbolic regions may not be type-correct. - // Double-check the inheritance here, and revert to a symbolic offset - // if it's invalid (e.g. due to a reinterpret_cast). - if (BOR->isVirtual()) { - if (!Child->isVirtuallyDerivedFrom(BOR->getDecl())) - SymbolicOffsetBase = R; - } else { - if (!isImmediateBase(Child, BOR->getDecl())) - SymbolicOffsetBase = R; + } else { + if (RootIsSymbolic) { + // Base layers on symbolic regions may not be type-correct. + // Double-check the inheritance here, and revert to a symbolic offset + // if it's invalid (e.g. due to a reinterpret_cast). + if (BOR->isVirtual()) { + if (!Child->isVirtuallyDerivedFrom(BOR->getDecl())) + SymbolicOffsetBase = R; + } else { + if (!isImmediateBase(Child, BOR->getDecl())) + SymbolicOffsetBase = R; + } } } diff --git a/test/Analysis/reinterpret-cast.cpp b/test/Analysis/reinterpret-cast.cpp index cb7cbfd325..f3b0a7b257 100644 --- a/test/Analysis/reinterpret-cast.cpp +++ b/test/Analysis/reinterpret-cast.cpp @@ -102,4 +102,17 @@ int radar_13146953(void) { set_x1(x); set_x2((void *&)y); return *x + *y; // no warning -} \ No newline at end of file +} + +namespace PR25426 { + struct Base { + int field; + }; + + struct Derived : Base { }; + + void foo(int &p) { + Derived &d = (Derived &)(p); + d.field = 2; + } +} -- 2.40.0