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