• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
23 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Decl.h"
26 #include "llvm/ADT/SmallVector.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:
NSErrorMethodChecker()44   NSErrorMethodChecker() : II(0) { }
45 
46   void checkASTDecl(const ObjCMethodDecl *D,
47                     AnalysisManager &mgr, BugReporter &BR) const;
48 };
49 }
50 
checkASTDecl(const ObjCMethodDecl * D,AnalysisManager & mgr,BugReporter & BR) const51 void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
52                                         AnalysisManager &mgr,
53                                         BugReporter &BR) const {
54   if (!D->isThisDeclarationADefinition())
55     return;
56   if (!D->getResultType()->isVoidType())
57     return;
58 
59   if (!II)
60     II = &D->getASTContext().Idents.get("NSError");
61 
62   bool hasNSError = false;
63   for (ObjCMethodDecl::param_const_iterator
64          I = D->param_begin(), E = D->param_end(); I != E; ++I)  {
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, "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:
CFErrorFunctionChecker()92   CFErrorFunctionChecker() : II(0) { }
93 
94   void checkASTDecl(const FunctionDecl *D,
95                     AnalysisManager &mgr, BugReporter &BR) const;
96 };
97 }
98 
checkASTDecl(const FunctionDecl * D,AnalysisManager & mgr,BugReporter & BR) const99 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
100                                         AnalysisManager &mgr,
101                                         BugReporter &BR) const {
102   if (!D->doesThisDeclarationHaveABody())
103     return;
104   if (!D->getResultType()->isVoidType())
105     return;
106 
107   if (!II)
108     II = &D->getASTContext().Idents.get("CFErrorRef");
109 
110   bool hasCFError = false;
111   for (FunctionDecl::param_const_iterator
112          I = D->param_begin(), E = D->param_end(); I != E; ++I)  {
113     if (IsCFError((*I)->getType(), II)) {
114       hasCFError = true;
115       break;
116     }
117   }
118 
119   if (hasCFError) {
120     const char *err = "Function accepting CFErrorRef* "
121         "should have a non-void return value to indicate whether or not an "
122         "error occurred";
123     PathDiagnosticLocation L =
124       PathDiagnosticLocation::create(D, BR.getSourceManager());
125     BR.EmitBasicReport(D, "Bad return type when passing CFErrorRef*",
126                        "Coding conventions (Apple)", err, L);
127   }
128 }
129 
130 //===----------------------------------------------------------------------===//
131 // NSOrCFErrorDerefChecker
132 //===----------------------------------------------------------------------===//
133 
134 namespace {
135 
136 class NSErrorDerefBug : public BugType {
137 public:
NSErrorDerefBug()138   NSErrorDerefBug() : BugType("NSError** null dereference",
139                               "Coding conventions (Apple)") {}
140 };
141 
142 class CFErrorDerefBug : public BugType {
143 public:
CFErrorDerefBug()144   CFErrorDerefBug() : BugType("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 public:
156   bool ShouldCheckNSError, ShouldCheckCFError;
NSOrCFErrorDerefChecker()157   NSOrCFErrorDerefChecker() : NSErrorII(0), CFErrorII(0),
158                               ShouldCheckNSError(0), ShouldCheckCFError(0) { }
159 
160   void checkLocation(SVal loc, bool isLoad, const Stmt *S,
161                      CheckerContext &C) const;
162   void checkEvent(ImplicitNullDerefEvent event) const;
163 };
164 }
165 
166 namespace { struct NSErrorOut {}; }
167 namespace { struct CFErrorOut {}; }
168 
169 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
170 
171 namespace clang {
172 namespace ento {
173   template <>
174   struct ProgramStateTrait<NSErrorOut> : public ProgramStatePartialTrait<ErrorOutFlag> {
GDMIndexclang::ento::ProgramStateTrait175     static void *GDMIndex() { static int index = 0; return &index; }
176   };
177   template <>
178   struct ProgramStateTrait<CFErrorOut> : public ProgramStatePartialTrait<ErrorOutFlag> {
GDMIndexclang::ento::ProgramStateTrait179     static void *GDMIndex() { static int index = 0; return &index; }
180   };
181 }
182 }
183 
184 template <typename T>
hasFlag(SVal val,ProgramStateRef state)185 static bool hasFlag(SVal val, ProgramStateRef state) {
186   if (SymbolRef sym = val.getAsSymbol())
187     if (const unsigned *attachedFlags = state->get<T>(sym))
188       return *attachedFlags;
189   return false;
190 }
191 
192 template <typename T>
setFlag(ProgramStateRef state,SVal val,CheckerContext & C)193 static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
194   // We tag the symbol that the SVal wraps.
195   if (SymbolRef sym = val.getAsSymbol())
196     C.addTransition(state->set<T>(sym, true));
197 }
198 
parameterTypeFromSVal(SVal val,CheckerContext & C)199 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
200   const StackFrameContext *
201     SFC = C.getLocationContext()->getCurrentStackFrame();
202   if (const loc::MemRegionVal* X = dyn_cast<loc::MemRegionVal>(&val)) {
203     const MemRegion* R = X->getRegion();
204     if (const VarRegion *VR = R->getAs<VarRegion>())
205       if (const StackArgumentsSpaceRegion *
206           stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
207         if (stackReg->getStackFrame() == SFC)
208           return VR->getValueType();
209   }
210 
211   return QualType();
212 }
213 
checkLocation(SVal loc,bool isLoad,const Stmt * S,CheckerContext & C) const214 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
215                                             const Stmt *S,
216                                             CheckerContext &C) const {
217   if (!isLoad)
218     return;
219   if (loc.isUndef() || !isa<Loc>(loc))
220     return;
221 
222   ASTContext &Ctx = C.getASTContext();
223   ProgramStateRef state = C.getState();
224 
225   // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
226   // SVal so that we can later check it when handling the
227   // ImplicitNullDerefEvent event.
228   // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
229   // function ?
230 
231   QualType parmT = parameterTypeFromSVal(loc, C);
232   if (parmT.isNull())
233     return;
234 
235   if (!NSErrorII)
236     NSErrorII = &Ctx.Idents.get("NSError");
237   if (!CFErrorII)
238     CFErrorII = &Ctx.Idents.get("CFErrorRef");
239 
240   if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
241     setFlag<NSErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
242     return;
243   }
244 
245   if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
246     setFlag<CFErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
247     return;
248   }
249 }
250 
checkEvent(ImplicitNullDerefEvent event) const251 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
252   if (event.IsLoad)
253     return;
254 
255   SVal loc = event.Location;
256   ProgramStateRef state = event.SinkNode->getState();
257   BugReporter &BR = *event.BR;
258 
259   bool isNSError = hasFlag<NSErrorOut>(loc, state);
260   bool isCFError = false;
261   if (!isNSError)
262     isCFError = hasFlag<CFErrorOut>(loc, state);
263 
264   if (!(isNSError || isCFError))
265     return;
266 
267   // Storing to possible null NSError/CFErrorRef out parameter.
268 
269   // Emit an error.
270   std::string err;
271   llvm::raw_string_ostream os(err);
272     os << "Potential null dereference.  According to coding standards ";
273 
274   if (isNSError)
275     os << "in 'Creating and Returning NSError Objects' the parameter '";
276   else
277     os << "documented in CoreFoundation/CFError.h the parameter '";
278 
279   os  << "' may be null.";
280 
281   BugType *bug = 0;
282   if (isNSError)
283     bug = new NSErrorDerefBug();
284   else
285     bug = new CFErrorDerefBug();
286   BugReport *report = new BugReport(*bug, os.str(),
287                                                     event.SinkNode);
288   BR.EmitReport(report);
289 }
290 
IsNSError(QualType T,IdentifierInfo * II)291 static bool IsNSError(QualType T, IdentifierInfo *II) {
292 
293   const PointerType* PPT = T->getAs<PointerType>();
294   if (!PPT)
295     return false;
296 
297   const ObjCObjectPointerType* PT =
298     PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
299 
300   if (!PT)
301     return false;
302 
303   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
304 
305   // FIXME: Can ID ever be NULL?
306   if (ID)
307     return II == ID->getIdentifier();
308 
309   return false;
310 }
311 
IsCFError(QualType T,IdentifierInfo * II)312 static bool IsCFError(QualType T, IdentifierInfo *II) {
313   const PointerType* PPT = T->getAs<PointerType>();
314   if (!PPT) return false;
315 
316   const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
317   if (!TT) return false;
318 
319   return TT->getDecl()->getIdentifier() == II;
320 }
321 
registerNSErrorChecker(CheckerManager & mgr)322 void ento::registerNSErrorChecker(CheckerManager &mgr) {
323   mgr.registerChecker<NSErrorMethodChecker>();
324   NSOrCFErrorDerefChecker *
325     checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
326   checker->ShouldCheckNSError = true;
327 }
328 
registerCFErrorChecker(CheckerManager & mgr)329 void ento::registerCFErrorChecker(CheckerManager &mgr) {
330   mgr.registerChecker<CFErrorFunctionChecker>();
331   NSOrCFErrorDerefChecker *
332     checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
333   checker->ShouldCheckCFError = true;
334 }
335