Index: clang/include/clang/AST/Type.h =================================================================== --- clang/include/clang/AST/Type.h +++ clang/include/clang/AST/Type.h @@ -972,6 +972,9 @@ 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) { Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h =================================================================== --- /dev/null +++ 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 CastKind { Success, Fail }; + + DynamicCastInfo(QualType from, QualType to, CastKind kind) + : From(from), To(to), Kind(kind) {} + + QualType from() const { return From; } + QualType to() const { return To; } + + bool equals(QualType from, QualType to) const { + return From == from && To == to; + } + + bool isSucceeds() const { return Kind == CastKind::Success; } + bool isFails() const { return Kind == CastKind::Fail; } + + 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(Kind); + } + +private: + QualType From, To; + CastKind Kind; +}; + +} // namespace ento +} // namespace clang + +#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h =================================================================== --- clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h +++ 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 @@ /// 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) {} + + /// 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; } - /// Return false if no dynamic type info is available. - bool isValid() const { return !T.isNull(); } + /// 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 T; } + QualType getType() const { return DynTy; } - /// Returns false if the type information is precise (the type T is - /// the only type in the lattice), true otherwise. - bool canBeASubClass() const { return CanBeASubClass; } + 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 Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h =================================================================== --- clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h +++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h @@ -13,45 +13,49 @@ #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_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/ProgramState_Fwd.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" #include "llvm/ADT/ImmutableMap.h" -#include "clang/AST/Type.h" - -namespace clang { -namespace ento { - -class MemRegion; +#include "llvm/ADT/Optional.h" +#include /// The GDM component containing the dynamic type info. This is a map from a /// symbol to its most likely type. -struct DynamicTypeMap {}; +REGISTER_MAP_WITH_PROGRAMSTATE(DynamicTypeMap, const clang::ento::MemRegion *, + clang::ento::DynamicTypeInfo) + +/// A set of dynamic cast informations. +REGISTER_SET_WITH_PROGRAMSTATE(DynamicCastSet, clang::ento::DynamicCastInfo) -using DynamicTypeMapTy = llvm::ImmutableMap; +namespace clang { +namespace ento { -template <> -struct ProgramStateTrait - : public ProgramStatePartialTrait { - static void *GDMIndex(); -}; +/// Get dynamic type information for the region \p MR. +DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR); -/// Get dynamic type information for a region. -DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, - const MemRegion *Reg); +/// Get dynamic cast information from \p CastFromTy type to \p CastToTy type. +const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State, + QualType CastFromTy, + QualType CastToTy); /// Set dynamic type information of the region; return the new state. -ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg, +ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, 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)); -} +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); void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n", unsigned int Space = 0, Index: clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp @@ -15,6 +15,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/DynamicTypeMap.h" #include "llvm/ADT/Optional.h" #include @@ -23,210 +24,245 @@ 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; 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(); + + if (Ty->isPointerType()) + return getRecordType(Ty->getPointeeType()); - return Ty->getPointeeCXXRecordDecl()->getNameAsString(); + if (Ty->isReferenceType()) + return getRecordType(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); - - return C.getNoteTag( - [CastFromName, CastToName, IsNullReturn, - IsCheckedCast](BugReport &) -> std::string { +//===----------------------------------------------------------------------===// +// 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; + + QualType RawCastFromTy = + (Call.getNumArgs() > 0) + ? Call.parameters()[0]->getType() + : cast(&Call)->getCXXThisExpr()->getType(); + + QualType CastFromTy = getRecordType(RawCastFromTy); + QualType CastToTy = getRecordType(Call.getResultType()); + + const DynamicCastInfo *Cast = getDynamicCastInfo(State, CastFromTy, CastToTy); + + // We assume that every checked cast succeeds. + bool IsCastSucceeds; + if (Cast) + IsCastSucceeds = IsCheckedCast || (IsNonNullReturn && Cast->isSucceeds()); + else + IsCastSucceeds = IsCheckedCast || IsNonNullReturn || CastFromTy == CastToTy; + + // Check for infeasible casts. + if (!IsCheckedCast && Cast) { + if ((IsCastSucceeds && Cast->isFails()) || + (!IsCastSucceeds && Cast->isSucceeds())) { + C.generateSink(State, C.getPredecessor()); + return; + } + } + + // Store the type and the cast information. + const MemRegion *MR = DV.getAsRegion(); + bool IsKnownCast = Cast || CastFromTy == CastToTy; + if (!IsKnownCast) + State = setDynamicTypeAndCastInfo(State, MR, CastFromTy, CastToTy, + Call.getResultType(), IsCastSucceeds); + + const NoteTag *Tag = C.getNoteTag( + [=](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 (!IsCheckedCast) + Out << (IsKnownCast ? "Dynamic cast" : "Assuming dynamic cast"); + else + Out << "Checked cast"; - Out << "to '" << CastToName << "' " - << (!IsNullReturn ? "succeeds" : "fails"); + Out << " from '" << CastFromTy->getAsCXXRecordDecl()->getNameAsString() + << "' to '" << CastToTy->getAsCXXRecordDecl()->getNameAsString() + << "' " << (IsCastSucceeds ? "succeeds" : "fails"); 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); + SVal V = IsCastSucceeds ? DV : C.getSValBuilder().makeNull(); + C.addTransition( + State->BindExpr(Call.getOriginExpr(), C.getLocationContext(), V, false), + Tag); } //===----------------------------------------------------------------------===// // 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 (!Call.getResultType()->getPointeeCXXRecordDecl()) 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. + case CallKind::Function: { + // We need to obtain the record type of the call's parameter to model it. QualType ArgTy = Call.parameters()[0]->getType(); if (!ArgTy->getAsCXXRecordDecl() && !ArgTy->getPointeeCXXRecordDecl()) return false; @@ -234,8 +270,7 @@ 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,7 +282,7 @@ if (!DV) return false; - Check(this, CE, *DV, C); + Check(this, Call, *DV, C); return true; } Index: clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp =================================================================== --- clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp +++ clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp @@ -25,20 +25,18 @@ namespace clang { namespace ento { -DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, - const MemRegion *Reg) { - Reg = Reg->StripCasts(); +DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR) { + MR = MR->StripCasts(); // Look up the dynamic type in the GDM. - const DynamicTypeInfo *GDMType = State->get(Reg); - if (GDMType) - return *GDMType; + 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(Reg)) + if (const auto *TR = dyn_cast(MR)) return DynamicTypeInfo(TR->getLocationType(), /*CanBeSub=*/false); - if (const auto *SR = dyn_cast(Reg)) { + if (const auto *SR = dyn_cast(MR)) { SymbolRef Sym = SR->getSymbol(); return DynamicTypeInfo(Sym->getType()); } @@ -46,40 +44,74 @@ return {}; } -ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg, +const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State, + QualType CastFromTy, + QualType CastToTy) { + for (const DynamicCastInfo &Cast : State->get()) + if (Cast.equals(CastFromTy, CastToTy)) + return &Cast; + + return nullptr; +} + +ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR, DynamicTypeInfo NewTy) { - Reg = Reg->StripCasts(); - ProgramStateRef NewState = State->set(Reg, NewTy); - assert(NewState); - return NewState; + State = State->set(MR->StripCasts(), NewTy); + assert(State); + return State; } -void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State, - const char *NL, unsigned int Space, bool IsDot) { +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 IsCastSucceeds) { + if (IsCastSucceeds) + State = State->set(MR, ResultTy); + + DynamicCastInfo::CastKind Kind = IsCastSucceeds + ? DynamicCastInfo::CastKind::Success + : DynamicCastInfo::CastKind::Fail; + + State = State->add({CastFromTy, CastToTy, Kind}); + + assert(State); + return State; +} + +static void printDynamicTypesJson(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()) { + const DynamicTypeMapTy &Map = State->get(); + if (Map.isEmpty()) { Out << "null," << NL; return; } ++Space; Out << '[' << NL; - for (DynamicTypeMapTy::iterator I = DTM.begin(); I != DTM.end(); ++I) { + for (DynamicTypeMapTy::iterator I = Map.begin(); I != Map.end(); ++I) { const MemRegion *MR = I->first; const DynamicTypeInfo &DTI = I->second; - Out << "{ \"region\": \"" << MR << "\", \"dyn_type\": "; - if (DTI.isValid()) { + 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"); - } else { - Out << "null"; // Invalid type info } - Out << "}"; + Out << " }"; - if (std::next(I) != DTM.end()) + if (std::next(I) != Map.end()) Out << ','; Out << NL; } @@ -88,9 +120,64 @@ Indent(Out, Space, IsDot) << "]," << NL; } -void *ProgramStateTrait::GDMIndex() { - static int index = 0; - return &index; +static void printDynamicCastsJson(raw_ostream &Out, ProgramStateRef State, + const char *NL, unsigned int Space, + bool IsDot) { + Indent(Out, Space, IsDot) << "\"dynamic_casts\": "; + + const DynamicCastSetTy &Set = State->get(); + if (Set.isEmpty()) { + Out << "null," << NL; + return; + } + + ++Space; + Out << '[' << NL; + + bool HasFailKind = false; + for (DynamicCastSetTy::iterator I = Set.begin(); I != Set.end(); ++I) { + if (I->isFails()) { + HasFailKind = true; + break; + } + } + + // Print 'Success' kind. + for (DynamicCastSetTy::iterator I = Set.begin(); I != Set.end(); ++I) { + if (I->isFails()) + continue; + + Indent(Out, Space, IsDot) + << "{ \"from\": \"" << I->from().getAsString() << "\", \"to\": \"" + << I->to().getAsString() << "\", \"kind\": \"success\" }"; + + if (HasFailKind || std::next(I) != Set.end()) + Out << ','; + Out << NL; + } + + // Print 'Fail' kind. + for (DynamicCastSetTy::iterator I = Set.begin(); I != Set.end(); ++I) { + if (I->isSucceeds()) + continue; + + Indent(Out, Space, IsDot) + << "{ \"from\": \"" << I->from().getAsString() << "\", \"to\": \"" + << I->to().getAsString() << "\", \"kind\": \"fail\" }"; + + if (std::next(I) != Set.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 Index: clang/test/Analysis/cast-value-logic.cpp =================================================================== --- /dev/null +++ clang/test/Analysis/cast-value-logic.cpp @@ -0,0 +1,139 @@ +// RUN: %clang_analyze_cc1 \ +// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\ +// RUN: -verify=logic %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 + Index: clang/test/Analysis/cast-value-notes.cpp =================================================================== --- clang/test/Analysis/cast-value-notes.cpp +++ clang/test/Analysis/cast-value-notes.cpp @@ -1,14 +1,7 @@ // 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); @@ -42,111 +35,25 @@ 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 evalContradiction(const Shape *S) { + const auto *C = dyn_cast_or_null(S); + // no-note: 'Assuming dynamic cast from 'Shape' to 'Circle' succeeds' + + if (dyn_cast_or_null(C)) { + // no-note: 'Dynamic cast from 'Circle' to 'Circle' fails' + return; + } + + (void)(1 / !C); + // no-note: "'C' is non-null" + // no-warning: Division by zero } void evalNonNullParamNonNullReturnReference(const Shape &S) { @@ -154,11 +61,28 @@ // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' succeeds}} // expected-note@-2 {{'C' initialized here}} - (void)(1 / !(bool)C); + if (!dyn_cast_or_null(C)) { + // expected-note@-1 {{Dynamic cast from 'Circle' to 'Circle' succeeds}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Assuming dynamic cast from 'Circle' to 'Triangle' fails}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Dynamic cast from 'Circle' to 'Triangle' fails}} + // 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}} - // logic-warning@-4 {{Division by zero}} } void evalNonNullParamNonNullReturn(const Shape *S) { @@ -166,11 +90,16 @@ // expected-note@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}} // expected-note@-2 {{'C' initialized here}} - (void)(1 / !(bool)C); + if (!cast(C)) { + // expected-note@-1 {{Checked cast from 'Circle' to 'Triangle' succeeds}} + // 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}} - // logic-warning@-4 {{Division by zero}} } void evalNonNullParamNullReturn(const Shape *S) { @@ -187,7 +116,6 @@ // 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}} } } @@ -199,41 +127,48 @@ (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@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}} // expected-note@-2 {{'C' initialized here}} - (void)(1 / !(bool)C); + (void)(1 / !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@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}} // expected-note@-2 {{'C' initialized here}} - (void)(1 / !(bool)C); + (void)(1 / !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@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' fails}} // expected-note@-2 {{'C' initialized to a null pointer value}} + if (!dyn_cast_or_null(S)) { + // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Triangle' succeeds}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (!dyn_cast_or_null(S)) { + // expected-note@-1 {{Dynamic cast from 'Shape' to 'Triangle' succeeds}} + // expected-note@-2 {{Taking false branch}} + return; + } + (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 Index: clang/test/Analysis/cast-value-state-dump.cpp =================================================================== --- /dev/null +++ clang/test/Analysis/cast-value-state-dump.cpp @@ -0,0 +1,69 @@ +// RUN: %clang_analyze_cc1 \ +// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\ +// RUN: -analyzer-output=text -verify %s 2>&1 | FileCheck %s + +void clang_analyzer_printState(); + +namespace llvm { +template +const X *dyn_cast_or_null(Y *Value); +template +const X *dyn_cast_or_null(Y &Value); +} // namespace llvm + +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 dynamic cast from 'Shape' to 'Circle' succeeds}} + // expected-note@-2 {{'C' initialized here}} + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Assuming dynamic cast from 'Circle' to 'Triangle' fails}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Dynamic cast from 'Circle' to 'Triangle' fails}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Assuming dynamic cast from 'Circle' to 'Square' fails}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(S)) { + // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Square' fails}} + // 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-NEXT: { "from": "struct clang::Shape", "to": "class clang::Circle", "kind": "success" }, + // CHECK-NEXT: { "from": "class clang::Circle", "to": "class clang::Triangle", "kind": "fail" }, + // CHECK-NEXT: { "from": "class clang::Circle", "to": "class clang::Square", "kind": "fail" }, + // 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}} +} Index: clang/test/Analysis/dump_egraph.cpp =================================================================== --- clang/test/Analysis/dump_egraph.cpp +++ clang/test/Analysis/dump_egraph.cpp @@ -24,4 +24,5 @@ // 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 + Index: clang/test/Analysis/expr-inspection.c =================================================================== --- clang/test/Analysis/expr-inspection.c +++ clang/test/Analysis/expr-inspection.c @@ -38,6 +38,7 @@ // 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: }