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