]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DynamicTypeChecker.cpp
Update clang to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Checkers / DynamicTypeChecker.cpp
1 //== DynamicTypeChecker.cpp ------------------------------------ -*- C++ -*--=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
16 // checkers.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "ClangSACheckers.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"
28
29 using namespace clang;
30 using namespace ento;
31
32 namespace {
33 class DynamicTypeChecker : public Checker<check::PostStmt<ImplicitCastExpr>> {
34   mutable std::unique_ptr<BugType> BT;
35   void initBugType() const {
36     if (!BT)
37       BT.reset(
38           new BugType(this, "Dynamic and static type mismatch", "Type Error"));
39   }
40
41   class DynamicTypeBugVisitor
42       : public BugReporterVisitorImpl<DynamicTypeBugVisitor> {
43   public:
44     DynamicTypeBugVisitor(const MemRegion *Reg) : Reg(Reg) {}
45
46     void Profile(llvm::FoldingSetNodeID &ID) const override {
47       static int X = 0;
48       ID.AddPointer(&X);
49       ID.AddPointer(Reg);
50     }
51
52     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
53                                    const ExplodedNode *PrevN,
54                                    BugReporterContext &BRC,
55                                    BugReport &BR) override;
56
57   private:
58     // The tracked region.
59     const MemRegion *Reg;
60   };
61
62   void reportTypeError(QualType DynamicType, QualType StaticType,
63                        const MemRegion *Reg, const Stmt *ReportedNode,
64                        CheckerContext &C) const;
65
66 public:
67   void checkPostStmt(const ImplicitCastExpr *CE, CheckerContext &C) const;
68 };
69 }
70
71 void DynamicTypeChecker::reportTypeError(QualType DynamicType,
72                                          QualType StaticType,
73                                          const MemRegion *Reg,
74                                          const Stmt *ReportedNode,
75                                          CheckerContext &C) const {
76   initBugType();
77   SmallString<192> Buf;
78   llvm::raw_svector_ostream OS(Buf);
79   OS << "Object has a dynamic type '";
80   QualType::print(DynamicType.getTypePtr(), Qualifiers(), OS, C.getLangOpts(),
81                   llvm::Twine());
82   OS << "' which is incompatible with static type '";
83   QualType::print(StaticType.getTypePtr(), Qualifiers(), OS, C.getLangOpts(),
84                   llvm::Twine());
85   OS << "'";
86   std::unique_ptr<BugReport> R(
87       new BugReport(*BT, OS.str(), C.generateNonFatalErrorNode()));
88   R->markInteresting(Reg);
89   R->addVisitor(llvm::make_unique<DynamicTypeBugVisitor>(Reg));
90   R->addRange(ReportedNode->getSourceRange());
91   C.emitReport(std::move(R));
92 }
93
94 PathDiagnosticPiece *DynamicTypeChecker::DynamicTypeBugVisitor::VisitNode(
95     const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
96     BugReport &BR) {
97   ProgramStateRef State = N->getState();
98   ProgramStateRef StatePrev = PrevN->getState();
99
100   DynamicTypeInfo TrackedType = getDynamicTypeInfo(State, Reg);
101   DynamicTypeInfo TrackedTypePrev = getDynamicTypeInfo(StatePrev, Reg);
102   if (!TrackedType.isValid())
103     return nullptr;
104
105   if (TrackedTypePrev.isValid() &&
106       TrackedTypePrev.getType() == TrackedType.getType())
107     return nullptr;
108
109   // Retrieve the associated statement.
110   const Stmt *S = PathDiagnosticLocation::getStmt(N);
111   if (!S)
112     return nullptr;
113
114   const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
115
116   SmallString<256> Buf;
117   llvm::raw_svector_ostream OS(Buf);
118   OS << "Type '";
119   QualType::print(TrackedType.getType().getTypePtr(), Qualifiers(), OS,
120                   LangOpts, llvm::Twine());
121   OS << "' is inferred from ";
122
123   if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
124     OS << "explicit cast (from '";
125     QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
126                     Qualifiers(), OS, LangOpts, llvm::Twine());
127     OS << "' to '";
128     QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
129                     LangOpts, llvm::Twine());
130     OS << "')";
131   } else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
132     OS << "implicit cast (from '";
133     QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
134                     Qualifiers(), OS, LangOpts, llvm::Twine());
135     OS << "' to '";
136     QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
137                     LangOpts, llvm::Twine());
138     OS << "')";
139   } else {
140     OS << "this context";
141   }
142
143   // Generate the extra diagnostic.
144   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
145                              N->getLocationContext());
146   return new PathDiagnosticEventPiece(Pos, OS.str(), true, nullptr);
147 }
148
149 static bool hasDefinition(const ObjCObjectPointerType *ObjPtr) {
150   const ObjCInterfaceDecl *Decl = ObjPtr->getInterfaceDecl();
151   if (!Decl)
152     return false;
153
154   return Decl->getDefinition();
155 }
156
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)
162     return;
163
164   const MemRegion *Region = C.getSVal(CE).getAsRegion();
165   if (!Region)
166     return;
167
168   ProgramStateRef State = C.getState();
169   DynamicTypeInfo DynTypeInfo = getDynamicTypeInfo(State, Region);
170
171   if (!DynTypeInfo.isValid())
172     return;
173
174   QualType DynType = DynTypeInfo.getType();
175   QualType StaticType = CE->getType();
176
177   const auto *DynObjCType = DynType->getAs<ObjCObjectPointerType>();
178   const auto *StaticObjCType = StaticType->getAs<ObjCObjectPointerType>();
179
180   if (!DynObjCType || !StaticObjCType)
181     return;
182
183   if (!hasDefinition(DynObjCType) || !hasDefinition(StaticObjCType))
184     return;
185
186   ASTContext &ASTCtxt = C.getASTContext();
187
188   // Strip kindeofness to correctly detect subtyping relationships.
189   DynObjCType = DynObjCType->stripObjCKindOfTypeAndQuals(ASTCtxt);
190   StaticObjCType = StaticObjCType->stripObjCKindOfTypeAndQuals(ASTCtxt);
191
192   // Specialized objects are handled by the generics checker.
193   if (StaticObjCType->isSpecialized())
194     return;
195
196   if (ASTCtxt.canAssignObjCInterfaces(StaticObjCType, DynObjCType))
197     return;
198
199   if (DynTypeInfo.canBeASubClass() &&
200       ASTCtxt.canAssignObjCInterfaces(DynObjCType, StaticObjCType))
201     return;
202
203   reportTypeError(DynType, StaticType, Region, CE, C);
204 }
205
206 void ento::registerDynamicTypeChecker(CheckerManager &mgr) {
207   mgr.registerChecker<DynamicTypeChecker>();
208 }