xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This checker tries to find nullability violations. There are several kinds of
107330f729Sjoerg // possible violations:
117330f729Sjoerg // * Null pointer is passed to a pointer which has a _Nonnull type.
127330f729Sjoerg // * Null pointer is returned from a function which has a _Nonnull return type.
137330f729Sjoerg // * Nullable pointer is passed to a pointer which has a _Nonnull type.
147330f729Sjoerg // * Nullable pointer is returned from a function which has a _Nonnull return
157330f729Sjoerg //   type.
167330f729Sjoerg // * Nullable pointer is dereferenced.
177330f729Sjoerg //
187330f729Sjoerg // This checker propagates the nullability information of the pointers and looks
197330f729Sjoerg // for the patterns that are described above. Explicit casts are trusted and are
207330f729Sjoerg // considered a way to suppress false positives for this checker. The other way
217330f729Sjoerg // to suppress warnings would be to add asserts or guarding if statements to the
227330f729Sjoerg // code. In addition to the nullability propagation this checker also uses some
237330f729Sjoerg // heuristics to suppress potential false positives.
247330f729Sjoerg //
257330f729Sjoerg //===----------------------------------------------------------------------===//
267330f729Sjoerg 
277330f729Sjoerg #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
287330f729Sjoerg 
297330f729Sjoerg #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
307330f729Sjoerg #include "clang/StaticAnalyzer/Core/Checker.h"
317330f729Sjoerg #include "clang/StaticAnalyzer/Core/CheckerManager.h"
327330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
337330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
347330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
357330f729Sjoerg 
367330f729Sjoerg #include "llvm/ADT/StringExtras.h"
377330f729Sjoerg #include "llvm/Support/Path.h"
387330f729Sjoerg 
397330f729Sjoerg using namespace clang;
407330f729Sjoerg using namespace ento;
417330f729Sjoerg 
427330f729Sjoerg namespace {
437330f729Sjoerg 
447330f729Sjoerg /// Returns the most nullable nullability. This is used for message expressions
457330f729Sjoerg /// like [receiver method], where the nullability of this expression is either
467330f729Sjoerg /// the nullability of the receiver or the nullability of the return type of the
477330f729Sjoerg /// method, depending on which is more nullable. Contradicted is considered to
487330f729Sjoerg /// be the most nullable, to avoid false positive results.
getMostNullable(Nullability Lhs,Nullability Rhs)497330f729Sjoerg Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
507330f729Sjoerg   return static_cast<Nullability>(
517330f729Sjoerg       std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
527330f729Sjoerg }
537330f729Sjoerg 
getNullabilityString(Nullability Nullab)547330f729Sjoerg const char *getNullabilityString(Nullability Nullab) {
557330f729Sjoerg   switch (Nullab) {
567330f729Sjoerg   case Nullability::Contradicted:
577330f729Sjoerg     return "contradicted";
587330f729Sjoerg   case Nullability::Nullable:
597330f729Sjoerg     return "nullable";
607330f729Sjoerg   case Nullability::Unspecified:
617330f729Sjoerg     return "unspecified";
627330f729Sjoerg   case Nullability::Nonnull:
637330f729Sjoerg     return "nonnull";
647330f729Sjoerg   }
657330f729Sjoerg   llvm_unreachable("Unexpected enumeration.");
667330f729Sjoerg   return "";
677330f729Sjoerg }
687330f729Sjoerg 
697330f729Sjoerg // These enums are used as an index to ErrorMessages array.
707330f729Sjoerg enum class ErrorKind : int {
717330f729Sjoerg   NilAssignedToNonnull,
727330f729Sjoerg   NilPassedToNonnull,
737330f729Sjoerg   NilReturnedToNonnull,
747330f729Sjoerg   NullableAssignedToNonnull,
757330f729Sjoerg   NullableReturnedToNonnull,
767330f729Sjoerg   NullableDereferenced,
777330f729Sjoerg   NullablePassedToNonnull
787330f729Sjoerg };
797330f729Sjoerg 
807330f729Sjoerg class NullabilityChecker
817330f729Sjoerg     : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
827330f729Sjoerg                      check::PostCall, check::PostStmt<ExplicitCastExpr>,
837330f729Sjoerg                      check::PostObjCMessage, check::DeadSymbols,
84*e038c9c4Sjoerg                      check::Location, check::Event<ImplicitNullDerefEvent>> {
857330f729Sjoerg 
867330f729Sjoerg public:
877330f729Sjoerg   // If true, the checker will not diagnose nullabilility issues for calls
887330f729Sjoerg   // to system headers. This option is motivated by the observation that large
897330f729Sjoerg   // projects may have many nullability warnings. These projects may
907330f729Sjoerg   // find warnings about nullability annotations that they have explicitly
917330f729Sjoerg   // added themselves higher priority to fix than warnings on calls to system
927330f729Sjoerg   // libraries.
937330f729Sjoerg   DefaultBool NoDiagnoseCallsToSystemHeaders;
947330f729Sjoerg 
957330f729Sjoerg   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
967330f729Sjoerg   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
977330f729Sjoerg   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
987330f729Sjoerg   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
997330f729Sjoerg   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
1007330f729Sjoerg   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
1017330f729Sjoerg   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
1027330f729Sjoerg   void checkEvent(ImplicitNullDerefEvent Event) const;
103*e038c9c4Sjoerg   void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
104*e038c9c4Sjoerg                      CheckerContext &C) const;
1057330f729Sjoerg 
1067330f729Sjoerg   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
1077330f729Sjoerg                   const char *Sep) const override;
1087330f729Sjoerg 
109*e038c9c4Sjoerg   enum CheckKind {
110*e038c9c4Sjoerg     CK_NullPassedToNonnull,
111*e038c9c4Sjoerg     CK_NullReturnedFromNonnull,
112*e038c9c4Sjoerg     CK_NullableDereferenced,
113*e038c9c4Sjoerg     CK_NullablePassedToNonnull,
114*e038c9c4Sjoerg     CK_NullableReturnedFromNonnull,
115*e038c9c4Sjoerg     CK_NumCheckKinds
1167330f729Sjoerg   };
1177330f729Sjoerg 
118*e038c9c4Sjoerg   DefaultBool ChecksEnabled[CK_NumCheckKinds];
119*e038c9c4Sjoerg   CheckerNameRef CheckNames[CK_NumCheckKinds];
120*e038c9c4Sjoerg   mutable std::unique_ptr<BugType> BTs[CK_NumCheckKinds];
121*e038c9c4Sjoerg 
getBugType(CheckKind Kind) const122*e038c9c4Sjoerg   const std::unique_ptr<BugType> &getBugType(CheckKind Kind) const {
123*e038c9c4Sjoerg     if (!BTs[Kind])
124*e038c9c4Sjoerg       BTs[Kind].reset(new BugType(CheckNames[Kind], "Nullability",
125*e038c9c4Sjoerg                                   categories::MemoryError));
126*e038c9c4Sjoerg     return BTs[Kind];
127*e038c9c4Sjoerg   }
128*e038c9c4Sjoerg 
1297330f729Sjoerg   // When set to false no nullability information will be tracked in
1307330f729Sjoerg   // NullabilityMap. It is possible to catch errors like passing a null pointer
1317330f729Sjoerg   // to a callee that expects nonnull argument without the information that is
1327330f729Sjoerg   // stroed in the NullabilityMap. This is an optimization.
1337330f729Sjoerg   DefaultBool NeedTracking;
1347330f729Sjoerg 
1357330f729Sjoerg private:
1367330f729Sjoerg   class NullabilityBugVisitor : public BugReporterVisitor {
1377330f729Sjoerg   public:
NullabilityBugVisitor(const MemRegion * M)1387330f729Sjoerg     NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
1397330f729Sjoerg 
Profile(llvm::FoldingSetNodeID & ID) const1407330f729Sjoerg     void Profile(llvm::FoldingSetNodeID &ID) const override {
1417330f729Sjoerg       static int X = 0;
1427330f729Sjoerg       ID.AddPointer(&X);
1437330f729Sjoerg       ID.AddPointer(Region);
1447330f729Sjoerg     }
1457330f729Sjoerg 
1467330f729Sjoerg     PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1477330f729Sjoerg                                      BugReporterContext &BRC,
1487330f729Sjoerg                                      PathSensitiveBugReport &BR) override;
1497330f729Sjoerg 
1507330f729Sjoerg   private:
1517330f729Sjoerg     // The tracked region.
1527330f729Sjoerg     const MemRegion *Region;
1537330f729Sjoerg   };
1547330f729Sjoerg 
1557330f729Sjoerg   /// When any of the nonnull arguments of the analyzed function is null, do not
1567330f729Sjoerg   /// report anything and turn off the check.
1577330f729Sjoerg   ///
1587330f729Sjoerg   /// When \p SuppressPath is set to true, no more bugs will be reported on this
1597330f729Sjoerg   /// path by this checker.
160*e038c9c4Sjoerg   void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
1617330f729Sjoerg                                  ExplodedNode *N, const MemRegion *Region,
1627330f729Sjoerg                                  CheckerContext &C,
1637330f729Sjoerg                                  const Stmt *ValueExpr = nullptr,
1647330f729Sjoerg                                  bool SuppressPath = false) const;
1657330f729Sjoerg 
reportBug(StringRef Msg,ErrorKind Error,CheckKind CK,ExplodedNode * N,const MemRegion * Region,BugReporter & BR,const Stmt * ValueExpr=nullptr) const166*e038c9c4Sjoerg   void reportBug(StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
1677330f729Sjoerg                  const MemRegion *Region, BugReporter &BR,
1687330f729Sjoerg                  const Stmt *ValueExpr = nullptr) const {
169*e038c9c4Sjoerg     const std::unique_ptr<BugType> &BT = getBugType(CK);
1707330f729Sjoerg     auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
1717330f729Sjoerg     if (Region) {
1727330f729Sjoerg       R->markInteresting(Region);
1737330f729Sjoerg       R->addVisitor(std::make_unique<NullabilityBugVisitor>(Region));
1747330f729Sjoerg     }
1757330f729Sjoerg     if (ValueExpr) {
1767330f729Sjoerg       R->addRange(ValueExpr->getSourceRange());
1777330f729Sjoerg       if (Error == ErrorKind::NilAssignedToNonnull ||
1787330f729Sjoerg           Error == ErrorKind::NilPassedToNonnull ||
1797330f729Sjoerg           Error == ErrorKind::NilReturnedToNonnull)
1807330f729Sjoerg         if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
1817330f729Sjoerg           bugreporter::trackExpressionValue(N, Ex, *R);
1827330f729Sjoerg     }
1837330f729Sjoerg     BR.emitReport(std::move(R));
1847330f729Sjoerg   }
1857330f729Sjoerg 
1867330f729Sjoerg   /// If an SVal wraps a region that should be tracked, it will return a pointer
1877330f729Sjoerg   /// to the wrapped region. Otherwise it will return a nullptr.
1887330f729Sjoerg   const SymbolicRegion *getTrackRegion(SVal Val,
1897330f729Sjoerg                                        bool CheckSuperRegion = false) const;
1907330f729Sjoerg 
1917330f729Sjoerg   /// Returns true if the call is diagnosable in the current analyzer
1927330f729Sjoerg   /// configuration.
isDiagnosableCall(const CallEvent & Call) const1937330f729Sjoerg   bool isDiagnosableCall(const CallEvent &Call) const {
1947330f729Sjoerg     if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
1957330f729Sjoerg       return false;
1967330f729Sjoerg 
1977330f729Sjoerg     return true;
1987330f729Sjoerg   }
1997330f729Sjoerg };
2007330f729Sjoerg 
2017330f729Sjoerg class NullabilityState {
2027330f729Sjoerg public:
NullabilityState(Nullability Nullab,const Stmt * Source=nullptr)2037330f729Sjoerg   NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
2047330f729Sjoerg       : Nullab(Nullab), Source(Source) {}
2057330f729Sjoerg 
getNullabilitySource() const2067330f729Sjoerg   const Stmt *getNullabilitySource() const { return Source; }
2077330f729Sjoerg 
getValue() const2087330f729Sjoerg   Nullability getValue() const { return Nullab; }
2097330f729Sjoerg 
Profile(llvm::FoldingSetNodeID & ID) const2107330f729Sjoerg   void Profile(llvm::FoldingSetNodeID &ID) const {
2117330f729Sjoerg     ID.AddInteger(static_cast<char>(Nullab));
2127330f729Sjoerg     ID.AddPointer(Source);
2137330f729Sjoerg   }
2147330f729Sjoerg 
print(raw_ostream & Out) const2157330f729Sjoerg   void print(raw_ostream &Out) const {
2167330f729Sjoerg     Out << getNullabilityString(Nullab) << "\n";
2177330f729Sjoerg   }
2187330f729Sjoerg 
2197330f729Sjoerg private:
2207330f729Sjoerg   Nullability Nullab;
2217330f729Sjoerg   // Source is the expression which determined the nullability. For example in a
2227330f729Sjoerg   // message like [nullable nonnull_returning] has nullable nullability, because
2237330f729Sjoerg   // the receiver is nullable. Here the receiver will be the source of the
2247330f729Sjoerg   // nullability. This is useful information when the diagnostics are generated.
2257330f729Sjoerg   const Stmt *Source;
2267330f729Sjoerg };
2277330f729Sjoerg 
operator ==(NullabilityState Lhs,NullabilityState Rhs)2287330f729Sjoerg bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
2297330f729Sjoerg   return Lhs.getValue() == Rhs.getValue() &&
2307330f729Sjoerg          Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
2317330f729Sjoerg }
2327330f729Sjoerg 
2337330f729Sjoerg } // end anonymous namespace
2347330f729Sjoerg 
2357330f729Sjoerg REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
2367330f729Sjoerg                                NullabilityState)
2377330f729Sjoerg 
2387330f729Sjoerg // We say "the nullability type invariant is violated" when a location with a
2397330f729Sjoerg // non-null type contains NULL or a function with a non-null return type returns
2407330f729Sjoerg // NULL. Violations of the nullability type invariant can be detected either
2417330f729Sjoerg // directly (for example, when NULL is passed as an argument to a nonnull
2427330f729Sjoerg // parameter) or indirectly (for example, when, inside a function, the
2437330f729Sjoerg // programmer defensively checks whether a nonnull parameter contains NULL and
2447330f729Sjoerg // finds that it does).
2457330f729Sjoerg //
2467330f729Sjoerg // As a matter of policy, the nullability checker typically warns on direct
2477330f729Sjoerg // violations of the nullability invariant (although it uses various
2487330f729Sjoerg // heuristics to suppress warnings in some cases) but will not warn if the
2497330f729Sjoerg // invariant has already been violated along the path (either directly or
2507330f729Sjoerg // indirectly). As a practical matter, this prevents the analyzer from
2517330f729Sjoerg // (1) warning on defensive code paths where a nullability precondition is
2527330f729Sjoerg // determined to have been violated, (2) warning additional times after an
2537330f729Sjoerg // initial direct violation has been discovered, and (3) warning after a direct
2547330f729Sjoerg // violation that has been implicitly or explicitly suppressed (for
2557330f729Sjoerg // example, with a cast of NULL to _Nonnull). In essence, once an invariant
2567330f729Sjoerg // violation is detected on a path, this checker will be essentially turned off
2577330f729Sjoerg // for the rest of the analysis
2587330f729Sjoerg //
2597330f729Sjoerg // The analyzer takes this approach (rather than generating a sink node) to
2607330f729Sjoerg // ensure coverage of defensive paths, which may be important for backwards
2617330f729Sjoerg // compatibility in codebases that were developed without nullability in mind.
2627330f729Sjoerg REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
2637330f729Sjoerg 
2647330f729Sjoerg enum class NullConstraint { IsNull, IsNotNull, Unknown };
2657330f729Sjoerg 
getNullConstraint(DefinedOrUnknownSVal Val,ProgramStateRef State)2667330f729Sjoerg static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
2677330f729Sjoerg                                         ProgramStateRef State) {
2687330f729Sjoerg   ConditionTruthVal Nullness = State->isNull(Val);
2697330f729Sjoerg   if (Nullness.isConstrainedFalse())
2707330f729Sjoerg     return NullConstraint::IsNotNull;
2717330f729Sjoerg   if (Nullness.isConstrainedTrue())
2727330f729Sjoerg     return NullConstraint::IsNull;
2737330f729Sjoerg   return NullConstraint::Unknown;
2747330f729Sjoerg }
2757330f729Sjoerg 
2767330f729Sjoerg const SymbolicRegion *
getTrackRegion(SVal Val,bool CheckSuperRegion) const2777330f729Sjoerg NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
2787330f729Sjoerg   if (!NeedTracking)
2797330f729Sjoerg     return nullptr;
2807330f729Sjoerg 
2817330f729Sjoerg   auto RegionSVal = Val.getAs<loc::MemRegionVal>();
2827330f729Sjoerg   if (!RegionSVal)
2837330f729Sjoerg     return nullptr;
2847330f729Sjoerg 
2857330f729Sjoerg   const MemRegion *Region = RegionSVal->getRegion();
2867330f729Sjoerg 
2877330f729Sjoerg   if (CheckSuperRegion) {
2887330f729Sjoerg     if (auto FieldReg = Region->getAs<FieldRegion>())
2897330f729Sjoerg       return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
2907330f729Sjoerg     if (auto ElementReg = Region->getAs<ElementRegion>())
2917330f729Sjoerg       return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
2927330f729Sjoerg   }
2937330f729Sjoerg 
2947330f729Sjoerg   return dyn_cast<SymbolicRegion>(Region);
2957330f729Sjoerg }
2967330f729Sjoerg 
VisitNode(const ExplodedNode * N,BugReporterContext & BRC,PathSensitiveBugReport & BR)2977330f729Sjoerg PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
2987330f729Sjoerg     const ExplodedNode *N, BugReporterContext &BRC,
2997330f729Sjoerg     PathSensitiveBugReport &BR) {
3007330f729Sjoerg   ProgramStateRef State = N->getState();
3017330f729Sjoerg   ProgramStateRef StatePrev = N->getFirstPred()->getState();
3027330f729Sjoerg 
3037330f729Sjoerg   const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
3047330f729Sjoerg   const NullabilityState *TrackedNullabPrev =
3057330f729Sjoerg       StatePrev->get<NullabilityMap>(Region);
3067330f729Sjoerg   if (!TrackedNullab)
3077330f729Sjoerg     return nullptr;
3087330f729Sjoerg 
3097330f729Sjoerg   if (TrackedNullabPrev &&
3107330f729Sjoerg       TrackedNullabPrev->getValue() == TrackedNullab->getValue())
3117330f729Sjoerg     return nullptr;
3127330f729Sjoerg 
3137330f729Sjoerg   // Retrieve the associated statement.
3147330f729Sjoerg   const Stmt *S = TrackedNullab->getNullabilitySource();
3157330f729Sjoerg   if (!S || S->getBeginLoc().isInvalid()) {
3167330f729Sjoerg     S = N->getStmtForDiagnostics();
3177330f729Sjoerg   }
3187330f729Sjoerg 
3197330f729Sjoerg   if (!S)
3207330f729Sjoerg     return nullptr;
3217330f729Sjoerg 
3227330f729Sjoerg   std::string InfoText =
3237330f729Sjoerg       (llvm::Twine("Nullability '") +
3247330f729Sjoerg        getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
3257330f729Sjoerg           .str();
3267330f729Sjoerg 
3277330f729Sjoerg   // Generate the extra diagnostic.
3287330f729Sjoerg   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
3297330f729Sjoerg                              N->getLocationContext());
3307330f729Sjoerg   return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
3317330f729Sjoerg }
3327330f729Sjoerg 
3337330f729Sjoerg /// Returns true when the value stored at the given location has been
3347330f729Sjoerg /// constrained to null after being passed through an object of nonnnull type.
checkValueAtLValForInvariantViolation(ProgramStateRef State,SVal LV,QualType T)3357330f729Sjoerg static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
3367330f729Sjoerg                                                   SVal LV, QualType T) {
3377330f729Sjoerg   if (getNullabilityAnnotation(T) != Nullability::Nonnull)
3387330f729Sjoerg     return false;
3397330f729Sjoerg 
3407330f729Sjoerg   auto RegionVal = LV.getAs<loc::MemRegionVal>();
3417330f729Sjoerg   if (!RegionVal)
3427330f729Sjoerg     return false;
3437330f729Sjoerg 
3447330f729Sjoerg   // If the value was constrained to null *after* it was passed through that
3457330f729Sjoerg   // location, it could not have been a concrete pointer *when* it was passed.
3467330f729Sjoerg   // In that case we would have handled the situation when the value was
3477330f729Sjoerg   // bound to that location, by emitting (or not emitting) a report.
3487330f729Sjoerg   // Therefore we are only interested in symbolic regions that can be either
3497330f729Sjoerg   // null or non-null depending on the value of their respective symbol.
3507330f729Sjoerg   auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
3517330f729Sjoerg   if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
3527330f729Sjoerg     return false;
3537330f729Sjoerg 
3547330f729Sjoerg   if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
3557330f729Sjoerg     return true;
3567330f729Sjoerg 
3577330f729Sjoerg   return false;
3587330f729Sjoerg }
3597330f729Sjoerg 
3607330f729Sjoerg static bool
checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl * > Params,ProgramStateRef State,const LocationContext * LocCtxt)3617330f729Sjoerg checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
3627330f729Sjoerg                                     ProgramStateRef State,
3637330f729Sjoerg                                     const LocationContext *LocCtxt) {
3647330f729Sjoerg   for (const auto *ParamDecl : Params) {
3657330f729Sjoerg     if (ParamDecl->isParameterPack())
3667330f729Sjoerg       break;
3677330f729Sjoerg 
3687330f729Sjoerg     SVal LV = State->getLValue(ParamDecl, LocCtxt);
3697330f729Sjoerg     if (checkValueAtLValForInvariantViolation(State, LV,
3707330f729Sjoerg                                               ParamDecl->getType())) {
3717330f729Sjoerg       return true;
3727330f729Sjoerg     }
3737330f729Sjoerg   }
3747330f729Sjoerg   return false;
3757330f729Sjoerg }
3767330f729Sjoerg 
3777330f729Sjoerg static bool
checkSelfIvarsForInvariantViolation(ProgramStateRef State,const LocationContext * LocCtxt)3787330f729Sjoerg checkSelfIvarsForInvariantViolation(ProgramStateRef State,
3797330f729Sjoerg                                     const LocationContext *LocCtxt) {
3807330f729Sjoerg   auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
3817330f729Sjoerg   if (!MD || !MD->isInstanceMethod())
3827330f729Sjoerg     return false;
3837330f729Sjoerg 
3847330f729Sjoerg   const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
3857330f729Sjoerg   if (!SelfDecl)
3867330f729Sjoerg     return false;
3877330f729Sjoerg 
3887330f729Sjoerg   SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
3897330f729Sjoerg 
3907330f729Sjoerg   const ObjCObjectPointerType *SelfType =
3917330f729Sjoerg       dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
3927330f729Sjoerg   if (!SelfType)
3937330f729Sjoerg     return false;
3947330f729Sjoerg 
3957330f729Sjoerg   const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
3967330f729Sjoerg   if (!ID)
3977330f729Sjoerg     return false;
3987330f729Sjoerg 
3997330f729Sjoerg   for (const auto *IvarDecl : ID->ivars()) {
4007330f729Sjoerg     SVal LV = State->getLValue(IvarDecl, SelfVal);
4017330f729Sjoerg     if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
4027330f729Sjoerg       return true;
4037330f729Sjoerg     }
4047330f729Sjoerg   }
4057330f729Sjoerg   return false;
4067330f729Sjoerg }
4077330f729Sjoerg 
checkInvariantViolation(ProgramStateRef State,ExplodedNode * N,CheckerContext & C)4087330f729Sjoerg static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
4097330f729Sjoerg                                     CheckerContext &C) {
4107330f729Sjoerg   if (State->get<InvariantViolated>())
4117330f729Sjoerg     return true;
4127330f729Sjoerg 
4137330f729Sjoerg   const LocationContext *LocCtxt = C.getLocationContext();
4147330f729Sjoerg   const Decl *D = LocCtxt->getDecl();
4157330f729Sjoerg   if (!D)
4167330f729Sjoerg     return false;
4177330f729Sjoerg 
4187330f729Sjoerg   ArrayRef<ParmVarDecl*> Params;
4197330f729Sjoerg   if (const auto *BD = dyn_cast<BlockDecl>(D))
4207330f729Sjoerg     Params = BD->parameters();
4217330f729Sjoerg   else if (const auto *FD = dyn_cast<FunctionDecl>(D))
4227330f729Sjoerg     Params = FD->parameters();
4237330f729Sjoerg   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
4247330f729Sjoerg     Params = MD->parameters();
4257330f729Sjoerg   else
4267330f729Sjoerg     return false;
4277330f729Sjoerg 
4287330f729Sjoerg   if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
4297330f729Sjoerg       checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
4307330f729Sjoerg     if (!N->isSink())
4317330f729Sjoerg       C.addTransition(State->set<InvariantViolated>(true), N);
4327330f729Sjoerg     return true;
4337330f729Sjoerg   }
4347330f729Sjoerg   return false;
4357330f729Sjoerg }
4367330f729Sjoerg 
reportBugIfInvariantHolds(StringRef Msg,ErrorKind Error,CheckKind CK,ExplodedNode * N,const MemRegion * Region,CheckerContext & C,const Stmt * ValueExpr,bool SuppressPath) const437*e038c9c4Sjoerg void NullabilityChecker::reportBugIfInvariantHolds(
438*e038c9c4Sjoerg     StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
439*e038c9c4Sjoerg     const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
440*e038c9c4Sjoerg     bool SuppressPath) const {
4417330f729Sjoerg   ProgramStateRef OriginalState = N->getState();
4427330f729Sjoerg 
4437330f729Sjoerg   if (checkInvariantViolation(OriginalState, N, C))
4447330f729Sjoerg     return;
4457330f729Sjoerg   if (SuppressPath) {
4467330f729Sjoerg     OriginalState = OriginalState->set<InvariantViolated>(true);
4477330f729Sjoerg     N = C.addTransition(OriginalState, N);
4487330f729Sjoerg   }
4497330f729Sjoerg 
450*e038c9c4Sjoerg   reportBug(Msg, Error, CK, N, Region, C.getBugReporter(), ValueExpr);
4517330f729Sjoerg }
4527330f729Sjoerg 
4537330f729Sjoerg /// Cleaning up the program state.
checkDeadSymbols(SymbolReaper & SR,CheckerContext & C) const4547330f729Sjoerg void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
4557330f729Sjoerg                                           CheckerContext &C) const {
4567330f729Sjoerg   ProgramStateRef State = C.getState();
4577330f729Sjoerg   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
4587330f729Sjoerg   for (NullabilityMapTy::iterator I = Nullabilities.begin(),
4597330f729Sjoerg                                   E = Nullabilities.end();
4607330f729Sjoerg        I != E; ++I) {
4617330f729Sjoerg     const auto *Region = I->first->getAs<SymbolicRegion>();
4627330f729Sjoerg     assert(Region && "Non-symbolic region is tracked.");
4637330f729Sjoerg     if (SR.isDead(Region->getSymbol())) {
4647330f729Sjoerg       State = State->remove<NullabilityMap>(I->first);
4657330f729Sjoerg     }
4667330f729Sjoerg   }
4677330f729Sjoerg   // When one of the nonnull arguments are constrained to be null, nullability
4687330f729Sjoerg   // preconditions are violated. It is not enough to check this only when we
4697330f729Sjoerg   // actually report an error, because at that time interesting symbols might be
4707330f729Sjoerg   // reaped.
4717330f729Sjoerg   if (checkInvariantViolation(State, C.getPredecessor(), C))
4727330f729Sjoerg     return;
4737330f729Sjoerg   C.addTransition(State);
4747330f729Sjoerg }
4757330f729Sjoerg 
4767330f729Sjoerg /// This callback triggers when a pointer is dereferenced and the analyzer does
4777330f729Sjoerg /// not know anything about the value of that pointer. When that pointer is
4787330f729Sjoerg /// nullable, this code emits a warning.
checkEvent(ImplicitNullDerefEvent Event) const4797330f729Sjoerg void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
4807330f729Sjoerg   if (Event.SinkNode->getState()->get<InvariantViolated>())
4817330f729Sjoerg     return;
4827330f729Sjoerg 
4837330f729Sjoerg   const MemRegion *Region =
4847330f729Sjoerg       getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
4857330f729Sjoerg   if (!Region)
4867330f729Sjoerg     return;
4877330f729Sjoerg 
4887330f729Sjoerg   ProgramStateRef State = Event.SinkNode->getState();
4897330f729Sjoerg   const NullabilityState *TrackedNullability =
4907330f729Sjoerg       State->get<NullabilityMap>(Region);
4917330f729Sjoerg 
4927330f729Sjoerg   if (!TrackedNullability)
4937330f729Sjoerg     return;
4947330f729Sjoerg 
495*e038c9c4Sjoerg   if (ChecksEnabled[CK_NullableDereferenced] &&
4967330f729Sjoerg       TrackedNullability->getValue() == Nullability::Nullable) {
4977330f729Sjoerg     BugReporter &BR = *Event.BR;
4987330f729Sjoerg     // Do not suppress errors on defensive code paths, because dereferencing
4997330f729Sjoerg     // a nullable pointer is always an error.
5007330f729Sjoerg     if (Event.IsDirectDereference)
5017330f729Sjoerg       reportBug("Nullable pointer is dereferenced",
502*e038c9c4Sjoerg                 ErrorKind::NullableDereferenced, CK_NullableDereferenced,
503*e038c9c4Sjoerg                 Event.SinkNode, Region, BR);
5047330f729Sjoerg     else {
5057330f729Sjoerg       reportBug("Nullable pointer is passed to a callee that requires a "
506*e038c9c4Sjoerg                 "non-null",
507*e038c9c4Sjoerg                 ErrorKind::NullablePassedToNonnull, CK_NullableDereferenced,
5087330f729Sjoerg                 Event.SinkNode, Region, BR);
5097330f729Sjoerg     }
5107330f729Sjoerg   }
5117330f729Sjoerg }
5127330f729Sjoerg 
513*e038c9c4Sjoerg // Whenever we see a load from a typed memory region that's been annotated as
514*e038c9c4Sjoerg // 'nonnull', we want to trust the user on that and assume that it is is indeed
515*e038c9c4Sjoerg // non-null.
516*e038c9c4Sjoerg //
517*e038c9c4Sjoerg // We do so even if the value is known to have been assigned to null.
518*e038c9c4Sjoerg // The user should be warned on assigning the null value to a non-null pointer
519*e038c9c4Sjoerg // as opposed to warning on the later dereference of this pointer.
520*e038c9c4Sjoerg //
521*e038c9c4Sjoerg // \code
522*e038c9c4Sjoerg //   int * _Nonnull var = 0; // we want to warn the user here...
523*e038c9c4Sjoerg //   // . . .
524*e038c9c4Sjoerg //   *var = 42;              // ...and not here
525*e038c9c4Sjoerg // \endcode
checkLocation(SVal Location,bool IsLoad,const Stmt * S,CheckerContext & Context) const526*e038c9c4Sjoerg void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
527*e038c9c4Sjoerg                                        const Stmt *S,
528*e038c9c4Sjoerg                                        CheckerContext &Context) const {
529*e038c9c4Sjoerg   // We should care only about loads.
530*e038c9c4Sjoerg   // The main idea is to add a constraint whenever we're loading a value from
531*e038c9c4Sjoerg   // an annotated pointer type.
532*e038c9c4Sjoerg   if (!IsLoad)
533*e038c9c4Sjoerg     return;
534*e038c9c4Sjoerg 
535*e038c9c4Sjoerg   // Annotations that we want to consider make sense only for types.
536*e038c9c4Sjoerg   const auto *Region =
537*e038c9c4Sjoerg       dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
538*e038c9c4Sjoerg   if (!Region)
539*e038c9c4Sjoerg     return;
540*e038c9c4Sjoerg 
541*e038c9c4Sjoerg   ProgramStateRef State = Context.getState();
542*e038c9c4Sjoerg 
543*e038c9c4Sjoerg   auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
544*e038c9c4Sjoerg   if (!StoredVal)
545*e038c9c4Sjoerg     return;
546*e038c9c4Sjoerg 
547*e038c9c4Sjoerg   Nullability NullabilityOfTheLoadedValue =
548*e038c9c4Sjoerg       getNullabilityAnnotation(Region->getValueType());
549*e038c9c4Sjoerg 
550*e038c9c4Sjoerg   if (NullabilityOfTheLoadedValue == Nullability::Nonnull) {
551*e038c9c4Sjoerg     // It doesn't matter what we think about this particular pointer, it should
552*e038c9c4Sjoerg     // be considered non-null as annotated by the developer.
553*e038c9c4Sjoerg     if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
554*e038c9c4Sjoerg       Context.addTransition(NewState);
555*e038c9c4Sjoerg     }
556*e038c9c4Sjoerg   }
557*e038c9c4Sjoerg }
558*e038c9c4Sjoerg 
5597330f729Sjoerg /// Find the outermost subexpression of E that is not an implicit cast.
5607330f729Sjoerg /// This looks through the implicit casts to _Nonnull that ARC adds to
5617330f729Sjoerg /// return expressions of ObjC types when the return type of the function or
5627330f729Sjoerg /// method is non-null but the express is not.
lookThroughImplicitCasts(const Expr * E)5637330f729Sjoerg static const Expr *lookThroughImplicitCasts(const Expr *E) {
564*e038c9c4Sjoerg   return E->IgnoreImpCasts();
5657330f729Sjoerg }
5667330f729Sjoerg 
5677330f729Sjoerg /// This method check when nullable pointer or null value is returned from a
5687330f729Sjoerg /// function that has nonnull return type.
checkPreStmt(const ReturnStmt * S,CheckerContext & C) const5697330f729Sjoerg void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
5707330f729Sjoerg                                       CheckerContext &C) const {
5717330f729Sjoerg   auto RetExpr = S->getRetValue();
5727330f729Sjoerg   if (!RetExpr)
5737330f729Sjoerg     return;
5747330f729Sjoerg 
5757330f729Sjoerg   if (!RetExpr->getType()->isAnyPointerType())
5767330f729Sjoerg     return;
5777330f729Sjoerg 
5787330f729Sjoerg   ProgramStateRef State = C.getState();
5797330f729Sjoerg   if (State->get<InvariantViolated>())
5807330f729Sjoerg     return;
5817330f729Sjoerg 
5827330f729Sjoerg   auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
5837330f729Sjoerg   if (!RetSVal)
5847330f729Sjoerg     return;
5857330f729Sjoerg 
5867330f729Sjoerg   bool InSuppressedMethodFamily = false;
5877330f729Sjoerg 
5887330f729Sjoerg   QualType RequiredRetType;
5897330f729Sjoerg   AnalysisDeclContext *DeclCtxt =
5907330f729Sjoerg       C.getLocationContext()->getAnalysisDeclContext();
5917330f729Sjoerg   const Decl *D = DeclCtxt->getDecl();
5927330f729Sjoerg   if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5937330f729Sjoerg     // HACK: This is a big hammer to avoid warning when there are defensive
5947330f729Sjoerg     // nil checks in -init and -copy methods. We should add more sophisticated
5957330f729Sjoerg     // logic here to suppress on common defensive idioms but still
5967330f729Sjoerg     // warn when there is a likely problem.
5977330f729Sjoerg     ObjCMethodFamily Family = MD->getMethodFamily();
5987330f729Sjoerg     if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
5997330f729Sjoerg       InSuppressedMethodFamily = true;
6007330f729Sjoerg 
6017330f729Sjoerg     RequiredRetType = MD->getReturnType();
6027330f729Sjoerg   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6037330f729Sjoerg     RequiredRetType = FD->getReturnType();
6047330f729Sjoerg   } else {
6057330f729Sjoerg     return;
6067330f729Sjoerg   }
6077330f729Sjoerg 
6087330f729Sjoerg   NullConstraint Nullness = getNullConstraint(*RetSVal, State);
6097330f729Sjoerg 
6107330f729Sjoerg   Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
6117330f729Sjoerg 
6127330f729Sjoerg   // If the returned value is null but the type of the expression
6137330f729Sjoerg   // generating it is nonnull then we will suppress the diagnostic.
6147330f729Sjoerg   // This enables explicit suppression when returning a nil literal in a
6157330f729Sjoerg   // function with a _Nonnull return type:
6167330f729Sjoerg   //    return (NSString * _Nonnull)0;
6177330f729Sjoerg   Nullability RetExprTypeLevelNullability =
6187330f729Sjoerg         getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
6197330f729Sjoerg 
6207330f729Sjoerg   bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
6217330f729Sjoerg                                   Nullness == NullConstraint::IsNull);
622*e038c9c4Sjoerg   if (ChecksEnabled[CK_NullReturnedFromNonnull] && NullReturnedFromNonNull &&
6237330f729Sjoerg       RetExprTypeLevelNullability != Nullability::Nonnull &&
624*e038c9c4Sjoerg       !InSuppressedMethodFamily && C.getLocationContext()->inTopFrame()) {
6257330f729Sjoerg     static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
6267330f729Sjoerg     ExplodedNode *N = C.generateErrorNode(State, &Tag);
6277330f729Sjoerg     if (!N)
6287330f729Sjoerg       return;
6297330f729Sjoerg 
6307330f729Sjoerg     SmallString<256> SBuf;
6317330f729Sjoerg     llvm::raw_svector_ostream OS(SBuf);
6327330f729Sjoerg     OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
6337330f729Sjoerg     OS << " returned from a " << C.getDeclDescription(D) <<
6347330f729Sjoerg           " that is expected to return a non-null value";
635*e038c9c4Sjoerg     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
636*e038c9c4Sjoerg                               CK_NullReturnedFromNonnull, N, nullptr, C,
6377330f729Sjoerg                               RetExpr);
6387330f729Sjoerg     return;
6397330f729Sjoerg   }
6407330f729Sjoerg 
6417330f729Sjoerg   // If null was returned from a non-null function, mark the nullability
6427330f729Sjoerg   // invariant as violated even if the diagnostic was suppressed.
6437330f729Sjoerg   if (NullReturnedFromNonNull) {
6447330f729Sjoerg     State = State->set<InvariantViolated>(true);
6457330f729Sjoerg     C.addTransition(State);
6467330f729Sjoerg     return;
6477330f729Sjoerg   }
6487330f729Sjoerg 
6497330f729Sjoerg   const MemRegion *Region = getTrackRegion(*RetSVal);
6507330f729Sjoerg   if (!Region)
6517330f729Sjoerg     return;
6527330f729Sjoerg 
6537330f729Sjoerg   const NullabilityState *TrackedNullability =
6547330f729Sjoerg       State->get<NullabilityMap>(Region);
6557330f729Sjoerg   if (TrackedNullability) {
6567330f729Sjoerg     Nullability TrackedNullabValue = TrackedNullability->getValue();
657*e038c9c4Sjoerg     if (ChecksEnabled[CK_NullableReturnedFromNonnull] &&
6587330f729Sjoerg         Nullness != NullConstraint::IsNotNull &&
6597330f729Sjoerg         TrackedNullabValue == Nullability::Nullable &&
6607330f729Sjoerg         RequiredNullability == Nullability::Nonnull) {
6617330f729Sjoerg       static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
6627330f729Sjoerg       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
6637330f729Sjoerg 
6647330f729Sjoerg       SmallString<256> SBuf;
6657330f729Sjoerg       llvm::raw_svector_ostream OS(SBuf);
6667330f729Sjoerg       OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
6677330f729Sjoerg             " that is expected to return a non-null value";
6687330f729Sjoerg 
669*e038c9c4Sjoerg       reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
670*e038c9c4Sjoerg                                 CK_NullableReturnedFromNonnull, N, Region, C);
6717330f729Sjoerg     }
6727330f729Sjoerg     return;
6737330f729Sjoerg   }
6747330f729Sjoerg   if (RequiredNullability == Nullability::Nullable) {
6757330f729Sjoerg     State = State->set<NullabilityMap>(Region,
6767330f729Sjoerg                                        NullabilityState(RequiredNullability,
6777330f729Sjoerg                                                         S));
6787330f729Sjoerg     C.addTransition(State);
6797330f729Sjoerg   }
6807330f729Sjoerg }
6817330f729Sjoerg 
6827330f729Sjoerg /// This callback warns when a nullable pointer or a null value is passed to a
6837330f729Sjoerg /// function that expects its argument to be nonnull.
checkPreCall(const CallEvent & Call,CheckerContext & C) const6847330f729Sjoerg void NullabilityChecker::checkPreCall(const CallEvent &Call,
6857330f729Sjoerg                                       CheckerContext &C) const {
6867330f729Sjoerg   if (!Call.getDecl())
6877330f729Sjoerg     return;
6887330f729Sjoerg 
6897330f729Sjoerg   ProgramStateRef State = C.getState();
6907330f729Sjoerg   if (State->get<InvariantViolated>())
6917330f729Sjoerg     return;
6927330f729Sjoerg 
6937330f729Sjoerg   ProgramStateRef OrigState = State;
6947330f729Sjoerg 
6957330f729Sjoerg   unsigned Idx = 0;
6967330f729Sjoerg   for (const ParmVarDecl *Param : Call.parameters()) {
6977330f729Sjoerg     if (Param->isParameterPack())
6987330f729Sjoerg       break;
6997330f729Sjoerg 
7007330f729Sjoerg     if (Idx >= Call.getNumArgs())
7017330f729Sjoerg       break;
7027330f729Sjoerg 
7037330f729Sjoerg     const Expr *ArgExpr = Call.getArgExpr(Idx);
7047330f729Sjoerg     auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
7057330f729Sjoerg     if (!ArgSVal)
7067330f729Sjoerg       continue;
7077330f729Sjoerg 
7087330f729Sjoerg     if (!Param->getType()->isAnyPointerType() &&
7097330f729Sjoerg         !Param->getType()->isReferenceType())
7107330f729Sjoerg       continue;
7117330f729Sjoerg 
7127330f729Sjoerg     NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
7137330f729Sjoerg 
7147330f729Sjoerg     Nullability RequiredNullability =
7157330f729Sjoerg         getNullabilityAnnotation(Param->getType());
7167330f729Sjoerg     Nullability ArgExprTypeLevelNullability =
7177330f729Sjoerg         getNullabilityAnnotation(ArgExpr->getType());
7187330f729Sjoerg 
7197330f729Sjoerg     unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
7207330f729Sjoerg 
721*e038c9c4Sjoerg     if (ChecksEnabled[CK_NullPassedToNonnull] &&
722*e038c9c4Sjoerg         Nullness == NullConstraint::IsNull &&
7237330f729Sjoerg         ArgExprTypeLevelNullability != Nullability::Nonnull &&
7247330f729Sjoerg         RequiredNullability == Nullability::Nonnull &&
7257330f729Sjoerg         isDiagnosableCall(Call)) {
7267330f729Sjoerg       ExplodedNode *N = C.generateErrorNode(State);
7277330f729Sjoerg       if (!N)
7287330f729Sjoerg         return;
7297330f729Sjoerg 
7307330f729Sjoerg       SmallString<256> SBuf;
7317330f729Sjoerg       llvm::raw_svector_ostream OS(SBuf);
7327330f729Sjoerg       OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
7337330f729Sjoerg       OS << " passed to a callee that requires a non-null " << ParamIdx
7347330f729Sjoerg          << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
735*e038c9c4Sjoerg       reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
736*e038c9c4Sjoerg                                 CK_NullPassedToNonnull, N, nullptr, C, ArgExpr,
737*e038c9c4Sjoerg                                 /*SuppressPath=*/false);
7387330f729Sjoerg       return;
7397330f729Sjoerg     }
7407330f729Sjoerg 
7417330f729Sjoerg     const MemRegion *Region = getTrackRegion(*ArgSVal);
7427330f729Sjoerg     if (!Region)
7437330f729Sjoerg       continue;
7447330f729Sjoerg 
7457330f729Sjoerg     const NullabilityState *TrackedNullability =
7467330f729Sjoerg         State->get<NullabilityMap>(Region);
7477330f729Sjoerg 
7487330f729Sjoerg     if (TrackedNullability) {
7497330f729Sjoerg       if (Nullness == NullConstraint::IsNotNull ||
7507330f729Sjoerg           TrackedNullability->getValue() != Nullability::Nullable)
7517330f729Sjoerg         continue;
7527330f729Sjoerg 
753*e038c9c4Sjoerg       if (ChecksEnabled[CK_NullablePassedToNonnull] &&
7547330f729Sjoerg           RequiredNullability == Nullability::Nonnull &&
7557330f729Sjoerg           isDiagnosableCall(Call)) {
7567330f729Sjoerg         ExplodedNode *N = C.addTransition(State);
7577330f729Sjoerg         SmallString<256> SBuf;
7587330f729Sjoerg         llvm::raw_svector_ostream OS(SBuf);
7597330f729Sjoerg         OS << "Nullable pointer is passed to a callee that requires a non-null "
7607330f729Sjoerg            << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
761*e038c9c4Sjoerg         reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
762*e038c9c4Sjoerg                                   CK_NullablePassedToNonnull, N, Region, C,
763*e038c9c4Sjoerg                                   ArgExpr, /*SuppressPath=*/true);
7647330f729Sjoerg         return;
7657330f729Sjoerg       }
766*e038c9c4Sjoerg       if (ChecksEnabled[CK_NullableDereferenced] &&
7677330f729Sjoerg           Param->getType()->isReferenceType()) {
7687330f729Sjoerg         ExplodedNode *N = C.addTransition(State);
7697330f729Sjoerg         reportBugIfInvariantHolds("Nullable pointer is dereferenced",
770*e038c9c4Sjoerg                                   ErrorKind::NullableDereferenced,
771*e038c9c4Sjoerg                                   CK_NullableDereferenced, N, Region, C,
772*e038c9c4Sjoerg                                   ArgExpr, /*SuppressPath=*/true);
7737330f729Sjoerg         return;
7747330f729Sjoerg       }
7757330f729Sjoerg       continue;
7767330f729Sjoerg     }
7777330f729Sjoerg   }
7787330f729Sjoerg   if (State != OrigState)
7797330f729Sjoerg     C.addTransition(State);
7807330f729Sjoerg }
7817330f729Sjoerg 
7827330f729Sjoerg /// Suppress the nullability warnings for some functions.
checkPostCall(const CallEvent & Call,CheckerContext & C) const7837330f729Sjoerg void NullabilityChecker::checkPostCall(const CallEvent &Call,
7847330f729Sjoerg                                        CheckerContext &C) const {
7857330f729Sjoerg   auto Decl = Call.getDecl();
7867330f729Sjoerg   if (!Decl)
7877330f729Sjoerg     return;
7887330f729Sjoerg   // ObjC Messages handles in a different callback.
7897330f729Sjoerg   if (Call.getKind() == CE_ObjCMessage)
7907330f729Sjoerg     return;
7917330f729Sjoerg   const FunctionType *FuncType = Decl->getFunctionType();
7927330f729Sjoerg   if (!FuncType)
7937330f729Sjoerg     return;
7947330f729Sjoerg   QualType ReturnType = FuncType->getReturnType();
7957330f729Sjoerg   if (!ReturnType->isAnyPointerType())
7967330f729Sjoerg     return;
7977330f729Sjoerg   ProgramStateRef State = C.getState();
7987330f729Sjoerg   if (State->get<InvariantViolated>())
7997330f729Sjoerg     return;
8007330f729Sjoerg 
8017330f729Sjoerg   const MemRegion *Region = getTrackRegion(Call.getReturnValue());
8027330f729Sjoerg   if (!Region)
8037330f729Sjoerg     return;
8047330f729Sjoerg 
8057330f729Sjoerg   // CG headers are misannotated. Do not warn for symbols that are the results
8067330f729Sjoerg   // of CG calls.
8077330f729Sjoerg   const SourceManager &SM = C.getSourceManager();
8087330f729Sjoerg   StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
8097330f729Sjoerg   if (llvm::sys::path::filename(FilePath).startswith("CG")) {
8107330f729Sjoerg     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
8117330f729Sjoerg     C.addTransition(State);
8127330f729Sjoerg     return;
8137330f729Sjoerg   }
8147330f729Sjoerg 
8157330f729Sjoerg   const NullabilityState *TrackedNullability =
8167330f729Sjoerg       State->get<NullabilityMap>(Region);
8177330f729Sjoerg 
8187330f729Sjoerg   if (!TrackedNullability &&
8197330f729Sjoerg       getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
8207330f729Sjoerg     State = State->set<NullabilityMap>(Region, Nullability::Nullable);
8217330f729Sjoerg     C.addTransition(State);
8227330f729Sjoerg   }
8237330f729Sjoerg }
8247330f729Sjoerg 
getReceiverNullability(const ObjCMethodCall & M,ProgramStateRef State)8257330f729Sjoerg static Nullability getReceiverNullability(const ObjCMethodCall &M,
8267330f729Sjoerg                                           ProgramStateRef State) {
8277330f729Sjoerg   if (M.isReceiverSelfOrSuper()) {
8287330f729Sjoerg     // For super and super class receivers we assume that the receiver is
8297330f729Sjoerg     // nonnull.
8307330f729Sjoerg     return Nullability::Nonnull;
8317330f729Sjoerg   }
8327330f729Sjoerg   // Otherwise look up nullability in the state.
8337330f729Sjoerg   SVal Receiver = M.getReceiverSVal();
8347330f729Sjoerg   if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
8357330f729Sjoerg     // If the receiver is constrained to be nonnull, assume that it is nonnull
8367330f729Sjoerg     // regardless of its type.
8377330f729Sjoerg     NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
8387330f729Sjoerg     if (Nullness == NullConstraint::IsNotNull)
8397330f729Sjoerg       return Nullability::Nonnull;
8407330f729Sjoerg   }
8417330f729Sjoerg   auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
8427330f729Sjoerg   if (ValueRegionSVal) {
8437330f729Sjoerg     const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
8447330f729Sjoerg     assert(SelfRegion);
8457330f729Sjoerg 
8467330f729Sjoerg     const NullabilityState *TrackedSelfNullability =
8477330f729Sjoerg         State->get<NullabilityMap>(SelfRegion);
8487330f729Sjoerg     if (TrackedSelfNullability)
8497330f729Sjoerg       return TrackedSelfNullability->getValue();
8507330f729Sjoerg   }
8517330f729Sjoerg   return Nullability::Unspecified;
8527330f729Sjoerg }
8537330f729Sjoerg 
8547330f729Sjoerg /// Calculate the nullability of the result of a message expr based on the
8557330f729Sjoerg /// nullability of the receiver, the nullability of the return value, and the
8567330f729Sjoerg /// constraints.
checkPostObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const8577330f729Sjoerg void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
8587330f729Sjoerg                                               CheckerContext &C) const {
8597330f729Sjoerg   auto Decl = M.getDecl();
8607330f729Sjoerg   if (!Decl)
8617330f729Sjoerg     return;
8627330f729Sjoerg   QualType RetType = Decl->getReturnType();
8637330f729Sjoerg   if (!RetType->isAnyPointerType())
8647330f729Sjoerg     return;
8657330f729Sjoerg 
8667330f729Sjoerg   ProgramStateRef State = C.getState();
8677330f729Sjoerg   if (State->get<InvariantViolated>())
8687330f729Sjoerg     return;
8697330f729Sjoerg 
8707330f729Sjoerg   const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
8717330f729Sjoerg   if (!ReturnRegion)
8727330f729Sjoerg     return;
8737330f729Sjoerg 
8747330f729Sjoerg   auto Interface = Decl->getClassInterface();
8757330f729Sjoerg   auto Name = Interface ? Interface->getName() : "";
8767330f729Sjoerg   // In order to reduce the noise in the diagnostics generated by this checker,
8777330f729Sjoerg   // some framework and programming style based heuristics are used. These
8787330f729Sjoerg   // heuristics are for Cocoa APIs which have NS prefix.
8797330f729Sjoerg   if (Name.startswith("NS")) {
8807330f729Sjoerg     // Developers rely on dynamic invariants such as an item should be available
8817330f729Sjoerg     // in a collection, or a collection is not empty often. Those invariants can
8827330f729Sjoerg     // not be inferred by any static analysis tool. To not to bother the users
8837330f729Sjoerg     // with too many false positives, every item retrieval function should be
8847330f729Sjoerg     // ignored for collections. The instance methods of dictionaries in Cocoa
8857330f729Sjoerg     // are either item retrieval related or not interesting nullability wise.
8867330f729Sjoerg     // Using this fact, to keep the code easier to read just ignore the return
8877330f729Sjoerg     // value of every instance method of dictionaries.
8887330f729Sjoerg     if (M.isInstanceMessage() && Name.contains("Dictionary")) {
8897330f729Sjoerg       State =
8907330f729Sjoerg           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
8917330f729Sjoerg       C.addTransition(State);
8927330f729Sjoerg       return;
8937330f729Sjoerg     }
8947330f729Sjoerg     // For similar reasons ignore some methods of Cocoa arrays.
8957330f729Sjoerg     StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
8967330f729Sjoerg     if (Name.contains("Array") &&
8977330f729Sjoerg         (FirstSelectorSlot == "firstObject" ||
8987330f729Sjoerg          FirstSelectorSlot == "lastObject")) {
8997330f729Sjoerg       State =
9007330f729Sjoerg           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
9017330f729Sjoerg       C.addTransition(State);
9027330f729Sjoerg       return;
9037330f729Sjoerg     }
9047330f729Sjoerg 
9057330f729Sjoerg     // Encoding related methods of string should not fail when lossless
9067330f729Sjoerg     // encodings are used. Using lossless encodings is so frequent that ignoring
9077330f729Sjoerg     // this class of methods reduced the emitted diagnostics by about 30% on
9087330f729Sjoerg     // some projects (and all of that was false positives).
9097330f729Sjoerg     if (Name.contains("String")) {
9107330f729Sjoerg       for (auto Param : M.parameters()) {
9117330f729Sjoerg         if (Param->getName() == "encoding") {
9127330f729Sjoerg           State = State->set<NullabilityMap>(ReturnRegion,
9137330f729Sjoerg                                              Nullability::Contradicted);
9147330f729Sjoerg           C.addTransition(State);
9157330f729Sjoerg           return;
9167330f729Sjoerg         }
9177330f729Sjoerg       }
9187330f729Sjoerg     }
9197330f729Sjoerg   }
9207330f729Sjoerg 
9217330f729Sjoerg   const ObjCMessageExpr *Message = M.getOriginExpr();
9227330f729Sjoerg   Nullability SelfNullability = getReceiverNullability(M, State);
9237330f729Sjoerg 
9247330f729Sjoerg   const NullabilityState *NullabilityOfReturn =
9257330f729Sjoerg       State->get<NullabilityMap>(ReturnRegion);
9267330f729Sjoerg 
9277330f729Sjoerg   if (NullabilityOfReturn) {
9287330f729Sjoerg     // When we have a nullability tracked for the return value, the nullability
9297330f729Sjoerg     // of the expression will be the most nullable of the receiver and the
9307330f729Sjoerg     // return value.
9317330f729Sjoerg     Nullability RetValTracked = NullabilityOfReturn->getValue();
9327330f729Sjoerg     Nullability ComputedNullab =
9337330f729Sjoerg         getMostNullable(RetValTracked, SelfNullability);
9347330f729Sjoerg     if (ComputedNullab != RetValTracked &&
9357330f729Sjoerg         ComputedNullab != Nullability::Unspecified) {
9367330f729Sjoerg       const Stmt *NullabilitySource =
9377330f729Sjoerg           ComputedNullab == RetValTracked
9387330f729Sjoerg               ? NullabilityOfReturn->getNullabilitySource()
9397330f729Sjoerg               : Message->getInstanceReceiver();
9407330f729Sjoerg       State = State->set<NullabilityMap>(
9417330f729Sjoerg           ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
9427330f729Sjoerg       C.addTransition(State);
9437330f729Sjoerg     }
9447330f729Sjoerg     return;
9457330f729Sjoerg   }
9467330f729Sjoerg 
9477330f729Sjoerg   // No tracked information. Use static type information for return value.
9487330f729Sjoerg   Nullability RetNullability = getNullabilityAnnotation(RetType);
9497330f729Sjoerg 
9507330f729Sjoerg   // Properties might be computed. For this reason the static analyzer creates a
9517330f729Sjoerg   // new symbol each time an unknown property  is read. To avoid false pozitives
9527330f729Sjoerg   // do not treat unknown properties as nullable, even when they explicitly
9537330f729Sjoerg   // marked nullable.
9547330f729Sjoerg   if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
9557330f729Sjoerg     RetNullability = Nullability::Nonnull;
9567330f729Sjoerg 
9577330f729Sjoerg   Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
9587330f729Sjoerg   if (ComputedNullab == Nullability::Nullable) {
9597330f729Sjoerg     const Stmt *NullabilitySource = ComputedNullab == RetNullability
9607330f729Sjoerg                                         ? Message
9617330f729Sjoerg                                         : Message->getInstanceReceiver();
9627330f729Sjoerg     State = State->set<NullabilityMap>(
9637330f729Sjoerg         ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
9647330f729Sjoerg     C.addTransition(State);
9657330f729Sjoerg   }
9667330f729Sjoerg }
9677330f729Sjoerg 
9687330f729Sjoerg /// Explicit casts are trusted. If there is a disagreement in the nullability
9697330f729Sjoerg /// annotations in the destination and the source or '0' is casted to nonnull
9707330f729Sjoerg /// track the value as having contraditory nullability. This will allow users to
9717330f729Sjoerg /// suppress warnings.
checkPostStmt(const ExplicitCastExpr * CE,CheckerContext & C) const9727330f729Sjoerg void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
9737330f729Sjoerg                                        CheckerContext &C) const {
9747330f729Sjoerg   QualType OriginType = CE->getSubExpr()->getType();
9757330f729Sjoerg   QualType DestType = CE->getType();
9767330f729Sjoerg   if (!OriginType->isAnyPointerType())
9777330f729Sjoerg     return;
9787330f729Sjoerg   if (!DestType->isAnyPointerType())
9797330f729Sjoerg     return;
9807330f729Sjoerg 
9817330f729Sjoerg   ProgramStateRef State = C.getState();
9827330f729Sjoerg   if (State->get<InvariantViolated>())
9837330f729Sjoerg     return;
9847330f729Sjoerg 
9857330f729Sjoerg   Nullability DestNullability = getNullabilityAnnotation(DestType);
9867330f729Sjoerg 
9877330f729Sjoerg   // No explicit nullability in the destination type, so this cast does not
9887330f729Sjoerg   // change the nullability.
9897330f729Sjoerg   if (DestNullability == Nullability::Unspecified)
9907330f729Sjoerg     return;
9917330f729Sjoerg 
9927330f729Sjoerg   auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
9937330f729Sjoerg   const MemRegion *Region = getTrackRegion(*RegionSVal);
9947330f729Sjoerg   if (!Region)
9957330f729Sjoerg     return;
9967330f729Sjoerg 
9977330f729Sjoerg   // When 0 is converted to nonnull mark it as contradicted.
9987330f729Sjoerg   if (DestNullability == Nullability::Nonnull) {
9997330f729Sjoerg     NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
10007330f729Sjoerg     if (Nullness == NullConstraint::IsNull) {
10017330f729Sjoerg       State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
10027330f729Sjoerg       C.addTransition(State);
10037330f729Sjoerg       return;
10047330f729Sjoerg     }
10057330f729Sjoerg   }
10067330f729Sjoerg 
10077330f729Sjoerg   const NullabilityState *TrackedNullability =
10087330f729Sjoerg       State->get<NullabilityMap>(Region);
10097330f729Sjoerg 
10107330f729Sjoerg   if (!TrackedNullability) {
10117330f729Sjoerg     if (DestNullability != Nullability::Nullable)
10127330f729Sjoerg       return;
10137330f729Sjoerg     State = State->set<NullabilityMap>(Region,
10147330f729Sjoerg                                        NullabilityState(DestNullability, CE));
10157330f729Sjoerg     C.addTransition(State);
10167330f729Sjoerg     return;
10177330f729Sjoerg   }
10187330f729Sjoerg 
10197330f729Sjoerg   if (TrackedNullability->getValue() != DestNullability &&
10207330f729Sjoerg       TrackedNullability->getValue() != Nullability::Contradicted) {
10217330f729Sjoerg     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
10227330f729Sjoerg     C.addTransition(State);
10237330f729Sjoerg   }
10247330f729Sjoerg }
10257330f729Sjoerg 
10267330f729Sjoerg /// For a given statement performing a bind, attempt to syntactically
10277330f729Sjoerg /// match the expression resulting in the bound value.
matchValueExprForBind(const Stmt * S)10287330f729Sjoerg static const Expr * matchValueExprForBind(const Stmt *S) {
10297330f729Sjoerg   // For `x = e` the value expression is the right-hand side.
10307330f729Sjoerg   if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
10317330f729Sjoerg     if (BinOp->getOpcode() == BO_Assign)
10327330f729Sjoerg       return BinOp->getRHS();
10337330f729Sjoerg   }
10347330f729Sjoerg 
10357330f729Sjoerg   // For `int x = e` the value expression is the initializer.
10367330f729Sjoerg   if (auto *DS = dyn_cast<DeclStmt>(S))  {
10377330f729Sjoerg     if (DS->isSingleDecl()) {
10387330f729Sjoerg       auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
10397330f729Sjoerg       if (!VD)
10407330f729Sjoerg         return nullptr;
10417330f729Sjoerg 
10427330f729Sjoerg       if (const Expr *Init = VD->getInit())
10437330f729Sjoerg         return Init;
10447330f729Sjoerg     }
10457330f729Sjoerg   }
10467330f729Sjoerg 
10477330f729Sjoerg   return nullptr;
10487330f729Sjoerg }
10497330f729Sjoerg 
10507330f729Sjoerg /// Returns true if \param S is a DeclStmt for a local variable that
10517330f729Sjoerg /// ObjC automated reference counting initialized with zero.
isARCNilInitializedLocal(CheckerContext & C,const Stmt * S)10527330f729Sjoerg static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
10537330f729Sjoerg   // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
10547330f729Sjoerg   // prevents false positives when a _Nonnull local variable cannot be
10557330f729Sjoerg   // initialized with an initialization expression:
10567330f729Sjoerg   //    NSString * _Nonnull s; // no-warning
10577330f729Sjoerg   //    @autoreleasepool {
10587330f729Sjoerg   //      s = ...
10597330f729Sjoerg   //    }
10607330f729Sjoerg   //
10617330f729Sjoerg   // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
10627330f729Sjoerg   // uninitialized in Sema's UninitializedValues analysis to warn when a use of
10637330f729Sjoerg   // the zero-initialized definition will unexpectedly yield nil.
10647330f729Sjoerg 
10657330f729Sjoerg   // Locals are only zero-initialized when automated reference counting
10667330f729Sjoerg   // is turned on.
10677330f729Sjoerg   if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
10687330f729Sjoerg     return false;
10697330f729Sjoerg 
10707330f729Sjoerg   auto *DS = dyn_cast<DeclStmt>(S);
10717330f729Sjoerg   if (!DS || !DS->isSingleDecl())
10727330f729Sjoerg     return false;
10737330f729Sjoerg 
10747330f729Sjoerg   auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
10757330f729Sjoerg   if (!VD)
10767330f729Sjoerg     return false;
10777330f729Sjoerg 
10787330f729Sjoerg   // Sema only zero-initializes locals with ObjCLifetimes.
10797330f729Sjoerg   if(!VD->getType().getQualifiers().hasObjCLifetime())
10807330f729Sjoerg     return false;
10817330f729Sjoerg 
10827330f729Sjoerg   const Expr *Init = VD->getInit();
10837330f729Sjoerg   assert(Init && "ObjC local under ARC without initializer");
10847330f729Sjoerg 
10857330f729Sjoerg   // Return false if the local is explicitly initialized (e.g., with '= nil').
10867330f729Sjoerg   if (!isa<ImplicitValueInitExpr>(Init))
10877330f729Sjoerg     return false;
10887330f729Sjoerg 
10897330f729Sjoerg   return true;
10907330f729Sjoerg }
10917330f729Sjoerg 
10927330f729Sjoerg /// Propagate the nullability information through binds and warn when nullable
10937330f729Sjoerg /// pointer or null symbol is assigned to a pointer with a nonnull type.
checkBind(SVal L,SVal V,const Stmt * S,CheckerContext & C) const10947330f729Sjoerg void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
10957330f729Sjoerg                                    CheckerContext &C) const {
10967330f729Sjoerg   const TypedValueRegion *TVR =
10977330f729Sjoerg       dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
10987330f729Sjoerg   if (!TVR)
10997330f729Sjoerg     return;
11007330f729Sjoerg 
11017330f729Sjoerg   QualType LocType = TVR->getValueType();
11027330f729Sjoerg   if (!LocType->isAnyPointerType())
11037330f729Sjoerg     return;
11047330f729Sjoerg 
11057330f729Sjoerg   ProgramStateRef State = C.getState();
11067330f729Sjoerg   if (State->get<InvariantViolated>())
11077330f729Sjoerg     return;
11087330f729Sjoerg 
11097330f729Sjoerg   auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
11107330f729Sjoerg   if (!ValDefOrUnknown)
11117330f729Sjoerg     return;
11127330f729Sjoerg 
11137330f729Sjoerg   NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
11147330f729Sjoerg 
11157330f729Sjoerg   Nullability ValNullability = Nullability::Unspecified;
11167330f729Sjoerg   if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
11177330f729Sjoerg     ValNullability = getNullabilityAnnotation(Sym->getType());
11187330f729Sjoerg 
11197330f729Sjoerg   Nullability LocNullability = getNullabilityAnnotation(LocType);
11207330f729Sjoerg 
11217330f729Sjoerg   // If the type of the RHS expression is nonnull, don't warn. This
11227330f729Sjoerg   // enables explicit suppression with a cast to nonnull.
11237330f729Sjoerg   Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
11247330f729Sjoerg   const Expr *ValueExpr = matchValueExprForBind(S);
11257330f729Sjoerg   if (ValueExpr) {
11267330f729Sjoerg     ValueExprTypeLevelNullability =
11277330f729Sjoerg       getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
11287330f729Sjoerg   }
11297330f729Sjoerg 
11307330f729Sjoerg   bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
11317330f729Sjoerg                                 RhsNullness == NullConstraint::IsNull);
1132*e038c9c4Sjoerg   if (ChecksEnabled[CK_NullPassedToNonnull] && NullAssignedToNonNull &&
11337330f729Sjoerg       ValNullability != Nullability::Nonnull &&
11347330f729Sjoerg       ValueExprTypeLevelNullability != Nullability::Nonnull &&
11357330f729Sjoerg       !isARCNilInitializedLocal(C, S)) {
11367330f729Sjoerg     static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
11377330f729Sjoerg     ExplodedNode *N = C.generateErrorNode(State, &Tag);
11387330f729Sjoerg     if (!N)
11397330f729Sjoerg       return;
11407330f729Sjoerg 
11417330f729Sjoerg 
11427330f729Sjoerg     const Stmt *ValueStmt = S;
11437330f729Sjoerg     if (ValueExpr)
11447330f729Sjoerg       ValueStmt = ValueExpr;
11457330f729Sjoerg 
11467330f729Sjoerg     SmallString<256> SBuf;
11477330f729Sjoerg     llvm::raw_svector_ostream OS(SBuf);
11487330f729Sjoerg     OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
11497330f729Sjoerg     OS << " assigned to a pointer which is expected to have non-null value";
1150*e038c9c4Sjoerg     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
1151*e038c9c4Sjoerg                               CK_NullPassedToNonnull, N, nullptr, C, ValueStmt);
11527330f729Sjoerg     return;
11537330f729Sjoerg   }
11547330f729Sjoerg 
11557330f729Sjoerg   // If null was returned from a non-null function, mark the nullability
11567330f729Sjoerg   // invariant as violated even if the diagnostic was suppressed.
11577330f729Sjoerg   if (NullAssignedToNonNull) {
11587330f729Sjoerg     State = State->set<InvariantViolated>(true);
11597330f729Sjoerg     C.addTransition(State);
11607330f729Sjoerg     return;
11617330f729Sjoerg   }
11627330f729Sjoerg 
11637330f729Sjoerg   // Intentionally missing case: '0' is bound to a reference. It is handled by
11647330f729Sjoerg   // the DereferenceChecker.
11657330f729Sjoerg 
11667330f729Sjoerg   const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
11677330f729Sjoerg   if (!ValueRegion)
11687330f729Sjoerg     return;
11697330f729Sjoerg 
11707330f729Sjoerg   const NullabilityState *TrackedNullability =
11717330f729Sjoerg       State->get<NullabilityMap>(ValueRegion);
11727330f729Sjoerg 
11737330f729Sjoerg   if (TrackedNullability) {
11747330f729Sjoerg     if (RhsNullness == NullConstraint::IsNotNull ||
11757330f729Sjoerg         TrackedNullability->getValue() != Nullability::Nullable)
11767330f729Sjoerg       return;
1177*e038c9c4Sjoerg     if (ChecksEnabled[CK_NullablePassedToNonnull] &&
11787330f729Sjoerg         LocNullability == Nullability::Nonnull) {
11797330f729Sjoerg       static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
11807330f729Sjoerg       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
11817330f729Sjoerg       reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
11827330f729Sjoerg                                 "which is expected to have non-null value",
1183*e038c9c4Sjoerg                                 ErrorKind::NullableAssignedToNonnull,
1184*e038c9c4Sjoerg                                 CK_NullablePassedToNonnull, N, ValueRegion, C);
11857330f729Sjoerg     }
11867330f729Sjoerg     return;
11877330f729Sjoerg   }
11887330f729Sjoerg 
11897330f729Sjoerg   const auto *BinOp = dyn_cast<BinaryOperator>(S);
11907330f729Sjoerg 
11917330f729Sjoerg   if (ValNullability == Nullability::Nullable) {
11927330f729Sjoerg     // Trust the static information of the value more than the static
11937330f729Sjoerg     // information on the location.
11947330f729Sjoerg     const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
11957330f729Sjoerg     State = State->set<NullabilityMap>(
11967330f729Sjoerg         ValueRegion, NullabilityState(ValNullability, NullabilitySource));
11977330f729Sjoerg     C.addTransition(State);
11987330f729Sjoerg     return;
11997330f729Sjoerg   }
12007330f729Sjoerg 
12017330f729Sjoerg   if (LocNullability == Nullability::Nullable) {
12027330f729Sjoerg     const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
12037330f729Sjoerg     State = State->set<NullabilityMap>(
12047330f729Sjoerg         ValueRegion, NullabilityState(LocNullability, NullabilitySource));
12057330f729Sjoerg     C.addTransition(State);
12067330f729Sjoerg   }
12077330f729Sjoerg }
12087330f729Sjoerg 
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const12097330f729Sjoerg void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
12107330f729Sjoerg                                     const char *NL, const char *Sep) const {
12117330f729Sjoerg 
12127330f729Sjoerg   NullabilityMapTy B = State->get<NullabilityMap>();
12137330f729Sjoerg 
12147330f729Sjoerg   if (State->get<InvariantViolated>())
12157330f729Sjoerg     Out << Sep << NL
12167330f729Sjoerg         << "Nullability invariant was violated, warnings suppressed." << NL;
12177330f729Sjoerg 
12187330f729Sjoerg   if (B.isEmpty())
12197330f729Sjoerg     return;
12207330f729Sjoerg 
12217330f729Sjoerg   if (!State->get<InvariantViolated>())
12227330f729Sjoerg     Out << Sep << NL;
12237330f729Sjoerg 
12247330f729Sjoerg   for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
12257330f729Sjoerg     Out << I->first << " : ";
12267330f729Sjoerg     I->second.print(Out);
12277330f729Sjoerg     Out << NL;
12287330f729Sjoerg   }
12297330f729Sjoerg }
12307330f729Sjoerg 
registerNullabilityBase(CheckerManager & mgr)12317330f729Sjoerg void ento::registerNullabilityBase(CheckerManager &mgr) {
12327330f729Sjoerg   mgr.registerChecker<NullabilityChecker>();
12337330f729Sjoerg }
12347330f729Sjoerg 
shouldRegisterNullabilityBase(const CheckerManager & mgr)1235*e038c9c4Sjoerg bool ento::shouldRegisterNullabilityBase(const CheckerManager &mgr) {
12367330f729Sjoerg   return true;
12377330f729Sjoerg }
12387330f729Sjoerg 
12397330f729Sjoerg #define REGISTER_CHECKER(name, trackingRequired)                               \
12407330f729Sjoerg   void ento::register##name##Checker(CheckerManager &mgr) {                    \
12417330f729Sjoerg     NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>();        \
1242*e038c9c4Sjoerg     checker->ChecksEnabled[NullabilityChecker::CK_##name] = true;              \
1243*e038c9c4Sjoerg     checker->CheckNames[NullabilityChecker::CK_##name] =                       \
1244*e038c9c4Sjoerg         mgr.getCurrentCheckerName();                                           \
12457330f729Sjoerg     checker->NeedTracking = checker->NeedTracking || trackingRequired;         \
12467330f729Sjoerg     checker->NoDiagnoseCallsToSystemHeaders =                                  \
12477330f729Sjoerg         checker->NoDiagnoseCallsToSystemHeaders ||                             \
12487330f729Sjoerg         mgr.getAnalyzerOptions().getCheckerBooleanOption(                      \
12497330f729Sjoerg             checker, "NoDiagnoseCallsToSystemHeaders", true);                  \
12507330f729Sjoerg   }                                                                            \
12517330f729Sjoerg                                                                                \
1252*e038c9c4Sjoerg   bool ento::shouldRegister##name##Checker(const CheckerManager &mgr) {        \
12537330f729Sjoerg     return true;                                                               \
12547330f729Sjoerg   }
12557330f729Sjoerg 
12567330f729Sjoerg // The checks are likely to be turned on by default and it is possible to do
12577330f729Sjoerg // them without tracking any nullability related information. As an optimization
12587330f729Sjoerg // no nullability information will be tracked when only these two checks are
12597330f729Sjoerg // enables.
12607330f729Sjoerg REGISTER_CHECKER(NullPassedToNonnull, false)
12617330f729Sjoerg REGISTER_CHECKER(NullReturnedFromNonnull, false)
12627330f729Sjoerg 
12637330f729Sjoerg REGISTER_CHECKER(NullableDereferenced, true)
12647330f729Sjoerg REGISTER_CHECKER(NullablePassedToNonnull, true)
12657330f729Sjoerg REGISTER_CHECKER(NullableReturnedFromNonnull, true)
1266