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/CheckerContext.h =================================================================== --- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h +++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h @@ -234,7 +234,7 @@ } /// 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 @@ 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. 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 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 Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h =================================================================== --- /dev/null +++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h @@ -0,0 +1,72 @@ +//===- 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 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 *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 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 +++ /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 Index: clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp @@ -6,15 +6,23 @@ // //===----------------------------------------------------------------------===// // -// 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. // //===----------------------------------------------------------------------===// +#include "clang/Lex/Lexer.h" #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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/CheckerContext.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" #include "llvm/ADT/Optional.h" #include @@ -23,219 +31,283 @@ 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(); + + if (Ty->isPointerType()) + Ty = Ty->getPointeeType(); + + if (Ty->isReferenceType()) + Ty = Ty.getNonReferenceType(); - return Ty->getPointeeCXXRecordDecl()->getNameAsString(); + 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 { +static std::string getObjectName(const Expr *E, CheckerContext &C) { + return Lexer::getSourceText( + CharSourceRange::getTokenRange(E->getSourceRange()), C.getSourceManager(), + C.getASTContext().getLangOpts()); +} + +static bool isInfeasibleCast(const DynamicCastInfo *CastInfo, + bool CastSucceeds) { + if (!CastInfo) + return false; + + return CastSucceeds ? CastInfo->fails() : CastInfo->succeeds(); +} + +//===----------------------------------------------------------------------===// +// 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; + + std::string ObjectName; + QualType CastFromTy; + QualType CastToTy = getRecordType(Call.getResultType()); + + if (Call.getNumArgs() > 0) { + CastFromTy = getRecordType(Call.parameters()[0]->getType()); + ObjectName = getObjectName(Call.getArgExpr(0), C); + } else { + const Expr *E = cast(&Call)->getCXXThisExpr(); + CastFromTy = getRecordType(E->getType()); + ObjectName = getObjectName(E, C); + } + + const DynamicCastInfo *CastInfo = + getDynamicCastInfo(State, 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. + const MemRegion *MR = DV.getAsRegion(); + bool IsKnownCast = CastInfo || IsCheckedCast || CastFromTy == CastToTy; + if (!IsKnownCast || IsCheckedCast) + State = setDynamicTypeAndCastInfo(State, MR, CastFromTy, CastToTy, + Call.getResultType(), CastSucceeds); + + const NoteTag *Tag = C.getNoteTag( + [=] { 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 << '\'' << ObjectName << "' is a '"; + + if (CastInfo) + Out << CastInfo->to()->getAsCXXRecordDecl()->getNameAsString(); + else + Out << CastToTy->getAsCXXRecordDecl()->getNameAsString(); + Out << '\''; - Out << "to '" << CastToName << "' " - << (!IsNullReturn ? "succeeds" : "fails"); + if (!CastSucceeds) { + Out << ", not a '"; + if (CastInfo) + Out << CastInfo->from()->getAsCXXRecordDecl()->getNameAsString(); + else + Out << CastFromTy->getAsCXXRecordDecl()->getNameAsString(); + Out << '\''; + } 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 = CastSucceeds ? 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 (!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 +319,15 @@ 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(); } Index: clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp +++ 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 @@ 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 @@ // 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. Index: clang/lib/StaticAnalyzer/Core/CMakeLists.txt =================================================================== --- clang/lib/StaticAnalyzer/Core/CMakeLists.txt +++ clang/lib/StaticAnalyzer/Core/CMakeLists.txt @@ -16,7 +16,7 @@ CommonBugCategories.cpp ConstraintManager.cpp CoreEngine.cpp - DynamicTypeMap.cpp + DynamicType.cpp Environment.cpp ExplodedGraph.cpp ExprEngine.cpp Index: clang/lib/StaticAnalyzer/Core/DynamicType.cpp =================================================================== --- /dev/null +++ clang/lib/StaticAnalyzer/Core/DynamicType.cpp @@ -0,0 +1,219 @@ +//===- 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, + QualType CastFromTy, + QualType CastToTy) { + for (const auto &Elem : State->get()) + for (const DynamicCastInfo &Cast : Elem.second) + 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 Index: clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp =================================================================== --- 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 Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp =================================================================== --- clang/lib/StaticAnalyzer/Core/ProgramState.cpp +++ 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" Index: clang/test/Analysis/Inputs/llvm.h =================================================================== --- /dev/null +++ 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 Index: clang/test/Analysis/cast-value-logic.cpp =================================================================== --- /dev/null +++ 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 + Index: clang/test/Analysis/cast-value-notes.cpp =================================================================== --- /dev/null +++ clang/test/Analysis/cast-value-notes.cpp @@ -0,0 +1,158 @@ +// 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 a 'Circle', not a 'Shape'}} + // expected-note@-2 {{Dereference of null pointer}} + // expected-warning@-3 {{Dereference of null pointer}} +} + +void evalContradiction(const Shape *S) { + const auto *C = dyn_cast_or_null(S); + // no-note: 'Assuming 'S' is a 'Circle'' + + if (dyn_cast_or_null(C)) { + // no-note: 'Assuming 'C' is a 'Circle', not a 'Circle'' + return; + } + + (void)(1 / !C); + // no-note: "'C' is non-null" + // no-warning: Division by zero +} + +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 a 'Triangle', not a 'Circle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{'C' is a 'Triangle', not a 'Circle'}} + // 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 a 'Circle', not a 'Shape'}} + + 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 a 'Circle', not a 'Shape'}} + // 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}} +} Index: clang/test/Analysis/cast-value-state-dump.cpp =================================================================== --- /dev/null +++ clang/test/Analysis/cast-value-state-dump.cpp @@ -0,0 +1,64 @@ +// 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}} + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Assuming 'C' is a 'Triangle', not a 'Circle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{'C' is a 'Triangle', not a 'Circle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(C)) { + // expected-note@-1 {{Assuming 'C' is a 'Square', not a 'Circle'}} + // expected-note@-2 {{Taking false branch}} + return; + } + + if (dyn_cast_or_null(S)) { + // expected-note@-1 {{Assuming 'S' is a 'Square', not a 'Shape'}} + // 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}} +} + Index: clang/test/Analysis/cast-value.cpp =================================================================== --- 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 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: }