Clang Project

clang_source_code/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
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
28using namespace clang;
29using namespace ento;
30
31static bool IsNSError(QualType TIdentifierInfo *II);
32static bool IsCFError(QualType TIdentifierInfo *II);
33
34//===----------------------------------------------------------------------===//
35// NSErrorMethodChecker
36//===----------------------------------------------------------------------===//
37
38namespace {
39class NSErrorMethodChecker
40    : public Checker< check::ASTDecl<ObjCMethodDecl> > {
41  mutable IdentifierInfo *II;
42
43public:
44  NSErrorMethodChecker() : II(nullptr) {}
45
46  void checkASTDecl(const ObjCMethodDecl *D,
47                    AnalysisManager &mgrBugReporter &BRconst;
48};
49}
50
51void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
52                                        AnalysisManager &mgr,
53                                        BugReporter &BRconst {
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(DBR.getSourceManager());
76    BR.EmitBasicReport(Dthis"Bad return type when passing NSError**",
77                       "Coding conventions (Apple)"errL);
78  }
79}
80
81//===----------------------------------------------------------------------===//
82// CFErrorFunctionChecker
83//===----------------------------------------------------------------------===//
84
85namespace {
86class CFErrorFunctionChecker
87    : public Checker< check::ASTDecl<FunctionDecl> > {
88  mutable IdentifierInfo *II;
89
90public:
91  CFErrorFunctionChecker() : II(nullptr) {}
92
93  void checkASTDecl(const FunctionDecl *D,
94                    AnalysisManager &mgrBugReporter &BRconst;
95};
96}
97
98void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
99                                        AnalysisManager &mgr,
100                                        BugReporter &BRconst {
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(DBR.getSourceManager());
123    BR.EmitBasicReport(Dthis"Bad return type when passing CFErrorRef*",
124                       "Coding conventions (Apple)"errL);
125  }
126}
127
128//===----------------------------------------------------------------------===//
129// NSOrCFErrorDerefChecker
130//===----------------------------------------------------------------------===//
131
132namespace {
133
134class NSErrorDerefBug : public BugType {
135public:
136  NSErrorDerefBug(const CheckerBase *Checker)
137      : BugType(Checker, "NSError** null dereference",
138                "Coding conventions (Apple)") {}
139};
140
141class CFErrorDerefBug : public BugType {
142public:
143  CFErrorDerefBug(const CheckerBase *Checker)
144      : BugType(Checker, "CFErrorRef* null dereference",
145                "Coding conventions (Apple)") {}
146};
147
148}
149
150namespace {
151class NSOrCFErrorDerefChecker
152    : public Checker< check::Location,
153                        check::Event<ImplicitNullDerefEvent> > {
154  mutable IdentifierInfo *NSErrorII, *CFErrorII;
155  mutable std::unique_ptr<NSErrorDerefBugNSBT;
156  mutable std::unique_ptr<CFErrorDerefBugCFBT;
157public:
158  bool ShouldCheckNSErrorShouldCheckCFError;
159  NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
160                              ShouldCheckNSError(0), ShouldCheckCFError(0) { }
161
162  void checkLocation(SVal locbool isLoadconst Stmt *S,
163                     CheckerContext &Cconst;
164  void checkEvent(ImplicitNullDerefEvent eventconst;
165};
166}
167
168typedef llvm::ImmutableMap<SymbolRef, unsignedErrorOutFlag;
169REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
170REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
171
172template <typename T>
173static bool hasFlag(SVal valProgramStateRef state) {
174  if (SymbolRef sym = val.getAsSymbol())
175    if (const unsigned *attachedFlags = state->get<T>(sym))
176      return *attachedFlags;
177  return false;
178}
179
180template <typename T>
181static void setFlag(ProgramStateRef stateSVal valCheckerContext &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
187static QualType parameterTypeFromSVal(SVal valCheckerContext &C) {
188  const StackFrameContext * SFC = C.getStackFrame();
189  if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
190    const MemRegionR = 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
201void NSOrCFErrorDerefChecker::checkLocation(SVal locbool isLoad,
202                                            const Stmt *S,
203                                            CheckerContext &Cconst {
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(locC);
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(parmTNSErrorII)) {
228    setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
229    return;
230  }
231
232  if (ShouldCheckCFError && IsCFError(parmTCFErrorII)) {
233    setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
234    return;
235  }
236}
237
238void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent eventconst {
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<128Buf;
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(llvm::make_unique<BugReport>(*bug, os.str(), event.SinkNode));
277}
278
279static bool IsNSError(QualType TIdentifierInfo *II) {
280
281  const PointerTypePPT = T->getAs<PointerType>();
282  if (!PPT)
283    return false;
284
285  const ObjCObjectPointerTypePT =
286    PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
287
288  if (!PT)
289    return false;
290
291  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
292
293  // FIXME: Can ID ever be NULL?
294  if (ID)
295    return II == ID->getIdentifier();
296
297  return false;
298}
299
300static bool IsCFError(QualType TIdentifierInfo *II) {
301  const PointerTypePPT = T->getAs<PointerType>();
302  if (!PPTreturn false;
303
304  const TypedefTypeTT = PPT->getPointeeType()->getAs<TypedefType>();
305  if (!TTreturn false;
306
307  return TT->getDecl()->getIdentifier() == II;
308}
309
310void ento::registerNSOrCFErrorDerefChecker(CheckerManager &mgr) {
311  mgr.registerChecker<NSOrCFErrorDerefChecker>();
312}
313
314bool ento::shouldRegisterNSOrCFErrorDerefChecker(const LangOptions &LO) {
315  return true;
316}
317
318void ento::registerNSErrorChecker(CheckerManager &mgr) {
319  mgr.registerChecker<NSErrorMethodChecker>();
320  NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
321  checker->ShouldCheckNSError = true;
322}
323
324bool ento::shouldRegisterNSErrorChecker(const LangOptions &LO) {
325  return true;
326}
327
328void ento::registerCFErrorChecker(CheckerManager &mgr) {
329  mgr.registerChecker<CFErrorFunctionChecker>();
330  NSOrCFErrorDerefChecker *checker = mgr.getChecker<NSOrCFErrorDerefChecker>();
331  checker->ShouldCheckCFError = true;
332}
333
334bool ento::shouldRegisterCFErrorChecker(const LangOptions &LO) {
335  return true;
336}
337