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