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/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"
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_const_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 PathDiagnosticLocation L =
76 PathDiagnosticLocation::create(D, BR.getSourceManager());
77 BR.EmitBasicReport("Bad return type when passing NSError**",
78 "Coding conventions (Apple)", err, L);
82 //===----------------------------------------------------------------------===//
83 // CFErrorFunctionChecker
84 //===----------------------------------------------------------------------===//
87 class CFErrorFunctionChecker
88 : public Checker< check::ASTDecl<FunctionDecl> > {
89 mutable IdentifierInfo *II;
92 CFErrorFunctionChecker() : II(0) { }
94 void checkASTDecl(const FunctionDecl *D,
95 AnalysisManager &mgr, BugReporter &BR) const;
99 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
100 AnalysisManager &mgr,
101 BugReporter &BR) const {
102 if (!D->doesThisDeclarationHaveABody())
104 if (!D->getResultType()->isVoidType())
108 II = &D->getASTContext().Idents.get("CFErrorRef");
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)) {
120 const char *err = "Function accepting CFErrorRef* "
121 "should have a non-void return value to indicate whether or not an "
123 PathDiagnosticLocation L =
124 PathDiagnosticLocation::create(D, BR.getSourceManager());
125 BR.EmitBasicReport("Bad return type when passing CFErrorRef*",
126 "Coding conventions (Apple)", err, L);
130 //===----------------------------------------------------------------------===//
131 // NSOrCFErrorDerefChecker
132 //===----------------------------------------------------------------------===//
136 class NSErrorDerefBug : public BugType {
138 NSErrorDerefBug() : BugType("NSError** null dereference",
139 "Coding conventions (Apple)") {}
142 class CFErrorDerefBug : public BugType {
144 CFErrorDerefBug() : BugType("CFErrorRef* null dereference",
145 "Coding conventions (Apple)") {}
151 class NSOrCFErrorDerefChecker
152 : public Checker< check::Location,
153 check::Event<ImplicitNullDerefEvent> > {
154 mutable IdentifierInfo *NSErrorII, *CFErrorII;
156 bool ShouldCheckNSError, ShouldCheckCFError;
157 NSOrCFErrorDerefChecker() : NSErrorII(0), CFErrorII(0),
158 ShouldCheckNSError(0), ShouldCheckCFError(0) { }
160 void checkLocation(SVal loc, bool isLoad, const Stmt *S,
161 CheckerContext &C) const;
162 void checkEvent(ImplicitNullDerefEvent event) const;
166 namespace { struct NSErrorOut {}; }
167 namespace { struct CFErrorOut {}; }
169 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
174 struct ProgramStateTrait<NSErrorOut> : public ProgramStatePartialTrait<ErrorOutFlag> {
175 static void *GDMIndex() { static int index = 0; return &index; }
178 struct ProgramStateTrait<CFErrorOut> : public ProgramStatePartialTrait<ErrorOutFlag> {
179 static void *GDMIndex() { static int index = 0; return &index; }
184 template <typename T>
185 static bool hasFlag(SVal val, const ProgramState *state) {
186 if (SymbolRef sym = val.getAsSymbol())
187 if (const unsigned *attachedFlags = state->get<T>(sym))
188 return *attachedFlags;
192 template <typename T>
193 static void setFlag(const ProgramState *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));
199 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
200 const StackFrameContext *
201 SFC = C.getPredecessor()->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();
214 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
216 CheckerContext &C) const {
219 if (loc.isUndef() || !isa<Loc>(loc))
222 ASTContext &Ctx = C.getASTContext();
223 const ProgramState *state = C.getState();
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
231 QualType parmT = parameterTypeFromSVal(loc, C);
236 NSErrorII = &Ctx.Idents.get("NSError");
238 CFErrorII = &Ctx.Idents.get("CFErrorRef");
240 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
241 setFlag<NSErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
245 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
246 setFlag<CFErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
251 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
255 SVal loc = event.Location;
256 const ProgramState *state = event.SinkNode->getState();
257 BugReporter &BR = *event.BR;
259 bool isNSError = hasFlag<NSErrorOut>(loc, state);
260 bool isCFError = false;
262 isCFError = hasFlag<CFErrorOut>(loc, state);
264 if (!(isNSError || isCFError))
267 // Storing to possible null NSError/CFErrorRef out parameter.
271 llvm::raw_string_ostream os(err);
272 os << "Potential null dereference. According to coding standards ";
275 os << "in 'Creating and Returning NSError Objects' the parameter '";
277 os << "documented in CoreFoundation/CFError.h the parameter '";
279 os << "' may be null.";
283 bug = new NSErrorDerefBug();
285 bug = new CFErrorDerefBug();
286 BugReport *report = new BugReport(*bug, os.str(),
288 BR.EmitReport(report);
291 static bool IsNSError(QualType T, IdentifierInfo *II) {
293 const PointerType* PPT = T->getAs<PointerType>();
297 const ObjCObjectPointerType* PT =
298 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
303 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
305 // FIXME: Can ID ever be NULL?
307 return II == ID->getIdentifier();
312 static bool IsCFError(QualType T, IdentifierInfo *II) {
313 const PointerType* PPT = T->getAs<PointerType>();
314 if (!PPT) return false;
316 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
317 if (!TT) return false;
319 return TT->getDecl()->getIdentifier() == II;
322 void ento::registerNSErrorChecker(CheckerManager &mgr) {
323 mgr.registerChecker<NSErrorMethodChecker>();
324 NSOrCFErrorDerefChecker *
325 checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
326 checker->ShouldCheckNSError = true;
329 void ento::registerCFErrorChecker(CheckerManager &mgr) {
330 mgr.registerChecker<CFErrorFunctionChecker>();
331 NSOrCFErrorDerefChecker *
332 checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
333 checker->ShouldCheckCFError = true;