From 0202c3596c52d453d1e9e5a43d7533b83444df4e Mon Sep 17 00:00:00 2001 From: Csaba Dabis Date: Thu, 22 Aug 2019 00:20:36 +0000 Subject: [PATCH] [analyzer] CastValueChecker: Store the dynamic types and casts Summary: This patch introduces `DynamicCastInfo` similar to `DynamicTypeInfo` which is stored in `CastSets` which are storing the dynamic cast informations of objects based on memory regions. It could be used to store and check the casts and prevent infeasible paths. Reviewed By: NoQ Differential Revision: https://reviews.llvm.org/D66325 llvm-svn: 369605 --- clang/include/clang/AST/Type.h | 3 + .../Core/PathSensitive/CheckerContext.h | 15 +- .../Core/PathSensitive/DynamicCastInfo.h | 55 ++++ .../Core/PathSensitive/DynamicType.h | 73 +++++ .../Core/PathSensitive/DynamicTypeInfo.h | 48 +-- .../Core/PathSensitive/DynamicTypeMap.h | 63 ---- .../Checkers/CastValueChecker.cpp | 276 +++++++++++------- .../Checkers/DynamicTypePropagation.cpp | 15 +- clang/lib/StaticAnalyzer/Core/CMakeLists.txt | 2 +- clang/lib/StaticAnalyzer/Core/DynamicType.cpp | 223 ++++++++++++++ .../StaticAnalyzer/Core/DynamicTypeMap.cpp | 97 ------ .../lib/StaticAnalyzer/Core/ProgramState.cpp | 2 +- clang/test/Analysis/Inputs/llvm.h | 19 ++ clang/test/Analysis/cast-value-logic.cpp | 128 ++++++++ clang/test/Analysis/cast-value-notes.cpp | 144 +++++++++ clang/test/Analysis/cast-value-state-dump.cpp | 47 +++ clang/test/Analysis/cast-value.cpp | 239 --------------- clang/test/Analysis/dump_egraph.cpp | 3 +- clang/test/Analysis/expr-inspection.c | 1 + 19 files changed, 915 insertions(+), 538 deletions(-) create mode 100644 clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h create mode 100644 clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h delete mode 100644 clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h create mode 100644 clang/lib/StaticAnalyzer/Core/DynamicType.cpp delete mode 100644 clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp create mode 100644 clang/test/Analysis/Inputs/llvm.h create mode 100644 clang/test/Analysis/cast-value-logic.cpp create mode 100644 clang/test/Analysis/cast-value-notes.cpp create mode 100644 clang/test/Analysis/cast-value-state-dump.cpp delete mode 100644 clang/test/Analysis/cast-value.cpp diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h index e80dd1a4ec40..dc1db0500f85 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -972,6 +972,9 @@ public: friend bool operator!=(const QualType &LHS, const QualType &RHS) { return LHS.Value != RHS.Value; } + friend bool operator<(const QualType &LHS, const QualType &RHS) { + return LHS.Value < RHS.Value; + } static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy) { diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h index 1d2e554ec273..7f4df0d88def 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h @@ -234,7 +234,7 @@ public: } /// A shorthand version of getNoteTag that doesn't require you to accept - /// the BugReporterContext arguments when you don't need it. + /// the 'BugReporterContext' argument when you don't need it. /// /// @param Cb Callback only with 'BugReport &' parameter. /// @param IsPrunable Whether the note is prunable. It allows BugReporter @@ -247,6 +247,19 @@ public: IsPrunable); } + /// A shorthand version of getNoteTag that doesn't require you to accept + /// the arguments when you don't need it. + /// + /// @param Cb Callback without parameters. + /// @param IsPrunable Whether the note is prunable. It allows BugReporter + /// to omit the note from the report if it would make the displayed + /// bug path significantly shorter. + const NoteTag *getNoteTag(std::function &&Cb, + bool IsPrunable = false) { + return getNoteTag([Cb](BugReporterContext &, BugReport &) { return Cb(); }, + IsPrunable); + } + /// A shorthand version of getNoteTag that accepts a plain note. /// /// @param Note The note. diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h new file mode 100644 index 000000000000..f5a710c77a6a --- /dev/null +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h @@ -0,0 +1,55 @@ +//===- DynamicCastInfo.h - Runtime cast information -------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H +#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H + +#include "clang/AST/Type.h" + +namespace clang { +namespace ento { + +class DynamicCastInfo { +public: + enum CastResult { Success, Failure }; + + DynamicCastInfo(QualType from, QualType to, CastResult resultKind) + : From(from), To(to), ResultKind(resultKind) {} + + QualType from() const { return From; } + QualType to() const { return To; } + + bool equals(QualType from, QualType to) const { + return From == from && To == to; + } + + bool succeeds() const { return ResultKind == CastResult::Success; } + bool fails() const { return ResultKind == CastResult::Failure; } + + bool operator==(const DynamicCastInfo &RHS) const { + return From == RHS.From && To == RHS.To; + } + bool operator<(const DynamicCastInfo &RHS) const { + return From < RHS.From && To < RHS.To; + } + + void Profile(llvm::FoldingSetNodeID &ID) const { + ID.Add(From); + ID.Add(To); + ID.AddInteger(ResultKind); + } + +private: + QualType From, To; + CastResult ResultKind; +}; + +} // namespace ento +} // namespace clang + +#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h new file mode 100644 index 000000000000..f300af2c0b87 --- /dev/null +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h @@ -0,0 +1,73 @@ +//===- DynamicType.h - Dynamic type related APIs ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines APIs that track and query dynamic type information. This +// information can be used to devirtualize calls during the symbolic execution +// or do type checking. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPE_H +#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPE_H + +#include "clang/AST/Type.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" +#include "llvm/ADT/ImmutableMap.h" +#include "llvm/ADT/Optional.h" +#include + +namespace clang { +namespace ento { + +/// Get dynamic type information for the region \p MR. +DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR); + +/// Get raw dynamic type information for the region \p MR. +const DynamicTypeInfo *getRawDynamicTypeInfo(ProgramStateRef State, + const MemRegion *MR); + +/// Get dynamic cast information from \p CastFromTy to \p CastToTy of \p MR. +const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State, + const MemRegion *MR, + QualType CastFromTy, + QualType CastToTy); + +/// Set dynamic type information of the region; return the new state. +ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, + DynamicTypeInfo NewTy); + +/// Set dynamic type information of the region; return the new state. +ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, + QualType NewTy, bool CanBeSubClassed = true); + +/// Set dynamic type and cast information of the region; return the new state. +ProgramStateRef setDynamicTypeAndCastInfo(ProgramStateRef State, + const MemRegion *MR, + QualType CastFromTy, + QualType CastToTy, QualType ResultTy, + bool IsCastSucceeds); + +/// Removes the dead type informations from \p State. +ProgramStateRef removeDeadTypes(ProgramStateRef State, SymbolReaper &SR); + +/// Removes the dead cast informations from \p State. +ProgramStateRef removeDeadCasts(ProgramStateRef State, SymbolReaper &SR); + +void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, + const char *NL = "\n", unsigned int Space = 0, + bool IsDot = false); + +} // namespace ento +} // namespace clang + +#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPE_H diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h index 9bb1e2137566..6262c4a1ce37 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h @@ -1,10 +1,11 @@ -//== DynamicTypeInfo.h - Runtime type information ----------------*- C++ -*--=// +//===- DynamicTypeInfo.h - Runtime type information -------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// + #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H @@ -16,36 +17,37 @@ namespace ento { /// Stores the currently inferred strictest bound on the runtime type /// of a region in a given state along the analysis path. class DynamicTypeInfo { -private: - QualType T; - bool CanBeASubClass; - public: + DynamicTypeInfo() : DynTy(QualType()) {} - DynamicTypeInfo() : T(QualType()) {} - DynamicTypeInfo(QualType WithType, bool CanBeSub = true) - : T(WithType), CanBeASubClass(CanBeSub) {} + DynamicTypeInfo(QualType Ty, bool CanBeSub = true) + : DynTy(Ty), CanBeASubClass(CanBeSub) {} - /// Return false if no dynamic type info is available. - bool isValid() const { return !T.isNull(); } - - /// Returns the currently inferred upper bound on the runtime type. - QualType getType() const { return T; } - - /// Returns false if the type information is precise (the type T is + /// Returns false if the type information is precise (the type 'DynTy' is /// the only type in the lattice), true otherwise. bool canBeASubClass() const { return CanBeASubClass; } + /// Returns true if the dynamic type info is available. + bool isValid() const { return !DynTy.isNull(); } + + /// Returns the currently inferred upper bound on the runtime type. + QualType getType() const { return DynTy; } + + bool operator==(const DynamicTypeInfo &RHS) const { + return DynTy == RHS.DynTy && CanBeASubClass == RHS.CanBeASubClass; + } + void Profile(llvm::FoldingSetNodeID &ID) const { - ID.Add(T); - ID.AddInteger((unsigned)CanBeASubClass); - } - bool operator==(const DynamicTypeInfo &X) const { - return T == X.T && CanBeASubClass == X.CanBeASubClass; + ID.Add(DynTy); + ID.AddBoolean(CanBeASubClass); } + +private: + QualType DynTy; + bool CanBeASubClass; }; -} // end ento -} // end clang +} // namespace ento +} // namespace clang -#endif +#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h deleted file mode 100644 index a84b24872061..000000000000 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h +++ /dev/null @@ -1,63 +0,0 @@ -//===- DynamicTypeMap.h - Dynamic type map ----------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file provides APIs for tracking dynamic type information. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H -#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H - -#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" -#include "llvm/ADT/ImmutableMap.h" -#include "clang/AST/Type.h" - -namespace clang { -namespace ento { - -class MemRegion; - -/// The GDM component containing the dynamic type info. This is a map from a -/// symbol to its most likely type. -struct DynamicTypeMap {}; - -using DynamicTypeMapTy = llvm::ImmutableMap; - -template <> -struct ProgramStateTrait - : public ProgramStatePartialTrait { - static void *GDMIndex(); -}; - -/// Get dynamic type information for a region. -DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, - const MemRegion *Reg); - -/// Set dynamic type information of the region; return the new state. -ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg, - DynamicTypeInfo NewTy); - -/// Set dynamic type information of the region; return the new state. -inline ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, - const MemRegion *Reg, QualType NewTy, - bool CanBeSubClassed = true) { - return setDynamicTypeInfo(State, Reg, - DynamicTypeInfo(NewTy, CanBeSubClassed)); -} - -void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, - const char *NL = "\n", unsigned int Space = 0, - bool IsDot = false); - -} // namespace ento -} // namespace clang - -#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H diff --git a/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp index 9cf1b0a020a2..e7472ab156b7 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp @@ -6,7 +6,13 @@ // //===----------------------------------------------------------------------===// // -// This defines CastValueChecker which models casts of custom RTTIs. +// This defines CastValueChecker which models casts of custom RTTIs. +// +// TODO list: +// - It only allows one succesful cast between two types however in the wild +// the object could be casted to multiple types. +// - It needs to check the most likely type information from the dynamic type +// map to increase precision of dynamic casting. // //===----------------------------------------------------------------------===// @@ -15,6 +21,7 @@ #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" #include "llvm/ADT/Optional.h" #include @@ -23,219 +30,281 @@ using namespace ento; namespace { class CastValueChecker : public Checker { - enum class CastKind { Function, Method }; + enum class CallKind { Function, Method }; using CastCheck = - std::function; - using CheckKindPair = std::pair; - public: // We have five cases to evaluate a cast: - // 1) The parameter is non-null, the return value is non-null - // 2) The parameter is non-null, the return value is null - // 3) The parameter is null, the return value is null + // 1) The parameter is non-null, the return value is non-null. + // 2) The parameter is non-null, the return value is null. + // 3) The parameter is null, the return value is null. // cast: 1; dyn_cast: 1, 2; cast_or_null: 1, 3; dyn_cast_or_null: 1, 2, 3. // - // 4) castAs: has no parameter, the return value is non-null. - // 5) getAs: has no parameter, the return value is null or non-null. + // 4) castAs: Has no parameter, the return value is non-null. + // 5) getAs: Has no parameter, the return value is null or non-null. bool evalCall(const CallEvent &Call, CheckerContext &C) const; + void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; private: // These are known in the LLVM project. The pairs are in the following form: // {{{namespace, call}, argument-count}, {callback, kind}} - const CallDescriptionMap CDM = { + const CallDescriptionMap> CDM = { {{{"llvm", "cast"}, 1}, - {&CastValueChecker::evalCast, CastKind::Function}}, + {&CastValueChecker::evalCast, CallKind::Function}}, {{{"llvm", "dyn_cast"}, 1}, - {&CastValueChecker::evalDynCast, CastKind::Function}}, + {&CastValueChecker::evalDynCast, CallKind::Function}}, {{{"llvm", "cast_or_null"}, 1}, - {&CastValueChecker::evalCastOrNull, CastKind::Function}}, + {&CastValueChecker::evalCastOrNull, CallKind::Function}}, {{{"llvm", "dyn_cast_or_null"}, 1}, - {&CastValueChecker::evalDynCastOrNull, CastKind::Function}}, + {&CastValueChecker::evalDynCastOrNull, CallKind::Function}}, {{{"clang", "castAs"}, 0}, - {&CastValueChecker::evalCastAs, CastKind::Method}}, + {&CastValueChecker::evalCastAs, CallKind::Method}}, {{{"clang", "getAs"}, 0}, - {&CastValueChecker::evalGetAs, CastKind::Method}}}; + {&CastValueChecker::evalGetAs, CallKind::Method}}}; - void evalCast(const CallExpr *CE, DefinedOrUnknownSVal DV, + void evalCast(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const; - void evalDynCast(const CallExpr *CE, DefinedOrUnknownSVal DV, + void evalDynCast(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const; - void evalCastOrNull(const CallExpr *CE, DefinedOrUnknownSVal DV, + void evalCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const; - void evalDynCastOrNull(const CallExpr *CE, DefinedOrUnknownSVal DV, + void evalDynCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const; - void evalCastAs(const CallExpr *CE, DefinedOrUnknownSVal DV, + void evalCastAs(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const; - void evalGetAs(const CallExpr *CE, DefinedOrUnknownSVal DV, + void evalGetAs(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const; }; } // namespace -static std::string getCastName(const Expr *Cast) { - QualType Ty = Cast->getType(); - if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) - return RD->getNameAsString(); +static QualType getRecordType(QualType Ty) { + Ty = Ty.getCanonicalType(); - return Ty->getPointeeCXXRecordDecl()->getNameAsString(); + if (Ty->isPointerType()) + Ty = Ty->getPointeeType(); + + if (Ty->isReferenceType()) + Ty = Ty.getNonReferenceType(); + + return Ty.getUnqualifiedType(); } -static const NoteTag *getCastTag(bool IsNullReturn, const CallExpr *CE, - CheckerContext &C, - bool IsCheckedCast = false) { - Optional CastFromName = (CE->getNumArgs() > 0) - ? getCastName(CE->getArg(0)) - : Optional(); - std::string CastToName = getCastName(CE); +static bool isInfeasibleCast(const DynamicCastInfo *CastInfo, + bool CastSucceeds) { + if (!CastInfo) + return false; + + return CastSucceeds ? CastInfo->fails() : CastInfo->succeeds(); +} + +static const NoteTag *getNoteTag(CheckerContext &C, + const DynamicCastInfo *CastInfo, + QualType CastToTy, const Expr *Object, + bool CastSucceeds, bool IsKnownCast) { + std::string CastToName = + CastInfo ? CastInfo->to()->getAsCXXRecordDecl()->getNameAsString() + : CastToTy->getAsCXXRecordDecl()->getNameAsString(); + Object = Object->IgnoreParenImpCasts(); return C.getNoteTag( - [CastFromName, CastToName, IsNullReturn, - IsCheckedCast](BugReport &) -> std::string { + [=] { SmallString<128> Msg; llvm::raw_svector_ostream Out(Msg); - Out << (!IsCheckedCast ? "Assuming dynamic cast " : "Checked cast "); - if (CastFromName) - Out << "from '" << *CastFromName << "' "; + if (!IsKnownCast) + Out << "Assuming "; - Out << "to '" << CastToName << "' " - << (!IsNullReturn ? "succeeds" : "fails"); + if (const auto *DRE = dyn_cast(Object)) { + Out << '\'' << DRE->getDecl()->getNameAsString() << '\''; + } else if (const auto *ME = dyn_cast(Object)) { + Out << (IsKnownCast ? "Field '" : "field '") + << ME->getMemberDecl()->getNameAsString() << '\''; + } else { + Out << (IsKnownCast ? "The object" : "the object"); + } + + Out << ' ' << (CastSucceeds ? "is a" : "is not a") << " '" << CastToName + << '\''; return Out.str(); }, /*IsPrunable=*/true); } -static ProgramStateRef getState(bool IsNullReturn, - DefinedOrUnknownSVal ReturnDV, - const CallExpr *CE, ProgramStateRef State, - CheckerContext &C) { - return State->BindExpr( - CE, C.getLocationContext(), - IsNullReturn ? C.getSValBuilder().makeNull() : ReturnDV, false); +//===----------------------------------------------------------------------===// +// Main logic to evaluate a cast. +//===----------------------------------------------------------------------===// + +static void addCastTransition(const CallEvent &Call, DefinedOrUnknownSVal DV, + CheckerContext &C, bool IsNonNullParam, + bool IsNonNullReturn, + bool IsCheckedCast = false) { + ProgramStateRef State = C.getState()->assume(DV, IsNonNullParam); + if (!State) + return; + + const Expr *Object; + QualType CastFromTy; + QualType CastToTy = getRecordType(Call.getResultType()); + + if (Call.getNumArgs() > 0) { + Object = Call.getArgExpr(0); + CastFromTy = getRecordType(Call.parameters()[0]->getType()); + } else { + Object = cast(&Call)->getCXXThisExpr(); + CastFromTy = getRecordType(Object->getType()); + } + + const MemRegion *MR = DV.getAsRegion(); + const DynamicCastInfo *CastInfo = + getDynamicCastInfo(State, MR, CastFromTy, CastToTy); + + // We assume that every checked cast succeeds. + bool CastSucceeds = IsCheckedCast || CastFromTy == CastToTy; + if (!CastSucceeds) { + if (CastInfo) + CastSucceeds = IsNonNullReturn && CastInfo->succeeds(); + else + CastSucceeds = IsNonNullReturn; + } + + // Check for infeasible casts. + if (isInfeasibleCast(CastInfo, CastSucceeds)) { + C.generateSink(State, C.getPredecessor()); + return; + } + + // Store the type and the cast information. + bool IsKnownCast = CastInfo || IsCheckedCast || CastFromTy == CastToTy; + if (!IsKnownCast || IsCheckedCast) + State = setDynamicTypeAndCastInfo(State, MR, CastFromTy, CastToTy, + Call.getResultType(), CastSucceeds); + + SVal V = CastSucceeds ? DV : C.getSValBuilder().makeNull(); + C.addTransition( + State->BindExpr(Call.getOriginExpr(), C.getLocationContext(), V, false), + getNoteTag(C, CastInfo, CastToTy, Object, CastSucceeds, IsKnownCast)); } //===----------------------------------------------------------------------===// // Evaluating cast, dyn_cast, cast_or_null, dyn_cast_or_null. //===----------------------------------------------------------------------===// -static void evalNonNullParamNonNullReturn(const CallExpr *CE, +static void evalNonNullParamNonNullReturn(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C, bool IsCheckedCast = false) { - bool IsNullReturn = false; - if (ProgramStateRef State = C.getState()->assume(DV, true)) - C.addTransition(getState(IsNullReturn, DV, CE, State, C), - getCastTag(IsNullReturn, CE, C, IsCheckedCast)); + addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, + /*IsNonNullReturn=*/true, IsCheckedCast); } -static void evalNonNullParamNullReturn(const CallExpr *CE, +static void evalNonNullParamNullReturn(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) { - bool IsNullReturn = true; - if (ProgramStateRef State = C.getState()->assume(DV, true)) - C.addTransition(getState(IsNullReturn, DV, CE, State, C), - getCastTag(IsNullReturn, CE, C)); + addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, + /*IsNonNullReturn=*/false); } -static void evalNullParamNullReturn(const CallExpr *CE, DefinedOrUnknownSVal DV, +static void evalNullParamNullReturn(const CallEvent &Call, + DefinedOrUnknownSVal DV, CheckerContext &C) { if (ProgramStateRef State = C.getState()->assume(DV, false)) - C.addTransition(getState(/*IsNullReturn=*/true, DV, CE, State, C), + C.addTransition(State->BindExpr(Call.getOriginExpr(), + C.getLocationContext(), + C.getSValBuilder().makeNull(), false), C.getNoteTag("Assuming null pointer is passed into cast", /*IsPrunable=*/true)); } -void CastValueChecker::evalCast(const CallExpr *CE, DefinedOrUnknownSVal DV, +void CastValueChecker::evalCast(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const { - evalNonNullParamNonNullReturn(CE, DV, C, /*IsCheckedCast=*/true); + evalNonNullParamNonNullReturn(Call, DV, C, /*IsCheckedCast=*/true); } -void CastValueChecker::evalDynCast(const CallExpr *CE, DefinedOrUnknownSVal DV, +void CastValueChecker::evalDynCast(const CallEvent &Call, + DefinedOrUnknownSVal DV, CheckerContext &C) const { - evalNonNullParamNonNullReturn(CE, DV, C); - evalNonNullParamNullReturn(CE, DV, C); + evalNonNullParamNonNullReturn(Call, DV, C); + evalNonNullParamNullReturn(Call, DV, C); } -void CastValueChecker::evalCastOrNull(const CallExpr *CE, +void CastValueChecker::evalCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const { - evalNonNullParamNonNullReturn(CE, DV, C); - evalNullParamNullReturn(CE, DV, C); + evalNonNullParamNonNullReturn(Call, DV, C); + evalNullParamNullReturn(Call, DV, C); } -void CastValueChecker::evalDynCastOrNull(const CallExpr *CE, +void CastValueChecker::evalDynCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const { - evalNonNullParamNonNullReturn(CE, DV, C); - evalNonNullParamNullReturn(CE, DV, C); - evalNullParamNullReturn(CE, DV, C); + evalNonNullParamNonNullReturn(Call, DV, C); + evalNonNullParamNullReturn(Call, DV, C); + evalNullParamNullReturn(Call, DV, C); } //===----------------------------------------------------------------------===// // Evaluating castAs, getAs. //===----------------------------------------------------------------------===// -static void evalZeroParamNonNullReturn(const CallExpr *CE, +static void evalZeroParamNonNullReturn(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C, bool IsCheckedCast = false) { - bool IsNullReturn = false; - if (ProgramStateRef State = C.getState()->assume(DV, true)) - C.addTransition(getState(IsNullReturn, DV, CE, C.getState(), C), - getCastTag(IsNullReturn, CE, C, IsCheckedCast)); + addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, + /*IsNonNullReturn=*/true, IsCheckedCast); } -static void evalZeroParamNullReturn(const CallExpr *CE, DefinedOrUnknownSVal DV, +static void evalZeroParamNullReturn(const CallEvent &Call, + DefinedOrUnknownSVal DV, CheckerContext &C) { - bool IsNullReturn = true; - if (ProgramStateRef State = C.getState()->assume(DV, true)) - C.addTransition(getState(IsNullReturn, DV, CE, C.getState(), C), - getCastTag(IsNullReturn, CE, C)); + addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, + /*IsNonNullReturn=*/false); } -void CastValueChecker::evalCastAs(const CallExpr *CE, DefinedOrUnknownSVal DV, +void CastValueChecker::evalCastAs(const CallEvent &Call, + DefinedOrUnknownSVal DV, CheckerContext &C) const { - evalZeroParamNonNullReturn(CE, DV, C, /*IsCheckedCast=*/true); + evalZeroParamNonNullReturn(Call, DV, C, /*IsCheckedCast=*/true); } -void CastValueChecker::evalGetAs(const CallExpr *CE, DefinedOrUnknownSVal DV, +void CastValueChecker::evalGetAs(const CallEvent &Call, DefinedOrUnknownSVal DV, CheckerContext &C) const { - evalZeroParamNonNullReturn(CE, DV, C); - evalZeroParamNullReturn(CE, DV, C); + evalZeroParamNonNullReturn(Call, DV, C); + evalZeroParamNullReturn(Call, DV, C); } +//===----------------------------------------------------------------------===// +// Main logic to evaluate a call. +//===----------------------------------------------------------------------===// + bool CastValueChecker::evalCall(const CallEvent &Call, CheckerContext &C) const { const auto *Lookup = CDM.lookup(Call); if (!Lookup) return false; - // If we cannot obtain the call's class we cannot be sure how to model it. - QualType ResultTy = Call.getResultType(); - if (!ResultTy->getPointeeCXXRecordDecl()) + // We need to obtain the record type of the call's result to model it. + if (!getRecordType(Call.getResultType())->isRecordType()) return false; const CastCheck &Check = Lookup->first; - CastKind Kind = Lookup->second; - - const auto *CE = cast(Call.getOriginExpr()); + CallKind Kind = Lookup->second; Optional DV; switch (Kind) { - case CastKind::Function: { - // If we cannot obtain the arg's class we cannot be sure how to model it. - QualType ArgTy = Call.parameters()[0]->getType(); - if (!ArgTy->getAsCXXRecordDecl() && !ArgTy->getPointeeCXXRecordDecl()) + case CallKind::Function: { + // We need to obtain the record type of the call's parameter to model it. + if (!getRecordType(Call.parameters()[0]->getType())->isRecordType()) return false; DV = Call.getArgSVal(0).getAs(); break; } - case CastKind::Method: - // If we cannot obtain the 'InstanceCall' we cannot be sure how to model it. + case CallKind::Method: const auto *InstanceCall = dyn_cast(&Call); if (!InstanceCall) return false; @@ -247,10 +316,15 @@ bool CastValueChecker::evalCall(const CallEvent &Call, if (!DV) return false; - Check(this, CE, *DV, C); + Check(this, Call, *DV, C); return true; } +void CastValueChecker::checkDeadSymbols(SymbolReaper &SR, + CheckerContext &C) const { + C.addTransition(removeDeadCasts(C.getState(), SR)); +} + void ento::registerCastValueChecker(CheckerManager &Mgr) { Mgr.registerChecker(); } diff --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp index f5a968bde372..f2d1d018914d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp @@ -20,16 +20,16 @@ // //===----------------------------------------------------------------------===// -#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" #include "clang/AST/ParentMap.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/Builtins.h" +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" using namespace clang; @@ -113,14 +113,7 @@ public: void DynamicTypePropagation::checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const { - ProgramStateRef State = C.getState(); - DynamicTypeMapTy TypeMap = State->get(); - for (DynamicTypeMapTy::iterator I = TypeMap.begin(), E = TypeMap.end(); - I != E; ++I) { - if (!SR.isLiveRegion(I->first)) { - State = State->remove(I->first); - } - } + ProgramStateRef State = removeDeadTypes(C.getState(), SR); MostSpecializedTypeArgsMapTy TyArgMap = State->get(); @@ -882,7 +875,7 @@ void DynamicTypePropagation::checkPostObjCMessage(const ObjCMethodCall &M, // When there is an entry available for the return symbol in DynamicTypeMap, // the call was inlined, and the information in the DynamicTypeMap is should // be precise. - if (RetRegion && !State->get(RetRegion)) { + if (RetRegion && !getRawDynamicTypeInfo(State, RetRegion)) { // TODO: we have duplicated information in DynamicTypeMap and // MostSpecializedTypeArgsMap. We should only store anything in the later if // the stored data differs from the one stored in the former. diff --git a/clang/lib/StaticAnalyzer/Core/CMakeLists.txt b/clang/lib/StaticAnalyzer/Core/CMakeLists.txt index 0affa8be5572..05bc94c7c984 100644 --- a/clang/lib/StaticAnalyzer/Core/CMakeLists.txt +++ b/clang/lib/StaticAnalyzer/Core/CMakeLists.txt @@ -16,7 +16,7 @@ add_clang_library(clangStaticAnalyzerCore CommonBugCategories.cpp ConstraintManager.cpp CoreEngine.cpp - DynamicTypeMap.cpp + DynamicType.cpp Environment.cpp ExplodedGraph.cpp ExprEngine.cpp diff --git a/clang/lib/StaticAnalyzer/Core/DynamicType.cpp b/clang/lib/StaticAnalyzer/Core/DynamicType.cpp new file mode 100644 index 000000000000..a9e281ec9e58 --- /dev/null +++ b/clang/lib/StaticAnalyzer/Core/DynamicType.cpp @@ -0,0 +1,223 @@ +//===- DynamicType.cpp - Dynamic type related APIs --------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines APIs that track and query dynamic type information. This +// information can be used to devirtualize calls during the symbolic execution +// or do type checking. +// +//===----------------------------------------------------------------------===// + +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" +#include "clang/Basic/JsonSupport.h" +#include "clang/Basic/LLVM.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/raw_ostream.h" +#include + +/// The GDM component containing the dynamic type info. This is a map from a +/// symbol to its most likely type. +REGISTER_MAP_WITH_PROGRAMSTATE(DynamicTypeMap, const clang::ento::MemRegion *, + clang::ento::DynamicTypeInfo) + +/// A set factory of dynamic cast informations. +REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(CastSet, clang::ento::DynamicCastInfo) + +/// A map from symbols to cast informations. +REGISTER_MAP_WITH_PROGRAMSTATE(DynamicCastMap, const clang::ento::MemRegion *, + CastSet) + +namespace clang { +namespace ento { + +DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR) { + MR = MR->StripCasts(); + + // Look up the dynamic type in the GDM. + if (const DynamicTypeInfo *DTI = State->get(MR)) + return *DTI; + + // Otherwise, fall back to what we know about the region. + if (const auto *TR = dyn_cast(MR)) + return DynamicTypeInfo(TR->getLocationType(), /*CanBeSub=*/false); + + if (const auto *SR = dyn_cast(MR)) { + SymbolRef Sym = SR->getSymbol(); + return DynamicTypeInfo(Sym->getType()); + } + + return {}; +} + +const DynamicTypeInfo *getRawDynamicTypeInfo(ProgramStateRef State, + const MemRegion *MR) { + return State->get(MR); +} + +const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State, + const MemRegion *MR, + QualType CastFromTy, + QualType CastToTy) { + const auto *Lookup = State->get().lookup(MR); + if (!Lookup) + return nullptr; + + for (const DynamicCastInfo &Cast : *Lookup) + if (Cast.equals(CastFromTy, CastToTy)) + return &Cast; + + return nullptr; +} + +ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, + DynamicTypeInfo NewTy) { + State = State->set(MR->StripCasts(), NewTy); + assert(State); + return State; +} + +ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, + QualType NewTy, bool CanBeSubClassed) { + return setDynamicTypeInfo(State, MR, DynamicTypeInfo(NewTy, CanBeSubClassed)); +} + +ProgramStateRef setDynamicTypeAndCastInfo(ProgramStateRef State, + const MemRegion *MR, + QualType CastFromTy, + QualType CastToTy, QualType ResultTy, + bool CastSucceeds) { + if (CastSucceeds) + State = State->set(MR, ResultTy); + + DynamicCastInfo::CastResult ResultKind = + CastSucceeds ? DynamicCastInfo::CastResult::Success + : DynamicCastInfo::CastResult::Failure; + + CastSet::Factory &F = State->get_context(); + + const CastSet *TempSet = State->get(MR); + CastSet Set = TempSet ? *TempSet : F.getEmptySet(); + + Set = F.add(Set, {CastFromTy, CastToTy, ResultKind}); + State = State->set(MR, Set); + + assert(State); + return State; +} + +template +ProgramStateRef removeDead(ProgramStateRef State, const MapTy &Map, + SymbolReaper &SR) { + for (const auto &Elem : Map) + if (!SR.isLiveRegion(Elem.first)) + State = State->remove(Elem.first); + + return State; +} + +ProgramStateRef removeDeadTypes(ProgramStateRef State, SymbolReaper &SR) { + return removeDead(State, State->get(), SR); +} + +ProgramStateRef removeDeadCasts(ProgramStateRef State, SymbolReaper &SR) { + return removeDead(State, State->get(), SR); +} + +static void printDynamicTypesJson(raw_ostream &Out, ProgramStateRef State, + const char *NL, unsigned int Space, + bool IsDot) { + Indent(Out, Space, IsDot) << "\"dynamic_types\": "; + + const DynamicTypeMapTy &Map = State->get(); + if (Map.isEmpty()) { + Out << "null," << NL; + return; + } + + ++Space; + Out << '[' << NL; + for (DynamicTypeMapTy::iterator I = Map.begin(); I != Map.end(); ++I) { + const MemRegion *MR = I->first; + const DynamicTypeInfo &DTI = I->second; + Indent(Out, Space, IsDot) + << "{ \"region\": \"" << MR << "\", \"dyn_type\": "; + if (!DTI.isValid()) { + Out << "null"; + } else { + Out << '\"' << DTI.getType()->getPointeeType().getAsString() + << "\", \"sub_classable\": " + << (DTI.canBeASubClass() ? "true" : "false"); + } + Out << " }"; + + if (std::next(I) != Map.end()) + Out << ','; + Out << NL; + } + + --Space; + Indent(Out, Space, IsDot) << "]," << NL; +} + +static void printDynamicCastsJson(raw_ostream &Out, ProgramStateRef State, + const char *NL, unsigned int Space, + bool IsDot) { + Indent(Out, Space, IsDot) << "\"dynamic_casts\": "; + + const DynamicCastMapTy &Map = State->get(); + if (Map.isEmpty()) { + Out << "null," << NL; + return; + } + + ++Space; + Out << '[' << NL; + for (DynamicCastMapTy::iterator I = Map.begin(); I != Map.end(); ++I) { + const MemRegion *MR = I->first; + const CastSet &Set = I->second; + + Indent(Out, Space, IsDot) << "{ \"region\": \"" << MR << "\", \"casts\": "; + if (Set.isEmpty()) { + Out << "null "; + } else { + ++Space; + Out << '[' << NL; + for (CastSet::iterator SI = Set.begin(); SI != Set.end(); ++SI) { + Indent(Out, Space, IsDot) + << "{ \"from\": \"" << SI->from().getAsString() << "\", \"to\": \"" + << SI->to().getAsString() << "\", \"kind\": \"" + << (SI->succeeds() ? "success" : "fail") << "\" }"; + + if (std::next(SI) != Set.end()) + Out << ','; + Out << NL; + } + --Space; + Indent(Out, Space, IsDot) << ']'; + } + Out << '}'; + + if (std::next(I) != Map.end()) + Out << ','; + Out << NL; + } + + --Space; + Indent(Out, Space, IsDot) << "]," << NL; +} + +void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, + const char *NL, unsigned int Space, bool IsDot) { + printDynamicTypesJson(Out, State, NL, Space, IsDot); + printDynamicCastsJson(Out, State, NL, Space, IsDot); +} + +} // namespace ento +} // namespace clang diff --git a/clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp b/clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp deleted file mode 100644 index 79424452240d..000000000000 --- a/clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp +++ /dev/null @@ -1,97 +0,0 @@ -//===- DynamicTypeMap.cpp - Dynamic Type Info related APIs ----------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file defines APIs that track and query dynamic type information. This -// information can be used to devirtualize calls during the symbolic execution -// or do type checking. -// -//===----------------------------------------------------------------------===// - -#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h" -#include "clang/Basic/JsonSupport.h" -#include "clang/Basic/LLVM.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h" -#include "llvm/Support/Casting.h" -#include "llvm/Support/raw_ostream.h" -#include - -namespace clang { -namespace ento { - -DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, - const MemRegion *Reg) { - Reg = Reg->StripCasts(); - - // Look up the dynamic type in the GDM. - const DynamicTypeInfo *GDMType = State->get(Reg); - if (GDMType) - return *GDMType; - - // Otherwise, fall back to what we know about the region. - if (const auto *TR = dyn_cast(Reg)) - return DynamicTypeInfo(TR->getLocationType(), /*CanBeSub=*/false); - - if (const auto *SR = dyn_cast(Reg)) { - SymbolRef Sym = SR->getSymbol(); - return DynamicTypeInfo(Sym->getType()); - } - - return {}; -} - -ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg, - DynamicTypeInfo NewTy) { - Reg = Reg->StripCasts(); - ProgramStateRef NewState = State->set(Reg, NewTy); - assert(NewState); - return NewState; -} - -void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, - const char *NL, unsigned int Space, bool IsDot) { - Indent(Out, Space, IsDot) << "\"dynamic_types\": "; - - const DynamicTypeMapTy &DTM = State->get(); - if (DTM.isEmpty()) { - Out << "null," << NL; - return; - } - - ++Space; - Out << '[' << NL; - for (DynamicTypeMapTy::iterator I = DTM.begin(); I != DTM.end(); ++I) { - const MemRegion *MR = I->first; - const DynamicTypeInfo &DTI = I->second; - Out << "{ \"region\": \"" << MR << "\", \"dyn_type\": "; - if (DTI.isValid()) { - Out << '\"' << DTI.getType()->getPointeeType().getAsString() - << "\", \"sub_classable\": " - << (DTI.canBeASubClass() ? "true" : "false"); - } else { - Out << "null"; // Invalid type info - } - Out << "}"; - - if (std::next(I) != DTM.end()) - Out << ','; - Out << NL; - } - - --Space; - Indent(Out, Space, IsDot) << "]," << NL; -} - -void *ProgramStateTrait::GDMIndex() { - static int index = 0; - return &index; -} - -} // namespace ento -} // namespace clang diff --git a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp index a1ca0b1b84bf..f50d82de3b28 100644 --- a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp +++ b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp @@ -15,7 +15,7 @@ #include "clang/Basic/JsonSupport.h" #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" -#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" #include "llvm/Support/raw_ostream.h" diff --git a/clang/test/Analysis/Inputs/llvm.h b/clang/test/Analysis/Inputs/llvm.h new file mode 100644 index 000000000000..9d465c65fda9 --- /dev/null +++ b/clang/test/Analysis/Inputs/llvm.h @@ -0,0 +1,19 @@ +#pragma clang system_header + +namespace llvm { +template +const X *cast(Y Value); + +template +const X *dyn_cast(Y *Value); +template +const X &dyn_cast(Y &Value); + +template +const X *cast_or_null(Y Value); + +template +const X *dyn_cast_or_null(Y *Value); +template +const X *dyn_cast_or_null(Y &Value); +} // namespace llvm diff --git a/clang/test/Analysis/cast-value-logic.cpp b/clang/test/Analysis/cast-value-logic.cpp new file mode 100644 index 000000000000..32001d8548a2 --- /dev/null +++ b/clang/test/Analysis/cast-value-logic.cpp @@ -0,0 +1,128 @@ +// RUN: %clang_analyze_cc1 \ +// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\ +// RUN: -verify %s + +#include "Inputs/llvm.h" + +void clang_analyzer_numTimesReached(); +void clang_analyzer_warnIfReached(); +void clang_analyzer_eval(bool); + +namespace clang { +struct Shape { + template + const T *castAs() const; + + template + const T *getAs() const; +}; +class Triangle : public Shape {}; +class Circle : public Shape {}; +} // namespace clang + +using namespace llvm; +using namespace clang; + +void test_regions(const Shape *A, const Shape *B) { + if (dyn_cast(A) && !dyn_cast(B)) + clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} +} + +namespace test_cast { +void evalLogic(const Shape *S) { + const Circle *C = cast(S); + clang_analyzer_numTimesReached(); // expected-warning {{1}} + + if (S && C) + clang_analyzer_eval(C == S); // expected-warning {{TRUE}} + + if (S && !C) + clang_analyzer_warnIfReached(); // no-warning + + if (!S) + clang_analyzer_warnIfReached(); // no-warning +} +} // namespace test_cast + +namespace test_dyn_cast { +void evalLogic(const Shape *S) { + const Circle *C = dyn_cast(S); + clang_analyzer_numTimesReached(); // expected-warning {{2}} + + if (S && C) + clang_analyzer_eval(C == S); // expected-warning {{TRUE}} + + if (S && !C) + clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} + + if (!S) + clang_analyzer_warnIfReached(); // no-warning +} +} // namespace test_dyn_cast + +namespace test_cast_or_null { +void evalLogic(const Shape *S) { + const Circle *C = cast_or_null(S); + clang_analyzer_numTimesReached(); // expected-warning {{2}} + + if (S && C) + clang_analyzer_eval(C == S); // expected-warning {{TRUE}} + + if (S && !C) + clang_analyzer_warnIfReached(); // no-warning + + if (!S) + clang_analyzer_eval(!C); // expected-warning {{TRUE}} +} +} // namespace test_cast_or_null + +namespace test_dyn_cast_or_null { +void evalLogic(const Shape *S) { + const Circle *C = dyn_cast_or_null(S); + clang_analyzer_numTimesReached(); // expected-warning {{3}} + + if (S && C) + clang_analyzer_eval(C == S); // expected-warning {{TRUE}} + + if (S && !C) + clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} + + if (!S) + clang_analyzer_eval(!C); // expected-warning {{TRUE}} +} +} // namespace test_dyn_cast_or_null + +namespace test_cast_as { +void evalLogic(const Shape *S) { + const Circle *C = S->castAs(); + clang_analyzer_numTimesReached(); // expected-warning {{1}} + + if (S && C) + clang_analyzer_eval(C == S); + // expected-warning@-1 {{TRUE}} + + if (S && !C) + clang_analyzer_warnIfReached(); // no-warning + + if (!S) + clang_analyzer_warnIfReached(); // no-warning +} +} // namespace test_cast_as + +namespace test_get_as { +void evalLogic(const Shape *S) { + const Circle *C = S->getAs(); + clang_analyzer_numTimesReached(); // expected-warning {{2}} + + if (S && C) + clang_analyzer_eval(C == S); + // expected-warning@-1 {{TRUE}} + + if (S && !C) + clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} + + if (!S) + clang_analyzer_warnIfReached(); // no-warning +} +} // namespace test_get_as + diff --git a/clang/test/Analysis/cast-value-notes.cpp b/clang/test/Analysis/cast-value-notes.cpp new file mode 100644 index 000000000000..77801d699350 --- /dev/null +++ b/clang/test/Analysis/cast-value-notes.cpp @@ -0,0 +1,144 @@ +// RUN: %clang_analyze_cc1 \ +// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue \ +// RUN: -analyzer-output=text -verify %s + +#include "Inputs/llvm.h" + +namespace clang { +struct Shape { + template + const T *castAs() const; + + template + const T *getAs() const; +}; +class Triangle : public Shape {}; +class Circle : public Shape {}; +} // namespace clang + +using namespace llvm; +using namespace clang; + +void evalReferences(const Shape &S) { + const auto &C = dyn_cast(S); + // expected-note@-1 {{Assuming 'S' is not a 'Circle'}} + // expected-note@-2 {{Dereference of null pointer}} + // expected-warning@-3 {{Dereference of null pointer}} +} + +void evalNonNullParamNonNullReturnReference(const Shape &S) { + const auto *C = dyn_cast_or_null(S); + // expected-note@-1 {{Assuming 'S' is a 'Circle'}} + // expected-note@-2 {{'C' initialized here}} + + if (!dyn_cast_or_null(C)) { + // expected-note@-1 {{'C' is a 'Circle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Assuming 'C' is not a 'Triangle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{'C' is not a 'Triangle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + (void)(1 / !C); + // expected-note@-1 {{'C' is non-null}} + // expected-note@-2 {{Division by zero}} + // expected-warning@-3 {{Division by zero}} +} + +void evalNonNullParamNonNullReturn(const Shape *S) { + const auto *C = cast(S); + // expected-note@-1 {{'S' is a 'Circle'}} + // expected-note@-2 {{'C' initialized here}} + + if (!cast(C)) { + // expected-note@-1 {{'C' is a 'Triangle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + (void)(1 / !C); + // expected-note@-1 {{'C' is non-null}} + // expected-note@-2 {{Division by zero}} + // expected-warning@-3 {{Division by zero}} +} + +void evalNonNullParamNullReturn(const Shape *S) { + const auto *C = dyn_cast_or_null(S); + // expected-note@-1 {{Assuming 'S' is not a 'Circle'}} + + if (const auto *T = dyn_cast_or_null(S)) { + // expected-note@-1 {{Assuming 'S' is a 'Triangle'}} + // expected-note@-2 {{'T' initialized here}} + // expected-note@-3 {{'T' is non-null}} + // expected-note@-4 {{Taking true branch}} + + (void)(1 / !T); + // expected-note@-1 {{'T' is non-null}} + // expected-note@-2 {{Division by zero}} + // expected-warning@-3 {{Division by zero}} + } +} + +void evalNullParamNullReturn(const Shape *S) { + const auto *C = dyn_cast_or_null(S); + // expected-note@-1 {{Assuming null pointer is passed into cast}} + // expected-note@-2 {{'C' initialized to a null pointer value}} + + (void)(1 / (bool)C); + // expected-note@-1 {{Division by zero}} + // expected-warning@-2 {{Division by zero}} +} + +void evalZeroParamNonNullReturnPointer(const Shape *S) { + const auto *C = S->castAs(); + // expected-note@-1 {{'S' is a 'Circle'}} + // expected-note@-2 {{'C' initialized here}} + + (void)(1 / !C); + // expected-note@-1 {{'C' is non-null}} + // expected-note@-2 {{Division by zero}} + // expected-warning@-3 {{Division by zero}} +} + +void evalZeroParamNonNullReturn(const Shape &S) { + const auto *C = S.castAs(); + // expected-note@-1 {{'S' is a 'Circle'}} + // expected-note@-2 {{'C' initialized here}} + + (void)(1 / !C); + // expected-note@-1 {{'C' is non-null}} + // expected-note@-2 {{Division by zero}} + // expected-warning@-3 {{Division by zero}} +} + +void evalZeroParamNullReturn(const Shape &S) { + const auto *C = S.getAs(); + // expected-note@-1 {{Assuming 'S' is not a 'Circle'}} + // expected-note@-2 {{'C' initialized to a null pointer value}} + + if (!dyn_cast_or_null(S)) { + // expected-note@-1 {{Assuming 'S' is a 'Triangle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (!dyn_cast_or_null(S)) { + // expected-note@-1 {{'S' is a 'Triangle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + (void)(1 / (bool)C); + // expected-note@-1 {{Division by zero}} + // expected-warning@-2 {{Division by zero}} +} diff --git a/clang/test/Analysis/cast-value-state-dump.cpp b/clang/test/Analysis/cast-value-state-dump.cpp new file mode 100644 index 000000000000..fd679984d6b2 --- /dev/null +++ b/clang/test/Analysis/cast-value-state-dump.cpp @@ -0,0 +1,47 @@ +// RUN: %clang_analyze_cc1 \ +// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\ +// RUN: -analyzer-output=text -verify %s 2>&1 | FileCheck %s + +#include "Inputs/llvm.h" + +void clang_analyzer_printState(); + +namespace clang { +struct Shape {}; +class Triangle : public Shape {}; +class Circle : public Shape {}; +class Square : public Shape {}; +} // namespace clang + +using namespace llvm; +using namespace clang; + +void evalNonNullParamNonNullReturnReference(const Shape &S) { + const auto *C = dyn_cast_or_null(S); + // expected-note@-1 {{Assuming 'S' is a 'Circle'}} + // expected-note@-2 {{'C' initialized here}} + + // FIXME: We assumed that 'S' is a 'Circle' therefore it is not a 'Square'. + if (dyn_cast_or_null(S)) { + // expected-note@-1 {{Assuming 'S' is not a 'Square'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + clang_analyzer_printState(); + + // CHECK: "dynamic_types": [ + // CHECK-NEXT: { "region": "SymRegion{reg_$0}", "dyn_type": "const class clang::Circle", "sub_classable": true } + // CHECK-NEXT: ], + // CHECK-NEXT: "dynamic_casts": [ + // CHECK: { "region": "SymRegion{reg_$0}", "casts": [ + // CHECK-NEXT: { "from": "struct clang::Shape", "to": "class clang::Circle", "kind": "success" }, + // CHECK-NEXT: { "from": "struct clang::Shape", "to": "class clang::Square", "kind": "fail" } + // CHECK-NEXT: ]} + + (void)(1 / !C); + // expected-note@-1 {{'C' is non-null}} + // expected-note@-2 {{Division by zero}} + // expected-warning@-3 {{Division by zero}} +} + diff --git a/clang/test/Analysis/cast-value.cpp b/clang/test/Analysis/cast-value.cpp deleted file mode 100644 index fcf145365ea4..000000000000 --- a/clang/test/Analysis/cast-value.cpp +++ /dev/null @@ -1,239 +0,0 @@ -// RUN: %clang_analyze_cc1 \ -// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\ -// RUN: -verify=logic %s -// RUN: %clang_analyze_cc1 \ -// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue \ -// RUN: -analyzer-output=text -verify %s - -void clang_analyzer_numTimesReached(); -void clang_analyzer_warnIfReached(); -void clang_analyzer_eval(bool); - -namespace llvm { -template -const X *cast(Y Value); - -template -const X *dyn_cast(Y *Value); -template -const X &dyn_cast(Y &Value); - -template -const X *cast_or_null(Y Value); - -template -const X *dyn_cast_or_null(Y *Value); -template -const X *dyn_cast_or_null(Y &Value); -} // namespace llvm - -namespace clang { -struct Shape { - template - const T *castAs() const; - - template - const T *getAs() const; -}; -class Triangle : public Shape {}; -class Circle : public Shape {}; -} // namespace clang - -using namespace llvm; -using namespace clang; - -namespace test_cast { -void evalLogic(const Shape *S) { - const Circle *C = cast(S); - clang_analyzer_numTimesReached(); // logic-warning {{1}} - - if (S && C) - clang_analyzer_eval(C == S); // logic-warning {{TRUE}} - - if (S && !C) - clang_analyzer_warnIfReached(); // no-warning - - if (!S) - clang_analyzer_warnIfReached(); // no-warning -} -} // namespace test_cast - -namespace test_dyn_cast { -void evalLogic(const Shape *S) { - const Circle *C = dyn_cast(S); - clang_analyzer_numTimesReached(); // logic-warning {{2}} - - if (S && C) - clang_analyzer_eval(C == S); // logic-warning {{TRUE}} - - if (S && !C) - clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}} - - if (!S) - clang_analyzer_warnIfReached(); // no-warning -} -} // namespace test_dyn_cast - -namespace test_cast_or_null { -void evalLogic(const Shape *S) { - const Circle *C = cast_or_null(S); - clang_analyzer_numTimesReached(); // logic-warning {{2}} - - if (S && C) - clang_analyzer_eval(C == S); // logic-warning {{TRUE}} - - if (S && !C) - clang_analyzer_warnIfReached(); // no-warning - - if (!S) - clang_analyzer_eval(!C); // logic-warning {{TRUE}} -} -} // namespace test_cast_or_null - -namespace test_dyn_cast_or_null { -void evalLogic(const Shape *S) { - const Circle *C = dyn_cast_or_null(S); - clang_analyzer_numTimesReached(); // logic-warning {{3}} - - if (S && C) - clang_analyzer_eval(C == S); // logic-warning {{TRUE}} - - if (S && !C) - clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}} - - if (!S) - clang_analyzer_eval(!C); // logic-warning {{TRUE}} -} -} // namespace test_dyn_cast_or_null - -namespace test_cast_as { -void evalLogic(const Shape *S) { - const Circle *C = S->castAs(); - clang_analyzer_numTimesReached(); // logic-warning {{1}} - - if (S && C) - clang_analyzer_eval(C == S); - // logic-warning@-1 {{TRUE}} - - if (S && !C) - clang_analyzer_warnIfReached(); // no-warning - - if (!S) - clang_analyzer_warnIfReached(); // no-warning -} -} // namespace test_cast_as - -namespace test_get_as { -void evalLogic(const Shape *S) { - const Circle *C = S->getAs(); - clang_analyzer_numTimesReached(); // logic-warning {{2}} - - if (S && C) - clang_analyzer_eval(C == S); - // logic-warning@-1 {{TRUE}} - - if (S && !C) - clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}} - - if (!S) - clang_analyzer_warnIfReached(); // no-warning -} -} // namespace test_get_as - -namespace test_notes { -void evalReferences(const Shape &S) { - const auto &C = dyn_cast(S); - // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' fails}} - // expected-note@-2 {{Dereference of null pointer}} - // expected-warning@-3 {{Dereference of null pointer}} - // logic-warning@-4 {{Dereference of null pointer}} -} - -void evalNonNullParamNonNullReturnReference(const Shape &S) { - const auto *C = dyn_cast_or_null(S); - // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' succeeds}} - // expected-note@-2 {{'C' initialized here}} - - (void)(1 / !(bool)C); - // expected-note@-1 {{'C' is non-null}} - // expected-note@-2 {{Division by zero}} - // expected-warning@-3 {{Division by zero}} - // logic-warning@-4 {{Division by zero}} -} - -void evalNonNullParamNonNullReturn(const Shape *S) { - const auto *C = cast(S); - // expected-note@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}} - // expected-note@-2 {{'C' initialized here}} - - (void)(1 / !(bool)C); - // expected-note@-1 {{'C' is non-null}} - // expected-note@-2 {{Division by zero}} - // expected-warning@-3 {{Division by zero}} - // logic-warning@-4 {{Division by zero}} -} - -void evalNonNullParamNullReturn(const Shape *S) { - const auto *C = dyn_cast_or_null(S); - // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' fails}} - - if (const auto *T = dyn_cast_or_null(S)) { - // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Triangle' succeeds}} - // expected-note@-2 {{'T' initialized here}} - // expected-note@-3 {{'T' is non-null}} - // expected-note@-4 {{Taking true branch}} - - (void)(1 / !T); - // expected-note@-1 {{'T' is non-null}} - // expected-note@-2 {{Division by zero}} - // expected-warning@-3 {{Division by zero}} - // logic-warning@-4 {{Division by zero}} - } -} - -void evalNullParamNullReturn(const Shape *S) { - const auto *C = dyn_cast_or_null(S); - // expected-note@-1 {{Assuming null pointer is passed into cast}} - // expected-note@-2 {{'C' initialized to a null pointer value}} - - (void)(1 / (bool)C); - // expected-note@-1 {{Division by zero}} - // expected-warning@-2 {{Division by zero}} - // logic-warning@-3 {{Division by zero}} -} - -void evalZeroParamNonNullReturnPointer(const Shape *S) { - const auto *C = S->castAs(); - // expected-note@-1 {{Checked cast to 'Circle' succeeds}} - // expected-note@-2 {{'C' initialized here}} - - (void)(1 / !(bool)C); - // expected-note@-1 {{'C' is non-null}} - // expected-note@-2 {{Division by zero}} - // expected-warning@-3 {{Division by zero}} - // logic-warning@-4 {{Division by zero}} -} - -void evalZeroParamNonNullReturn(const Shape &S) { - const auto *C = S.castAs(); - // expected-note@-1 {{Checked cast to 'Circle' succeeds}} - // expected-note@-2 {{'C' initialized here}} - - (void)(1 / !(bool)C); - // expected-note@-1 {{'C' is non-null}} - // expected-note@-2 {{Division by zero}} - // expected-warning@-3 {{Division by zero}} - // logic-warning@-4 {{Division by zero}} -} - -void evalZeroParamNullReturn(const Shape &S) { - const auto *C = S.getAs(); - // expected-note@-1 {{Assuming dynamic cast to 'Circle' fails}} - // expected-note@-2 {{'C' initialized to a null pointer value}} - - (void)(1 / (bool)C); - // expected-note@-1 {{Division by zero}} - // expected-warning@-2 {{Division by zero}} - // logic-warning@-3 {{Division by zero}} -} -} // namespace test_notes diff --git a/clang/test/Analysis/dump_egraph.cpp b/clang/test/Analysis/dump_egraph.cpp index f5db3d142eed..a56f06194927 100644 --- a/clang/test/Analysis/dump_egraph.cpp +++ b/clang/test/Analysis/dump_egraph.cpp @@ -24,4 +24,5 @@ void foo() { // CHECK: \"cluster\": \"t\", \"pointer\": \"{{0x[0-9a-f]+}}\", \"items\": [\l        \{ \"kind\": \"Default\", \"offset\": 0, \"value\": \"conj_$2\{int, LC5, no stmt, #1\}\" -// CHECK: \"dynamic_types\": [\l\{ \"region\": \"HeapSymRegion\{conj_$1\{struct S *, LC1, S{{[0-9]+}}, #1\}\}\", \"dyn_type\": \"struct S\", \"sub_classable\": false\}\l +// CHECK: \"dynamic_types\": [\l      \{ \"region\": \"HeapSymRegion\{conj_$1\{struct S *, LC1, S{{[0-9]+}}, #1\}\}\", \"dyn_type\": \"struct S\", \"sub_classable\": false \}\l + diff --git a/clang/test/Analysis/expr-inspection.c b/clang/test/Analysis/expr-inspection.c index c2bcafe06896..6d9ea4bb26c1 100644 --- a/clang/test/Analysis/expr-inspection.c +++ b/clang/test/Analysis/expr-inspection.c @@ -38,6 +38,7 @@ void foo(int x) { // CHECK-NEXT: { "symbol": "reg_$0", "range": "{ [-2147483648, 13] }" } // CHECK-NEXT: ], // CHECK-NEXT: "dynamic_types": null, +// CHECK-NEXT: "dynamic_casts": null, // CHECK-NEXT: "constructing_objects": null, // CHECK-NEXT: "checker_messages": null // CHECK-NEXT: }