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(D, "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(D, "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 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
167 REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
168 REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
170 template <typename T>
171 static bool hasFlag(SVal val, ProgramStateRef state) {
172 if (SymbolRef sym = val.getAsSymbol())
173 if (const unsigned *attachedFlags = state->get<T>(sym))
174 return *attachedFlags;
178 template <typename T>
179 static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
180 // We tag the symbol that the SVal wraps.
181 if (SymbolRef sym = val.getAsSymbol())
182 C.addTransition(state->set<T>(sym, true));
185 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
186 const StackFrameContext *
187 SFC = C.getLocationContext()->getCurrentStackFrame();
188 if (const loc::MemRegionVal* X = dyn_cast<loc::MemRegionVal>(&val)) {
189 const MemRegion* R = X->getRegion();
190 if (const VarRegion *VR = R->getAs<VarRegion>())
191 if (const StackArgumentsSpaceRegion *
192 stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
193 if (stackReg->getStackFrame() == SFC)
194 return VR->getValueType();
200 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
202 CheckerContext &C) const {
205 if (loc.isUndef() || !isa<Loc>(loc))
208 ASTContext &Ctx = C.getASTContext();
209 ProgramStateRef state = C.getState();
211 // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
212 // SVal so that we can later check it when handling the
213 // ImplicitNullDerefEvent event.
214 // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
217 QualType parmT = parameterTypeFromSVal(loc, C);
222 NSErrorII = &Ctx.Idents.get("NSError");
224 CFErrorII = &Ctx.Idents.get("CFErrorRef");
226 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
227 setFlag<NSErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
231 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
232 setFlag<CFErrorOut>(state, state->getSVal(cast<Loc>(loc)), C);
237 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
241 SVal loc = event.Location;
242 ProgramStateRef state = event.SinkNode->getState();
243 BugReporter &BR = *event.BR;
245 bool isNSError = hasFlag<NSErrorOut>(loc, state);
246 bool isCFError = false;
248 isCFError = hasFlag<CFErrorOut>(loc, state);
250 if (!(isNSError || isCFError))
253 // Storing to possible null NSError/CFErrorRef out parameter.
257 llvm::raw_string_ostream os(err);
258 os << "Potential null dereference. According to coding standards ";
261 os << "in 'Creating and Returning NSError Objects' the parameter '";
263 os << "documented in CoreFoundation/CFError.h the parameter '";
265 os << "' may be null.";
269 bug = new NSErrorDerefBug();
271 bug = new CFErrorDerefBug();
272 BugReport *report = new BugReport(*bug, os.str(),
274 BR.emitReport(report);
277 static bool IsNSError(QualType T, IdentifierInfo *II) {
279 const PointerType* PPT = T->getAs<PointerType>();
283 const ObjCObjectPointerType* PT =
284 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
289 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
291 // FIXME: Can ID ever be NULL?
293 return II == ID->getIdentifier();
298 static bool IsCFError(QualType T, IdentifierInfo *II) {
299 const PointerType* PPT = T->getAs<PointerType>();
300 if (!PPT) return false;
302 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
303 if (!TT) return false;
305 return TT->getDecl()->getIdentifier() == II;
308 void ento::registerNSErrorChecker(CheckerManager &mgr) {
309 mgr.registerChecker<NSErrorMethodChecker>();
310 NSOrCFErrorDerefChecker *
311 checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
312 checker->ShouldCheckNSError = true;
315 void ento::registerCFErrorChecker(CheckerManager &mgr) {
316 mgr.registerChecker<CFErrorFunctionChecker>();
317 NSOrCFErrorDerefChecker *
318 checker = mgr.registerChecker<NSOrCFErrorDerefChecker>();
319 checker->ShouldCheckCFError = true;