1 //== DynamicTypeChecker.cpp ------------------------------------ -*- C++ -*--=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This checker looks for cases where the dynamic type of an object is unrelated
11 // to its static type. The type information utilized by this check is collected
12 // by the DynamicTypePropagation checker. This check does not report any type
13 // error for ObjC Generic types, in order to avoid duplicate erros from the
14 // ObjC Generics checker. This checker is not supposed to modify the program
15 // state, it is just the observer of the type information provided by other
18 //===----------------------------------------------------------------------===//
20 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
29 using namespace clang;
33 class DynamicTypeChecker : public Checker<check::PostStmt<ImplicitCastExpr>> {
34 mutable std::unique_ptr<BugType> BT;
35 void initBugType() const {
38 new BugType(this, "Dynamic and static type mismatch", "Type Error"));
41 class DynamicTypeBugVisitor : public BugReporterVisitor {
43 DynamicTypeBugVisitor(const MemRegion *Reg) : Reg(Reg) {}
45 void Profile(llvm::FoldingSetNodeID &ID) const override {
51 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
52 BugReporterContext &BRC,
53 BugReport &BR) override;
56 // The tracked region.
60 void reportTypeError(QualType DynamicType, QualType StaticType,
61 const MemRegion *Reg, const Stmt *ReportedNode,
62 CheckerContext &C) const;
65 void checkPostStmt(const ImplicitCastExpr *CE, CheckerContext &C) const;
69 void DynamicTypeChecker::reportTypeError(QualType DynamicType,
72 const Stmt *ReportedNode,
73 CheckerContext &C) const {
76 llvm::raw_svector_ostream OS(Buf);
77 OS << "Object has a dynamic type '";
78 QualType::print(DynamicType.getTypePtr(), Qualifiers(), OS, C.getLangOpts(),
80 OS << "' which is incompatible with static type '";
81 QualType::print(StaticType.getTypePtr(), Qualifiers(), OS, C.getLangOpts(),
84 std::unique_ptr<BugReport> R(
85 new BugReport(*BT, OS.str(), C.generateNonFatalErrorNode()));
86 R->markInteresting(Reg);
87 R->addVisitor(llvm::make_unique<DynamicTypeBugVisitor>(Reg));
88 R->addRange(ReportedNode->getSourceRange());
89 C.emitReport(std::move(R));
92 std::shared_ptr<PathDiagnosticPiece>
93 DynamicTypeChecker::DynamicTypeBugVisitor::VisitNode(const ExplodedNode *N,
94 BugReporterContext &BRC,
96 ProgramStateRef State = N->getState();
97 ProgramStateRef StatePrev = N->getFirstPred()->getState();
99 DynamicTypeInfo TrackedType = getDynamicTypeInfo(State, Reg);
100 DynamicTypeInfo TrackedTypePrev = getDynamicTypeInfo(StatePrev, Reg);
101 if (!TrackedType.isValid())
104 if (TrackedTypePrev.isValid() &&
105 TrackedTypePrev.getType() == TrackedType.getType())
108 // Retrieve the associated statement.
109 const Stmt *S = PathDiagnosticLocation::getStmt(N);
113 const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
115 SmallString<256> Buf;
116 llvm::raw_svector_ostream OS(Buf);
118 QualType::print(TrackedType.getType().getTypePtr(), Qualifiers(), OS,
119 LangOpts, llvm::Twine());
120 OS << "' is inferred from ";
122 if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
123 OS << "explicit cast (from '";
124 QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
125 Qualifiers(), OS, LangOpts, llvm::Twine());
127 QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
128 LangOpts, llvm::Twine());
130 } else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
131 OS << "implicit cast (from '";
132 QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
133 Qualifiers(), OS, LangOpts, llvm::Twine());
135 QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
136 LangOpts, llvm::Twine());
139 OS << "this context";
142 // Generate the extra diagnostic.
143 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
144 N->getLocationContext());
145 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true,
149 static bool hasDefinition(const ObjCObjectPointerType *ObjPtr) {
150 const ObjCInterfaceDecl *Decl = ObjPtr->getInterfaceDecl();
154 return Decl->getDefinition();
157 // TODO: consider checking explicit casts?
158 void DynamicTypeChecker::checkPostStmt(const ImplicitCastExpr *CE,
159 CheckerContext &C) const {
160 // TODO: C++ support.
161 if (CE->getCastKind() != CK_BitCast)
164 const MemRegion *Region = C.getSVal(CE).getAsRegion();
168 ProgramStateRef State = C.getState();
169 DynamicTypeInfo DynTypeInfo = getDynamicTypeInfo(State, Region);
171 if (!DynTypeInfo.isValid())
174 QualType DynType = DynTypeInfo.getType();
175 QualType StaticType = CE->getType();
177 const auto *DynObjCType = DynType->getAs<ObjCObjectPointerType>();
178 const auto *StaticObjCType = StaticType->getAs<ObjCObjectPointerType>();
180 if (!DynObjCType || !StaticObjCType)
183 if (!hasDefinition(DynObjCType) || !hasDefinition(StaticObjCType))
186 ASTContext &ASTCtxt = C.getASTContext();
188 // Strip kindeofness to correctly detect subtyping relationships.
189 DynObjCType = DynObjCType->stripObjCKindOfTypeAndQuals(ASTCtxt);
190 StaticObjCType = StaticObjCType->stripObjCKindOfTypeAndQuals(ASTCtxt);
192 // Specialized objects are handled by the generics checker.
193 if (StaticObjCType->isSpecialized())
196 if (ASTCtxt.canAssignObjCInterfaces(StaticObjCType, DynObjCType))
199 if (DynTypeInfo.canBeASubClass() &&
200 ASTCtxt.canAssignObjCInterfaces(DynObjCType, StaticObjCType))
203 reportTypeError(DynType, StaticType, Region, CE, C);
206 void ento::registerDynamicTypeChecker(CheckerManager &mgr) {
207 mgr.registerChecker<DynamicTypeChecker>();