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/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"
29 using namespace clang;
32 static bool IsNSError(QualType T, IdentifierInfo *II);
33 static bool IsCFError(QualType T, IdentifierInfo *II);
35 //===----------------------------------------------------------------------===//
36 // NSErrorMethodChecker
37 //===----------------------------------------------------------------------===//
40 class NSErrorMethodChecker
41 : public Checker< check::ASTDecl<ObjCMethodDecl> > {
42 mutable IdentifierInfo *II;
45 NSErrorMethodChecker() : II(nullptr) {}
47 void checkASTDecl(const ObjCMethodDecl *D,
48 AnalysisManager &mgr, BugReporter &BR) const;
52 void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
54 BugReporter &BR) const {
55 if (!D->isThisDeclarationADefinition())
57 if (!D->getReturnType()->isVoidType())
61 II = &D->getASTContext().Idents.get("NSError");
63 bool hasNSError = false;
64 for (const auto *I : D->parameters()) {
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, this, "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(nullptr) {}
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->getReturnType()->isVoidType())
108 II = &D->getASTContext().Idents.get("CFErrorRef");
110 bool hasCFError = false;
111 for (auto I : D->parameters()) {
112 if (IsCFError(I->getType(), II)) {
119 const char *err = "Function accepting CFErrorRef* "
120 "should have a non-void return value to indicate whether or not an "
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);
129 //===----------------------------------------------------------------------===//
130 // NSOrCFErrorDerefChecker
131 //===----------------------------------------------------------------------===//
135 class NSErrorDerefBug : public BugType {
137 NSErrorDerefBug(const CheckerBase *Checker)
138 : BugType(Checker, "NSError** null dereference",
139 "Coding conventions (Apple)") {}
142 class CFErrorDerefBug : public BugType {
144 CFErrorDerefBug(const CheckerBase *Checker)
145 : BugType(Checker, "CFErrorRef* null dereference",
146 "Coding conventions (Apple)") {}
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;
159 bool ShouldCheckNSError, ShouldCheckCFError;
160 NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
161 ShouldCheckNSError(0), ShouldCheckCFError(0) { }
163 void checkLocation(SVal loc, bool isLoad, const Stmt *S,
164 CheckerContext &C) const;
165 void checkEvent(ImplicitNullDerefEvent event) const;
169 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
170 REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
171 REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
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;
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));
188 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
189 const StackFrameContext *
190 SFC = C.getLocationContext()->getCurrentStackFrame();
191 if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
192 const MemRegion* R = X->getRegion();
193 if (const VarRegion *VR = R->getAs<VarRegion>())
194 if (const StackArgumentsSpaceRegion *
195 stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
196 if (stackReg->getStackFrame() == SFC)
197 return VR->getValueType();
203 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
205 CheckerContext &C) const {
208 if (loc.isUndef() || !loc.getAs<Loc>())
211 ASTContext &Ctx = C.getASTContext();
212 ProgramStateRef state = C.getState();
214 // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
215 // SVal so that we can later check it when handling the
216 // ImplicitNullDerefEvent event.
217 // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
220 QualType parmT = parameterTypeFromSVal(loc, C);
225 NSErrorII = &Ctx.Idents.get("NSError");
227 CFErrorII = &Ctx.Idents.get("CFErrorRef");
229 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
230 setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
234 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
235 setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
240 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
244 SVal loc = event.Location;
245 ProgramStateRef state = event.SinkNode->getState();
246 BugReporter &BR = *event.BR;
248 bool isNSError = hasFlag<NSErrorOut>(loc, state);
249 bool isCFError = false;
251 isCFError = hasFlag<CFErrorOut>(loc, state);
253 if (!(isNSError || isCFError))
256 // Storing to possible null NSError/CFErrorRef out parameter.
257 SmallString<128> Buf;
258 llvm::raw_svector_ostream os(Buf);
260 os << "Potential null dereference. According to coding standards ";
262 ? "in 'Creating and Returning NSError Objects' the parameter"
263 : "documented in CoreFoundation/CFError.h the parameter");
265 os << " may be null";
267 BugType *bug = nullptr;
270 NSBT.reset(new NSErrorDerefBug(this));
275 CFBT.reset(new CFErrorDerefBug(this));
278 BR.emitReport(llvm::make_unique<BugReport>(*bug, os.str(), event.SinkNode));
281 static bool IsNSError(QualType T, IdentifierInfo *II) {
283 const PointerType* PPT = T->getAs<PointerType>();
287 const ObjCObjectPointerType* PT =
288 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
293 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
295 // FIXME: Can ID ever be NULL?
297 return II == ID->getIdentifier();
302 static bool IsCFError(QualType T, IdentifierInfo *II) {
303 const PointerType* PPT = T->getAs<PointerType>();
304 if (!PPT) return false;
306 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
307 if (!TT) return false;
309 return TT->getDecl()->getIdentifier() == II;
312 void ento::registerNSErrorChecker(CheckerManager &mgr) {
313 mgr.registerChecker<NSErrorMethodChecker>();
314 NSOrCFErrorDerefChecker *checker =
315 mgr.registerChecker<NSOrCFErrorDerefChecker>();
316 checker->ShouldCheckNSError = true;
319 void ento::registerCFErrorChecker(CheckerManager &mgr) {
320 mgr.registerChecker<CFErrorFunctionChecker>();
321 NSOrCFErrorDerefChecker *checker =
322 mgr.registerChecker<NSOrCFErrorDerefChecker>();
323 checker->ShouldCheckCFError = true;