clang  16.0.0git
NullabilityChecker.cpp
Go to the documentation of this file.
1 //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
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 checker tries to find nullability violations. There are several kinds of
10 // possible violations:
11 // * Null pointer is passed to a pointer which has a _Nonnull type.
12 // * Null pointer is returned from a function which has a _Nonnull return type.
13 // * Nullable pointer is passed to a pointer which has a _Nonnull type.
14 // * Nullable pointer is returned from a function which has a _Nonnull return
15 // type.
16 // * Nullable pointer is dereferenced.
17 //
18 // This checker propagates the nullability information of the pointers and looks
19 // for the patterns that are described above. Explicit casts are trusted and are
20 // considered a way to suppress false positives for this checker. The other way
21 // to suppress warnings would be to add asserts or guarding if statements to the
22 // code. In addition to the nullability propagation this checker also uses some
23 // heuristics to suppress potential false positives.
24 //
25 //===----------------------------------------------------------------------===//
26 
28 
35 
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/Path.h"
38 
39 using namespace clang;
40 using namespace ento;
41 
42 namespace {
43 
44 /// Returns the most nullable nullability. This is used for message expressions
45 /// like [receiver method], where the nullability of this expression is either
46 /// the nullability of the receiver or the nullability of the return type of the
47 /// method, depending on which is more nullable. Contradicted is considered to
48 /// be the most nullable, to avoid false positive results.
49 Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
50  return static_cast<Nullability>(
51  std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
52 }
53 
54 const char *getNullabilityString(Nullability Nullab) {
55  switch (Nullab) {
57  return "contradicted";
59  return "nullable";
61  return "unspecified";
63  return "nonnull";
64  }
65  llvm_unreachable("Unexpected enumeration.");
66  return "";
67 }
68 
69 // These enums are used as an index to ErrorMessages array.
70 enum class ErrorKind : int {
71  NilAssignedToNonnull,
72  NilPassedToNonnull,
73  NilReturnedToNonnull,
74  NullableAssignedToNonnull,
75  NullableReturnedToNonnull,
76  NullableDereferenced,
77  NullablePassedToNonnull
78 };
79 
80 class NullabilityChecker
81  : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
82  check::PostCall, check::PostStmt<ExplicitCastExpr>,
83  check::PostObjCMessage, check::DeadSymbols,
84  check::Location, check::Event<ImplicitNullDerefEvent>> {
85 
86 public:
87  // If true, the checker will not diagnose nullabilility issues for calls
88  // to system headers. This option is motivated by the observation that large
89  // projects may have many nullability warnings. These projects may
90  // find warnings about nullability annotations that they have explicitly
91  // added themselves higher priority to fix than warnings on calls to system
92  // libraries.
93  bool NoDiagnoseCallsToSystemHeaders = false;
94 
95  void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
96  void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
97  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
98  void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
99  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
100  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
101  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
102  void checkEvent(ImplicitNullDerefEvent Event) const;
103  void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
104  CheckerContext &C) const;
105 
106  void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
107  const char *Sep) const override;
108 
109  enum CheckKind {
110  CK_NullPassedToNonnull,
111  CK_NullReturnedFromNonnull,
112  CK_NullableDereferenced,
113  CK_NullablePassedToNonnull,
114  CK_NullableReturnedFromNonnull,
115  CK_NumCheckKinds
116  };
117 
118  bool ChecksEnabled[CK_NumCheckKinds] = {false};
119  CheckerNameRef CheckNames[CK_NumCheckKinds];
120  mutable std::unique_ptr<BugType> BTs[CK_NumCheckKinds];
121 
122  const std::unique_ptr<BugType> &getBugType(CheckKind Kind) const {
123  if (!BTs[Kind])
124  BTs[Kind].reset(new BugType(CheckNames[Kind], "Nullability",
126  return BTs[Kind];
127  }
128 
129  // When set to false no nullability information will be tracked in
130  // NullabilityMap. It is possible to catch errors like passing a null pointer
131  // to a callee that expects nonnull argument without the information that is
132  // stroed in the NullabilityMap. This is an optimization.
133  bool NeedTracking = false;
134 
135 private:
136  class NullabilityBugVisitor : public BugReporterVisitor {
137  public:
138  NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
139 
140  void Profile(llvm::FoldingSetNodeID &ID) const override {
141  static int X = 0;
142  ID.AddPointer(&X);
143  ID.AddPointer(Region);
144  }
145 
146  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
147  BugReporterContext &BRC,
148  PathSensitiveBugReport &BR) override;
149 
150  private:
151  // The tracked region.
152  const MemRegion *Region;
153  };
154 
155  /// When any of the nonnull arguments of the analyzed function is null, do not
156  /// report anything and turn off the check.
157  ///
158  /// When \p SuppressPath is set to true, no more bugs will be reported on this
159  /// path by this checker.
160  void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
161  ExplodedNode *N, const MemRegion *Region,
162  CheckerContext &C,
163  const Stmt *ValueExpr = nullptr,
164  bool SuppressPath = false) const;
165 
166  void reportBug(StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
167  const MemRegion *Region, BugReporter &BR,
168  const Stmt *ValueExpr = nullptr) const {
169  const std::unique_ptr<BugType> &BT = getBugType(CK);
170  auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
171  if (Region) {
172  R->markInteresting(Region);
173  R->addVisitor<NullabilityBugVisitor>(Region);
174  }
175  if (ValueExpr) {
176  R->addRange(ValueExpr->getSourceRange());
177  if (Error == ErrorKind::NilAssignedToNonnull ||
178  Error == ErrorKind::NilPassedToNonnull ||
179  Error == ErrorKind::NilReturnedToNonnull)
180  if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
182  }
183  BR.emitReport(std::move(R));
184  }
185 
186  /// If an SVal wraps a region that should be tracked, it will return a pointer
187  /// to the wrapped region. Otherwise it will return a nullptr.
188  const SymbolicRegion *getTrackRegion(SVal Val,
189  bool CheckSuperRegion = false) const;
190 
191  /// Returns true if the call is diagnosable in the current analyzer
192  /// configuration.
193  bool isDiagnosableCall(const CallEvent &Call) const {
194  if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
195  return false;
196 
197  return true;
198  }
199 };
200 
201 class NullabilityState {
202 public:
203  NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
204  : Nullab(Nullab), Source(Source) {}
205 
206  const Stmt *getNullabilitySource() const { return Source; }
207 
208  Nullability getValue() const { return Nullab; }
209 
210  void Profile(llvm::FoldingSetNodeID &ID) const {
211  ID.AddInteger(static_cast<char>(Nullab));
212  ID.AddPointer(Source);
213  }
214 
215  void print(raw_ostream &Out) const {
216  Out << getNullabilityString(Nullab) << "\n";
217  }
218 
219 private:
220  Nullability Nullab;
221  // Source is the expression which determined the nullability. For example in a
222  // message like [nullable nonnull_returning] has nullable nullability, because
223  // the receiver is nullable. Here the receiver will be the source of the
224  // nullability. This is useful information when the diagnostics are generated.
225  const Stmt *Source;
226 };
227 
228 bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
229  return Lhs.getValue() == Rhs.getValue() &&
230  Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
231 }
232 
233 } // end anonymous namespace
234 
235 REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
236  NullabilityState)
237 
238 // We say "the nullability type invariant is violated" when a location with a
239 // non-null type contains NULL or a function with a non-null return type returns
240 // NULL. Violations of the nullability type invariant can be detected either
241 // directly (for example, when NULL is passed as an argument to a nonnull
242 // parameter) or indirectly (for example, when, inside a function, the
243 // programmer defensively checks whether a nonnull parameter contains NULL and
244 // finds that it does).
245 //
246 // As a matter of policy, the nullability checker typically warns on direct
247 // violations of the nullability invariant (although it uses various
248 // heuristics to suppress warnings in some cases) but will not warn if the
249 // invariant has already been violated along the path (either directly or
250 // indirectly). As a practical matter, this prevents the analyzer from
251 // (1) warning on defensive code paths where a nullability precondition is
252 // determined to have been violated, (2) warning additional times after an
253 // initial direct violation has been discovered, and (3) warning after a direct
254 // violation that has been implicitly or explicitly suppressed (for
255 // example, with a cast of NULL to _Nonnull). In essence, once an invariant
256 // violation is detected on a path, this checker will be essentially turned off
257 // for the rest of the analysis
258 //
259 // The analyzer takes this approach (rather than generating a sink node) to
260 // ensure coverage of defensive paths, which may be important for backwards
261 // compatibility in codebases that were developed without nullability in mind.
262 REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
263 
264 enum class NullConstraint { IsNull, IsNotNull, Unknown };
265 
266 static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
268  ConditionTruthVal Nullness = State->isNull(Val);
269  if (Nullness.isConstrainedFalse())
270  return NullConstraint::IsNotNull;
271  if (Nullness.isConstrainedTrue())
272  return NullConstraint::IsNull;
274 }
275 
276 const SymbolicRegion *
277 NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
278  if (!NeedTracking)
279  return nullptr;
280 
281  auto RegionSVal = Val.getAs<loc::MemRegionVal>();
282  if (!RegionSVal)
283  return nullptr;
284 
285  const MemRegion *Region = RegionSVal->getRegion();
286 
287  if (CheckSuperRegion) {
288  if (const SubRegion *FieldReg = Region->getAs<FieldRegion>()) {
289  if (const auto *ER = dyn_cast<ElementRegion>(FieldReg->getSuperRegion()))
290  FieldReg = ER;
291  return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
292  }
293  if (auto ElementReg = Region->getAs<ElementRegion>())
294  return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
295  }
296 
297  return dyn_cast<SymbolicRegion>(Region);
298 }
299 
300 PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
301  const ExplodedNode *N, BugReporterContext &BRC,
302  PathSensitiveBugReport &BR) {
303  ProgramStateRef State = N->getState();
304  ProgramStateRef StatePrev = N->getFirstPred()->getState();
305 
306  const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
307  const NullabilityState *TrackedNullabPrev =
308  StatePrev->get<NullabilityMap>(Region);
309  if (!TrackedNullab)
310  return nullptr;
311 
312  if (TrackedNullabPrev &&
313  TrackedNullabPrev->getValue() == TrackedNullab->getValue())
314  return nullptr;
315 
316  // Retrieve the associated statement.
317  const Stmt *S = TrackedNullab->getNullabilitySource();
318  if (!S || S->getBeginLoc().isInvalid()) {
319  S = N->getStmtForDiagnostics();
320  }
321 
322  if (!S)
323  return nullptr;
324 
325  std::string InfoText =
326  (llvm::Twine("Nullability '") +
327  getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
328  .str();
329 
330  // Generate the extra diagnostic.
331  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
332  N->getLocationContext());
333  return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
334 }
335 
336 /// Returns true when the value stored at the given location has been
337 /// constrained to null after being passed through an object of nonnnull type.
339  SVal LV, QualType T) {
341  return false;
342 
343  auto RegionVal = LV.getAs<loc::MemRegionVal>();
344  if (!RegionVal)
345  return false;
346 
347  // If the value was constrained to null *after* it was passed through that
348  // location, it could not have been a concrete pointer *when* it was passed.
349  // In that case we would have handled the situation when the value was
350  // bound to that location, by emitting (or not emitting) a report.
351  // Therefore we are only interested in symbolic regions that can be either
352  // null or non-null depending on the value of their respective symbol.
353  auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
354  if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
355  return false;
356 
357  if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
358  return true;
359 
360  return false;
361 }
362 
363 static bool
366  const LocationContext *LocCtxt) {
367  for (const auto *ParamDecl : Params) {
368  if (ParamDecl->isParameterPack())
369  break;
370 
371  SVal LV = State->getLValue(ParamDecl, LocCtxt);
373  ParamDecl->getType())) {
374  return true;
375  }
376  }
377  return false;
378 }
379 
380 static bool
382  const LocationContext *LocCtxt) {
383  auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
384  if (!MD || !MD->isInstanceMethod())
385  return false;
386 
387  const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
388  if (!SelfDecl)
389  return false;
390 
391  SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
392 
393  const ObjCObjectPointerType *SelfType =
394  dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
395  if (!SelfType)
396  return false;
397 
398  const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
399  if (!ID)
400  return false;
401 
402  for (const auto *IvarDecl : ID->ivars()) {
403  SVal LV = State->getLValue(IvarDecl, SelfVal);
404  if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
405  return true;
406  }
407  }
408  return false;
409 }
410 
411 static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
412  CheckerContext &C) {
413  if (State->get<InvariantViolated>())
414  return true;
415 
416  const LocationContext *LocCtxt = C.getLocationContext();
417  const Decl *D = LocCtxt->getDecl();
418  if (!D)
419  return false;
420 
421  ArrayRef<ParmVarDecl*> Params;
422  if (const auto *BD = dyn_cast<BlockDecl>(D))
423  Params = BD->parameters();
424  else if (const auto *FD = dyn_cast<FunctionDecl>(D))
425  Params = FD->parameters();
426  else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
427  Params = MD->parameters();
428  else
429  return false;
430 
431  if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
433  if (!N->isSink())
434  C.addTransition(State->set<InvariantViolated>(true), N);
435  return true;
436  }
437  return false;
438 }
439 
440 void NullabilityChecker::reportBugIfInvariantHolds(
441  StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
442  const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
443  bool SuppressPath) const {
444  ProgramStateRef OriginalState = N->getState();
445 
446  if (checkInvariantViolation(OriginalState, N, C))
447  return;
448  if (SuppressPath) {
449  OriginalState = OriginalState->set<InvariantViolated>(true);
450  N = C.addTransition(OriginalState, N);
451  }
452 
453  reportBug(Msg, Error, CK, N, Region, C.getBugReporter(), ValueExpr);
454 }
455 
456 /// Cleaning up the program state.
457 void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
458  CheckerContext &C) const {
459  ProgramStateRef State = C.getState();
460  NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
461  for (NullabilityMapTy::iterator I = Nullabilities.begin(),
462  E = Nullabilities.end();
463  I != E; ++I) {
464  const auto *Region = I->first->getAs<SymbolicRegion>();
465  assert(Region && "Non-symbolic region is tracked.");
466  if (SR.isDead(Region->getSymbol())) {
467  State = State->remove<NullabilityMap>(I->first);
468  }
469  }
470  // When one of the nonnull arguments are constrained to be null, nullability
471  // preconditions are violated. It is not enough to check this only when we
472  // actually report an error, because at that time interesting symbols might be
473  // reaped.
474  if (checkInvariantViolation(State, C.getPredecessor(), C))
475  return;
476  C.addTransition(State);
477 }
478 
479 /// This callback triggers when a pointer is dereferenced and the analyzer does
480 /// not know anything about the value of that pointer. When that pointer is
481 /// nullable, this code emits a warning.
482 void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
483  if (Event.SinkNode->getState()->get<InvariantViolated>())
484  return;
485 
486  const MemRegion *Region =
487  getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
488  if (!Region)
489  return;
490 
491  ProgramStateRef State = Event.SinkNode->getState();
492  const NullabilityState *TrackedNullability =
493  State->get<NullabilityMap>(Region);
494 
495  if (!TrackedNullability)
496  return;
497 
498  if (ChecksEnabled[CK_NullableDereferenced] &&
499  TrackedNullability->getValue() == Nullability::Nullable) {
500  BugReporter &BR = *Event.BR;
501  // Do not suppress errors on defensive code paths, because dereferencing
502  // a nullable pointer is always an error.
503  if (Event.IsDirectDereference)
504  reportBug("Nullable pointer is dereferenced",
505  ErrorKind::NullableDereferenced, CK_NullableDereferenced,
506  Event.SinkNode, Region, BR);
507  else {
508  reportBug("Nullable pointer is passed to a callee that requires a "
509  "non-null",
510  ErrorKind::NullablePassedToNonnull, CK_NullableDereferenced,
511  Event.SinkNode, Region, BR);
512  }
513  }
514 }
515 
516 // Whenever we see a load from a typed memory region that's been annotated as
517 // 'nonnull', we want to trust the user on that and assume that it is is indeed
518 // non-null.
519 //
520 // We do so even if the value is known to have been assigned to null.
521 // The user should be warned on assigning the null value to a non-null pointer
522 // as opposed to warning on the later dereference of this pointer.
523 //
524 // \code
525 // int * _Nonnull var = 0; // we want to warn the user here...
526 // // . . .
527 // *var = 42; // ...and not here
528 // \endcode
529 void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
530  const Stmt *S,
531  CheckerContext &Context) const {
532  // We should care only about loads.
533  // The main idea is to add a constraint whenever we're loading a value from
534  // an annotated pointer type.
535  if (!IsLoad)
536  return;
537 
538  // Annotations that we want to consider make sense only for types.
539  const auto *Region =
540  dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
541  if (!Region)
542  return;
543 
544  ProgramStateRef State = Context.getState();
545 
546  auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
547  if (!StoredVal)
548  return;
549 
550  Nullability NullabilityOfTheLoadedValue =
551  getNullabilityAnnotation(Region->getValueType());
552 
553  if (NullabilityOfTheLoadedValue == Nullability::Nonnull) {
554  // It doesn't matter what we think about this particular pointer, it should
555  // be considered non-null as annotated by the developer.
556  if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
557  Context.addTransition(NewState);
558  }
559  }
560 }
561 
562 /// Find the outermost subexpression of E that is not an implicit cast.
563 /// This looks through the implicit casts to _Nonnull that ARC adds to
564 /// return expressions of ObjC types when the return type of the function or
565 /// method is non-null but the express is not.
566 static const Expr *lookThroughImplicitCasts(const Expr *E) {
567  return E->IgnoreImpCasts();
568 }
569 
570 /// This method check when nullable pointer or null value is returned from a
571 /// function that has nonnull return type.
572 void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
573  CheckerContext &C) const {
574  auto RetExpr = S->getRetValue();
575  if (!RetExpr)
576  return;
577 
578  if (!RetExpr->getType()->isAnyPointerType())
579  return;
580 
581  ProgramStateRef State = C.getState();
582  if (State->get<InvariantViolated>())
583  return;
584 
585  auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
586  if (!RetSVal)
587  return;
588 
589  bool InSuppressedMethodFamily = false;
590 
591  QualType RequiredRetType;
592  AnalysisDeclContext *DeclCtxt =
593  C.getLocationContext()->getAnalysisDeclContext();
594  const Decl *D = DeclCtxt->getDecl();
595  if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
596  // HACK: This is a big hammer to avoid warning when there are defensive
597  // nil checks in -init and -copy methods. We should add more sophisticated
598  // logic here to suppress on common defensive idioms but still
599  // warn when there is a likely problem.
600  ObjCMethodFamily Family = MD->getMethodFamily();
601  if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
602  InSuppressedMethodFamily = true;
603 
604  RequiredRetType = MD->getReturnType();
605  } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
606  RequiredRetType = FD->getReturnType();
607  } else {
608  return;
609  }
610 
611  NullConstraint Nullness = getNullConstraint(*RetSVal, State);
612 
613  Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
614 
615  // If the returned value is null but the type of the expression
616  // generating it is nonnull then we will suppress the diagnostic.
617  // This enables explicit suppression when returning a nil literal in a
618  // function with a _Nonnull return type:
619  // return (NSString * _Nonnull)0;
620  Nullability RetExprTypeLevelNullability =
622 
623  bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
624  Nullness == NullConstraint::IsNull);
625  if (ChecksEnabled[CK_NullReturnedFromNonnull] && NullReturnedFromNonNull &&
626  RetExprTypeLevelNullability != Nullability::Nonnull &&
627  !InSuppressedMethodFamily && C.getLocationContext()->inTopFrame()) {
628  static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
629  ExplodedNode *N = C.generateErrorNode(State, &Tag);
630  if (!N)
631  return;
632 
633  SmallString<256> SBuf;
634  llvm::raw_svector_ostream OS(SBuf);
635  OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
636  OS << " returned from a " << C.getDeclDescription(D) <<
637  " that is expected to return a non-null value";
638  reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
639  CK_NullReturnedFromNonnull, N, nullptr, C,
640  RetExpr);
641  return;
642  }
643 
644  // If null was returned from a non-null function, mark the nullability
645  // invariant as violated even if the diagnostic was suppressed.
646  if (NullReturnedFromNonNull) {
647  State = State->set<InvariantViolated>(true);
648  C.addTransition(State);
649  return;
650  }
651 
652  const MemRegion *Region = getTrackRegion(*RetSVal);
653  if (!Region)
654  return;
655 
656  const NullabilityState *TrackedNullability =
657  State->get<NullabilityMap>(Region);
658  if (TrackedNullability) {
659  Nullability TrackedNullabValue = TrackedNullability->getValue();
660  if (ChecksEnabled[CK_NullableReturnedFromNonnull] &&
661  Nullness != NullConstraint::IsNotNull &&
662  TrackedNullabValue == Nullability::Nullable &&
663  RequiredNullability == Nullability::Nonnull) {
664  static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
665  ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
666 
667  SmallString<256> SBuf;
668  llvm::raw_svector_ostream OS(SBuf);
669  OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
670  " that is expected to return a non-null value";
671 
672  reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
673  CK_NullableReturnedFromNonnull, N, Region, C);
674  }
675  return;
676  }
677  if (RequiredNullability == Nullability::Nullable) {
678  State = State->set<NullabilityMap>(Region,
679  NullabilityState(RequiredNullability,
680  S));
681  C.addTransition(State);
682  }
683 }
684 
685 /// This callback warns when a nullable pointer or a null value is passed to a
686 /// function that expects its argument to be nonnull.
687 void NullabilityChecker::checkPreCall(const CallEvent &Call,
688  CheckerContext &C) const {
689  if (!Call.getDecl())
690  return;
691 
692  ProgramStateRef State = C.getState();
693  if (State->get<InvariantViolated>())
694  return;
695 
696  ProgramStateRef OrigState = State;
697 
698  unsigned Idx = 0;
699  for (const ParmVarDecl *Param : Call.parameters()) {
700  if (Param->isParameterPack())
701  break;
702 
703  if (Idx >= Call.getNumArgs())
704  break;
705 
706  const Expr *ArgExpr = Call.getArgExpr(Idx);
707  auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
708  if (!ArgSVal)
709  continue;
710 
711  if (!Param->getType()->isAnyPointerType() &&
712  !Param->getType()->isReferenceType())
713  continue;
714 
715  NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
716 
717  Nullability RequiredNullability =
718  getNullabilityAnnotation(Param->getType());
719  Nullability ArgExprTypeLevelNullability =
720  getNullabilityAnnotation(ArgExpr->getType());
721 
722  unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
723 
724  if (ChecksEnabled[CK_NullPassedToNonnull] &&
725  Nullness == NullConstraint::IsNull &&
726  ArgExprTypeLevelNullability != Nullability::Nonnull &&
727  RequiredNullability == Nullability::Nonnull &&
728  isDiagnosableCall(Call)) {
729  ExplodedNode *N = C.generateErrorNode(State);
730  if (!N)
731  return;
732 
733  SmallString<256> SBuf;
734  llvm::raw_svector_ostream OS(SBuf);
735  OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
736  OS << " passed to a callee that requires a non-null " << ParamIdx
737  << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
738  reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
739  CK_NullPassedToNonnull, N, nullptr, C, ArgExpr,
740  /*SuppressPath=*/false);
741  return;
742  }
743 
744  const MemRegion *Region = getTrackRegion(*ArgSVal);
745  if (!Region)
746  continue;
747 
748  const NullabilityState *TrackedNullability =
749  State->get<NullabilityMap>(Region);
750 
751  if (TrackedNullability) {
752  if (Nullness == NullConstraint::IsNotNull ||
753  TrackedNullability->getValue() != Nullability::Nullable)
754  continue;
755 
756  if (ChecksEnabled[CK_NullablePassedToNonnull] &&
757  RequiredNullability == Nullability::Nonnull &&
758  isDiagnosableCall(Call)) {
759  ExplodedNode *N = C.addTransition(State);
760  SmallString<256> SBuf;
761  llvm::raw_svector_ostream OS(SBuf);
762  OS << "Nullable pointer is passed to a callee that requires a non-null "
763  << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
764  reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
765  CK_NullablePassedToNonnull, N, Region, C,
766  ArgExpr, /*SuppressPath=*/true);
767  return;
768  }
769  if (ChecksEnabled[CK_NullableDereferenced] &&
770  Param->getType()->isReferenceType()) {
771  ExplodedNode *N = C.addTransition(State);
772  reportBugIfInvariantHolds("Nullable pointer is dereferenced",
773  ErrorKind::NullableDereferenced,
774  CK_NullableDereferenced, N, Region, C,
775  ArgExpr, /*SuppressPath=*/true);
776  return;
777  }
778  continue;
779  }
780  }
781  if (State != OrigState)
782  C.addTransition(State);
783 }
784 
785 /// Suppress the nullability warnings for some functions.
786 void NullabilityChecker::checkPostCall(const CallEvent &Call,
787  CheckerContext &C) const {
788  auto Decl = Call.getDecl();
789  if (!Decl)
790  return;
791  // ObjC Messages handles in a different callback.
792  if (Call.getKind() == CE_ObjCMessage)
793  return;
794  const FunctionType *FuncType = Decl->getFunctionType();
795  if (!FuncType)
796  return;
797  QualType ReturnType = FuncType->getReturnType();
798  if (!ReturnType->isAnyPointerType())
799  return;
800  ProgramStateRef State = C.getState();
801  if (State->get<InvariantViolated>())
802  return;
803 
804  const MemRegion *Region = getTrackRegion(Call.getReturnValue());
805  if (!Region)
806  return;
807 
808  // CG headers are misannotated. Do not warn for symbols that are the results
809  // of CG calls.
810  const SourceManager &SM = C.getSourceManager();
811  StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
812  if (llvm::sys::path::filename(FilePath).startswith("CG")) {
813  State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
814  C.addTransition(State);
815  return;
816  }
817 
818  const NullabilityState *TrackedNullability =
819  State->get<NullabilityMap>(Region);
820 
821  if (!TrackedNullability &&
823  State = State->set<NullabilityMap>(Region, Nullability::Nullable);
824  C.addTransition(State);
825  }
826 }
827 
828 static Nullability getReceiverNullability(const ObjCMethodCall &M,
830  if (M.isReceiverSelfOrSuper()) {
831  // For super and super class receivers we assume that the receiver is
832  // nonnull.
833  return Nullability::Nonnull;
834  }
835  // Otherwise look up nullability in the state.
836  SVal Receiver = M.getReceiverSVal();
837  if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
838  // If the receiver is constrained to be nonnull, assume that it is nonnull
839  // regardless of its type.
840  NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
841  if (Nullness == NullConstraint::IsNotNull)
842  return Nullability::Nonnull;
843  }
844  auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
845  if (ValueRegionSVal) {
846  const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
847  assert(SelfRegion);
848 
849  const NullabilityState *TrackedSelfNullability =
850  State->get<NullabilityMap>(SelfRegion);
851  if (TrackedSelfNullability)
852  return TrackedSelfNullability->getValue();
853  }
855 }
856 
857 /// Calculate the nullability of the result of a message expr based on the
858 /// nullability of the receiver, the nullability of the return value, and the
859 /// constraints.
860 void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
861  CheckerContext &C) const {
862  auto Decl = M.getDecl();
863  if (!Decl)
864  return;
865  QualType RetType = Decl->getReturnType();
866  if (!RetType->isAnyPointerType())
867  return;
868 
869  ProgramStateRef State = C.getState();
870  if (State->get<InvariantViolated>())
871  return;
872 
873  const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
874  if (!ReturnRegion)
875  return;
876 
877  auto Interface = Decl->getClassInterface();
878  auto Name = Interface ? Interface->getName() : "";
879  // In order to reduce the noise in the diagnostics generated by this checker,
880  // some framework and programming style based heuristics are used. These
881  // heuristics are for Cocoa APIs which have NS prefix.
882  if (Name.startswith("NS")) {
883  // Developers rely on dynamic invariants such as an item should be available
884  // in a collection, or a collection is not empty often. Those invariants can
885  // not be inferred by any static analysis tool. To not to bother the users
886  // with too many false positives, every item retrieval function should be
887  // ignored for collections. The instance methods of dictionaries in Cocoa
888  // are either item retrieval related or not interesting nullability wise.
889  // Using this fact, to keep the code easier to read just ignore the return
890  // value of every instance method of dictionaries.
891  if (M.isInstanceMessage() && Name.contains("Dictionary")) {
892  State =
893  State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
894  C.addTransition(State);
895  return;
896  }
897  // For similar reasons ignore some methods of Cocoa arrays.
898  StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
899  if (Name.contains("Array") &&
900  (FirstSelectorSlot == "firstObject" ||
901  FirstSelectorSlot == "lastObject")) {
902  State =
903  State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
904  C.addTransition(State);
905  return;
906  }
907 
908  // Encoding related methods of string should not fail when lossless
909  // encodings are used. Using lossless encodings is so frequent that ignoring
910  // this class of methods reduced the emitted diagnostics by about 30% on
911  // some projects (and all of that was false positives).
912  if (Name.contains("String")) {
913  for (auto *Param : M.parameters()) {
914  if (Param->getName() == "encoding") {
915  State = State->set<NullabilityMap>(ReturnRegion,
917  C.addTransition(State);
918  return;
919  }
920  }
921  }
922  }
923 
924  const ObjCMessageExpr *Message = M.getOriginExpr();
925  Nullability SelfNullability = getReceiverNullability(M, State);
926 
927  const NullabilityState *NullabilityOfReturn =
928  State->get<NullabilityMap>(ReturnRegion);
929 
930  if (NullabilityOfReturn) {
931  // When we have a nullability tracked for the return value, the nullability
932  // of the expression will be the most nullable of the receiver and the
933  // return value.
934  Nullability RetValTracked = NullabilityOfReturn->getValue();
935  Nullability ComputedNullab =
936  getMostNullable(RetValTracked, SelfNullability);
937  if (ComputedNullab != RetValTracked &&
938  ComputedNullab != Nullability::Unspecified) {
939  const Stmt *NullabilitySource =
940  ComputedNullab == RetValTracked
941  ? NullabilityOfReturn->getNullabilitySource()
942  : Message->getInstanceReceiver();
943  State = State->set<NullabilityMap>(
944  ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
945  C.addTransition(State);
946  }
947  return;
948  }
949 
950  // No tracked information. Use static type information for return value.
951  Nullability RetNullability = getNullabilityAnnotation(RetType);
952 
953  // Properties might be computed. For this reason the static analyzer creates a
954  // new symbol each time an unknown property is read. To avoid false pozitives
955  // do not treat unknown properties as nullable, even when they explicitly
956  // marked nullable.
957  if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
958  RetNullability = Nullability::Nonnull;
959 
960  Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
961  if (ComputedNullab == Nullability::Nullable) {
962  const Stmt *NullabilitySource = ComputedNullab == RetNullability
963  ? Message
964  : Message->getInstanceReceiver();
965  State = State->set<NullabilityMap>(
966  ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
967  C.addTransition(State);
968  }
969 }
970 
971 /// Explicit casts are trusted. If there is a disagreement in the nullability
972 /// annotations in the destination and the source or '0' is casted to nonnull
973 /// track the value as having contraditory nullability. This will allow users to
974 /// suppress warnings.
975 void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
976  CheckerContext &C) const {
977  QualType OriginType = CE->getSubExpr()->getType();
978  QualType DestType = CE->getType();
979  if (!OriginType->isAnyPointerType())
980  return;
981  if (!DestType->isAnyPointerType())
982  return;
983 
984  ProgramStateRef State = C.getState();
985  if (State->get<InvariantViolated>())
986  return;
987 
988  Nullability DestNullability = getNullabilityAnnotation(DestType);
989 
990  // No explicit nullability in the destination type, so this cast does not
991  // change the nullability.
992  if (DestNullability == Nullability::Unspecified)
993  return;
994 
995  auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
996  const MemRegion *Region = getTrackRegion(*RegionSVal);
997  if (!Region)
998  return;
999 
1000  // When 0 is converted to nonnull mark it as contradicted.
1001  if (DestNullability == Nullability::Nonnull) {
1002  NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
1003  if (Nullness == NullConstraint::IsNull) {
1004  State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1005  C.addTransition(State);
1006  return;
1007  }
1008  }
1009 
1010  const NullabilityState *TrackedNullability =
1011  State->get<NullabilityMap>(Region);
1012 
1013  if (!TrackedNullability) {
1014  if (DestNullability != Nullability::Nullable)
1015  return;
1016  State = State->set<NullabilityMap>(Region,
1017  NullabilityState(DestNullability, CE));
1018  C.addTransition(State);
1019  return;
1020  }
1021 
1022  if (TrackedNullability->getValue() != DestNullability &&
1023  TrackedNullability->getValue() != Nullability::Contradicted) {
1024  State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1025  C.addTransition(State);
1026  }
1027 }
1028 
1029 /// For a given statement performing a bind, attempt to syntactically
1030 /// match the expression resulting in the bound value.
1031 static const Expr * matchValueExprForBind(const Stmt *S) {
1032  // For `x = e` the value expression is the right-hand side.
1033  if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
1034  if (BinOp->getOpcode() == BO_Assign)
1035  return BinOp->getRHS();
1036  }
1037 
1038  // For `int x = e` the value expression is the initializer.
1039  if (auto *DS = dyn_cast<DeclStmt>(S)) {
1040  if (DS->isSingleDecl()) {
1041  auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1042  if (!VD)
1043  return nullptr;
1044 
1045  if (const Expr *Init = VD->getInit())
1046  return Init;
1047  }
1048  }
1049 
1050  return nullptr;
1051 }
1052 
1053 /// Returns true if \param S is a DeclStmt for a local variable that
1054 /// ObjC automated reference counting initialized with zero.
1055 static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
1056  // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
1057  // prevents false positives when a _Nonnull local variable cannot be
1058  // initialized with an initialization expression:
1059  // NSString * _Nonnull s; // no-warning
1060  // @autoreleasepool {
1061  // s = ...
1062  // }
1063  //
1064  // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
1065  // uninitialized in Sema's UninitializedValues analysis to warn when a use of
1066  // the zero-initialized definition will unexpectedly yield nil.
1067 
1068  // Locals are only zero-initialized when automated reference counting
1069  // is turned on.
1070  if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
1071  return false;
1072 
1073  auto *DS = dyn_cast<DeclStmt>(S);
1074  if (!DS || !DS->isSingleDecl())
1075  return false;
1076 
1077  auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1078  if (!VD)
1079  return false;
1080 
1081  // Sema only zero-initializes locals with ObjCLifetimes.
1082  if(!VD->getType().getQualifiers().hasObjCLifetime())
1083  return false;
1084 
1085  const Expr *Init = VD->getInit();
1086  assert(Init && "ObjC local under ARC without initializer");
1087 
1088  // Return false if the local is explicitly initialized (e.g., with '= nil').
1089  if (!isa<ImplicitValueInitExpr>(Init))
1090  return false;
1091 
1092  return true;
1093 }
1094 
1095 /// Propagate the nullability information through binds and warn when nullable
1096 /// pointer or null symbol is assigned to a pointer with a nonnull type.
1097 void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
1098  CheckerContext &C) const {
1099  const TypedValueRegion *TVR =
1100  dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
1101  if (!TVR)
1102  return;
1103 
1104  QualType LocType = TVR->getValueType();
1105  if (!LocType->isAnyPointerType())
1106  return;
1107 
1108  ProgramStateRef State = C.getState();
1109  if (State->get<InvariantViolated>())
1110  return;
1111 
1112  auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
1113  if (!ValDefOrUnknown)
1114  return;
1115 
1116  NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
1117 
1118  Nullability ValNullability = Nullability::Unspecified;
1119  if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
1120  ValNullability = getNullabilityAnnotation(Sym->getType());
1121 
1122  Nullability LocNullability = getNullabilityAnnotation(LocType);
1123 
1124  // If the type of the RHS expression is nonnull, don't warn. This
1125  // enables explicit suppression with a cast to nonnull.
1126  Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
1127  const Expr *ValueExpr = matchValueExprForBind(S);
1128  if (ValueExpr) {
1129  ValueExprTypeLevelNullability =
1130  getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
1131  }
1132 
1133  bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
1134  RhsNullness == NullConstraint::IsNull);
1135  if (ChecksEnabled[CK_NullPassedToNonnull] && NullAssignedToNonNull &&
1136  ValNullability != Nullability::Nonnull &&
1137  ValueExprTypeLevelNullability != Nullability::Nonnull &&
1138  !isARCNilInitializedLocal(C, S)) {
1139  static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
1140  ExplodedNode *N = C.generateErrorNode(State, &Tag);
1141  if (!N)
1142  return;
1143 
1144 
1145  const Stmt *ValueStmt = S;
1146  if (ValueExpr)
1147  ValueStmt = ValueExpr;
1148 
1149  SmallString<256> SBuf;
1150  llvm::raw_svector_ostream OS(SBuf);
1151  OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
1152  OS << " assigned to a pointer which is expected to have non-null value";
1153  reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
1154  CK_NullPassedToNonnull, N, nullptr, C, ValueStmt);
1155  return;
1156  }
1157 
1158  // If null was returned from a non-null function, mark the nullability
1159  // invariant as violated even if the diagnostic was suppressed.
1160  if (NullAssignedToNonNull) {
1161  State = State->set<InvariantViolated>(true);
1162  C.addTransition(State);
1163  return;
1164  }
1165 
1166  // Intentionally missing case: '0' is bound to a reference. It is handled by
1167  // the DereferenceChecker.
1168 
1169  const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
1170  if (!ValueRegion)
1171  return;
1172 
1173  const NullabilityState *TrackedNullability =
1174  State->get<NullabilityMap>(ValueRegion);
1175 
1176  if (TrackedNullability) {
1177  if (RhsNullness == NullConstraint::IsNotNull ||
1178  TrackedNullability->getValue() != Nullability::Nullable)
1179  return;
1180  if (ChecksEnabled[CK_NullablePassedToNonnull] &&
1181  LocNullability == Nullability::Nonnull) {
1182  static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
1183  ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
1184  reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
1185  "which is expected to have non-null value",
1186  ErrorKind::NullableAssignedToNonnull,
1187  CK_NullablePassedToNonnull, N, ValueRegion, C);
1188  }
1189  return;
1190  }
1191 
1192  const auto *BinOp = dyn_cast<BinaryOperator>(S);
1193 
1194  if (ValNullability == Nullability::Nullable) {
1195  // Trust the static information of the value more than the static
1196  // information on the location.
1197  const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
1198  State = State->set<NullabilityMap>(
1199  ValueRegion, NullabilityState(ValNullability, NullabilitySource));
1200  C.addTransition(State);
1201  return;
1202  }
1203 
1204  if (LocNullability == Nullability::Nullable) {
1205  const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
1206  State = State->set<NullabilityMap>(
1207  ValueRegion, NullabilityState(LocNullability, NullabilitySource));
1208  C.addTransition(State);
1209  }
1210 }
1211 
1212 void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
1213  const char *NL, const char *Sep) const {
1214 
1215  NullabilityMapTy B = State->get<NullabilityMap>();
1216 
1217  if (State->get<InvariantViolated>())
1218  Out << Sep << NL
1219  << "Nullability invariant was violated, warnings suppressed." << NL;
1220 
1221  if (B.isEmpty())
1222  return;
1223 
1224  if (!State->get<InvariantViolated>())
1225  Out << Sep << NL;
1226 
1227  for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1228  Out << I->first << " : ";
1229  I->second.print(Out);
1230  Out << NL;
1231  }
1232 }
1233 
1234 void ento::registerNullabilityBase(CheckerManager &mgr) {
1235  mgr.registerChecker<NullabilityChecker>();
1236 }
1237 
1238 bool ento::shouldRegisterNullabilityBase(const CheckerManager &mgr) {
1239  return true;
1240 }
1241 
1242 #define REGISTER_CHECKER(name, trackingRequired) \
1243  void ento::register##name##Checker(CheckerManager &mgr) { \
1244  NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>(); \
1245  checker->ChecksEnabled[NullabilityChecker::CK_##name] = true; \
1246  checker->CheckNames[NullabilityChecker::CK_##name] = \
1247  mgr.getCurrentCheckerName(); \
1248  checker->NeedTracking = checker->NeedTracking || trackingRequired; \
1249  checker->NoDiagnoseCallsToSystemHeaders = \
1250  checker->NoDiagnoseCallsToSystemHeaders || \
1251  mgr.getAnalyzerOptions().getCheckerBooleanOption( \
1252  checker, "NoDiagnoseCallsToSystemHeaders", true); \
1253  } \
1254  \
1255  bool ento::shouldRegister##name##Checker(const CheckerManager &mgr) { \
1256  return true; \
1257  }
1258 
1259 // The checks are likely to be turned on by default and it is possible to do
1260 // them without tracking any nullability related information. As an optimization
1261 // no nullability information will be tracked when only these two checks are
1262 // enables.
1263 REGISTER_CHECKER(NullPassedToNonnull, false)
1264 REGISTER_CHECKER(NullReturnedFromNonnull, false)
1265 
1266 REGISTER_CHECKER(NullableDereferenced, true)
1267 REGISTER_CHECKER(NullablePassedToNonnull, true)
1268 REGISTER_CHECKER(NullableReturnedFromNonnull, true)
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1149
clang::Decl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:424
clang::LocationContext
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
Definition: AnalysisDeclContext.h:215
clang::ento::Nullability
Nullability
Definition: CheckerHelpers.h:55
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
getReceiverNullability
static Nullability getReceiverNullability(const ObjCMethodCall &M, ProgramStateRef State)
Definition: NullabilityChecker.cpp:828
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::ObjCMethodFamily
ObjCMethodFamily
A family of Objective-C methods.
Definition: IdentifierTable.h:697
clang::ento::PathDiagnosticPieceRef
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
Definition: PathDiagnostic.h:492
clang::ento::Nullability::Contradicted
@ Contradicted
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3530
clang::ento::ProgramStateRef
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Definition: ProgramState_Fwd.h:37
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:737
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:56
clang::AnalysisDeclContext
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Definition: AnalysisDeclContext.h:72
clang::OMF_init
@ OMF_init
Definition: IdentifierTable.h:707
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1712
int
__device__ int
Definition: __clang_hip_libdevice_declares.h:63
clang::ento::SymbolRef
const SymExpr * SymbolRef
Definition: SymExpr.h:111
clang::tooling::X
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
print
void print(llvm::raw_ostream &OS, const Pointer &P, ASTContext &Ctx, QualType Ty)
Definition: InterpFrame.cpp:97
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3675
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3015
clang::ObjCObjectPointerType::getInterfaceDecl
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:6322
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:636
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:34
getValue
static SVal getValue(SVal val, SValBuilder &svalBuilder)
Definition: ArrayBoundCheckerV2.cpp:276
REGISTER_CHECKER
#define REGISTER_CHECKER(name, trackingRequired)
Definition: NullabilityChecker.cpp:1242
CallEvent.h
clang::Decl::getFunctionType
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1031
clang::OMF_copy
@ OMF_copy
Definition: IdentifierTable.h:706
V
#define V(N, I)
Definition: ASTContext.h:3235
clang::prec::Unknown
@ Unknown
Definition: OperatorPrecedence.h:27
clang::ento::OCM_PropertyAccess
@ OCM_PropertyAccess
Definition: CallEvent.h:1123
min
__DEVICE__ int min(int __a, int __b)
Definition: __clang_cuda_math.h:197
BuiltinCheckerRegistration.h
CheckerManager.h
clang::ParamIdx
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:242
clang::ento::Nullability::Nonnull
@ Nonnull
clang::ValueStmt
Represents a statement that could possibly have a value and type.
Definition: Stmt.h:1816
clang::ento::Nullability::Nullable
@ Nullable
clang::LocationContext::getSelfDecl
const ImplicitParamDecl * getSelfDecl() const
Definition: AnalysisDeclContext.h:260
clang::ImplicitParamDecl
Definition: Decl.h:1645
llvm::SmallString
Definition: LLVM.h:37
REGISTER_MAP_WITH_PROGRAMSTATE
REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *, NullabilityState) enum class NullConstraint
Definition: NullabilityChecker.cpp:235
getNullConstraint
static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val, ProgramStateRef State)
Definition: NullabilityChecker.cpp:266
clang::ento::CE_ObjCMessage
@ CE_ObjCMessage
Definition: CallEvent.h:75
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:7011
clang::ento::bugreporter::trackExpressionValue
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:6270
clang::ento::categories::MemoryError
const char *const MemoryError
Definition: CommonBugCategories.cpp:20
lookThroughImplicitCasts
static const Expr * lookThroughImplicitCasts(const Expr *E)
Find the outermost subexpression of E that is not an implicit cast.
Definition: NullabilityChecker.cpp:566
checkInvariantViolation
static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N, CheckerContext &C)
Definition: NullabilityChecker.cpp:411
false
#define false
Definition: stdbool.h:22
BugType.h
llvm::ArrayRef
Definition: LLVM.h:34
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::syntax::NodeRole::Message
@ Message
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1147
CheckerContext.h
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
Checker.h
clang::ento::getNullabilityAnnotation
Nullability getNullabilityAnnotation(QualType Type)
Get nullability annotation for a given type.
Definition: CheckerHelpers.cpp:102
clang::Builtin::ID
ID
Definition: Builtins.h:52
clang
Definition: CalledOnceCheck.h:17
checkValueAtLValForInvariantViolation
static bool checkValueAtLValForInvariantViolation(ProgramStateRef State, SVal LV, QualType T)
Returns true when the value stored at the given location has been constrained to null after being pas...
Definition: NullabilityChecker.cpp:338
clang::Type::isAnyPointerType
bool isAnyPointerType() const
Definition: Type.h:6887
clang::AnalysisDeclContext::getDecl
const Decl * getDecl() const
Definition: AnalysisDeclContext.h:106
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:71
CheckerHelpers.h
clang::Expr::getType
QualType getType() const
Definition: Expr.h:141
clang::OMF_mutableCopy
@ OMF_mutableCopy
Definition: IdentifierTable.h:708
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3940
clang::ento::Nullability::Unspecified
@ Unspecified
clang::interp::Call
bool Call(InterpState &S, CodePtr &PC, const Function *Func)
Definition: Interp.h:1246
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:712
true
#define true
Definition: stdbool.h:21
clang::Expr
This represents one expression.
Definition: Expr.h:109
SM
#define SM(sm)
Definition: Cuda.cpp:79
isARCNilInitializedLocal
static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S)
Returns true if.
Definition: NullabilityChecker.cpp:1055
matchValueExprForBind
static const Expr * matchValueExprForBind(const Stmt *S)
For a given statement performing a bind, attempt to syntactically match the expression resulting in t...
Definition: NullabilityChecker.cpp:1031
clang::LocationContext::getDecl
const Decl * getDecl() const
Definition: AnalysisDeclContext.h:251
checkParamsForPreconditionViolation
static bool checkParamsForPreconditionViolation(ArrayRef< ParmVarDecl * > Params, ProgramStateRef State, const LocationContext *LocCtxt)
Definition: NullabilityChecker.cpp:364
checkSelfIvarsForInvariantViolation
static bool checkSelfIvarsForInvariantViolation(ProgramStateRef State, const LocationContext *LocCtxt)
Definition: NullabilityChecker.cpp:381
clang::operator==
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:207
clang::ExplicitCastExpr
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3702
clang::ento::ObjKind::OS
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2796