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 static bool hasReservedReturnType(const FunctionDecl *D) {
99 if (isa<CXXConstructorDecl>(D))
102 // operators delete and delete[] are required to have 'void' return type
103 auto OperatorKind = D->getOverloadedOperator();
104 return OperatorKind == OO_Delete || OperatorKind == OO_Array_Delete;
107 void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
108 AnalysisManager &mgr,
109 BugReporter &BR) const {
110 if (!D->doesThisDeclarationHaveABody())
112 if (!D->getReturnType()->isVoidType())
114 if (hasReservedReturnType(D))
118 II = &D->getASTContext().Idents.get("CFErrorRef");
120 bool hasCFError = false;
121 for (auto I : D->parameters()) {
122 if (IsCFError(I->getType(), II)) {
129 const char *err = "Function accepting CFErrorRef* "
130 "should have a non-void return value to indicate whether or not an "
132 PathDiagnosticLocation L =
133 PathDiagnosticLocation::create(D, BR.getSourceManager());
134 BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*",
135 "Coding conventions (Apple)", err, L);
139 //===----------------------------------------------------------------------===//
140 // NSOrCFErrorDerefChecker
141 //===----------------------------------------------------------------------===//
145 class NSErrorDerefBug : public BugType {
147 NSErrorDerefBug(const CheckerNameRef Checker)
148 : BugType(Checker, "NSError** null dereference",
149 "Coding conventions (Apple)") {}
152 class CFErrorDerefBug : public BugType {
154 CFErrorDerefBug(const CheckerNameRef Checker)
155 : BugType(Checker, "CFErrorRef* null dereference",
156 "Coding conventions (Apple)") {}
162 class NSOrCFErrorDerefChecker
163 : public Checker< check::Location,
164 check::Event<ImplicitNullDerefEvent> > {
165 mutable IdentifierInfo *NSErrorII, *CFErrorII;
166 mutable std::unique_ptr<NSErrorDerefBug> NSBT;
167 mutable std::unique_ptr<CFErrorDerefBug> CFBT;
169 DefaultBool ShouldCheckNSError, ShouldCheckCFError;
170 CheckerNameRef NSErrorName, CFErrorName;
171 NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr) {}
173 void checkLocation(SVal loc, bool isLoad, const Stmt *S,
174 CheckerContext &C) const;
175 void checkEvent(ImplicitNullDerefEvent event) const;
179 typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
180 REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
181 REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
183 template <typename T>
184 static bool hasFlag(SVal val, ProgramStateRef state) {
185 if (SymbolRef sym = val.getAsSymbol())
186 if (const unsigned *attachedFlags = state->get<T>(sym))
187 return *attachedFlags;
191 template <typename T>
192 static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
193 // We tag the symbol that the SVal wraps.
194 if (SymbolRef sym = val.getAsSymbol())
195 C.addTransition(state->set<T>(sym, true));
198 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
199 const StackFrameContext * SFC = C.getStackFrame();
200 if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
201 const MemRegion* R = X->getRegion();
202 if (const VarRegion *VR = R->getAs<VarRegion>())
203 if (const StackArgumentsSpaceRegion *
204 stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
205 if (stackReg->getStackFrame() == SFC)
206 return VR->getValueType();
212 void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
214 CheckerContext &C) const {
217 if (loc.isUndef() || !loc.getAs<Loc>())
220 ASTContext &Ctx = C.getASTContext();
221 ProgramStateRef state = C.getState();
223 // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
224 // SVal so that we can later check it when handling the
225 // ImplicitNullDerefEvent event.
226 // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
229 QualType parmT = parameterTypeFromSVal(loc, C);
234 NSErrorII = &Ctx.Idents.get("NSError");
236 CFErrorII = &Ctx.Idents.get("CFErrorRef");
238 if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
239 setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
243 if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
244 setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
249 void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
253 SVal loc = event.Location;
254 ProgramStateRef state = event.SinkNode->getState();
255 BugReporter &BR = *event.BR;
257 bool isNSError = hasFlag<NSErrorOut>(loc, state);
258 bool isCFError = false;
260 isCFError = hasFlag<CFErrorOut>(loc, state);
262 if (!(isNSError || isCFError))
265 // Storing to possible null NSError/CFErrorRef out parameter.
266 SmallString<128> Buf;
267 llvm::raw_svector_ostream os(Buf);
269 os << "Potential null dereference. According to coding standards ";
271 ? "in 'Creating and Returning NSError Objects' the parameter"
272 : "documented in CoreFoundation/CFError.h the parameter");
274 os << " may be null";
276 BugType *bug = nullptr;
279 NSBT.reset(new NSErrorDerefBug(NSErrorName));
284 CFBT.reset(new CFErrorDerefBug(CFErrorName));
288 std::make_unique<PathSensitiveBugReport>(*bug, os.str(), event.SinkNode));
291 static bool IsNSError(QualType T, IdentifierInfo *II) {
293 const PointerType* PPT = T->getAs<PointerType>();
297 const ObjCObjectPointerType* PT =
298 PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
303 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
305 // FIXME: Can ID ever be NULL?
307 return II == ID->getIdentifier();
312 static bool IsCFError(QualType T, IdentifierInfo *II) {
313 const PointerType* PPT = T->getAs<PointerType>();
314 if (!PPT) return false;
316 const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
317 if (!TT) return false;
319 return TT->getDecl()->getIdentifier() == II;
322 void ento::registerNSOrCFErrorDerefChecker(CheckerManager &mgr) {
323 mgr.registerChecker<NSOrCFErrorDerefChecker>();
326 bool ento::shouldRegisterNSOrCFErrorDerefChecker(const CheckerManager &mgr) {
330 void ento::registerNSErrorChecker(CheckerManager &mgr) {
331 mgr.registerChecker<NSErrorMethodChecker>();
332 NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
333 checker->ShouldCheckNSError = true;
334 checker->NSErrorName = mgr.getCurrentCheckerName();
337 bool ento::shouldRegisterNSErrorChecker(const CheckerManager &mgr) {
341 void ento::registerCFErrorChecker(CheckerManager &mgr) {
342 mgr.registerChecker<CFErrorFunctionChecker>();
343 NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
344 checker->ShouldCheckCFError = true;
345 checker->CFErrorName = mgr.getCurrentCheckerName();
348 bool ento::shouldRegisterCFErrorChecker(const CheckerManager &mgr) {