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