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(0) { }
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 (ObjCMethodDecl::param_const_iterator
65          I = D->param_begin(), E = D->param_end(); I != E; ++I)  {
66     if (IsNSError((*I)->getType(), II)) {
67       hasNSError = true;
68       break;
69     }
70   }
71 
72   if (hasNSError) {
73     const char *err = "Method accepting NSError** "
74         "should have a non-void return value to indicate whether or not an "
75         "error occurred";
76     PathDiagnosticLocation L =
77       PathDiagnosticLocation::create(D, BR.getSourceManager());
78     BR.EmitBasicReport(D, this, "Bad return type when passing NSError**",
79                        "Coding conventions (Apple)", err, L);
80   }
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // CFErrorFunctionChecker
85 //===----------------------------------------------------------------------===//
86 
87 namespace {
88 class CFErrorFunctionChecker
89     : public Checker< check::ASTDecl<FunctionDecl> > {
90   mutable IdentifierInfo *II;
91 
92 public:
93   CFErrorFunctionChecker() : II(0) { }
94 
95   void checkASTDecl(const FunctionDecl *D,
96                     AnalysisManager &mgr, BugReporter &BR) const;
97 };
98 }
99 
100 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
101                                         AnalysisManager &mgr,
102                                         BugReporter &BR) const {
103   if (!D->doesThisDeclarationHaveABody())
104     return;
105   if (!D->getReturnType()->isVoidType())
106     return;
107 
108   if (!II)
109     II = &D->getASTContext().Idents.get("CFErrorRef");
110 
111   bool hasCFError = false;
112   for (FunctionDecl::param_const_iterator
113          I = D->param_begin(), E = D->param_end(); I != E; ++I)  {
114     if (IsCFError((*I)->getType(), II)) {
115       hasCFError = true;
116       break;
117     }
118   }
119 
120   if (hasCFError) {
121     const char *err = "Function accepting CFErrorRef* "
122         "should have a non-void return value to indicate whether or not an "
123         "error occurred";
124     PathDiagnosticLocation L =
125       PathDiagnosticLocation::create(D, BR.getSourceManager());
126     BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*",
127                        "Coding conventions (Apple)", err, L);
128   }
129 }
130 
131 //===----------------------------------------------------------------------===//
132 // NSOrCFErrorDerefChecker
133 //===----------------------------------------------------------------------===//
134 
135 namespace {
136 
137 class NSErrorDerefBug : public BugType {
138 public:
139   NSErrorDerefBug(const CheckerBase *Checker)
140       : BugType(Checker, "NSError** null dereference",
141                 "Coding conventions (Apple)") {}
142 };
143 
144 class CFErrorDerefBug : public BugType {
145 public:
146   CFErrorDerefBug(const CheckerBase *Checker)
147       : BugType(Checker, "CFErrorRef* null dereference",
148                 "Coding conventions (Apple)") {}
149 };
150 
151 }
152 
153 namespace {
154 class NSOrCFErrorDerefChecker
155     : public Checker< check::Location,
156                         check::Event<ImplicitNullDerefEvent> > {
157   mutable IdentifierInfo *NSErrorII, *CFErrorII;
158 public:
159   bool ShouldCheckNSError, ShouldCheckCFError;
160   NSOrCFErrorDerefChecker() : NSErrorII(0), CFErrorII(0),
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 *
190     SFC = C.getLocationContext()->getCurrentStackFrame();
191   if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
192     const MemRegion* R = X->getRegion();
193     if (const VarRegion *VR = R->getAs<VarRegion>())
194       if (const StackArgumentsSpaceRegion *
195           stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
196         if (stackReg->getStackFrame() == SFC)
197           return VR->getValueType();
198   }
199 
200   return QualType();
201 }
202 
203 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
204                                             const Stmt *S,
205                                             CheckerContext &C) const {
206   if (!isLoad)
207     return;
208   if (loc.isUndef() || !loc.getAs<Loc>())
209     return;
210 
211   ASTContext &Ctx = C.getASTContext();
212   ProgramStateRef state = C.getState();
213 
214   // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
215   // SVal so that we can later check it when handling the
216   // ImplicitNullDerefEvent event.
217   // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
218   // function ?
219 
220   QualType parmT = parameterTypeFromSVal(loc, C);
221   if (parmT.isNull())
222     return;
223 
224   if (!NSErrorII)
225     NSErrorII = &Ctx.Idents.get("NSError");
226   if (!CFErrorII)
227     CFErrorII = &Ctx.Idents.get("CFErrorRef");
228 
229   if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
230     setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
231     return;
232   }
233 
234   if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
235     setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
236     return;
237   }
238 }
239 
240 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
241   if (event.IsLoad)
242     return;
243 
244   SVal loc = event.Location;
245   ProgramStateRef state = event.SinkNode->getState();
246   BugReporter &BR = *event.BR;
247 
248   bool isNSError = hasFlag<NSErrorOut>(loc, state);
249   bool isCFError = false;
250   if (!isNSError)
251     isCFError = hasFlag<CFErrorOut>(loc, state);
252 
253   if (!(isNSError || isCFError))
254     return;
255 
256   // Storing to possible null NSError/CFErrorRef out parameter.
257   SmallString<128> Buf;
258   llvm::raw_svector_ostream os(Buf);
259 
260   os << "Potential null dereference.  According to coding standards ";
261   os << (isNSError
262          ? "in 'Creating and Returning NSError Objects' the parameter"
263          : "documented in CoreFoundation/CFError.h the parameter");
264 
265   os  << " may be null";
266 
267   BugType *bug = 0;
268   if (isNSError)
269     bug = new NSErrorDerefBug(this);
270   else
271     bug = new CFErrorDerefBug(this);
272   BugReport *report = new BugReport(*bug, os.str(), event.SinkNode);
273   BR.emitReport(report);
274 }
275 
276 static bool IsNSError(QualType T, IdentifierInfo *II) {
277 
278   const PointerType* PPT = T->getAs<PointerType>();
279   if (!PPT)
280     return false;
281 
282   const ObjCObjectPointerType* PT =
283     PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
284 
285   if (!PT)
286     return false;
287 
288   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
289 
290   // FIXME: Can ID ever be NULL?
291   if (ID)
292     return II == ID->getIdentifier();
293 
294   return false;
295 }
296 
297 static bool IsCFError(QualType T, IdentifierInfo *II) {
298   const PointerType* PPT = T->getAs<PointerType>();
299   if (!PPT) return false;
300 
301   const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
302   if (!TT) return false;
303 
304   return TT->getDecl()->getIdentifier() == II;
305 }
306 
307 void ento::registerNSErrorChecker(CheckerManager &mgr) {
308   mgr.registerChecker<NSErrorMethodChecker>();
309   NSOrCFErrorDerefChecker *checker =
310       mgr.registerChecker<NSOrCFErrorDerefChecker>();
311   checker->ShouldCheckNSError = true;
312 }
313 
314 void ento::registerCFErrorChecker(CheckerManager &mgr) {
315   mgr.registerChecker<CFErrorFunctionChecker>();
316   NSOrCFErrorDerefChecker *checker =
317       mgr.registerChecker<NSOrCFErrorDerefChecker>();
318   checker->ShouldCheckCFError = true;
319 }
320