clang 10.0.0git

NSErrorChecker.cpp
Go to the documentation of this file.
1 //=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a CheckNSError, a flow-insenstive check
10 // that determines if an Objective-C class interface correctly returns
11 // a non-void return type.
12 //
13 // File under feature request PR 2600.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21 #include "clang/StaticAnalyzer/Core/Checker.h"
22 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/raw_ostream.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:
44 NSErrorMethodChecker() : II(nullptr) {}
45
46 void checkASTDecl(const ObjCMethodDecl *D,
47 AnalysisManager &mgr, BugReporter &BR) const;
48 };
49 }
50
51 void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
52 AnalysisManager &mgr,
53 BugReporter &BR) const {
54 if (!D->isThisDeclarationADefinition())
55 return;
56 if (!D->getReturnType()->isVoidType())
57 return;
58
59 if (!II)
60 II = &D->getASTContext().Idents.get("NSError");
61
62 bool hasNSError = false;
63 for (const auto *I : D->parameters()) {
64 if (IsNSError(I->getType(), II)) {
65 hasNSError = true;
66 break;
67 }
68 }
69
70 if (hasNSError) {
71 const char *err = "Method accepting NSError** "
72 "should have a non-void return value to indicate whether or not an "
73 "error occurred";
74 PathDiagnosticLocation L =
75 PathDiagnosticLocation::create(D, BR.getSourceManager());
76 BR.EmitBasicReport(D, this, "Bad return type when passing NSError**",
77 "Coding conventions (Apple)", err, L);
78 }
79 }
80
81 //===----------------------------------------------------------------------===//
82 // CFErrorFunctionChecker
83 //===----------------------------------------------------------------------===//
84
85 namespace {
86 class CFErrorFunctionChecker
87 : public Checker< check::ASTDecl<FunctionDecl> > {
88 mutable IdentifierInfo *II;
89
90 public:
91 CFErrorFunctionChecker() : II(nullptr) {}
92
93 void checkASTDecl(const FunctionDecl *D,
94 AnalysisManager &mgr, BugReporter &BR) const;
95 };
96 }
97
98 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
99 AnalysisManager &mgr,
100 BugReporter &BR) const {
101 if (!D->doesThisDeclarationHaveABody())
102 return;
103 if (!D->getReturnType()->isVoidType())
104 return;
105
106 if (!II)
107 II = &D->getASTContext().Idents.get("CFErrorRef");
108
109 bool hasCFError = false;
110 for (auto I : D->parameters()) {
111 if (IsCFError(I->getType(), II)) {
112 hasCFError = true;
113 break;
114 }
115 }
116
117 if (hasCFError) {
118 const char *err = "Function accepting CFErrorRef* "
119 "should have a non-void return value to indicate whether or not an "
120 "error occurred";
121 PathDiagnosticLocation L =
122 PathDiagnosticLocation::create(D, BR.getSourceManager());
123 BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*",
124 "Coding conventions (Apple)", err, L);
125 }
126 }
127
128 //===----------------------------------------------------------------------===//
129 // NSOrCFErrorDerefChecker
130 //===----------------------------------------------------------------------===//
131
132 namespace {
133
134 class NSErrorDerefBug : public BugType {
135 public:
136 NSErrorDerefBug(const CheckerBase *Checker)
137 : BugType(Checker, "NSError** null dereference",
138 "Coding conventions (Apple)") {}
139 };
140
141 class CFErrorDerefBug : public BugType {
142 public:
143 CFErrorDerefBug(const CheckerBase *Checker)
144 : BugType(Checker, "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 mutable std::unique_ptr<NSErrorDerefBug> NSBT;
156 mutable std::unique_ptr<CFErrorDerefBug> CFBT;
157 public:
158 bool ShouldCheckNSError, ShouldCheckCFError;
159 NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
160 ShouldCheckNSError(0), ShouldCheckCFError(0) { }
161
162 void checkLocation(SVal loc, bool isLoad, const Stmt *S,
163 CheckerContext &C) const;
164 void checkEvent(ImplicitNullDerefEvent event) const;
165 };
166 }
167
168 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
169 REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
170 REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
171
172 template <typename T>
173 static bool hasFlag(SVal val, ProgramStateRef state) {
174 if (SymbolRef sym = val.getAsSymbol())
175 if (const unsigned *attachedFlags = state->get<T>(sym))
176 return *attachedFlags;
177 return false;
178 }
179
180 template <typename T>
181 static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
182 // We tag the symbol that the SVal wraps.
183 if (SymbolRef sym = val.getAsSymbol())
184 C.addTransition(state->set<T>(sym, true));
185 }
186
187 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
188 const StackFrameContext * SFC = C.getStackFrame();
189 if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
190 const MemRegion* R = X->getRegion();
191 if (const VarRegion *VR = R->getAs<VarRegion>())
192 if (const StackArgumentsSpaceRegion *
193 stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
194 if (stackReg->getStackFrame() == SFC)
195 return VR->getValueType();
196 }
197
198 return QualType();
199 }
200
201 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
202 const Stmt *S,
203 CheckerContext &C) const {
204 if (!isLoad)
205 return;
206 if (loc.isUndef() || !loc.getAs<Loc>())
207 return;
208
209 ASTContext &Ctx = C.getASTContext();
210 ProgramStateRef state = C.getState();
211
212 // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
213 // SVal so that we can later check it when handling the
214 // ImplicitNullDerefEvent event.
215 // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
216 // function ?
217
218 QualType parmT = parameterTypeFromSVal(loc, C);
219 if (parmT.isNull())
220 return;
221
222 if (!NSErrorII)
223 NSErrorII = &Ctx.Idents.get("NSError");
224 if (!CFErrorII)
225 CFErrorII = &Ctx.Idents.get("CFErrorRef");
226
227 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
228 setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
229 return;
230 }
231
232 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
233 setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
234 return;
235 }
236 }
237
238 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
239 if (event.IsLoad)
240 return;
241
242 SVal loc = event.Location;
243 ProgramStateRef state = event.SinkNode->getState();
244 BugReporter &BR = *event.BR;
245
246 bool isNSError = hasFlag<NSErrorOut>(loc, state);
247 bool isCFError = false;
248 if (!isNSError)
249 isCFError = hasFlag<CFErrorOut>(loc, state);
250
251 if (!(isNSError || isCFError))
252 return;
253
254 // Storing to possible null NSError/CFErrorRef out parameter.
255 SmallString<128> Buf;
256 llvm::raw_svector_ostream os(Buf);
257
258 os << "Potential null dereference. According to coding standards ";
259 os << (isNSError
260 ? "in 'Creating and Returning NSError Objects' the parameter"
261 : "documented in CoreFoundation/CFError.h the parameter");
262
263 os << " may be null";
264
265 BugType *bug = nullptr;
266 if (isNSError) {
267 if (!NSBT)
268 NSBT.reset(new NSErrorDerefBug(this));
269 bug = NSBT.get();
270 }
271 else {
272 if (!CFBT)
273 CFBT.reset(new CFErrorDerefBug(this));
274 bug = CFBT.get();
275 }
276 BR.emitReport(
277 std::make_unique<PathSensitiveBugReport>(*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::registerNSOrCFErrorDerefChecker(CheckerManager &mgr) {
312 mgr.registerChecker<NSOrCFErrorDerefChecker>();
313 }
314
315 bool ento::shouldRegisterNSOrCFErrorDerefChecker(const LangOptions &LO) {
316 return true;
317 }
318
319 void ento::registerNSErrorChecker(CheckerManager &mgr) {
320 mgr.registerChecker<NSErrorMethodChecker>();
321 NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
322 checker->ShouldCheckNSError = true;
323 }
324
325 bool ento::shouldRegisterNSErrorChecker(const LangOptions &LO) {
326 return true;
327 }
328
329 void ento::registerCFErrorChecker(CheckerManager &mgr) {
330 mgr.registerChecker<CFErrorFunctionChecker>();
331 NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
332 checker->ShouldCheckCFError = true;
333 }
334
335 bool ento::shouldRegisterCFErrorChecker(const LangOptions &LO) {
336 return true;
337 }
clang::Builtin::ID
ID
Definition: Builtins.h:46
ento
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1783
clang::ObjCMethodDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition: DeclObjC.h:527
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2627
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:654
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:66
clang::ento::ProgramStateRef
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Definition: ProgramState_Fwd.h:37
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:2445
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:57
clang::ento::SymbolRef
const SymExpr * SymbolRef
Definition: SymExpr.h:110
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
llvm::Optional
Definition: LLVM.h:37
Checker.h
CheckerManager.h
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
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:802
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:580
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
clang::ento::PathDiagnosticLocation::create
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
Definition: PathDiagnostic.h:210
ErrorOutFlag
llvm::ImmutableMap< SymbolRef, unsigned > ErrorOutFlag
Definition: NSErrorChecker.cpp:168
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:324
llvm::SmallString< 128 >
setFlag
static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C)
Definition: NSErrorChecker.cpp:181
BuiltinCheckerRegistration.h
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
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:33
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:529
clang::Decl::getASTContext
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:377
hasFlag
static bool hasFlag(SVal val, ProgramStateRef state)
Definition: NSErrorChecker.cpp:173
Decl.h
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:21
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:5951
clang::ObjCObjectPointerType::getInterfaceDecl
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:6007
clang::LocationContext::getStackFrame
const StackFrameContext * getStackFrame() const
Definition: AnalysisDeclContext.cpp:442
clang::StackFrameContext
Definition: AnalysisDeclContext.h:296
clang::TypedefType::getDecl
TypedefNameDecl * getDecl() const
Definition: Type.h:4256
X
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:14780
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6777
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2078
clang::TypedefType
Definition: Type.h:4240
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:187
CheckerContext.h
clang::ObjCMethodDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:368