]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Checkers / NSErrorChecker.cpp
1 //=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- 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 file defines a CheckNSError, a flow-insenstive check
11 //  that determines if an Objective-C class interface correctly returns
12 //  a non-void return type.
13 //
14 //  File under feature request PR 2600.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "ClangSACheckers.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclObjC.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/CheckerContext.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/Support/raw_ostream.h"
28
29 using namespace clang;
30 using namespace ento;
31
32 static bool IsNSError(QualType T, IdentifierInfo *II);
33 static bool IsCFError(QualType T, IdentifierInfo *II);
34
35 //===----------------------------------------------------------------------===//
36 // NSErrorMethodChecker
37 //===----------------------------------------------------------------------===//
38
39 namespace {
40 class NSErrorMethodChecker
41     : public Checker< check::ASTDecl<ObjCMethodDecl> > {
42   mutable IdentifierInfo *II;
43
44 public:
45   NSErrorMethodChecker() : II(nullptr) {}
46
47   void checkASTDecl(const ObjCMethodDecl *D,
48                     AnalysisManager &mgr, BugReporter &BR) const;
49 };
50 }
51
52 void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
53                                         AnalysisManager &mgr,
54                                         BugReporter &BR) const {
55   if (!D->isThisDeclarationADefinition())
56     return;
57   if (!D->getReturnType()->isVoidType())
58     return;
59
60   if (!II)
61     II = &D->getASTContext().Idents.get("NSError");
62
63   bool hasNSError = false;
64   for (const auto *I : D->parameters())  {
65     if (IsNSError(I->getType(), II)) {
66       hasNSError = true;
67       break;
68     }
69   }
70
71   if (hasNSError) {
72     const char *err = "Method accepting NSError** "
73         "should have a non-void return value to indicate whether or not an "
74         "error occurred";
75     PathDiagnosticLocation L =
76       PathDiagnosticLocation::create(D, BR.getSourceManager());
77     BR.EmitBasicReport(D, this, "Bad return type when passing NSError**",
78                        "Coding conventions (Apple)", err, L);
79   }
80 }
81
82 //===----------------------------------------------------------------------===//
83 // CFErrorFunctionChecker
84 //===----------------------------------------------------------------------===//
85
86 namespace {
87 class CFErrorFunctionChecker
88     : public Checker< check::ASTDecl<FunctionDecl> > {
89   mutable IdentifierInfo *II;
90
91 public:
92   CFErrorFunctionChecker() : II(nullptr) {}
93
94   void checkASTDecl(const FunctionDecl *D,
95                     AnalysisManager &mgr, BugReporter &BR) const;
96 };
97 }
98
99 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
100                                         AnalysisManager &mgr,
101                                         BugReporter &BR) const {
102   if (!D->doesThisDeclarationHaveABody())
103     return;
104   if (!D->getReturnType()->isVoidType())
105     return;
106
107   if (!II)
108     II = &D->getASTContext().Idents.get("CFErrorRef");
109
110   bool hasCFError = false;
111   for (auto I : D->parameters())  {
112     if (IsCFError(I->getType(), II)) {
113       hasCFError = true;
114       break;
115     }
116   }
117
118   if (hasCFError) {
119     const char *err = "Function accepting CFErrorRef* "
120         "should have a non-void return value to indicate whether or not an "
121         "error occurred";
122     PathDiagnosticLocation L =
123       PathDiagnosticLocation::create(D, BR.getSourceManager());
124     BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*",
125                        "Coding conventions (Apple)", err, L);
126   }
127 }
128
129 //===----------------------------------------------------------------------===//
130 // NSOrCFErrorDerefChecker
131 //===----------------------------------------------------------------------===//
132
133 namespace {
134
135 class NSErrorDerefBug : public BugType {
136 public:
137   NSErrorDerefBug(const CheckerBase *Checker)
138       : BugType(Checker, "NSError** null dereference",
139                 "Coding conventions (Apple)") {}
140 };
141
142 class CFErrorDerefBug : public BugType {
143 public:
144   CFErrorDerefBug(const CheckerBase *Checker)
145       : BugType(Checker, "CFErrorRef* null dereference",
146                 "Coding conventions (Apple)") {}
147 };
148
149 }
150
151 namespace {
152 class NSOrCFErrorDerefChecker
153     : public Checker< check::Location,
154                         check::Event<ImplicitNullDerefEvent> > {
155   mutable IdentifierInfo *NSErrorII, *CFErrorII;
156   mutable std::unique_ptr<NSErrorDerefBug> NSBT;
157   mutable std::unique_ptr<CFErrorDerefBug> CFBT;
158 public:
159   bool ShouldCheckNSError, ShouldCheckCFError;
160   NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
161                               ShouldCheckNSError(0), ShouldCheckCFError(0) { }
162
163   void checkLocation(SVal loc, bool isLoad, const Stmt *S,
164                      CheckerContext &C) const;
165   void checkEvent(ImplicitNullDerefEvent event) const;
166 };
167 }
168
169 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
170 REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
171 REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
172
173 template <typename T>
174 static bool hasFlag(SVal val, ProgramStateRef state) {
175   if (SymbolRef sym = val.getAsSymbol())
176     if (const unsigned *attachedFlags = state->get<T>(sym))
177       return *attachedFlags;
178   return false;
179 }
180
181 template <typename T>
182 static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
183   // We tag the symbol that the SVal wraps.
184   if (SymbolRef sym = val.getAsSymbol())
185     C.addTransition(state->set<T>(sym, true));
186 }
187
188 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
189   const StackFrameContext * SFC = C.getStackFrame();
190   if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
191     const MemRegion* R = X->getRegion();
192     if (const VarRegion *VR = R->getAs<VarRegion>())
193       if (const StackArgumentsSpaceRegion *
194           stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
195         if (stackReg->getStackFrame() == SFC)
196           return VR->getValueType();
197   }
198
199   return QualType();
200 }
201
202 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
203                                             const Stmt *S,
204                                             CheckerContext &C) const {
205   if (!isLoad)
206     return;
207   if (loc.isUndef() || !loc.getAs<Loc>())
208     return;
209
210   ASTContext &Ctx = C.getASTContext();
211   ProgramStateRef state = C.getState();
212
213   // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
214   // SVal so that we can later check it when handling the
215   // ImplicitNullDerefEvent event.
216   // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
217   // function ?
218
219   QualType parmT = parameterTypeFromSVal(loc, C);
220   if (parmT.isNull())
221     return;
222
223   if (!NSErrorII)
224     NSErrorII = &Ctx.Idents.get("NSError");
225   if (!CFErrorII)
226     CFErrorII = &Ctx.Idents.get("CFErrorRef");
227
228   if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
229     setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
230     return;
231   }
232
233   if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
234     setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
235     return;
236   }
237 }
238
239 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
240   if (event.IsLoad)
241     return;
242
243   SVal loc = event.Location;
244   ProgramStateRef state = event.SinkNode->getState();
245   BugReporter &BR = *event.BR;
246
247   bool isNSError = hasFlag<NSErrorOut>(loc, state);
248   bool isCFError = false;
249   if (!isNSError)
250     isCFError = hasFlag<CFErrorOut>(loc, state);
251
252   if (!(isNSError || isCFError))
253     return;
254
255   // Storing to possible null NSError/CFErrorRef out parameter.
256   SmallString<128> Buf;
257   llvm::raw_svector_ostream os(Buf);
258
259   os << "Potential null dereference.  According to coding standards ";
260   os << (isNSError
261          ? "in 'Creating and Returning NSError Objects' the parameter"
262          : "documented in CoreFoundation/CFError.h the parameter");
263
264   os  << " may be null";
265
266   BugType *bug = nullptr;
267   if (isNSError) {
268     if (!NSBT)
269       NSBT.reset(new NSErrorDerefBug(this));
270     bug = NSBT.get();
271   }
272   else {
273     if (!CFBT)
274       CFBT.reset(new CFErrorDerefBug(this));
275     bug = CFBT.get();
276   }
277   BR.emitReport(llvm::make_unique<BugReport>(*bug, os.str(), event.SinkNode));
278 }
279
280 static bool IsNSError(QualType T, IdentifierInfo *II) {
281
282   const PointerType* PPT = T->getAs<PointerType>();
283   if (!PPT)
284     return false;
285
286   const ObjCObjectPointerType* PT =
287     PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
288
289   if (!PT)
290     return false;
291
292   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
293
294   // FIXME: Can ID ever be NULL?
295   if (ID)
296     return II == ID->getIdentifier();
297
298   return false;
299 }
300
301 static bool IsCFError(QualType T, IdentifierInfo *II) {
302   const PointerType* PPT = T->getAs<PointerType>();
303   if (!PPT) return false;
304
305   const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
306   if (!TT) return false;
307
308   return TT->getDecl()->getIdentifier() == II;
309 }
310
311 void ento::registerNSErrorChecker(CheckerManager &mgr) {
312   mgr.registerChecker<NSErrorMethodChecker>();
313   NSOrCFErrorDerefChecker *checker =
314       mgr.registerChecker<NSOrCFErrorDerefChecker>();
315   checker->ShouldCheckNSError = true;
316 }
317
318 void ento::registerCFErrorChecker(CheckerManager &mgr) {
319   mgr.registerChecker<CFErrorFunctionChecker>();
320   NSOrCFErrorDerefChecker *checker =
321       mgr.registerChecker<NSOrCFErrorDerefChecker>();
322   checker->ShouldCheckCFError = true;
323 }