1 //=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- C++ -*-==//
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
7 //===----------------------------------------------------------------------===//
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.
13 // File under feature request PR 2600.
15 //===----------------------------------------------------------------------===//
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"
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(nullptr) {}
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->getReturnType()->isVoidType())
60 II = &D->getASTContext().Idents.get("NSError");
62 bool hasNSError = false;
63 for (const auto *I : D->parameters()) {
64 if (IsNSError(I->getType(), II)) {
71 const char *err = "Method accepting NSError** "
72 "should have a non-void return value to indicate whether or not an "
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);
81 //===----------------------------------------------------------------------===//
82 // CFErrorFunctionChecker
83 //===----------------------------------------------------------------------===//
86 class CFErrorFunctionChecker
87 : public Checker< check::ASTDecl<FunctionDecl> > {
88 mutable IdentifierInfo *II;
91 CFErrorFunctionChecker() : II(nullptr) {}
93 void checkASTDecl(const FunctionDecl *D,
94 AnalysisManager &mgr, BugReporter &BR) const;
98 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
100 BugReporter &BR) const {
101 if (!D->doesThisDeclarationHaveABody())
103 if (!D->getReturnType()->isVoidType())
107 II = &D->getASTContext().Idents.get("CFErrorRef");
109 bool hasCFError = false;
110 for (auto I : D->parameters()) {
111 if (IsCFError(I->getType(), II)) {
118 const char *err = "Function accepting CFErrorRef* "
119 "should have a non-void return value to indicate whether or not an "
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);
128 //===----------------------------------------------------------------------===//
129 // NSOrCFErrorDerefChecker
130 //===----------------------------------------------------------------------===//
134 class NSErrorDerefBug : public BugType {
136 NSErrorDerefBug(const CheckerBase *Checker)
137 : BugType(Checker, "NSError** null dereference",
138 "Coding conventions (Apple)") {}
141 class CFErrorDerefBug : public BugType {
143 CFErrorDerefBug(const CheckerBase *Checker)
144 : BugType(Checker, "CFErrorRef* null dereference",
145 "Coding conventions (Apple)") {}
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;
158 bool ShouldCheckNSError, ShouldCheckCFError;
159 NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
160 ShouldCheckNSError(0), ShouldCheckCFError(0) { }
162 void checkLocation(SVal loc, bool isLoad, const Stmt *S,
163 CheckerContext &C) const;
164 void checkEvent(ImplicitNullDerefEvent event) const;
168 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
169 REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
170 REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
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;
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));
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();
201 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
203 CheckerContext &C) const {
206 if (loc.isUndef() || !loc.getAs<Loc>())
209 ASTContext &Ctx = C.getASTContext();
210 ProgramStateRef state = C.getState();
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
218 QualType parmT = parameterTypeFromSVal(loc, C);
223 NSErrorII = &Ctx.Idents.get("NSError");
225 CFErrorII = &Ctx.Idents.get("CFErrorRef");
227 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
228 setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
232 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
233 setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
238 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
242 SVal loc = event.Location;
243 ProgramStateRef state = event.SinkNode->getState();
244 BugReporter &BR = *event.BR;
246 bool isNSError = hasFlag<NSErrorOut>(loc, state);
247 bool isCFError = false;
249 isCFError = hasFlag<CFErrorOut>(loc, state);
251 if (!(isNSError || isCFError))
254 // Storing to possible null NSError/CFErrorRef out parameter.
255 SmallString<128> Buf;
256 llvm::raw_svector_ostream os(Buf);
258 os << "Potential null dereference. According to coding standards ";
260 ? "in 'Creating and Returning NSError Objects' the parameter"
261 : "documented in CoreFoundation/CFError.h the parameter");
263 os << " may be null";
265 BugType *bug = nullptr;
268 NSBT.reset(new NSErrorDerefBug(this));
273 CFBT.reset(new CFErrorDerefBug(this));
277 std::make_unique<PathSensitiveBugReport>(*bug, os.str(), event.SinkNode));
280 static bool IsNSError(QualType T, IdentifierInfo *II) {
282 const PointerType* PPT = T->getAs<PointerType>();
286 const ObjCObjectPointerType* PT =
287 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
292 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
294 // FIXME: Can ID ever be NULL?
296 return II == ID->getIdentifier();
301 static bool IsCFError(QualType T, IdentifierInfo *II) {
302 const PointerType* PPT = T->getAs<PointerType>();
303 if (!PPT) return false;
305 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
306 if (!TT) return false;
308 return TT->getDecl()->getIdentifier() == II;
311 void ento::registerNSOrCFErrorDerefChecker(CheckerManager &mgr) {
312 mgr.registerChecker<NSOrCFErrorDerefChecker>();
315 bool ento::shouldRegisterNSOrCFErrorDerefChecker(const LangOptions &LO) {
319 void ento::registerNSErrorChecker(CheckerManager &mgr) {
320 mgr.registerChecker<NSErrorMethodChecker>();
321 NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
322 checker->ShouldCheckNSError = true;
325 bool ento::shouldRegisterNSErrorChecker(const LangOptions &LO) {
329 void ento::registerCFErrorChecker(CheckerManager &mgr) {
330 mgr.registerChecker<CFErrorFunctionChecker>();
331 NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
332 checker->ShouldCheckCFError = true;
335 bool ento::shouldRegisterCFErrorChecker(const LangOptions &LO) {