xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp (revision 28690925ed8318d7024d417e45902a23841d03df)
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 static 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 static 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   assert(false);
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 *ErrorMessages[] = {"Null pointer is assigned to a pointer which "
93                                "has _Nonnull type",
94                                "Null pointer is passed to a parameter which is "
95                                "marked as _Nonnull",
96                                "Null pointer is returned from a function that "
97                                "has _Nonnull return type",
98                                "Nullable pointer is assigned to a pointer "
99                                "which has _Nonnull type",
100                                "Nullable pointer is returned from a function "
101                                "that has _Nonnull return type",
102                                "Nullable pointer is dereferenced",
103                                "Nullable pointer is passed to a parameter "
104                                "which is marked as _Nonnull"};
105 
106 class NullabilityChecker
107     : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
108                      check::PostCall, check::PostStmt<ExplicitCastExpr>,
109                      check::PostObjCMessage, check::DeadSymbols,
110                      check::Event<ImplicitNullDerefEvent>> {
111   mutable std::unique_ptr<BugType> BT;
112 
113 public:
114   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
115   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
116   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
117   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
118   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
119   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
120   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
121   void checkEvent(ImplicitNullDerefEvent Event) const;
122 
123   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
124                   const char *Sep) const override;
125 
126   struct NullabilityChecksFilter {
127     DefaultBool CheckNullPassedToNonnull;
128     DefaultBool CheckNullReturnedFromNonnull;
129     DefaultBool CheckNullableDereferenced;
130     DefaultBool CheckNullablePassedToNonnull;
131     DefaultBool CheckNullableReturnedFromNonnull;
132 
133     CheckName CheckNameNullPassedToNonnull;
134     CheckName CheckNameNullReturnedFromNonnull;
135     CheckName CheckNameNullableDereferenced;
136     CheckName CheckNameNullablePassedToNonnull;
137     CheckName CheckNameNullableReturnedFromNonnull;
138   };
139 
140   NullabilityChecksFilter Filter;
141 
142 private:
143   class NullabilityBugVisitor
144       : public BugReporterVisitorImpl<NullabilityBugVisitor> {
145   public:
146     NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
147 
148     void Profile(llvm::FoldingSetNodeID &ID) const override {
149       static int X = 0;
150       ID.AddPointer(&X);
151       ID.AddPointer(Region);
152     }
153 
154     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
155                                    const ExplodedNode *PrevN,
156                                    BugReporterContext &BRC,
157                                    BugReport &BR) override;
158 
159   private:
160     // The tracked region.
161     const MemRegion *Region;
162   };
163 
164   void reportBug(ErrorKind Error, ExplodedNode *N, const MemRegion *Region,
165                  BugReporter &BR, const Stmt *ValueExpr = nullptr) const {
166     if (!BT)
167       BT.reset(new BugType(this, "Nullability", "Memory error"));
168     const char *Msg = ErrorMessages[static_cast<int>(Error)];
169     assert(Msg);
170     std::unique_ptr<BugReport> R(new BugReport(*BT, Msg, N));
171     if (Region) {
172       R->markInteresting(Region);
173       R->addVisitor(llvm::make_unique<NullabilityBugVisitor>(Region));
174     }
175     if (ValueExpr) {
176       R->addRange(ValueExpr->getSourceRange());
177       if (Error == ErrorKind::NilAssignedToNonnull ||
178           Error == ErrorKind::NilPassedToNonnull ||
179           Error == ErrorKind::NilReturnedToNonnull)
180         bugreporter::trackNullOrUndefValue(N, ValueExpr, *R);
181     }
182     BR.emitReport(std::move(R));
183   }
184 };
185 
186 class NullabilityState {
187 public:
188   NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
189       : Nullab(Nullab), Source(Source) {}
190 
191   const Stmt *getNullabilitySource() const { return Source; }
192 
193   Nullability getValue() const { return Nullab; }
194 
195   void Profile(llvm::FoldingSetNodeID &ID) const {
196     ID.AddInteger(static_cast<char>(Nullab));
197     ID.AddPointer(Source);
198   }
199 
200   void print(raw_ostream &Out) const {
201     Out << getNullabilityString(Nullab) << "\n";
202   }
203 
204 private:
205   Nullability Nullab;
206   // Source is the expression which determined the nullability. For example in a
207   // message like [nullable nonnull_returning] has nullable nullability, because
208   // the receiver is nullable. Here the receiver will be the source of the
209   // nullability. This is useful information when the diagnostics are generated.
210   const Stmt *Source;
211 };
212 
213 bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
214   return Lhs.getValue() == Rhs.getValue() &&
215          Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
216 }
217 
218 } // end anonymous namespace
219 
220 REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
221                                NullabilityState)
222 
223 enum class NullConstraint { IsNull, IsNotNull, Unknown };
224 
225 static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
226                                         ProgramStateRef State) {
227   ConditionTruthVal Nullness = State->isNull(Val);
228   if (Nullness.isConstrainedFalse())
229     return NullConstraint::IsNotNull;
230   if (Nullness.isConstrainedTrue())
231     return NullConstraint::IsNull;
232   return NullConstraint::Unknown;
233 }
234 
235 // If an SVal wraps a region that should be tracked, it will return a pointer
236 // to the wrapped region. Otherwise it will return a nullptr.
237 static const SymbolicRegion *getTrackRegion(SVal Val,
238                                             bool CheckSuperRegion = false) {
239   auto RegionSVal = Val.getAs<loc::MemRegionVal>();
240   if (!RegionSVal)
241     return nullptr;
242 
243   const MemRegion *Region = RegionSVal->getRegion();
244 
245   if (CheckSuperRegion) {
246     if (auto FieldReg = Region->getAs<FieldRegion>())
247       return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
248     else if (auto ElementReg = Region->getAs<ElementRegion>())
249       return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
250   }
251 
252   return dyn_cast<SymbolicRegion>(Region);
253 }
254 
255 PathDiagnosticPiece *NullabilityChecker::NullabilityBugVisitor::VisitNode(
256     const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
257     BugReport &BR) {
258   ProgramStateRef state = N->getState();
259   ProgramStateRef statePrev = PrevN->getState();
260 
261   const NullabilityState *TrackedNullab = state->get<NullabilityMap>(Region);
262   const NullabilityState *TrackedNullabPrev =
263       statePrev->get<NullabilityMap>(Region);
264   if (!TrackedNullab)
265     return nullptr;
266 
267   if (TrackedNullabPrev &&
268       TrackedNullabPrev->getValue() == TrackedNullab->getValue())
269     return nullptr;
270 
271   // Retrieve the associated statement.
272   const Stmt *S = TrackedNullab->getNullabilitySource();
273   if (!S) {
274     ProgramPoint ProgLoc = N->getLocation();
275     if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
276       S = SP->getStmt();
277     }
278   }
279 
280   if (!S)
281     return nullptr;
282 
283   std::string InfoText =
284       (llvm::Twine("Nullability '") +
285        getNullabilityString(TrackedNullab->getValue()) + "' is infered")
286           .str();
287 
288   // Generate the extra diagnostic.
289   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
290                              N->getLocationContext());
291   return new PathDiagnosticEventPiece(Pos, InfoText, true, nullptr);
292 }
293 
294 static Nullability getNullabilityAnnotation(QualType Type) {
295   const auto *AttrType = Type->getAs<AttributedType>();
296   if (!AttrType)
297     return Nullability::Unspecified;
298   if (AttrType->getAttrKind() == AttributedType::attr_nullable)
299     return Nullability::Nullable;
300   else if (AttrType->getAttrKind() == AttributedType::attr_nonnull)
301     return Nullability::Nonnull;
302   return Nullability::Unspecified;
303 }
304 
305 /// Cleaning up the program state.
306 void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
307                                           CheckerContext &C) const {
308   ProgramStateRef State = C.getState();
309   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
310   for (NullabilityMapTy::iterator I = Nullabilities.begin(),
311                                   E = Nullabilities.end();
312        I != E; ++I) {
313     if (!SR.isLiveRegion(I->first)) {
314       State = State->remove<NullabilityMap>(I->first);
315     }
316   }
317 }
318 
319 /// This callback triggers when a pointer is dereferenced and the analyzer does
320 /// not know anything about the value of that pointer. When that pointer is
321 /// nullable, this code emits a warning.
322 void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
323   const MemRegion *Region =
324       getTrackRegion(Event.Location, /*CheckSuperregion=*/true);
325   if (!Region)
326     return;
327 
328   ProgramStateRef State = Event.SinkNode->getState();
329   const NullabilityState *TrackedNullability =
330       State->get<NullabilityMap>(Region);
331 
332   if (!TrackedNullability)
333     return;
334 
335   if (Filter.CheckNullableDereferenced &&
336       TrackedNullability->getValue() == Nullability::Nullable) {
337     BugReporter &BR = *Event.BR;
338     reportBug(ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR);
339   }
340 }
341 
342 /// This method check when nullable pointer or null value is returned from a
343 /// function that has nonnull return type.
344 ///
345 /// TODO: when nullability preconditons are violated, it is ok to violate the
346 /// nullability postconditons (i.e.: when one of the nonnull parameters are null
347 /// this check should not report any nullability related issue).
348 void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
349                                       CheckerContext &C) const {
350   auto RetExpr = S->getRetValue();
351   if (!RetExpr)
352     return;
353 
354   if (!RetExpr->getType()->isAnyPointerType())
355     return;
356 
357   ProgramStateRef State = C.getState();
358   auto RetSVal =
359       State->getSVal(S, C.getLocationContext()).getAs<DefinedOrUnknownSVal>();
360   if (!RetSVal)
361     return;
362 
363   AnalysisDeclContext *DeclCtxt =
364       C.getLocationContext()->getAnalysisDeclContext();
365   const FunctionType *FuncType = DeclCtxt->getDecl()->getFunctionType();
366   if (!FuncType)
367     return;
368 
369   NullConstraint Nullness = getNullConstraint(*RetSVal, State);
370 
371   Nullability StaticNullability =
372       getNullabilityAnnotation(FuncType->getReturnType());
373 
374   if (Filter.CheckNullReturnedFromNonnull &&
375       Nullness == NullConstraint::IsNull &&
376       StaticNullability == Nullability::Nonnull) {
377     static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
378     ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
379     reportBug(ErrorKind::NilReturnedToNonnull, N, nullptr, C.getBugReporter(),
380               S);
381     return;
382   }
383 
384   const MemRegion *Region = getTrackRegion(*RetSVal);
385   if (!Region)
386     return;
387 
388   const NullabilityState *TrackedNullability =
389       State->get<NullabilityMap>(Region);
390   if (TrackedNullability) {
391     Nullability TrackedNullabValue = TrackedNullability->getValue();
392     if (Filter.CheckNullableReturnedFromNonnull &&
393         Nullness != NullConstraint::IsNotNull &&
394         TrackedNullabValue == Nullability::Nullable &&
395         StaticNullability == Nullability::Nonnull) {
396       static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
397       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
398       reportBug(ErrorKind::NullableReturnedToNonnull, N, Region,
399                 C.getBugReporter());
400     }
401     return;
402   }
403   if (StaticNullability == Nullability::Nullable) {
404     State = State->set<NullabilityMap>(Region,
405                                        NullabilityState(StaticNullability, S));
406     C.addTransition(State);
407   }
408 }
409 
410 /// This callback warns when a nullable pointer or a null value is passed to a
411 /// function that expects its argument to be nonnull.
412 void NullabilityChecker::checkPreCall(const CallEvent &Call,
413                                       CheckerContext &C) const {
414   if (!Call.getDecl())
415     return;
416 
417   ProgramStateRef State = C.getState();
418   ProgramStateRef OrigState = State;
419 
420   unsigned Idx = 0;
421   for (const ParmVarDecl *Param : Call.parameters()) {
422     if (Param->isParameterPack())
423       break;
424 
425     const Expr *ArgExpr = nullptr;
426     if (Idx < Call.getNumArgs())
427       ArgExpr = Call.getArgExpr(Idx);
428     auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
429     if (!ArgSVal)
430       continue;
431 
432     if (!Param->getType()->isAnyPointerType() &&
433         !Param->getType()->isReferenceType())
434       continue;
435 
436     NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
437 
438     Nullability ParamNullability = getNullabilityAnnotation(Param->getType());
439     Nullability ArgStaticNullability =
440         getNullabilityAnnotation(ArgExpr->getType());
441 
442     if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull &&
443         ArgStaticNullability != Nullability::Nonnull &&
444         ParamNullability == Nullability::Nonnull) {
445       static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
446       ExplodedNode *N = C.generateSink(State, C.getPredecessor(), &Tag);
447       reportBug(ErrorKind::NilPassedToNonnull, N, nullptr, C.getBugReporter(),
448                 ArgExpr);
449       return;
450     }
451 
452     const MemRegion *Region = getTrackRegion(*ArgSVal);
453     if (!Region)
454       continue;
455 
456     const NullabilityState *TrackedNullability =
457         State->get<NullabilityMap>(Region);
458 
459     if (TrackedNullability) {
460       if (Nullness == NullConstraint::IsNotNull ||
461           TrackedNullability->getValue() != Nullability::Nullable)
462         continue;
463 
464       if (Filter.CheckNullablePassedToNonnull &&
465           ParamNullability == Nullability::Nonnull) {
466         static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
467         ExplodedNode *N = C.generateSink(State, C.getPredecessor(), &Tag);
468         reportBug(ErrorKind::NullablePassedToNonnull, N, Region,
469                   C.getBugReporter(), ArgExpr);
470         return;
471       }
472       if (Filter.CheckNullableDereferenced &&
473           Param->getType()->isReferenceType()) {
474         static CheckerProgramPointTag Tag(this, "NullableDereferenced");
475         ExplodedNode *N = C.generateSink(State, C.getPredecessor(), &Tag);
476         reportBug(ErrorKind::NullableDereferenced, N, Region,
477                   C.getBugReporter(), ArgExpr);
478         return;
479       }
480       continue;
481     }
482     // No tracked nullability yet.
483     if (ArgStaticNullability != Nullability::Nullable)
484       continue;
485     State = State->set<NullabilityMap>(
486         Region, NullabilityState(ArgStaticNullability, ArgExpr));
487   }
488   if (State != OrigState)
489     C.addTransition(State);
490 }
491 
492 /// Suppress the nullability warnings for some functions.
493 void NullabilityChecker::checkPostCall(const CallEvent &Call,
494                                        CheckerContext &C) const {
495   auto Decl = Call.getDecl();
496   if (!Decl)
497     return;
498   // ObjC Messages handles in a different callback.
499   if (Call.getKind() == CE_ObjCMessage)
500     return;
501   const FunctionType *FuncType = Decl->getFunctionType();
502   if (!FuncType)
503     return;
504   QualType ReturnType = FuncType->getReturnType();
505   if (!ReturnType->isAnyPointerType())
506     return;
507   const MemRegion *Region = getTrackRegion(Call.getReturnValue());
508   if (!Region)
509     return;
510   ProgramStateRef State = C.getState();
511 
512   // CG headers are misannotated. Do not warn for symbols that are the results
513   // of CG calls.
514   const SourceManager &SM = C.getSourceManager();
515   StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getLocStart()));
516   if (llvm::sys::path::filename(FilePath).startswith("CG")) {
517     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
518     C.addTransition(State);
519     return;
520   }
521 
522   const NullabilityState *TrackedNullability =
523       State->get<NullabilityMap>(Region);
524 
525   if (!TrackedNullability &&
526       getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
527     State = State->set<NullabilityMap>(Region, Nullability::Nullable);
528     C.addTransition(State);
529   }
530 }
531 
532 static Nullability getReceiverNullability(const ObjCMethodCall &M,
533                                           ProgramStateRef State) {
534   Nullability RetNullability = Nullability::Unspecified;
535   if (M.isReceiverSelfOrSuper()) {
536     // For super and super class receivers we assume that the receiver is
537     // nonnull.
538     RetNullability = Nullability::Nonnull;
539   } else {
540     // Otherwise look up nullability in the state.
541     SVal Receiver = M.getReceiverSVal();
542     auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
543     if (ValueRegionSVal) {
544       const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
545       assert(SelfRegion);
546 
547       const NullabilityState *TrackedSelfNullability =
548           State->get<NullabilityMap>(SelfRegion);
549       if (TrackedSelfNullability) {
550         RetNullability = TrackedSelfNullability->getValue();
551       }
552     }
553     if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
554       // If the receiver is constrained to be nonnull, assume that it is nonnull
555       // regardless of its type.
556       NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
557       if (Nullness == NullConstraint::IsNotNull)
558         RetNullability = Nullability::Nonnull;
559     }
560   }
561   return RetNullability;
562 }
563 
564 /// Calculate the nullability of the result of a message expr based on the
565 /// nullability of the receiver, the nullability of the return value, and the
566 /// constraints.
567 void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
568                                               CheckerContext &C) const {
569   auto Decl = M.getDecl();
570   if (!Decl)
571     return;
572   QualType RetType = Decl->getReturnType();
573   if (!RetType->isAnyPointerType())
574     return;
575 
576   const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
577   if (!ReturnRegion)
578     return;
579 
580   ProgramStateRef State = C.getState();
581   auto Interface = Decl->getClassInterface();
582   auto Name = Interface ? Interface->getName() : "";
583   // In order to reduce the noise in the diagnostics generated by this checker,
584   // some framework and programming style based heuristics are used. These
585   // heuristics are for Cocoa APIs which have NS prefix.
586   if (Name.startswith("NS")) {
587     // Developers rely on dynamic invariants such as an item should be available
588     // in a collection, or a collection is not empty often. Those invariants can
589     // not be inferred by any static analysis tool. To not to bother the users
590     // with too many false positives, every item retrieval function should be
591     // ignored for collections. The instance methods of dictionaries in Cocoa
592     // are either item retrieval related or not interesting nullability wise.
593     // Using this fact, to keep the code easier to read just ignore the return
594     // value of every instance method of dictionaries.
595     if (M.isInstanceMessage() && Name.find("Dictionary") != StringRef::npos) {
596       State =
597           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
598       C.addTransition(State);
599       return;
600     }
601     // For similar reasons ignore some methods of Cocoa arrays.
602     StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
603     if (Name.find("Array") != StringRef::npos &&
604         (FirstSelectorSlot == "firstObject" ||
605          FirstSelectorSlot == "lastObject")) {
606       State =
607           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
608       C.addTransition(State);
609       return;
610     }
611 
612     // Encoding related methods of string should not fail when lossless
613     // encodings are used. Using lossless encodings is so frequent that ignoring
614     // this class of methods reduced the emitted diagnostics by about 30% on
615     // some projects (and all of that was false positives).
616     if (Name.find("String") != StringRef::npos) {
617       for (auto Param : M.parameters()) {
618         if (Param->getName() == "encoding") {
619           State = State->set<NullabilityMap>(ReturnRegion,
620                                              Nullability::Contradicted);
621           C.addTransition(State);
622           return;
623         }
624       }
625     }
626   }
627 
628   const ObjCMessageExpr *Message = M.getOriginExpr();
629   Nullability SelfNullability = getReceiverNullability(M, State);
630 
631   const NullabilityState *NullabilityOfReturn =
632       State->get<NullabilityMap>(ReturnRegion);
633 
634   if (NullabilityOfReturn) {
635     // When we have a nullability tracked for the return value, the nullability
636     // of the expression will be the most nullable of the receiver and the
637     // return value.
638     Nullability RetValTracked = NullabilityOfReturn->getValue();
639     Nullability ComputedNullab =
640         getMostNullable(RetValTracked, SelfNullability);
641     if (ComputedNullab != RetValTracked &&
642         ComputedNullab != Nullability::Unspecified) {
643       const Stmt *NullabilitySource =
644           ComputedNullab == RetValTracked
645               ? NullabilityOfReturn->getNullabilitySource()
646               : Message->getInstanceReceiver();
647       State = State->set<NullabilityMap>(
648           ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
649       C.addTransition(State);
650     }
651     return;
652   }
653 
654   // No tracked information. Use static type information for return value.
655   Nullability RetNullability = getNullabilityAnnotation(RetType);
656 
657   // Properties might be computed. For this reason the static analyzer creates a
658   // new symbol each time an unknown property  is read. To avoid false pozitives
659   // do not treat unknown properties as nullable, even when they explicitly
660   // marked nullable.
661   if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
662     RetNullability = Nullability::Nonnull;
663 
664   Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
665   if (ComputedNullab == Nullability::Nullable) {
666     const Stmt *NullabilitySource = ComputedNullab == RetNullability
667                                         ? Message
668                                         : Message->getInstanceReceiver();
669     State = State->set<NullabilityMap>(
670         ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
671     C.addTransition(State);
672   }
673 }
674 
675 /// Explicit casts are trusted. If there is a disagreement in the nullability
676 /// annotations in the destination and the source or '0' is casted to nonnull
677 /// track the value as having contraditory nullability. This will allow users to
678 /// suppress warnings.
679 void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
680                                        CheckerContext &C) const {
681   QualType OriginType = CE->getSubExpr()->getType();
682   QualType DestType = CE->getType();
683   if (!OriginType->isAnyPointerType())
684     return;
685   if (!DestType->isAnyPointerType())
686     return;
687 
688   Nullability DestNullability = getNullabilityAnnotation(DestType);
689 
690   // No explicit nullability in the destination type, so this cast does not
691   // change the nullability.
692   if (DestNullability == Nullability::Unspecified)
693     return;
694 
695   ProgramStateRef State = C.getState();
696   auto RegionSVal =
697       State->getSVal(CE, C.getLocationContext()).getAs<DefinedOrUnknownSVal>();
698   const MemRegion *Region = getTrackRegion(*RegionSVal);
699   if (!Region)
700     return;
701 
702   // When 0 is converted to nonnull mark it as contradicted.
703   if (DestNullability == Nullability::Nonnull) {
704     NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
705     if (Nullness == NullConstraint::IsNull) {
706       State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
707       C.addTransition(State);
708       return;
709     }
710   }
711 
712   const NullabilityState *TrackedNullability =
713       State->get<NullabilityMap>(Region);
714 
715   if (!TrackedNullability) {
716     if (DestNullability != Nullability::Nullable)
717       return;
718     State = State->set<NullabilityMap>(Region,
719                                        NullabilityState(DestNullability, CE));
720     C.addTransition(State);
721     return;
722   }
723 
724   if (TrackedNullability->getValue() != DestNullability &&
725       TrackedNullability->getValue() != Nullability::Contradicted) {
726     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
727     C.addTransition(State);
728   }
729 }
730 
731 /// Propagate the nullability information through binds and warn when nullable
732 /// pointer or null symbol is assigned to a pointer with a nonnull type.
733 void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
734                                    CheckerContext &C) const {
735   const TypedValueRegion *TVR =
736       dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
737   if (!TVR)
738     return;
739 
740   QualType LocType = TVR->getValueType();
741   if (!LocType->isAnyPointerType())
742     return;
743 
744   auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
745   if (!ValDefOrUnknown)
746     return;
747 
748   ProgramStateRef State = C.getState();
749   NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
750 
751   Nullability ValNullability = Nullability::Unspecified;
752   if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
753     ValNullability = getNullabilityAnnotation(Sym->getType());
754 
755   Nullability LocNullability = getNullabilityAnnotation(LocType);
756   if (Filter.CheckNullPassedToNonnull &&
757       RhsNullness == NullConstraint::IsNull &&
758       ValNullability != Nullability::Nonnull &&
759       LocNullability == Nullability::Nonnull) {
760     static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
761     ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
762     reportBug(ErrorKind::NilAssignedToNonnull, N, nullptr, C.getBugReporter(),
763               S);
764     return;
765   }
766   // Intentionally missing case: '0' is bound to a reference. It is handled by
767   // the DereferenceChecker.
768 
769   const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
770   if (!ValueRegion)
771     return;
772 
773   const NullabilityState *TrackedNullability =
774       State->get<NullabilityMap>(ValueRegion);
775 
776   if (TrackedNullability) {
777     if (RhsNullness == NullConstraint::IsNotNull ||
778         TrackedNullability->getValue() != Nullability::Nullable)
779       return;
780     if (Filter.CheckNullablePassedToNonnull &&
781         LocNullability == Nullability::Nonnull) {
782       static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
783       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
784       reportBug(ErrorKind::NullableAssignedToNonnull, N, ValueRegion,
785                 C.getBugReporter());
786     }
787     return;
788   }
789 
790   const auto *BinOp = dyn_cast<BinaryOperator>(S);
791 
792   if (ValNullability == Nullability::Nullable) {
793     // Trust the static information of the value more than the static
794     // information on the location.
795     const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
796     State = State->set<NullabilityMap>(
797         ValueRegion, NullabilityState(ValNullability, NullabilitySource));
798     C.addTransition(State);
799     return;
800   }
801 
802   if (LocNullability == Nullability::Nullable) {
803     const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
804     State = State->set<NullabilityMap>(
805         ValueRegion, NullabilityState(LocNullability, NullabilitySource));
806     C.addTransition(State);
807   }
808 }
809 
810 void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
811                                     const char *NL, const char *Sep) const {
812 
813   NullabilityMapTy B = State->get<NullabilityMap>();
814 
815   if (B.isEmpty())
816     return;
817 
818   Out << Sep << NL;
819 
820   for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
821     Out << I->first << " : ";
822     I->second.print(Out);
823     Out << NL;
824   }
825 }
826 
827 #define REGISTER_CHECKER(name)                                                 \
828   void ento::register##name##Checker(CheckerManager &mgr) {                    \
829     NullabilityChecker *checker = mgr.registerChecker<NullabilityChecker>();   \
830     checker->Filter.Check##name = true;                                        \
831     checker->Filter.CheckName##name = mgr.getCurrentCheckName();               \
832   }
833 
834 REGISTER_CHECKER(NullPassedToNonnull)
835 REGISTER_CHECKER(NullReturnedFromNonnull)
836 REGISTER_CHECKER(NullableDereferenced)
837 REGISTER_CHECKER(NullablePassedToNonnull)
838 REGISTER_CHECKER(NullableReturnedFromNonnull)
839