xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
10b57cec5SDimitry Andric //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This checker tries to find nullability violations. There are several kinds of
100b57cec5SDimitry Andric // possible violations:
110b57cec5SDimitry Andric // * Null pointer is passed to a pointer which has a _Nonnull type.
120b57cec5SDimitry Andric // * Null pointer is returned from a function which has a _Nonnull return type.
130b57cec5SDimitry Andric // * Nullable pointer is passed to a pointer which has a _Nonnull type.
140b57cec5SDimitry Andric // * Nullable pointer is returned from a function which has a _Nonnull return
150b57cec5SDimitry Andric //   type.
160b57cec5SDimitry Andric // * Nullable pointer is dereferenced.
170b57cec5SDimitry Andric //
180b57cec5SDimitry Andric // This checker propagates the nullability information of the pointers and looks
190b57cec5SDimitry Andric // for the patterns that are described above. Explicit casts are trusted and are
200b57cec5SDimitry Andric // considered a way to suppress false positives for this checker. The other way
210b57cec5SDimitry Andric // to suppress warnings would be to add asserts or guarding if statements to the
220b57cec5SDimitry Andric // code. In addition to the nullability propagation this checker also uses some
230b57cec5SDimitry Andric // heuristics to suppress potential false positives.
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
300b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
310b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
320b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
330b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
340b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
370b57cec5SDimitry Andric #include "llvm/Support/Path.h"
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric using namespace clang;
400b57cec5SDimitry Andric using namespace ento;
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric namespace {
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric /// Returns the most nullable nullability. This is used for message expressions
450b57cec5SDimitry Andric /// like [receiver method], where the nullability of this expression is either
460b57cec5SDimitry Andric /// the nullability of the receiver or the nullability of the return type of the
470b57cec5SDimitry Andric /// method, depending on which is more nullable. Contradicted is considered to
480b57cec5SDimitry Andric /// be the most nullable, to avoid false positive results.
490b57cec5SDimitry Andric Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
500b57cec5SDimitry Andric   return static_cast<Nullability>(
510b57cec5SDimitry Andric       std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
520b57cec5SDimitry Andric }
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric const char *getNullabilityString(Nullability Nullab) {
550b57cec5SDimitry Andric   switch (Nullab) {
560b57cec5SDimitry Andric   case Nullability::Contradicted:
570b57cec5SDimitry Andric     return "contradicted";
580b57cec5SDimitry Andric   case Nullability::Nullable:
590b57cec5SDimitry Andric     return "nullable";
600b57cec5SDimitry Andric   case Nullability::Unspecified:
610b57cec5SDimitry Andric     return "unspecified";
620b57cec5SDimitry Andric   case Nullability::Nonnull:
630b57cec5SDimitry Andric     return "nonnull";
640b57cec5SDimitry Andric   }
650b57cec5SDimitry Andric   llvm_unreachable("Unexpected enumeration.");
660b57cec5SDimitry Andric   return "";
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric // These enums are used as an index to ErrorMessages array.
700b57cec5SDimitry Andric enum class ErrorKind : int {
710b57cec5SDimitry Andric   NilAssignedToNonnull,
720b57cec5SDimitry Andric   NilPassedToNonnull,
730b57cec5SDimitry Andric   NilReturnedToNonnull,
740b57cec5SDimitry Andric   NullableAssignedToNonnull,
750b57cec5SDimitry Andric   NullableReturnedToNonnull,
760b57cec5SDimitry Andric   NullableDereferenced,
770b57cec5SDimitry Andric   NullablePassedToNonnull
780b57cec5SDimitry Andric };
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric class NullabilityChecker
810b57cec5SDimitry Andric     : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
820b57cec5SDimitry Andric                      check::PostCall, check::PostStmt<ExplicitCastExpr>,
830b57cec5SDimitry Andric                      check::PostObjCMessage, check::DeadSymbols,
845ffd83dbSDimitry Andric                      check::Location, check::Event<ImplicitNullDerefEvent>> {
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric public:
870b57cec5SDimitry Andric   // If true, the checker will not diagnose nullabilility issues for calls
880b57cec5SDimitry Andric   // to system headers. This option is motivated by the observation that large
890b57cec5SDimitry Andric   // projects may have many nullability warnings. These projects may
900b57cec5SDimitry Andric   // find warnings about nullability annotations that they have explicitly
910b57cec5SDimitry Andric   // added themselves higher priority to fix than warnings on calls to system
920b57cec5SDimitry Andric   // libraries.
930b57cec5SDimitry Andric   DefaultBool NoDiagnoseCallsToSystemHeaders;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
960b57cec5SDimitry Andric   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
970b57cec5SDimitry Andric   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
980b57cec5SDimitry Andric   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
990b57cec5SDimitry Andric   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
1000b57cec5SDimitry Andric   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
1010b57cec5SDimitry Andric   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
1020b57cec5SDimitry Andric   void checkEvent(ImplicitNullDerefEvent Event) const;
1035ffd83dbSDimitry Andric   void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
1045ffd83dbSDimitry Andric                      CheckerContext &C) const;
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
1070b57cec5SDimitry Andric                   const char *Sep) const override;
1080b57cec5SDimitry Andric 
1095ffd83dbSDimitry Andric   enum CheckKind {
1105ffd83dbSDimitry Andric     CK_NullPassedToNonnull,
1115ffd83dbSDimitry Andric     CK_NullReturnedFromNonnull,
1125ffd83dbSDimitry Andric     CK_NullableDereferenced,
1135ffd83dbSDimitry Andric     CK_NullablePassedToNonnull,
1145ffd83dbSDimitry Andric     CK_NullableReturnedFromNonnull,
1155ffd83dbSDimitry Andric     CK_NumCheckKinds
1160b57cec5SDimitry Andric   };
1170b57cec5SDimitry Andric 
1185ffd83dbSDimitry Andric   DefaultBool ChecksEnabled[CK_NumCheckKinds];
1195ffd83dbSDimitry Andric   CheckerNameRef CheckNames[CK_NumCheckKinds];
1205ffd83dbSDimitry Andric   mutable std::unique_ptr<BugType> BTs[CK_NumCheckKinds];
1215ffd83dbSDimitry Andric 
1225ffd83dbSDimitry Andric   const std::unique_ptr<BugType> &getBugType(CheckKind Kind) const {
1235ffd83dbSDimitry Andric     if (!BTs[Kind])
1245ffd83dbSDimitry Andric       BTs[Kind].reset(new BugType(CheckNames[Kind], "Nullability",
1255ffd83dbSDimitry Andric                                   categories::MemoryError));
1265ffd83dbSDimitry Andric     return BTs[Kind];
1275ffd83dbSDimitry Andric   }
1285ffd83dbSDimitry Andric 
1290b57cec5SDimitry Andric   // When set to false no nullability information will be tracked in
1300b57cec5SDimitry Andric   // NullabilityMap. It is possible to catch errors like passing a null pointer
1310b57cec5SDimitry Andric   // to a callee that expects nonnull argument without the information that is
1320b57cec5SDimitry Andric   // stroed in the NullabilityMap. This is an optimization.
1330b57cec5SDimitry Andric   DefaultBool NeedTracking;
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric private:
1360b57cec5SDimitry Andric   class NullabilityBugVisitor : public BugReporterVisitor {
1370b57cec5SDimitry Andric   public:
1380b57cec5SDimitry Andric     NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     void Profile(llvm::FoldingSetNodeID &ID) const override {
1410b57cec5SDimitry Andric       static int X = 0;
1420b57cec5SDimitry Andric       ID.AddPointer(&X);
1430b57cec5SDimitry Andric       ID.AddPointer(Region);
1440b57cec5SDimitry Andric     }
1450b57cec5SDimitry Andric 
146a7dea167SDimitry Andric     PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1470b57cec5SDimitry Andric                                      BugReporterContext &BRC,
148a7dea167SDimitry Andric                                      PathSensitiveBugReport &BR) override;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   private:
1510b57cec5SDimitry Andric     // The tracked region.
1520b57cec5SDimitry Andric     const MemRegion *Region;
1530b57cec5SDimitry Andric   };
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   /// When any of the nonnull arguments of the analyzed function is null, do not
1560b57cec5SDimitry Andric   /// report anything and turn off the check.
1570b57cec5SDimitry Andric   ///
1580b57cec5SDimitry Andric   /// When \p SuppressPath is set to true, no more bugs will be reported on this
1590b57cec5SDimitry Andric   /// path by this checker.
1605ffd83dbSDimitry Andric   void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
1610b57cec5SDimitry Andric                                  ExplodedNode *N, const MemRegion *Region,
1620b57cec5SDimitry Andric                                  CheckerContext &C,
1630b57cec5SDimitry Andric                                  const Stmt *ValueExpr = nullptr,
1640b57cec5SDimitry Andric                                  bool SuppressPath = false) const;
1650b57cec5SDimitry Andric 
1665ffd83dbSDimitry Andric   void reportBug(StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
1670b57cec5SDimitry Andric                  const MemRegion *Region, BugReporter &BR,
1680b57cec5SDimitry Andric                  const Stmt *ValueExpr = nullptr) const {
1695ffd83dbSDimitry Andric     const std::unique_ptr<BugType> &BT = getBugType(CK);
170a7dea167SDimitry Andric     auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
1710b57cec5SDimitry Andric     if (Region) {
1720b57cec5SDimitry Andric       R->markInteresting(Region);
173*fe6060f1SDimitry Andric       R->addVisitor<NullabilityBugVisitor>(Region);
1740b57cec5SDimitry Andric     }
1750b57cec5SDimitry Andric     if (ValueExpr) {
1760b57cec5SDimitry Andric       R->addRange(ValueExpr->getSourceRange());
1770b57cec5SDimitry Andric       if (Error == ErrorKind::NilAssignedToNonnull ||
1780b57cec5SDimitry Andric           Error == ErrorKind::NilPassedToNonnull ||
1790b57cec5SDimitry Andric           Error == ErrorKind::NilReturnedToNonnull)
1800b57cec5SDimitry Andric         if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
1810b57cec5SDimitry Andric           bugreporter::trackExpressionValue(N, Ex, *R);
1820b57cec5SDimitry Andric     }
1830b57cec5SDimitry Andric     BR.emitReport(std::move(R));
1840b57cec5SDimitry Andric   }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   /// If an SVal wraps a region that should be tracked, it will return a pointer
1870b57cec5SDimitry Andric   /// to the wrapped region. Otherwise it will return a nullptr.
1880b57cec5SDimitry Andric   const SymbolicRegion *getTrackRegion(SVal Val,
1890b57cec5SDimitry Andric                                        bool CheckSuperRegion = false) const;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   /// Returns true if the call is diagnosable in the current analyzer
1920b57cec5SDimitry Andric   /// configuration.
1930b57cec5SDimitry Andric   bool isDiagnosableCall(const CallEvent &Call) const {
1940b57cec5SDimitry Andric     if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
1950b57cec5SDimitry Andric       return false;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric     return true;
1980b57cec5SDimitry Andric   }
1990b57cec5SDimitry Andric };
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric class NullabilityState {
2020b57cec5SDimitry Andric public:
2030b57cec5SDimitry Andric   NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
2040b57cec5SDimitry Andric       : Nullab(Nullab), Source(Source) {}
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   const Stmt *getNullabilitySource() const { return Source; }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   Nullability getValue() const { return Nullab; }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   void Profile(llvm::FoldingSetNodeID &ID) const {
2110b57cec5SDimitry Andric     ID.AddInteger(static_cast<char>(Nullab));
2120b57cec5SDimitry Andric     ID.AddPointer(Source);
2130b57cec5SDimitry Andric   }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   void print(raw_ostream &Out) const {
2160b57cec5SDimitry Andric     Out << getNullabilityString(Nullab) << "\n";
2170b57cec5SDimitry Andric   }
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric private:
2200b57cec5SDimitry Andric   Nullability Nullab;
2210b57cec5SDimitry Andric   // Source is the expression which determined the nullability. For example in a
2220b57cec5SDimitry Andric   // message like [nullable nonnull_returning] has nullable nullability, because
2230b57cec5SDimitry Andric   // the receiver is nullable. Here the receiver will be the source of the
2240b57cec5SDimitry Andric   // nullability. This is useful information when the diagnostics are generated.
2250b57cec5SDimitry Andric   const Stmt *Source;
2260b57cec5SDimitry Andric };
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
2290b57cec5SDimitry Andric   return Lhs.getValue() == Rhs.getValue() &&
2300b57cec5SDimitry Andric          Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric } // end anonymous namespace
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
2360b57cec5SDimitry Andric                                NullabilityState)
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric // We say "the nullability type invariant is violated" when a location with a
2390b57cec5SDimitry Andric // non-null type contains NULL or a function with a non-null return type returns
2400b57cec5SDimitry Andric // NULL. Violations of the nullability type invariant can be detected either
2410b57cec5SDimitry Andric // directly (for example, when NULL is passed as an argument to a nonnull
2420b57cec5SDimitry Andric // parameter) or indirectly (for example, when, inside a function, the
2430b57cec5SDimitry Andric // programmer defensively checks whether a nonnull parameter contains NULL and
2440b57cec5SDimitry Andric // finds that it does).
2450b57cec5SDimitry Andric //
2460b57cec5SDimitry Andric // As a matter of policy, the nullability checker typically warns on direct
2470b57cec5SDimitry Andric // violations of the nullability invariant (although it uses various
2480b57cec5SDimitry Andric // heuristics to suppress warnings in some cases) but will not warn if the
2490b57cec5SDimitry Andric // invariant has already been violated along the path (either directly or
2500b57cec5SDimitry Andric // indirectly). As a practical matter, this prevents the analyzer from
2510b57cec5SDimitry Andric // (1) warning on defensive code paths where a nullability precondition is
2520b57cec5SDimitry Andric // determined to have been violated, (2) warning additional times after an
2530b57cec5SDimitry Andric // initial direct violation has been discovered, and (3) warning after a direct
2540b57cec5SDimitry Andric // violation that has been implicitly or explicitly suppressed (for
2550b57cec5SDimitry Andric // example, with a cast of NULL to _Nonnull). In essence, once an invariant
2560b57cec5SDimitry Andric // violation is detected on a path, this checker will be essentially turned off
2570b57cec5SDimitry Andric // for the rest of the analysis
2580b57cec5SDimitry Andric //
2590b57cec5SDimitry Andric // The analyzer takes this approach (rather than generating a sink node) to
2600b57cec5SDimitry Andric // ensure coverage of defensive paths, which may be important for backwards
2610b57cec5SDimitry Andric // compatibility in codebases that were developed without nullability in mind.
2620b57cec5SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric enum class NullConstraint { IsNull, IsNotNull, Unknown };
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
2670b57cec5SDimitry Andric                                         ProgramStateRef State) {
2680b57cec5SDimitry Andric   ConditionTruthVal Nullness = State->isNull(Val);
2690b57cec5SDimitry Andric   if (Nullness.isConstrainedFalse())
2700b57cec5SDimitry Andric     return NullConstraint::IsNotNull;
2710b57cec5SDimitry Andric   if (Nullness.isConstrainedTrue())
2720b57cec5SDimitry Andric     return NullConstraint::IsNull;
2730b57cec5SDimitry Andric   return NullConstraint::Unknown;
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric const SymbolicRegion *
2770b57cec5SDimitry Andric NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
2780b57cec5SDimitry Andric   if (!NeedTracking)
2790b57cec5SDimitry Andric     return nullptr;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   auto RegionSVal = Val.getAs<loc::MemRegionVal>();
2820b57cec5SDimitry Andric   if (!RegionSVal)
2830b57cec5SDimitry Andric     return nullptr;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   const MemRegion *Region = RegionSVal->getRegion();
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   if (CheckSuperRegion) {
2880b57cec5SDimitry Andric     if (auto FieldReg = Region->getAs<FieldRegion>())
2890b57cec5SDimitry Andric       return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
2900b57cec5SDimitry Andric     if (auto ElementReg = Region->getAs<ElementRegion>())
2910b57cec5SDimitry Andric       return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
2920b57cec5SDimitry Andric   }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   return dyn_cast<SymbolicRegion>(Region);
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric 
297a7dea167SDimitry Andric PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
298a7dea167SDimitry Andric     const ExplodedNode *N, BugReporterContext &BRC,
299a7dea167SDimitry Andric     PathSensitiveBugReport &BR) {
3000b57cec5SDimitry Andric   ProgramStateRef State = N->getState();
3010b57cec5SDimitry Andric   ProgramStateRef StatePrev = N->getFirstPred()->getState();
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
3040b57cec5SDimitry Andric   const NullabilityState *TrackedNullabPrev =
3050b57cec5SDimitry Andric       StatePrev->get<NullabilityMap>(Region);
3060b57cec5SDimitry Andric   if (!TrackedNullab)
3070b57cec5SDimitry Andric     return nullptr;
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   if (TrackedNullabPrev &&
3100b57cec5SDimitry Andric       TrackedNullabPrev->getValue() == TrackedNullab->getValue())
3110b57cec5SDimitry Andric     return nullptr;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   // Retrieve the associated statement.
3140b57cec5SDimitry Andric   const Stmt *S = TrackedNullab->getNullabilitySource();
3150b57cec5SDimitry Andric   if (!S || S->getBeginLoc().isInvalid()) {
316a7dea167SDimitry Andric     S = N->getStmtForDiagnostics();
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   if (!S)
3200b57cec5SDimitry Andric     return nullptr;
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   std::string InfoText =
3230b57cec5SDimitry Andric       (llvm::Twine("Nullability '") +
3240b57cec5SDimitry Andric        getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
3250b57cec5SDimitry Andric           .str();
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   // Generate the extra diagnostic.
3280b57cec5SDimitry Andric   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
3290b57cec5SDimitry Andric                              N->getLocationContext());
330a7dea167SDimitry Andric   return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric /// Returns true when the value stored at the given location has been
3340b57cec5SDimitry Andric /// constrained to null after being passed through an object of nonnnull type.
3350b57cec5SDimitry Andric static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
3360b57cec5SDimitry Andric                                                   SVal LV, QualType T) {
3370b57cec5SDimitry Andric   if (getNullabilityAnnotation(T) != Nullability::Nonnull)
3380b57cec5SDimitry Andric     return false;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   auto RegionVal = LV.getAs<loc::MemRegionVal>();
3410b57cec5SDimitry Andric   if (!RegionVal)
3420b57cec5SDimitry Andric     return false;
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   // If the value was constrained to null *after* it was passed through that
3450b57cec5SDimitry Andric   // location, it could not have been a concrete pointer *when* it was passed.
3460b57cec5SDimitry Andric   // In that case we would have handled the situation when the value was
3470b57cec5SDimitry Andric   // bound to that location, by emitting (or not emitting) a report.
3480b57cec5SDimitry Andric   // Therefore we are only interested in symbolic regions that can be either
3490b57cec5SDimitry Andric   // null or non-null depending on the value of their respective symbol.
3500b57cec5SDimitry Andric   auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
3510b57cec5SDimitry Andric   if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
3520b57cec5SDimitry Andric     return false;
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
3550b57cec5SDimitry Andric     return true;
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   return false;
3580b57cec5SDimitry Andric }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric static bool
3610b57cec5SDimitry Andric checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
3620b57cec5SDimitry Andric                                     ProgramStateRef State,
3630b57cec5SDimitry Andric                                     const LocationContext *LocCtxt) {
3640b57cec5SDimitry Andric   for (const auto *ParamDecl : Params) {
3650b57cec5SDimitry Andric     if (ParamDecl->isParameterPack())
3660b57cec5SDimitry Andric       break;
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric     SVal LV = State->getLValue(ParamDecl, LocCtxt);
3690b57cec5SDimitry Andric     if (checkValueAtLValForInvariantViolation(State, LV,
3700b57cec5SDimitry Andric                                               ParamDecl->getType())) {
3710b57cec5SDimitry Andric       return true;
3720b57cec5SDimitry Andric     }
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric   return false;
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric static bool
3780b57cec5SDimitry Andric checkSelfIvarsForInvariantViolation(ProgramStateRef State,
3790b57cec5SDimitry Andric                                     const LocationContext *LocCtxt) {
3800b57cec5SDimitry Andric   auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
3810b57cec5SDimitry Andric   if (!MD || !MD->isInstanceMethod())
3820b57cec5SDimitry Andric     return false;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
3850b57cec5SDimitry Andric   if (!SelfDecl)
3860b57cec5SDimitry Andric     return false;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   const ObjCObjectPointerType *SelfType =
3910b57cec5SDimitry Andric       dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
3920b57cec5SDimitry Andric   if (!SelfType)
3930b57cec5SDimitry Andric     return false;
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
3960b57cec5SDimitry Andric   if (!ID)
3970b57cec5SDimitry Andric     return false;
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   for (const auto *IvarDecl : ID->ivars()) {
4000b57cec5SDimitry Andric     SVal LV = State->getLValue(IvarDecl, SelfVal);
4010b57cec5SDimitry Andric     if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
4020b57cec5SDimitry Andric       return true;
4030b57cec5SDimitry Andric     }
4040b57cec5SDimitry Andric   }
4050b57cec5SDimitry Andric   return false;
4060b57cec5SDimitry Andric }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
4090b57cec5SDimitry Andric                                     CheckerContext &C) {
4100b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
4110b57cec5SDimitry Andric     return true;
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   const LocationContext *LocCtxt = C.getLocationContext();
4140b57cec5SDimitry Andric   const Decl *D = LocCtxt->getDecl();
4150b57cec5SDimitry Andric   if (!D)
4160b57cec5SDimitry Andric     return false;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   ArrayRef<ParmVarDecl*> Params;
4190b57cec5SDimitry Andric   if (const auto *BD = dyn_cast<BlockDecl>(D))
4200b57cec5SDimitry Andric     Params = BD->parameters();
4210b57cec5SDimitry Andric   else if (const auto *FD = dyn_cast<FunctionDecl>(D))
4220b57cec5SDimitry Andric     Params = FD->parameters();
4230b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
4240b57cec5SDimitry Andric     Params = MD->parameters();
4250b57cec5SDimitry Andric   else
4260b57cec5SDimitry Andric     return false;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
4290b57cec5SDimitry Andric       checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
4300b57cec5SDimitry Andric     if (!N->isSink())
4310b57cec5SDimitry Andric       C.addTransition(State->set<InvariantViolated>(true), N);
4320b57cec5SDimitry Andric     return true;
4330b57cec5SDimitry Andric   }
4340b57cec5SDimitry Andric   return false;
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric 
4375ffd83dbSDimitry Andric void NullabilityChecker::reportBugIfInvariantHolds(
4385ffd83dbSDimitry Andric     StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
4395ffd83dbSDimitry Andric     const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
4405ffd83dbSDimitry Andric     bool SuppressPath) const {
4410b57cec5SDimitry Andric   ProgramStateRef OriginalState = N->getState();
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   if (checkInvariantViolation(OriginalState, N, C))
4440b57cec5SDimitry Andric     return;
4450b57cec5SDimitry Andric   if (SuppressPath) {
4460b57cec5SDimitry Andric     OriginalState = OriginalState->set<InvariantViolated>(true);
4470b57cec5SDimitry Andric     N = C.addTransition(OriginalState, N);
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric 
4505ffd83dbSDimitry Andric   reportBug(Msg, Error, CK, N, Region, C.getBugReporter(), ValueExpr);
4510b57cec5SDimitry Andric }
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric /// Cleaning up the program state.
4540b57cec5SDimitry Andric void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
4550b57cec5SDimitry Andric                                           CheckerContext &C) const {
4560b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
4570b57cec5SDimitry Andric   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
4580b57cec5SDimitry Andric   for (NullabilityMapTy::iterator I = Nullabilities.begin(),
4590b57cec5SDimitry Andric                                   E = Nullabilities.end();
4600b57cec5SDimitry Andric        I != E; ++I) {
4610b57cec5SDimitry Andric     const auto *Region = I->first->getAs<SymbolicRegion>();
4620b57cec5SDimitry Andric     assert(Region && "Non-symbolic region is tracked.");
4630b57cec5SDimitry Andric     if (SR.isDead(Region->getSymbol())) {
4640b57cec5SDimitry Andric       State = State->remove<NullabilityMap>(I->first);
4650b57cec5SDimitry Andric     }
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric   // When one of the nonnull arguments are constrained to be null, nullability
4680b57cec5SDimitry Andric   // preconditions are violated. It is not enough to check this only when we
4690b57cec5SDimitry Andric   // actually report an error, because at that time interesting symbols might be
4700b57cec5SDimitry Andric   // reaped.
4710b57cec5SDimitry Andric   if (checkInvariantViolation(State, C.getPredecessor(), C))
4720b57cec5SDimitry Andric     return;
4730b57cec5SDimitry Andric   C.addTransition(State);
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric /// This callback triggers when a pointer is dereferenced and the analyzer does
4770b57cec5SDimitry Andric /// not know anything about the value of that pointer. When that pointer is
4780b57cec5SDimitry Andric /// nullable, this code emits a warning.
4790b57cec5SDimitry Andric void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
4800b57cec5SDimitry Andric   if (Event.SinkNode->getState()->get<InvariantViolated>())
4810b57cec5SDimitry Andric     return;
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   const MemRegion *Region =
4840b57cec5SDimitry Andric       getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
4850b57cec5SDimitry Andric   if (!Region)
4860b57cec5SDimitry Andric     return;
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric   ProgramStateRef State = Event.SinkNode->getState();
4890b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
4900b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   if (!TrackedNullability)
4930b57cec5SDimitry Andric     return;
4940b57cec5SDimitry Andric 
4955ffd83dbSDimitry Andric   if (ChecksEnabled[CK_NullableDereferenced] &&
4960b57cec5SDimitry Andric       TrackedNullability->getValue() == Nullability::Nullable) {
4970b57cec5SDimitry Andric     BugReporter &BR = *Event.BR;
4980b57cec5SDimitry Andric     // Do not suppress errors on defensive code paths, because dereferencing
4990b57cec5SDimitry Andric     // a nullable pointer is always an error.
5000b57cec5SDimitry Andric     if (Event.IsDirectDereference)
5010b57cec5SDimitry Andric       reportBug("Nullable pointer is dereferenced",
5025ffd83dbSDimitry Andric                 ErrorKind::NullableDereferenced, CK_NullableDereferenced,
5035ffd83dbSDimitry Andric                 Event.SinkNode, Region, BR);
5040b57cec5SDimitry Andric     else {
5050b57cec5SDimitry Andric       reportBug("Nullable pointer is passed to a callee that requires a "
5065ffd83dbSDimitry Andric                 "non-null",
5075ffd83dbSDimitry Andric                 ErrorKind::NullablePassedToNonnull, CK_NullableDereferenced,
5080b57cec5SDimitry Andric                 Event.SinkNode, Region, BR);
5090b57cec5SDimitry Andric     }
5100b57cec5SDimitry Andric   }
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
5135ffd83dbSDimitry Andric // Whenever we see a load from a typed memory region that's been annotated as
5145ffd83dbSDimitry Andric // 'nonnull', we want to trust the user on that and assume that it is is indeed
5155ffd83dbSDimitry Andric // non-null.
5165ffd83dbSDimitry Andric //
5175ffd83dbSDimitry Andric // We do so even if the value is known to have been assigned to null.
5185ffd83dbSDimitry Andric // The user should be warned on assigning the null value to a non-null pointer
5195ffd83dbSDimitry Andric // as opposed to warning on the later dereference of this pointer.
5205ffd83dbSDimitry Andric //
5215ffd83dbSDimitry Andric // \code
5225ffd83dbSDimitry Andric //   int * _Nonnull var = 0; // we want to warn the user here...
5235ffd83dbSDimitry Andric //   // . . .
5245ffd83dbSDimitry Andric //   *var = 42;              // ...and not here
5255ffd83dbSDimitry Andric // \endcode
5265ffd83dbSDimitry Andric void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
5275ffd83dbSDimitry Andric                                        const Stmt *S,
5285ffd83dbSDimitry Andric                                        CheckerContext &Context) const {
5295ffd83dbSDimitry Andric   // We should care only about loads.
5305ffd83dbSDimitry Andric   // The main idea is to add a constraint whenever we're loading a value from
5315ffd83dbSDimitry Andric   // an annotated pointer type.
5325ffd83dbSDimitry Andric   if (!IsLoad)
5335ffd83dbSDimitry Andric     return;
5345ffd83dbSDimitry Andric 
5355ffd83dbSDimitry Andric   // Annotations that we want to consider make sense only for types.
5365ffd83dbSDimitry Andric   const auto *Region =
5375ffd83dbSDimitry Andric       dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
5385ffd83dbSDimitry Andric   if (!Region)
5395ffd83dbSDimitry Andric     return;
5405ffd83dbSDimitry Andric 
5415ffd83dbSDimitry Andric   ProgramStateRef State = Context.getState();
5425ffd83dbSDimitry Andric 
5435ffd83dbSDimitry Andric   auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
5445ffd83dbSDimitry Andric   if (!StoredVal)
5455ffd83dbSDimitry Andric     return;
5465ffd83dbSDimitry Andric 
5475ffd83dbSDimitry Andric   Nullability NullabilityOfTheLoadedValue =
5485ffd83dbSDimitry Andric       getNullabilityAnnotation(Region->getValueType());
5495ffd83dbSDimitry Andric 
5505ffd83dbSDimitry Andric   if (NullabilityOfTheLoadedValue == Nullability::Nonnull) {
5515ffd83dbSDimitry Andric     // It doesn't matter what we think about this particular pointer, it should
5525ffd83dbSDimitry Andric     // be considered non-null as annotated by the developer.
5535ffd83dbSDimitry Andric     if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
5545ffd83dbSDimitry Andric       Context.addTransition(NewState);
5555ffd83dbSDimitry Andric     }
5565ffd83dbSDimitry Andric   }
5575ffd83dbSDimitry Andric }
5585ffd83dbSDimitry Andric 
5590b57cec5SDimitry Andric /// Find the outermost subexpression of E that is not an implicit cast.
5600b57cec5SDimitry Andric /// This looks through the implicit casts to _Nonnull that ARC adds to
5610b57cec5SDimitry Andric /// return expressions of ObjC types when the return type of the function or
5620b57cec5SDimitry Andric /// method is non-null but the express is not.
5630b57cec5SDimitry Andric static const Expr *lookThroughImplicitCasts(const Expr *E) {
5645ffd83dbSDimitry Andric   return E->IgnoreImpCasts();
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric /// This method check when nullable pointer or null value is returned from a
5680b57cec5SDimitry Andric /// function that has nonnull return type.
5690b57cec5SDimitry Andric void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
5700b57cec5SDimitry Andric                                       CheckerContext &C) const {
5710b57cec5SDimitry Andric   auto RetExpr = S->getRetValue();
5720b57cec5SDimitry Andric   if (!RetExpr)
5730b57cec5SDimitry Andric     return;
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric   if (!RetExpr->getType()->isAnyPointerType())
5760b57cec5SDimitry Andric     return;
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
5790b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
5800b57cec5SDimitry Andric     return;
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric   auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
5830b57cec5SDimitry Andric   if (!RetSVal)
5840b57cec5SDimitry Andric     return;
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   bool InSuppressedMethodFamily = false;
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric   QualType RequiredRetType;
5890b57cec5SDimitry Andric   AnalysisDeclContext *DeclCtxt =
5900b57cec5SDimitry Andric       C.getLocationContext()->getAnalysisDeclContext();
5910b57cec5SDimitry Andric   const Decl *D = DeclCtxt->getDecl();
5920b57cec5SDimitry Andric   if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5930b57cec5SDimitry Andric     // HACK: This is a big hammer to avoid warning when there are defensive
5940b57cec5SDimitry Andric     // nil checks in -init and -copy methods. We should add more sophisticated
5950b57cec5SDimitry Andric     // logic here to suppress on common defensive idioms but still
5960b57cec5SDimitry Andric     // warn when there is a likely problem.
5970b57cec5SDimitry Andric     ObjCMethodFamily Family = MD->getMethodFamily();
5980b57cec5SDimitry Andric     if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
5990b57cec5SDimitry Andric       InSuppressedMethodFamily = true;
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric     RequiredRetType = MD->getReturnType();
6020b57cec5SDimitry Andric   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6030b57cec5SDimitry Andric     RequiredRetType = FD->getReturnType();
6040b57cec5SDimitry Andric   } else {
6050b57cec5SDimitry Andric     return;
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   NullConstraint Nullness = getNullConstraint(*RetSVal, State);
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   // If the returned value is null but the type of the expression
6130b57cec5SDimitry Andric   // generating it is nonnull then we will suppress the diagnostic.
6140b57cec5SDimitry Andric   // This enables explicit suppression when returning a nil literal in a
6150b57cec5SDimitry Andric   // function with a _Nonnull return type:
6160b57cec5SDimitry Andric   //    return (NSString * _Nonnull)0;
6170b57cec5SDimitry Andric   Nullability RetExprTypeLevelNullability =
6180b57cec5SDimitry Andric         getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
6210b57cec5SDimitry Andric                                   Nullness == NullConstraint::IsNull);
6225ffd83dbSDimitry Andric   if (ChecksEnabled[CK_NullReturnedFromNonnull] && NullReturnedFromNonNull &&
6230b57cec5SDimitry Andric       RetExprTypeLevelNullability != Nullability::Nonnull &&
6245ffd83dbSDimitry Andric       !InSuppressedMethodFamily && C.getLocationContext()->inTopFrame()) {
6250b57cec5SDimitry Andric     static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
6260b57cec5SDimitry Andric     ExplodedNode *N = C.generateErrorNode(State, &Tag);
6270b57cec5SDimitry Andric     if (!N)
6280b57cec5SDimitry Andric       return;
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric     SmallString<256> SBuf;
6310b57cec5SDimitry Andric     llvm::raw_svector_ostream OS(SBuf);
6320b57cec5SDimitry Andric     OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
6330b57cec5SDimitry Andric     OS << " returned from a " << C.getDeclDescription(D) <<
6340b57cec5SDimitry Andric           " that is expected to return a non-null value";
6355ffd83dbSDimitry Andric     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
6365ffd83dbSDimitry Andric                               CK_NullReturnedFromNonnull, N, nullptr, C,
6370b57cec5SDimitry Andric                               RetExpr);
6380b57cec5SDimitry Andric     return;
6390b57cec5SDimitry Andric   }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // If null was returned from a non-null function, mark the nullability
6420b57cec5SDimitry Andric   // invariant as violated even if the diagnostic was suppressed.
6430b57cec5SDimitry Andric   if (NullReturnedFromNonNull) {
6440b57cec5SDimitry Andric     State = State->set<InvariantViolated>(true);
6450b57cec5SDimitry Andric     C.addTransition(State);
6460b57cec5SDimitry Andric     return;
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   const MemRegion *Region = getTrackRegion(*RetSVal);
6500b57cec5SDimitry Andric   if (!Region)
6510b57cec5SDimitry Andric     return;
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
6540b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
6550b57cec5SDimitry Andric   if (TrackedNullability) {
6560b57cec5SDimitry Andric     Nullability TrackedNullabValue = TrackedNullability->getValue();
6575ffd83dbSDimitry Andric     if (ChecksEnabled[CK_NullableReturnedFromNonnull] &&
6580b57cec5SDimitry Andric         Nullness != NullConstraint::IsNotNull &&
6590b57cec5SDimitry Andric         TrackedNullabValue == Nullability::Nullable &&
6600b57cec5SDimitry Andric         RequiredNullability == Nullability::Nonnull) {
6610b57cec5SDimitry Andric       static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
6620b57cec5SDimitry Andric       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric       SmallString<256> SBuf;
6650b57cec5SDimitry Andric       llvm::raw_svector_ostream OS(SBuf);
6660b57cec5SDimitry Andric       OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
6670b57cec5SDimitry Andric             " that is expected to return a non-null value";
6680b57cec5SDimitry Andric 
6695ffd83dbSDimitry Andric       reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
6705ffd83dbSDimitry Andric                                 CK_NullableReturnedFromNonnull, N, Region, C);
6710b57cec5SDimitry Andric     }
6720b57cec5SDimitry Andric     return;
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric   if (RequiredNullability == Nullability::Nullable) {
6750b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region,
6760b57cec5SDimitry Andric                                        NullabilityState(RequiredNullability,
6770b57cec5SDimitry Andric                                                         S));
6780b57cec5SDimitry Andric     C.addTransition(State);
6790b57cec5SDimitry Andric   }
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric /// This callback warns when a nullable pointer or a null value is passed to a
6830b57cec5SDimitry Andric /// function that expects its argument to be nonnull.
6840b57cec5SDimitry Andric void NullabilityChecker::checkPreCall(const CallEvent &Call,
6850b57cec5SDimitry Andric                                       CheckerContext &C) const {
6860b57cec5SDimitry Andric   if (!Call.getDecl())
6870b57cec5SDimitry Andric     return;
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
6900b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
6910b57cec5SDimitry Andric     return;
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   ProgramStateRef OrigState = State;
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   unsigned Idx = 0;
6960b57cec5SDimitry Andric   for (const ParmVarDecl *Param : Call.parameters()) {
6970b57cec5SDimitry Andric     if (Param->isParameterPack())
6980b57cec5SDimitry Andric       break;
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric     if (Idx >= Call.getNumArgs())
7010b57cec5SDimitry Andric       break;
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric     const Expr *ArgExpr = Call.getArgExpr(Idx);
7040b57cec5SDimitry Andric     auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
7050b57cec5SDimitry Andric     if (!ArgSVal)
7060b57cec5SDimitry Andric       continue;
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     if (!Param->getType()->isAnyPointerType() &&
7090b57cec5SDimitry Andric         !Param->getType()->isReferenceType())
7100b57cec5SDimitry Andric       continue;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric     NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric     Nullability RequiredNullability =
7150b57cec5SDimitry Andric         getNullabilityAnnotation(Param->getType());
7160b57cec5SDimitry Andric     Nullability ArgExprTypeLevelNullability =
7170b57cec5SDimitry Andric         getNullabilityAnnotation(ArgExpr->getType());
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric     unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
7200b57cec5SDimitry Andric 
7215ffd83dbSDimitry Andric     if (ChecksEnabled[CK_NullPassedToNonnull] &&
7225ffd83dbSDimitry Andric         Nullness == NullConstraint::IsNull &&
7230b57cec5SDimitry Andric         ArgExprTypeLevelNullability != Nullability::Nonnull &&
7240b57cec5SDimitry Andric         RequiredNullability == Nullability::Nonnull &&
7250b57cec5SDimitry Andric         isDiagnosableCall(Call)) {
7260b57cec5SDimitry Andric       ExplodedNode *N = C.generateErrorNode(State);
7270b57cec5SDimitry Andric       if (!N)
7280b57cec5SDimitry Andric         return;
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric       SmallString<256> SBuf;
7310b57cec5SDimitry Andric       llvm::raw_svector_ostream OS(SBuf);
7320b57cec5SDimitry Andric       OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
7330b57cec5SDimitry Andric       OS << " passed to a callee that requires a non-null " << ParamIdx
7340b57cec5SDimitry Andric          << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
7355ffd83dbSDimitry Andric       reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
7365ffd83dbSDimitry Andric                                 CK_NullPassedToNonnull, N, nullptr, C, ArgExpr,
7375ffd83dbSDimitry Andric                                 /*SuppressPath=*/false);
7380b57cec5SDimitry Andric       return;
7390b57cec5SDimitry Andric     }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric     const MemRegion *Region = getTrackRegion(*ArgSVal);
7420b57cec5SDimitry Andric     if (!Region)
7430b57cec5SDimitry Andric       continue;
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric     const NullabilityState *TrackedNullability =
7460b57cec5SDimitry Andric         State->get<NullabilityMap>(Region);
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric     if (TrackedNullability) {
7490b57cec5SDimitry Andric       if (Nullness == NullConstraint::IsNotNull ||
7500b57cec5SDimitry Andric           TrackedNullability->getValue() != Nullability::Nullable)
7510b57cec5SDimitry Andric         continue;
7520b57cec5SDimitry Andric 
7535ffd83dbSDimitry Andric       if (ChecksEnabled[CK_NullablePassedToNonnull] &&
7540b57cec5SDimitry Andric           RequiredNullability == Nullability::Nonnull &&
7550b57cec5SDimitry Andric           isDiagnosableCall(Call)) {
7560b57cec5SDimitry Andric         ExplodedNode *N = C.addTransition(State);
7570b57cec5SDimitry Andric         SmallString<256> SBuf;
7580b57cec5SDimitry Andric         llvm::raw_svector_ostream OS(SBuf);
7590b57cec5SDimitry Andric         OS << "Nullable pointer is passed to a callee that requires a non-null "
7600b57cec5SDimitry Andric            << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
7615ffd83dbSDimitry Andric         reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
7625ffd83dbSDimitry Andric                                   CK_NullablePassedToNonnull, N, Region, C,
7635ffd83dbSDimitry Andric                                   ArgExpr, /*SuppressPath=*/true);
7640b57cec5SDimitry Andric         return;
7650b57cec5SDimitry Andric       }
7665ffd83dbSDimitry Andric       if (ChecksEnabled[CK_NullableDereferenced] &&
7670b57cec5SDimitry Andric           Param->getType()->isReferenceType()) {
7680b57cec5SDimitry Andric         ExplodedNode *N = C.addTransition(State);
7690b57cec5SDimitry Andric         reportBugIfInvariantHolds("Nullable pointer is dereferenced",
7705ffd83dbSDimitry Andric                                   ErrorKind::NullableDereferenced,
7715ffd83dbSDimitry Andric                                   CK_NullableDereferenced, N, Region, C,
7725ffd83dbSDimitry Andric                                   ArgExpr, /*SuppressPath=*/true);
7730b57cec5SDimitry Andric         return;
7740b57cec5SDimitry Andric       }
7750b57cec5SDimitry Andric       continue;
7760b57cec5SDimitry Andric     }
7770b57cec5SDimitry Andric   }
7780b57cec5SDimitry Andric   if (State != OrigState)
7790b57cec5SDimitry Andric     C.addTransition(State);
7800b57cec5SDimitry Andric }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric /// Suppress the nullability warnings for some functions.
7830b57cec5SDimitry Andric void NullabilityChecker::checkPostCall(const CallEvent &Call,
7840b57cec5SDimitry Andric                                        CheckerContext &C) const {
7850b57cec5SDimitry Andric   auto Decl = Call.getDecl();
7860b57cec5SDimitry Andric   if (!Decl)
7870b57cec5SDimitry Andric     return;
7880b57cec5SDimitry Andric   // ObjC Messages handles in a different callback.
7890b57cec5SDimitry Andric   if (Call.getKind() == CE_ObjCMessage)
7900b57cec5SDimitry Andric     return;
7910b57cec5SDimitry Andric   const FunctionType *FuncType = Decl->getFunctionType();
7920b57cec5SDimitry Andric   if (!FuncType)
7930b57cec5SDimitry Andric     return;
7940b57cec5SDimitry Andric   QualType ReturnType = FuncType->getReturnType();
7950b57cec5SDimitry Andric   if (!ReturnType->isAnyPointerType())
7960b57cec5SDimitry Andric     return;
7970b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
7980b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
7990b57cec5SDimitry Andric     return;
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric   const MemRegion *Region = getTrackRegion(Call.getReturnValue());
8020b57cec5SDimitry Andric   if (!Region)
8030b57cec5SDimitry Andric     return;
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   // CG headers are misannotated. Do not warn for symbols that are the results
8060b57cec5SDimitry Andric   // of CG calls.
8070b57cec5SDimitry Andric   const SourceManager &SM = C.getSourceManager();
8080b57cec5SDimitry Andric   StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
8090b57cec5SDimitry Andric   if (llvm::sys::path::filename(FilePath).startswith("CG")) {
8100b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
8110b57cec5SDimitry Andric     C.addTransition(State);
8120b57cec5SDimitry Andric     return;
8130b57cec5SDimitry Andric   }
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
8160b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   if (!TrackedNullability &&
8190b57cec5SDimitry Andric       getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
8200b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region, Nullability::Nullable);
8210b57cec5SDimitry Andric     C.addTransition(State);
8220b57cec5SDimitry Andric   }
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric static Nullability getReceiverNullability(const ObjCMethodCall &M,
8260b57cec5SDimitry Andric                                           ProgramStateRef State) {
8270b57cec5SDimitry Andric   if (M.isReceiverSelfOrSuper()) {
8280b57cec5SDimitry Andric     // For super and super class receivers we assume that the receiver is
8290b57cec5SDimitry Andric     // nonnull.
8300b57cec5SDimitry Andric     return Nullability::Nonnull;
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric   // Otherwise look up nullability in the state.
8330b57cec5SDimitry Andric   SVal Receiver = M.getReceiverSVal();
8340b57cec5SDimitry Andric   if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
8350b57cec5SDimitry Andric     // If the receiver is constrained to be nonnull, assume that it is nonnull
8360b57cec5SDimitry Andric     // regardless of its type.
8370b57cec5SDimitry Andric     NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
8380b57cec5SDimitry Andric     if (Nullness == NullConstraint::IsNotNull)
8390b57cec5SDimitry Andric       return Nullability::Nonnull;
8400b57cec5SDimitry Andric   }
8410b57cec5SDimitry Andric   auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
8420b57cec5SDimitry Andric   if (ValueRegionSVal) {
8430b57cec5SDimitry Andric     const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
8440b57cec5SDimitry Andric     assert(SelfRegion);
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric     const NullabilityState *TrackedSelfNullability =
8470b57cec5SDimitry Andric         State->get<NullabilityMap>(SelfRegion);
8480b57cec5SDimitry Andric     if (TrackedSelfNullability)
8490b57cec5SDimitry Andric       return TrackedSelfNullability->getValue();
8500b57cec5SDimitry Andric   }
8510b57cec5SDimitry Andric   return Nullability::Unspecified;
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric /// Calculate the nullability of the result of a message expr based on the
8550b57cec5SDimitry Andric /// nullability of the receiver, the nullability of the return value, and the
8560b57cec5SDimitry Andric /// constraints.
8570b57cec5SDimitry Andric void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
8580b57cec5SDimitry Andric                                               CheckerContext &C) const {
8590b57cec5SDimitry Andric   auto Decl = M.getDecl();
8600b57cec5SDimitry Andric   if (!Decl)
8610b57cec5SDimitry Andric     return;
8620b57cec5SDimitry Andric   QualType RetType = Decl->getReturnType();
8630b57cec5SDimitry Andric   if (!RetType->isAnyPointerType())
8640b57cec5SDimitry Andric     return;
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
8670b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
8680b57cec5SDimitry Andric     return;
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
8710b57cec5SDimitry Andric   if (!ReturnRegion)
8720b57cec5SDimitry Andric     return;
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   auto Interface = Decl->getClassInterface();
8750b57cec5SDimitry Andric   auto Name = Interface ? Interface->getName() : "";
8760b57cec5SDimitry Andric   // In order to reduce the noise in the diagnostics generated by this checker,
8770b57cec5SDimitry Andric   // some framework and programming style based heuristics are used. These
8780b57cec5SDimitry Andric   // heuristics are for Cocoa APIs which have NS prefix.
8790b57cec5SDimitry Andric   if (Name.startswith("NS")) {
8800b57cec5SDimitry Andric     // Developers rely on dynamic invariants such as an item should be available
8810b57cec5SDimitry Andric     // in a collection, or a collection is not empty often. Those invariants can
8820b57cec5SDimitry Andric     // not be inferred by any static analysis tool. To not to bother the users
8830b57cec5SDimitry Andric     // with too many false positives, every item retrieval function should be
8840b57cec5SDimitry Andric     // ignored for collections. The instance methods of dictionaries in Cocoa
8850b57cec5SDimitry Andric     // are either item retrieval related or not interesting nullability wise.
8860b57cec5SDimitry Andric     // Using this fact, to keep the code easier to read just ignore the return
8870b57cec5SDimitry Andric     // value of every instance method of dictionaries.
8880b57cec5SDimitry Andric     if (M.isInstanceMessage() && Name.contains("Dictionary")) {
8890b57cec5SDimitry Andric       State =
8900b57cec5SDimitry Andric           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
8910b57cec5SDimitry Andric       C.addTransition(State);
8920b57cec5SDimitry Andric       return;
8930b57cec5SDimitry Andric     }
8940b57cec5SDimitry Andric     // For similar reasons ignore some methods of Cocoa arrays.
8950b57cec5SDimitry Andric     StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
8960b57cec5SDimitry Andric     if (Name.contains("Array") &&
8970b57cec5SDimitry Andric         (FirstSelectorSlot == "firstObject" ||
8980b57cec5SDimitry Andric          FirstSelectorSlot == "lastObject")) {
8990b57cec5SDimitry Andric       State =
9000b57cec5SDimitry Andric           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
9010b57cec5SDimitry Andric       C.addTransition(State);
9020b57cec5SDimitry Andric       return;
9030b57cec5SDimitry Andric     }
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric     // Encoding related methods of string should not fail when lossless
9060b57cec5SDimitry Andric     // encodings are used. Using lossless encodings is so frequent that ignoring
9070b57cec5SDimitry Andric     // this class of methods reduced the emitted diagnostics by about 30% on
9080b57cec5SDimitry Andric     // some projects (and all of that was false positives).
9090b57cec5SDimitry Andric     if (Name.contains("String")) {
9100b57cec5SDimitry Andric       for (auto Param : M.parameters()) {
9110b57cec5SDimitry Andric         if (Param->getName() == "encoding") {
9120b57cec5SDimitry Andric           State = State->set<NullabilityMap>(ReturnRegion,
9130b57cec5SDimitry Andric                                              Nullability::Contradicted);
9140b57cec5SDimitry Andric           C.addTransition(State);
9150b57cec5SDimitry Andric           return;
9160b57cec5SDimitry Andric         }
9170b57cec5SDimitry Andric       }
9180b57cec5SDimitry Andric     }
9190b57cec5SDimitry Andric   }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   const ObjCMessageExpr *Message = M.getOriginExpr();
9220b57cec5SDimitry Andric   Nullability SelfNullability = getReceiverNullability(M, State);
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   const NullabilityState *NullabilityOfReturn =
9250b57cec5SDimitry Andric       State->get<NullabilityMap>(ReturnRegion);
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   if (NullabilityOfReturn) {
9280b57cec5SDimitry Andric     // When we have a nullability tracked for the return value, the nullability
9290b57cec5SDimitry Andric     // of the expression will be the most nullable of the receiver and the
9300b57cec5SDimitry Andric     // return value.
9310b57cec5SDimitry Andric     Nullability RetValTracked = NullabilityOfReturn->getValue();
9320b57cec5SDimitry Andric     Nullability ComputedNullab =
9330b57cec5SDimitry Andric         getMostNullable(RetValTracked, SelfNullability);
9340b57cec5SDimitry Andric     if (ComputedNullab != RetValTracked &&
9350b57cec5SDimitry Andric         ComputedNullab != Nullability::Unspecified) {
9360b57cec5SDimitry Andric       const Stmt *NullabilitySource =
9370b57cec5SDimitry Andric           ComputedNullab == RetValTracked
9380b57cec5SDimitry Andric               ? NullabilityOfReturn->getNullabilitySource()
9390b57cec5SDimitry Andric               : Message->getInstanceReceiver();
9400b57cec5SDimitry Andric       State = State->set<NullabilityMap>(
9410b57cec5SDimitry Andric           ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
9420b57cec5SDimitry Andric       C.addTransition(State);
9430b57cec5SDimitry Andric     }
9440b57cec5SDimitry Andric     return;
9450b57cec5SDimitry Andric   }
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   // No tracked information. Use static type information for return value.
9480b57cec5SDimitry Andric   Nullability RetNullability = getNullabilityAnnotation(RetType);
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   // Properties might be computed. For this reason the static analyzer creates a
9510b57cec5SDimitry Andric   // new symbol each time an unknown property  is read. To avoid false pozitives
9520b57cec5SDimitry Andric   // do not treat unknown properties as nullable, even when they explicitly
9530b57cec5SDimitry Andric   // marked nullable.
9540b57cec5SDimitry Andric   if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
9550b57cec5SDimitry Andric     RetNullability = Nullability::Nonnull;
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
9580b57cec5SDimitry Andric   if (ComputedNullab == Nullability::Nullable) {
9590b57cec5SDimitry Andric     const Stmt *NullabilitySource = ComputedNullab == RetNullability
9600b57cec5SDimitry Andric                                         ? Message
9610b57cec5SDimitry Andric                                         : Message->getInstanceReceiver();
9620b57cec5SDimitry Andric     State = State->set<NullabilityMap>(
9630b57cec5SDimitry Andric         ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
9640b57cec5SDimitry Andric     C.addTransition(State);
9650b57cec5SDimitry Andric   }
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric /// Explicit casts are trusted. If there is a disagreement in the nullability
9690b57cec5SDimitry Andric /// annotations in the destination and the source or '0' is casted to nonnull
9700b57cec5SDimitry Andric /// track the value as having contraditory nullability. This will allow users to
9710b57cec5SDimitry Andric /// suppress warnings.
9720b57cec5SDimitry Andric void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
9730b57cec5SDimitry Andric                                        CheckerContext &C) const {
9740b57cec5SDimitry Andric   QualType OriginType = CE->getSubExpr()->getType();
9750b57cec5SDimitry Andric   QualType DestType = CE->getType();
9760b57cec5SDimitry Andric   if (!OriginType->isAnyPointerType())
9770b57cec5SDimitry Andric     return;
9780b57cec5SDimitry Andric   if (!DestType->isAnyPointerType())
9790b57cec5SDimitry Andric     return;
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
9820b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
9830b57cec5SDimitry Andric     return;
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   Nullability DestNullability = getNullabilityAnnotation(DestType);
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   // No explicit nullability in the destination type, so this cast does not
9880b57cec5SDimitry Andric   // change the nullability.
9890b57cec5SDimitry Andric   if (DestNullability == Nullability::Unspecified)
9900b57cec5SDimitry Andric     return;
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
9930b57cec5SDimitry Andric   const MemRegion *Region = getTrackRegion(*RegionSVal);
9940b57cec5SDimitry Andric   if (!Region)
9950b57cec5SDimitry Andric     return;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   // When 0 is converted to nonnull mark it as contradicted.
9980b57cec5SDimitry Andric   if (DestNullability == Nullability::Nonnull) {
9990b57cec5SDimitry Andric     NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
10000b57cec5SDimitry Andric     if (Nullness == NullConstraint::IsNull) {
10010b57cec5SDimitry Andric       State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
10020b57cec5SDimitry Andric       C.addTransition(State);
10030b57cec5SDimitry Andric       return;
10040b57cec5SDimitry Andric     }
10050b57cec5SDimitry Andric   }
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
10080b57cec5SDimitry Andric       State->get<NullabilityMap>(Region);
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   if (!TrackedNullability) {
10110b57cec5SDimitry Andric     if (DestNullability != Nullability::Nullable)
10120b57cec5SDimitry Andric       return;
10130b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region,
10140b57cec5SDimitry Andric                                        NullabilityState(DestNullability, CE));
10150b57cec5SDimitry Andric     C.addTransition(State);
10160b57cec5SDimitry Andric     return;
10170b57cec5SDimitry Andric   }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   if (TrackedNullability->getValue() != DestNullability &&
10200b57cec5SDimitry Andric       TrackedNullability->getValue() != Nullability::Contradicted) {
10210b57cec5SDimitry Andric     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
10220b57cec5SDimitry Andric     C.addTransition(State);
10230b57cec5SDimitry Andric   }
10240b57cec5SDimitry Andric }
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric /// For a given statement performing a bind, attempt to syntactically
10270b57cec5SDimitry Andric /// match the expression resulting in the bound value.
10280b57cec5SDimitry Andric static const Expr * matchValueExprForBind(const Stmt *S) {
10290b57cec5SDimitry Andric   // For `x = e` the value expression is the right-hand side.
10300b57cec5SDimitry Andric   if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
10310b57cec5SDimitry Andric     if (BinOp->getOpcode() == BO_Assign)
10320b57cec5SDimitry Andric       return BinOp->getRHS();
10330b57cec5SDimitry Andric   }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   // For `int x = e` the value expression is the initializer.
10360b57cec5SDimitry Andric   if (auto *DS = dyn_cast<DeclStmt>(S))  {
10370b57cec5SDimitry Andric     if (DS->isSingleDecl()) {
10380b57cec5SDimitry Andric       auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
10390b57cec5SDimitry Andric       if (!VD)
10400b57cec5SDimitry Andric         return nullptr;
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric       if (const Expr *Init = VD->getInit())
10430b57cec5SDimitry Andric         return Init;
10440b57cec5SDimitry Andric     }
10450b57cec5SDimitry Andric   }
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric   return nullptr;
10480b57cec5SDimitry Andric }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric /// Returns true if \param S is a DeclStmt for a local variable that
10510b57cec5SDimitry Andric /// ObjC automated reference counting initialized with zero.
10520b57cec5SDimitry Andric static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
10530b57cec5SDimitry Andric   // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
10540b57cec5SDimitry Andric   // prevents false positives when a _Nonnull local variable cannot be
10550b57cec5SDimitry Andric   // initialized with an initialization expression:
10560b57cec5SDimitry Andric   //    NSString * _Nonnull s; // no-warning
10570b57cec5SDimitry Andric   //    @autoreleasepool {
10580b57cec5SDimitry Andric   //      s = ...
10590b57cec5SDimitry Andric   //    }
10600b57cec5SDimitry Andric   //
10610b57cec5SDimitry Andric   // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
10620b57cec5SDimitry Andric   // uninitialized in Sema's UninitializedValues analysis to warn when a use of
10630b57cec5SDimitry Andric   // the zero-initialized definition will unexpectedly yield nil.
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric   // Locals are only zero-initialized when automated reference counting
10660b57cec5SDimitry Andric   // is turned on.
10670b57cec5SDimitry Andric   if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
10680b57cec5SDimitry Andric     return false;
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   auto *DS = dyn_cast<DeclStmt>(S);
10710b57cec5SDimitry Andric   if (!DS || !DS->isSingleDecl())
10720b57cec5SDimitry Andric     return false;
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric   auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
10750b57cec5SDimitry Andric   if (!VD)
10760b57cec5SDimitry Andric     return false;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric   // Sema only zero-initializes locals with ObjCLifetimes.
10790b57cec5SDimitry Andric   if(!VD->getType().getQualifiers().hasObjCLifetime())
10800b57cec5SDimitry Andric     return false;
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric   const Expr *Init = VD->getInit();
10830b57cec5SDimitry Andric   assert(Init && "ObjC local under ARC without initializer");
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric   // Return false if the local is explicitly initialized (e.g., with '= nil').
10860b57cec5SDimitry Andric   if (!isa<ImplicitValueInitExpr>(Init))
10870b57cec5SDimitry Andric     return false;
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   return true;
10900b57cec5SDimitry Andric }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric /// Propagate the nullability information through binds and warn when nullable
10930b57cec5SDimitry Andric /// pointer or null symbol is assigned to a pointer with a nonnull type.
10940b57cec5SDimitry Andric void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
10950b57cec5SDimitry Andric                                    CheckerContext &C) const {
10960b57cec5SDimitry Andric   const TypedValueRegion *TVR =
10970b57cec5SDimitry Andric       dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
10980b57cec5SDimitry Andric   if (!TVR)
10990b57cec5SDimitry Andric     return;
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   QualType LocType = TVR->getValueType();
11020b57cec5SDimitry Andric   if (!LocType->isAnyPointerType())
11030b57cec5SDimitry Andric     return;
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
11060b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
11070b57cec5SDimitry Andric     return;
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
11100b57cec5SDimitry Andric   if (!ValDefOrUnknown)
11110b57cec5SDimitry Andric     return;
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric   NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   Nullability ValNullability = Nullability::Unspecified;
11160b57cec5SDimitry Andric   if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
11170b57cec5SDimitry Andric     ValNullability = getNullabilityAnnotation(Sym->getType());
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   Nullability LocNullability = getNullabilityAnnotation(LocType);
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric   // If the type of the RHS expression is nonnull, don't warn. This
11220b57cec5SDimitry Andric   // enables explicit suppression with a cast to nonnull.
11230b57cec5SDimitry Andric   Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
11240b57cec5SDimitry Andric   const Expr *ValueExpr = matchValueExprForBind(S);
11250b57cec5SDimitry Andric   if (ValueExpr) {
11260b57cec5SDimitry Andric     ValueExprTypeLevelNullability =
11270b57cec5SDimitry Andric       getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
11280b57cec5SDimitry Andric   }
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
11310b57cec5SDimitry Andric                                 RhsNullness == NullConstraint::IsNull);
11325ffd83dbSDimitry Andric   if (ChecksEnabled[CK_NullPassedToNonnull] && NullAssignedToNonNull &&
11330b57cec5SDimitry Andric       ValNullability != Nullability::Nonnull &&
11340b57cec5SDimitry Andric       ValueExprTypeLevelNullability != Nullability::Nonnull &&
11350b57cec5SDimitry Andric       !isARCNilInitializedLocal(C, S)) {
11360b57cec5SDimitry Andric     static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
11370b57cec5SDimitry Andric     ExplodedNode *N = C.generateErrorNode(State, &Tag);
11380b57cec5SDimitry Andric     if (!N)
11390b57cec5SDimitry Andric       return;
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric     const Stmt *ValueStmt = S;
11430b57cec5SDimitry Andric     if (ValueExpr)
11440b57cec5SDimitry Andric       ValueStmt = ValueExpr;
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     SmallString<256> SBuf;
11470b57cec5SDimitry Andric     llvm::raw_svector_ostream OS(SBuf);
11480b57cec5SDimitry Andric     OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
11490b57cec5SDimitry Andric     OS << " assigned to a pointer which is expected to have non-null value";
11505ffd83dbSDimitry Andric     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
11515ffd83dbSDimitry Andric                               CK_NullPassedToNonnull, N, nullptr, C, ValueStmt);
11520b57cec5SDimitry Andric     return;
11530b57cec5SDimitry Andric   }
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   // If null was returned from a non-null function, mark the nullability
11560b57cec5SDimitry Andric   // invariant as violated even if the diagnostic was suppressed.
11570b57cec5SDimitry Andric   if (NullAssignedToNonNull) {
11580b57cec5SDimitry Andric     State = State->set<InvariantViolated>(true);
11590b57cec5SDimitry Andric     C.addTransition(State);
11600b57cec5SDimitry Andric     return;
11610b57cec5SDimitry Andric   }
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   // Intentionally missing case: '0' is bound to a reference. It is handled by
11640b57cec5SDimitry Andric   // the DereferenceChecker.
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
11670b57cec5SDimitry Andric   if (!ValueRegion)
11680b57cec5SDimitry Andric     return;
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   const NullabilityState *TrackedNullability =
11710b57cec5SDimitry Andric       State->get<NullabilityMap>(ValueRegion);
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   if (TrackedNullability) {
11740b57cec5SDimitry Andric     if (RhsNullness == NullConstraint::IsNotNull ||
11750b57cec5SDimitry Andric         TrackedNullability->getValue() != Nullability::Nullable)
11760b57cec5SDimitry Andric       return;
11775ffd83dbSDimitry Andric     if (ChecksEnabled[CK_NullablePassedToNonnull] &&
11780b57cec5SDimitry Andric         LocNullability == Nullability::Nonnull) {
11790b57cec5SDimitry Andric       static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
11800b57cec5SDimitry Andric       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
11810b57cec5SDimitry Andric       reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
11820b57cec5SDimitry Andric                                 "which is expected to have non-null value",
11835ffd83dbSDimitry Andric                                 ErrorKind::NullableAssignedToNonnull,
11845ffd83dbSDimitry Andric                                 CK_NullablePassedToNonnull, N, ValueRegion, C);
11850b57cec5SDimitry Andric     }
11860b57cec5SDimitry Andric     return;
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   const auto *BinOp = dyn_cast<BinaryOperator>(S);
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   if (ValNullability == Nullability::Nullable) {
11920b57cec5SDimitry Andric     // Trust the static information of the value more than the static
11930b57cec5SDimitry Andric     // information on the location.
11940b57cec5SDimitry Andric     const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
11950b57cec5SDimitry Andric     State = State->set<NullabilityMap>(
11960b57cec5SDimitry Andric         ValueRegion, NullabilityState(ValNullability, NullabilitySource));
11970b57cec5SDimitry Andric     C.addTransition(State);
11980b57cec5SDimitry Andric     return;
11990b57cec5SDimitry Andric   }
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric   if (LocNullability == Nullability::Nullable) {
12020b57cec5SDimitry Andric     const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
12030b57cec5SDimitry Andric     State = State->set<NullabilityMap>(
12040b57cec5SDimitry Andric         ValueRegion, NullabilityState(LocNullability, NullabilitySource));
12050b57cec5SDimitry Andric     C.addTransition(State);
12060b57cec5SDimitry Andric   }
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
12100b57cec5SDimitry Andric                                     const char *NL, const char *Sep) const {
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric   NullabilityMapTy B = State->get<NullabilityMap>();
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   if (State->get<InvariantViolated>())
12150b57cec5SDimitry Andric     Out << Sep << NL
12160b57cec5SDimitry Andric         << "Nullability invariant was violated, warnings suppressed." << NL;
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   if (B.isEmpty())
12190b57cec5SDimitry Andric     return;
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric   if (!State->get<InvariantViolated>())
12220b57cec5SDimitry Andric     Out << Sep << NL;
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric   for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
12250b57cec5SDimitry Andric     Out << I->first << " : ";
12260b57cec5SDimitry Andric     I->second.print(Out);
12270b57cec5SDimitry Andric     Out << NL;
12280b57cec5SDimitry Andric   }
12290b57cec5SDimitry Andric }
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric void ento::registerNullabilityBase(CheckerManager &mgr) {
12320b57cec5SDimitry Andric   mgr.registerChecker<NullabilityChecker>();
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric 
12355ffd83dbSDimitry Andric bool ento::shouldRegisterNullabilityBase(const CheckerManager &mgr) {
12360b57cec5SDimitry Andric   return true;
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric #define REGISTER_CHECKER(name, trackingRequired)                               \
12400b57cec5SDimitry Andric   void ento::register##name##Checker(CheckerManager &mgr) {                    \
12410b57cec5SDimitry Andric     NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>();        \
12425ffd83dbSDimitry Andric     checker->ChecksEnabled[NullabilityChecker::CK_##name] = true;              \
12435ffd83dbSDimitry Andric     checker->CheckNames[NullabilityChecker::CK_##name] =                       \
12445ffd83dbSDimitry Andric         mgr.getCurrentCheckerName();                                           \
12450b57cec5SDimitry Andric     checker->NeedTracking = checker->NeedTracking || trackingRequired;         \
12460b57cec5SDimitry Andric     checker->NoDiagnoseCallsToSystemHeaders =                                  \
12470b57cec5SDimitry Andric         checker->NoDiagnoseCallsToSystemHeaders ||                             \
12480b57cec5SDimitry Andric         mgr.getAnalyzerOptions().getCheckerBooleanOption(                      \
12490b57cec5SDimitry Andric             checker, "NoDiagnoseCallsToSystemHeaders", true);                  \
12500b57cec5SDimitry Andric   }                                                                            \
12510b57cec5SDimitry Andric                                                                                \
12525ffd83dbSDimitry Andric   bool ento::shouldRegister##name##Checker(const CheckerManager &mgr) {        \
12530b57cec5SDimitry Andric     return true;                                                               \
12540b57cec5SDimitry Andric   }
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric // The checks are likely to be turned on by default and it is possible to do
12570b57cec5SDimitry Andric // them without tracking any nullability related information. As an optimization
12580b57cec5SDimitry Andric // no nullability information will be tracked when only these two checks are
12590b57cec5SDimitry Andric // enables.
12600b57cec5SDimitry Andric REGISTER_CHECKER(NullPassedToNonnull, false)
12610b57cec5SDimitry Andric REGISTER_CHECKER(NullReturnedFromNonnull, false)
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric REGISTER_CHECKER(NullableDereferenced, true)
12640b57cec5SDimitry Andric REGISTER_CHECKER(NullablePassedToNonnull, true)
12650b57cec5SDimitry Andric REGISTER_CHECKER(NullableReturnedFromNonnull, true)
1266