clang 8.0.0

NSErrorChecker.cpp
Go to the documentation of this file.
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 "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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(nullptr) {}
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 (const auto *I : D->parameters()) {
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, this, "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:
92 CFErrorFunctionChecker() : II(nullptr) {}
93
94 void checkASTDecl(const FunctionDecl *D,
95 AnalysisManager &mgr, BugReporter &BR) const;
96 };
97 }
98
99 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
100 AnalysisManager &mgr,
101 BugReporter &BR) const {
102 if (!D->doesThisDeclarationHaveABody())
103 return;
104 if (!D->getReturnType()->isVoidType())
105 return;
106
107 if (!II)
108 II = &D->getASTContext().Idents.get("CFErrorRef");
109
110 bool hasCFError = false;
111 for (auto I : D->parameters()) {
112 if (IsCFError(I->getType(), II)) {
113 hasCFError = true;
114 break;
115 }
116 }
117
118 if (hasCFError) {
119 const char *err = "Function accepting CFErrorRef* "
120 "should have a non-void return value to indicate whether or not an "
121 "error occurred";
122 PathDiagnosticLocation L =
123 PathDiagnosticLocation::create(D, BR.getSourceManager());
124 BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*",
125 "Coding conventions (Apple)", err, L);
126 }
127 }
128
129 //===----------------------------------------------------------------------===//
130 // NSOrCFErrorDerefChecker
131 //===----------------------------------------------------------------------===//
132
133 namespace {
134
135 class NSErrorDerefBug : public BugType {
136 public:
137 NSErrorDerefBug(const CheckerBase *Checker)
138 : BugType(Checker, "NSError** null dereference",
139 "Coding conventions (Apple)") {}
140 };
141
142 class CFErrorDerefBug : public BugType {
143 public:
144 CFErrorDerefBug(const CheckerBase *Checker)
145 : BugType(Checker, "CFErrorRef* null dereference",
146 "Coding conventions (Apple)") {}
147 };
148
149 }
150
151 namespace {
152 class NSOrCFErrorDerefChecker
153 : public Checker< check::Location,
154 check::Event<ImplicitNullDerefEvent> > {
155 mutable IdentifierInfo *NSErrorII, *CFErrorII;
156 mutable std::unique_ptr<NSErrorDerefBug> NSBT;
157 mutable std::unique_ptr<CFErrorDerefBug> CFBT;
158 public:
159 bool ShouldCheckNSError, ShouldCheckCFError;
160 NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
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 * SFC = C.getStackFrame();
190 if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
191 const MemRegion* R = X->getRegion();
192 if (const VarRegion *VR = R->getAs<VarRegion>())
193 if (const StackArgumentsSpaceRegion *
194 stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
195 if (stackReg->getStackFrame() == SFC)
196 return VR->getValueType();
197 }
198
199 return QualType();
200 }
201
202 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
203 const Stmt *S,
204 CheckerContext &C) const {
205 if (!isLoad)
206 return;
207 if (loc.isUndef() || !loc.getAs<Loc>())
208 return;
209
210 ASTContext &Ctx = C.getASTContext();
211 ProgramStateRef state = C.getState();
212
213 // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
214 // SVal so that we can later check it when handling the
215 // ImplicitNullDerefEvent event.
216 // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
217 // function ?
218
219 QualType parmT = parameterTypeFromSVal(loc, C);
220 if (parmT.isNull())
221 return;
222
223 if (!NSErrorII)
224 NSErrorII = &Ctx.Idents.get("NSError");
225 if (!CFErrorII)
226 CFErrorII = &Ctx.Idents.get("CFErrorRef");
227
228 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
229 setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
230 return;
231 }
232
233 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
234 setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
235 return;
236 }
237 }
238
239 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
240 if (event.IsLoad)
241 return;
242
243 SVal loc = event.Location;
244 ProgramStateRef state = event.SinkNode->getState();
245 BugReporter &BR = *event.BR;
246
247 bool isNSError = hasFlag<NSErrorOut>(loc, state);
248 bool isCFError = false;
249 if (!isNSError)
250 isCFError = hasFlag<CFErrorOut>(loc, state);
251
252 if (!(isNSError || isCFError))
253 return;
254
255 // Storing to possible null NSError/CFErrorRef out parameter.
256 SmallString<128> Buf;
257 llvm::raw_svector_ostream os(Buf);
258
259 os << "Potential null dereference. According to coding standards ";
260 os << (isNSError
261 ? "in 'Creating and Returning NSError Objects' the parameter"
262 : "documented in CoreFoundation/CFError.h the parameter");
263
264 os << " may be null";
265
266 BugType *bug = nullptr;
267 if (isNSError) {
268 if (!NSBT)
269 NSBT.reset(new NSErrorDerefBug(this));
270 bug = NSBT.get();
271 }
272 else {
273 if (!CFBT)
274 CFBT.reset(new CFErrorDerefBug(this));
275 bug = CFBT.get();
276 }
277 BR.emitReport(llvm::make_unique<BugReport>(*bug, os.str(), event.SinkNode));
278 }
279
280 static bool IsNSError(QualType T, IdentifierInfo *II) {
281
282 const PointerType* PPT = T->getAs<PointerType>();
283 if (!PPT)
284 return false;
285
286 const ObjCObjectPointerType* PT =
287 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
288
289 if (!PT)
290 return false;
291
292 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
293
294 // FIXME: Can ID ever be NULL?
295 if (ID)
296 return II == ID->getIdentifier();
297
298 return false;
299 }
300
301 static bool IsCFError(QualType T, IdentifierInfo *II) {
302 const PointerType* PPT = T->getAs<PointerType>();
303 if (!PPT) return false;
304
305 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
306 if (!TT) return false;
307
308 return TT->getDecl()->getIdentifier() == II;
309 }
310
311 void ento::registerNSErrorChecker(CheckerManager &mgr) {
312 mgr.registerChecker<NSErrorMethodChecker>();
313 NSOrCFErrorDerefChecker *checker =
314 mgr.registerChecker<NSOrCFErrorDerefChecker>();
315 checker->ShouldCheckNSError = true;
316 }
317
318 void ento::registerCFErrorChecker(CheckerManager &mgr) {
319 mgr.registerChecker<CFErrorFunctionChecker>();
320 NSOrCFErrorDerefChecker *checker =
321 mgr.registerChecker<NSOrCFErrorDerefChecker>();
322 checker->ShouldCheckCFError = true;
323 }
clang::Builtin::ID
ID
Definition: Builtins.h:49
ento
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1738
clang::ObjCMethodDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition: DeclObjC.h:515
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2550
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:638
clang::ento::SymbolRef
const SymExpr * SymbolRef
Definition: PathDiagnostic.h:59
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:66
clang::ento::ProgramStateRef
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Definition: ProgramState_Fwd.h:38
IsCFError
static bool IsCFError(QualType T, IdentifierInfo *II)
Definition: NSErrorChecker.cpp:301
DeclObjC.h
BugType.h
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2302
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:58
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
llvm::Optional
Definition: LLVM.h:38
Checker.h
CheckerManager.h
clang::CodeGen::state
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
Definition: CGOpenMPRuntime.h:748
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:566
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2262
clang::ento::PathDiagnosticLocation::create
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
Definition: PathDiagnostic.h:209
ErrorOutFlag
llvm::ImmutableMap< SymbolRef, unsigned > ErrorOutFlag
Definition: NSErrorChecker.cpp:169
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:323
llvm::SmallString
Definition: LLVM.h:35
setFlag
static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C)
Definition: NSErrorChecker.cpp:182
BuiltinCheckerRegistration.h
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
REGISTER_TRAIT_WITH_PROGRAMSTATE
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy...
Definition: ProgramStateTrait.h:34
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:519
clang::Decl::getASTContext
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
hasFlag
static bool hasFlag(SVal val, ProgramStateRef state)
Definition: NSErrorChecker.cpp:174
Decl.h
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:22
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:5794
clang::ObjCObjectPointerType::getInterfaceDecl
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:5850
clang::LocationContext::getStackFrame
const StackFrameContext * getStackFrame() const
Definition: AnalysisDeclContext.cpp:440
clang::StackFrameContext
Definition: AnalysisDeclContext.h:292
clang::TypedefType::getDecl
TypedefNameDecl * getDecl() const
Definition: Type.h:4167
X
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13954
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6544
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:1989
clang::TypedefType
Definition: Type.h:4151
ProgramStateTrait.h
IsNSError
static bool IsNSError(QualType T, IdentifierInfo *II)
Definition: NSErrorChecker.cpp:280
parameterTypeFromSVal
static QualType parameterTypeFromSVal(SVal val, CheckerContext &C)
Definition: NSErrorChecker.cpp:188
CheckerContext.h
clang::ObjCMethodDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:367