1 //=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 // File under feature request PR 2600.
16 //===----------------------------------------------------------------------===//
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/GRStateTrait.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"
28 using namespace clang;
31 static bool IsNSError(QualType T, IdentifierInfo *II);
32 static bool IsCFError(QualType T, IdentifierInfo *II);
34 //===----------------------------------------------------------------------===//
35 // NSErrorMethodChecker
36 //===----------------------------------------------------------------------===//
39 class NSErrorMethodChecker
40 : public Checker< check::ASTDecl<ObjCMethodDecl> > {
41 mutable IdentifierInfo *II;
44 NSErrorMethodChecker() : II(0) { }
46 void checkASTDecl(const ObjCMethodDecl *D,
47 AnalysisManager &mgr, BugReporter &BR) const;
51 void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
53 BugReporter &BR) const {
54 if (!D->isThisDeclarationADefinition())
56 if (!D->getResultType()->isVoidType())
60 II = &D->getASTContext().Idents.get("NSError");
62 bool hasNSError = false;
63 for (ObjCMethodDecl::param_iterator
64 I = D->param_begin(), E = D->param_end(); I != E; ++I) {
65 if (IsNSError((*I)->getType(), II)) {
72 const char *err = "Method accepting NSError** "
73 "should have a non-void return value to indicate whether or not an "
75 BR.EmitBasicReport("Bad return type when passing NSError**",
76 "Coding conventions (Apple)", err, D->getLocation());
80 //===----------------------------------------------------------------------===//
81 // CFErrorFunctionChecker
82 //===----------------------------------------------------------------------===//
85 class CFErrorFunctionChecker
86 : public Checker< check::ASTDecl<FunctionDecl> > {
87 mutable IdentifierInfo *II;
90 CFErrorFunctionChecker() : II(0) { }
92 void checkASTDecl(const FunctionDecl *D,
93 AnalysisManager &mgr, BugReporter &BR) const;
97 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
99 BugReporter &BR) const {
100 if (!D->doesThisDeclarationHaveABody())
102 if (!D->getResultType()->isVoidType())
106 II = &D->getASTContext().Idents.get("CFErrorRef");
108 bool hasCFError = false;
109 for (FunctionDecl::param_const_iterator
110 I = D->param_begin(), E = D->param_end(); I != E; ++I) {
111 if (IsCFError((*I)->getType(), II)) {
118 const char *err = "Function accepting CFErrorRef* "
119 "should have a non-void return value to indicate whether or not an "
121 BR.EmitBasicReport("Bad return type when passing CFErrorRef*",
122 "Coding conventions (Apple)", err, D->getLocation());
126 //===----------------------------------------------------------------------===//
127 // NSOrCFErrorDerefChecker
128 //===----------------------------------------------------------------------===//
132 class NSErrorDerefBug : public BugType {
134 NSErrorDerefBug() : BugType("NSError** null dereference",
135 "Coding conventions (Apple)") {}
138 class CFErrorDerefBug : public BugType {
140 CFErrorDerefBug() : BugType("CFErrorRef* null dereference",
141 "Coding conventions (Apple)") {}
147 class NSOrCFErrorDerefChecker
148 : public Checker< check::Location,
149 check::Event<ImplicitNullDerefEvent> > {
150 mutable IdentifierInfo *NSErrorII, *CFErrorII;
152 bool ShouldCheckNSError, ShouldCheckCFError;
153 NSOrCFErrorDerefChecker() : NSErrorII(0), CFErrorII(0),
154 ShouldCheckNSError(0), ShouldCheckCFError(0) { }
156 void checkLocation(SVal loc, bool isLoad, CheckerContext &C) const;
157 void checkEvent(ImplicitNullDerefEvent event) const;
161 namespace { struct NSErrorOut {}; }
162 namespace { struct CFErrorOut {}; }
164 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
169 struct GRStateTrait<NSErrorOut> : public GRStatePartialTrait<ErrorOutFlag> {
170 static void *GDMIndex() { static int index = 0; return &index; }
173 struct GRStateTrait<CFErrorOut> : public GRStatePartialTrait<ErrorOutFlag> {
174 static void *GDMIndex() { static int index = 0; return &index; }
179 template <typename T>
180 static bool hasFlag(SVal val, const GRState *state) {
181 if (SymbolRef sym = val.getAsSymbol())
182 if (const unsigned *attachedFlags = state->get<T>(sym))
183 return *attachedFlags;
187 template <typename T>
188 static void setFlag(const GRState *state, SVal val, CheckerContext &C) {
189 // We tag the symbol that the SVal wraps.
190 if (SymbolRef sym = val.getAsSymbol())
191 C.addTransition(state->set<T>(sym, true));
194 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
195 const StackFrameContext *
196 SFC = C.getPredecessor()->getLocationContext()->getCurrentStackFrame();
197 if (const loc::MemRegionVal* X = dyn_cast<loc::MemRegionVal>(&val)) {
198 const MemRegion* R = X->getRegion();
199 if (const VarRegion *VR = R->getAs<VarRegion>())
200 if (const StackArgumentsSpaceRegion *
201 stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
202 if (stackReg->getStackFrame() == SFC)
203 return VR->getValueType();
209 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
210 CheckerContext &C) const {
213 if (loc.isUndef() || !isa<Loc>(loc))
216 ASTContext &Ctx = C.getASTContext();
217 const GRState *state = C.getState();
219 // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
220 // SVal so that we can later check it when handling the
221 // ImplicitNullDerefEvent event.
222 // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
225 QualType parmT = parameterTypeFromSVal(loc, C);
230 NSErrorII = &Ctx.Idents.get("NSError");
232 CFErrorII = &Ctx.Idents.get("CFErrorRef");
234 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
235 setFlag<NSErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
239 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
240 setFlag<CFErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
245 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
249 SVal loc = event.Location;
250 const GRState *state = event.SinkNode->getState();
251 BugReporter &BR = *event.BR;
253 bool isNSError = hasFlag<NSErrorOut>(loc, state);
254 bool isCFError = false;
256 isCFError = hasFlag<CFErrorOut>(loc, state);
258 if (!(isNSError || isCFError))
261 // Storing to possible null NSError/CFErrorRef out parameter.
265 llvm::raw_string_ostream os(err);
266 os << "Potential null dereference. According to coding standards ";
269 os << "in 'Creating and Returning NSError Objects' the parameter '";
271 os << "documented in CoreFoundation/CFError.h the parameter '";
273 os << "' may be null.";
277 bug = new NSErrorDerefBug();
279 bug = new CFErrorDerefBug();
280 EnhancedBugReport *report = new EnhancedBugReport(*bug, os.str(),
282 BR.EmitReport(report);
285 static bool IsNSError(QualType T, IdentifierInfo *II) {
287 const PointerType* PPT = T->getAs<PointerType>();
291 const ObjCObjectPointerType* PT =
292 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
297 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
299 // FIXME: Can ID ever be NULL?
301 return II == ID->getIdentifier();
306 static bool IsCFError(QualType T, IdentifierInfo *II) {
307 const PointerType* PPT = T->getAs<PointerType>();
308 if (!PPT) return false;
310 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
311 if (!TT) return false;
313 return TT->getDecl()->getIdentifier() == II;
316 void ento::registerNSErrorChecker(CheckerManager &mgr) {
317 mgr.registerChecker<NSErrorMethodChecker>();
318 NSOrCFErrorDerefChecker *
319 checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
320 checker->ShouldCheckNSError = true;
323 void ento::registerCFErrorChecker(CheckerManager &mgr) {
324 mgr.registerChecker<CFErrorFunctionChecker>();
325 NSOrCFErrorDerefChecker *
326 checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
327 checker->ShouldCheckCFError = true;