1524b3c18SFangrui Song //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
228690925SGabor Horvath //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
628690925SGabor Horvath //
728690925SGabor Horvath //===----------------------------------------------------------------------===//
828690925SGabor Horvath //
928690925SGabor Horvath // This checker tries to find nullability violations. There are several kinds of
1028690925SGabor Horvath // possible violations:
1128690925SGabor Horvath // * Null pointer is passed to a pointer which has a _Nonnull type.
1228690925SGabor Horvath // * Null pointer is returned from a function which has a _Nonnull return type.
1328690925SGabor Horvath // * Nullable pointer is passed to a pointer which has a _Nonnull type.
1428690925SGabor Horvath // * Nullable pointer is returned from a function which has a _Nonnull return
1528690925SGabor Horvath //   type.
1628690925SGabor Horvath // * Nullable pointer is dereferenced.
1728690925SGabor Horvath //
1828690925SGabor Horvath // This checker propagates the nullability information of the pointers and looks
1928690925SGabor Horvath // for the patterns that are described above. Explicit casts are trusted and are
2028690925SGabor Horvath // considered a way to suppress false positives for this checker. The other way
2128690925SGabor Horvath // to suppress warnings would be to add asserts or guarding if statements to the
2228690925SGabor Horvath // code. In addition to the nullability propagation this checker also uses some
2328690925SGabor Horvath // heuristics to suppress potential false positives.
2428690925SGabor Horvath //
2528690925SGabor Horvath //===----------------------------------------------------------------------===//
2628690925SGabor Horvath 
2776a21502SKristof Umann #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
28ad9e7ea6SAnna Zaks 
2928690925SGabor Horvath #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
3028690925SGabor Horvath #include "clang/StaticAnalyzer/Core/Checker.h"
3128690925SGabor Horvath #include "clang/StaticAnalyzer/Core/CheckerManager.h"
322301c5abSGeorge Karpenkov #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
3328690925SGabor Horvath #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
3428690925SGabor Horvath #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
3528690925SGabor Horvath 
36ad9e7ea6SAnna Zaks #include "llvm/ADT/StringExtras.h"
37ad9e7ea6SAnna Zaks #include "llvm/Support/Path.h"
38ad9e7ea6SAnna Zaks 
3928690925SGabor Horvath using namespace clang;
4028690925SGabor Horvath using namespace ento;
4128690925SGabor Horvath 
4228690925SGabor Horvath namespace {
4328690925SGabor Horvath 
4428690925SGabor Horvath /// Returns the most nullable nullability. This is used for message expressions
452c51880aSSimon Pilgrim /// like [receiver method], where the nullability of this expression is either
4628690925SGabor Horvath /// the nullability of the receiver or the nullability of the return type of the
4728690925SGabor Horvath /// method, depending on which is more nullable. Contradicted is considered to
4828690925SGabor Horvath /// be the most nullable, to avoid false positive results.
getMostNullable(Nullability Lhs,Nullability Rhs)493943adb5SGabor Horvath Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
5028690925SGabor Horvath   return static_cast<Nullability>(
5128690925SGabor Horvath       std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
5228690925SGabor Horvath }
5328690925SGabor Horvath 
getNullabilityString(Nullability Nullab)543943adb5SGabor Horvath const char *getNullabilityString(Nullability Nullab) {
5528690925SGabor Horvath   switch (Nullab) {
5628690925SGabor Horvath   case Nullability::Contradicted:
5728690925SGabor Horvath     return "contradicted";
5828690925SGabor Horvath   case Nullability::Nullable:
5928690925SGabor Horvath     return "nullable";
6028690925SGabor Horvath   case Nullability::Unspecified:
6128690925SGabor Horvath     return "unspecified";
6228690925SGabor Horvath   case Nullability::Nonnull:
6328690925SGabor Horvath     return "nonnull";
6428690925SGabor Horvath   }
653943adb5SGabor Horvath   llvm_unreachable("Unexpected enumeration.");
6628690925SGabor Horvath   return "";
6728690925SGabor Horvath }
6828690925SGabor Horvath 
6928690925SGabor Horvath // These enums are used as an index to ErrorMessages array.
7028690925SGabor Horvath enum class ErrorKind : int {
7128690925SGabor Horvath   NilAssignedToNonnull,
7228690925SGabor Horvath   NilPassedToNonnull,
7328690925SGabor Horvath   NilReturnedToNonnull,
7428690925SGabor Horvath   NullableAssignedToNonnull,
7528690925SGabor Horvath   NullableReturnedToNonnull,
7628690925SGabor Horvath   NullableDereferenced,
7728690925SGabor Horvath   NullablePassedToNonnull
7828690925SGabor Horvath };
7928690925SGabor Horvath 
8028690925SGabor Horvath class NullabilityChecker
8128690925SGabor Horvath     : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
8228690925SGabor Horvath                      check::PostCall, check::PostStmt<ExplicitCastExpr>,
8328690925SGabor Horvath                      check::PostObjCMessage, check::DeadSymbols,
8409a1f090SValeriy Savchenko                      check::Location, check::Event<ImplicitNullDerefEvent>> {
8528690925SGabor Horvath 
8628690925SGabor Horvath public:
87a1d9d75aSDevin Coughlin   // If true, the checker will not diagnose nullabilility issues for calls
88a1d9d75aSDevin Coughlin   // to system headers. This option is motivated by the observation that large
89a1d9d75aSDevin Coughlin   // projects may have many nullability warnings. These projects may
90a1d9d75aSDevin Coughlin   // find warnings about nullability annotations that they have explicitly
91a1d9d75aSDevin Coughlin   // added themselves higher priority to fix than warnings on calls to system
92a1d9d75aSDevin Coughlin   // libraries.
93*5114db93SVince Bridgers   bool NoDiagnoseCallsToSystemHeaders = false;
94a1d9d75aSDevin Coughlin 
9528690925SGabor Horvath   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
9628690925SGabor Horvath   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
9728690925SGabor Horvath   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
9828690925SGabor Horvath   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
9928690925SGabor Horvath   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
10028690925SGabor Horvath   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
10128690925SGabor Horvath   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
10228690925SGabor Horvath   void checkEvent(ImplicitNullDerefEvent Event) const;
10309a1f090SValeriy Savchenko   void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
10409a1f090SValeriy Savchenko                      CheckerContext &C) const;
10528690925SGabor Horvath 
10628690925SGabor Horvath   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
10728690925SGabor Horvath                   const char *Sep) const override;
10828690925SGabor Horvath 
109e4e1080aSKirstóf Umann   enum CheckKind {
110e4e1080aSKirstóf Umann     CK_NullPassedToNonnull,
111e4e1080aSKirstóf Umann     CK_NullReturnedFromNonnull,
112e4e1080aSKirstóf Umann     CK_NullableDereferenced,
113e4e1080aSKirstóf Umann     CK_NullablePassedToNonnull,
114e4e1080aSKirstóf Umann     CK_NullableReturnedFromNonnull,
115e4e1080aSKirstóf Umann     CK_NumCheckKinds
11628690925SGabor Horvath   };
11728690925SGabor Horvath 
118*5114db93SVince Bridgers   bool ChecksEnabled[CK_NumCheckKinds] = {false};
119e4e1080aSKirstóf Umann   CheckerNameRef CheckNames[CK_NumCheckKinds];
120e4e1080aSKirstóf Umann   mutable std::unique_ptr<BugType> BTs[CK_NumCheckKinds];
121e4e1080aSKirstóf Umann 
getBugType(CheckKind Kind) const122e4e1080aSKirstóf Umann   const std::unique_ptr<BugType> &getBugType(CheckKind Kind) const {
123e4e1080aSKirstóf Umann     if (!BTs[Kind])
124e4e1080aSKirstóf Umann       BTs[Kind].reset(new BugType(CheckNames[Kind], "Nullability",
125e4e1080aSKirstóf Umann                                   categories::MemoryError));
126e4e1080aSKirstóf Umann     return BTs[Kind];
127e4e1080aSKirstóf Umann   }
128e4e1080aSKirstóf Umann 
1292930735cSGabor Horvath   // When set to false no nullability information will be tracked in
1302930735cSGabor Horvath   // NullabilityMap. It is possible to catch errors like passing a null pointer
1312930735cSGabor Horvath   // to a callee that expects nonnull argument without the information that is
1322930735cSGabor Horvath   // stroed in the NullabilityMap. This is an optimization.
133*5114db93SVince Bridgers   bool NeedTracking = false;
13428690925SGabor Horvath 
13528690925SGabor Horvath private:
13670ec1dd1SGeorge Karpenkov   class NullabilityBugVisitor : public BugReporterVisitor {
13728690925SGabor Horvath   public:
NullabilityBugVisitor(const MemRegion * M)13828690925SGabor Horvath     NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
13928690925SGabor Horvath 
Profile(llvm::FoldingSetNodeID & ID) const14028690925SGabor Horvath     void Profile(llvm::FoldingSetNodeID &ID) const override {
14128690925SGabor Horvath       static int X = 0;
14228690925SGabor Horvath       ID.AddPointer(&X);
14328690925SGabor Horvath       ID.AddPointer(Region);
14428690925SGabor Horvath     }
14528690925SGabor Horvath 
1466d716ef1SKristof Umann     PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
14728690925SGabor Horvath                                      BugReporterContext &BRC,
1482f169e7cSArtem Dergachev                                      PathSensitiveBugReport &BR) override;
14928690925SGabor Horvath 
15028690925SGabor Horvath   private:
15128690925SGabor Horvath     // The tracked region.
15228690925SGabor Horvath     const MemRegion *Region;
15328690925SGabor Horvath   };
15428690925SGabor Horvath 
155b47128aaSGabor Horvath   /// When any of the nonnull arguments of the analyzed function is null, do not
156b47128aaSGabor Horvath   /// report anything and turn off the check.
157b47128aaSGabor Horvath   ///
158b47128aaSGabor Horvath   /// When \p SuppressPath is set to true, no more bugs will be reported on this
159b47128aaSGabor Horvath   /// path by this checker.
160e4e1080aSKirstóf Umann   void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
161ad9e7ea6SAnna Zaks                                  ExplodedNode *N, const MemRegion *Region,
162ad9e7ea6SAnna Zaks                                  CheckerContext &C,
163b47128aaSGabor Horvath                                  const Stmt *ValueExpr = nullptr,
164b47128aaSGabor Horvath                                  bool SuppressPath = false) const;
165b47128aaSGabor Horvath 
reportBug(StringRef Msg,ErrorKind Error,CheckKind CK,ExplodedNode * N,const MemRegion * Region,BugReporter & BR,const Stmt * ValueExpr=nullptr) const166e4e1080aSKirstóf Umann   void reportBug(StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
167ad9e7ea6SAnna Zaks                  const MemRegion *Region, BugReporter &BR,
168ad9e7ea6SAnna Zaks                  const Stmt *ValueExpr = nullptr) const {
169e4e1080aSKirstóf Umann     const std::unique_ptr<BugType> &BT = getBugType(CK);
1702f169e7cSArtem Dergachev     auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
17128690925SGabor Horvath     if (Region) {
17228690925SGabor Horvath       R->markInteresting(Region);
17392d03c20SValeriy Savchenko       R->addVisitor<NullabilityBugVisitor>(Region);
17428690925SGabor Horvath     }
17528690925SGabor Horvath     if (ValueExpr) {
17628690925SGabor Horvath       R->addRange(ValueExpr->getSourceRange());
17728690925SGabor Horvath       if (Error == ErrorKind::NilAssignedToNonnull ||
17828690925SGabor Horvath           Error == ErrorKind::NilPassedToNonnull ||
17928690925SGabor Horvath           Error == ErrorKind::NilReturnedToNonnull)
180b2cf0063SGeorge Karpenkov         if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
181b2cf0063SGeorge Karpenkov           bugreporter::trackExpressionValue(N, Ex, *R);
18228690925SGabor Horvath     }
18328690925SGabor Horvath     BR.emitReport(std::move(R));
18428690925SGabor Horvath   }
1852930735cSGabor Horvath 
1862930735cSGabor Horvath   /// If an SVal wraps a region that should be tracked, it will return a pointer
1872930735cSGabor Horvath   /// to the wrapped region. Otherwise it will return a nullptr.
1882930735cSGabor Horvath   const SymbolicRegion *getTrackRegion(SVal Val,
1892930735cSGabor Horvath                                        bool CheckSuperRegion = false) const;
190a1d9d75aSDevin Coughlin 
191b23ccecbSRaphael Isemann   /// Returns true if the call is diagnosable in the current analyzer
192a1d9d75aSDevin Coughlin   /// configuration.
isDiagnosableCall(const CallEvent & Call) const193a1d9d75aSDevin Coughlin   bool isDiagnosableCall(const CallEvent &Call) const {
194a1d9d75aSDevin Coughlin     if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
195a1d9d75aSDevin Coughlin       return false;
196a1d9d75aSDevin Coughlin 
197a1d9d75aSDevin Coughlin     return true;
198a1d9d75aSDevin Coughlin   }
19928690925SGabor Horvath };
20028690925SGabor Horvath 
20128690925SGabor Horvath class NullabilityState {
20228690925SGabor Horvath public:
NullabilityState(Nullability Nullab,const Stmt * Source=nullptr)20328690925SGabor Horvath   NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
20428690925SGabor Horvath       : Nullab(Nullab), Source(Source) {}
20528690925SGabor Horvath 
getNullabilitySource() const20628690925SGabor Horvath   const Stmt *getNullabilitySource() const { return Source; }
20728690925SGabor Horvath 
getValue() const20828690925SGabor Horvath   Nullability getValue() const { return Nullab; }
20928690925SGabor Horvath 
Profile(llvm::FoldingSetNodeID & ID) const21028690925SGabor Horvath   void Profile(llvm::FoldingSetNodeID &ID) const {
21128690925SGabor Horvath     ID.AddInteger(static_cast<char>(Nullab));
21228690925SGabor Horvath     ID.AddPointer(Source);
21328690925SGabor Horvath   }
21428690925SGabor Horvath 
print(raw_ostream & Out) const21528690925SGabor Horvath   void print(raw_ostream &Out) const {
21628690925SGabor Horvath     Out << getNullabilityString(Nullab) << "\n";
21728690925SGabor Horvath   }
21828690925SGabor Horvath 
21928690925SGabor Horvath private:
22028690925SGabor Horvath   Nullability Nullab;
22128690925SGabor Horvath   // Source is the expression which determined the nullability. For example in a
22228690925SGabor Horvath   // message like [nullable nonnull_returning] has nullable nullability, because
22328690925SGabor Horvath   // the receiver is nullable. Here the receiver will be the source of the
22428690925SGabor Horvath   // nullability. This is useful information when the diagnostics are generated.
22528690925SGabor Horvath   const Stmt *Source;
22628690925SGabor Horvath };
22728690925SGabor Horvath 
operator ==(NullabilityState Lhs,NullabilityState Rhs)22828690925SGabor Horvath bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
22928690925SGabor Horvath   return Lhs.getValue() == Rhs.getValue() &&
23028690925SGabor Horvath          Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
23128690925SGabor Horvath }
23228690925SGabor Horvath 
23328690925SGabor Horvath } // end anonymous namespace
23428690925SGabor Horvath 
23528690925SGabor Horvath REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
23628690925SGabor Horvath                                NullabilityState)
23728690925SGabor Horvath 
23877942db0SDevin Coughlin // We say "the nullability type invariant is violated" when a location with a
23977942db0SDevin Coughlin // non-null type contains NULL or a function with a non-null return type returns
24077942db0SDevin Coughlin // NULL. Violations of the nullability type invariant can be detected either
24177942db0SDevin Coughlin // directly (for example, when NULL is passed as an argument to a nonnull
24277942db0SDevin Coughlin // parameter) or indirectly (for example, when, inside a function, the
24377942db0SDevin Coughlin // programmer defensively checks whether a nonnull parameter contains NULL and
24477942db0SDevin Coughlin // finds that it does).
24577942db0SDevin Coughlin //
24677942db0SDevin Coughlin // As a matter of policy, the nullability checker typically warns on direct
24777942db0SDevin Coughlin // violations of the nullability invariant (although it uses various
24877942db0SDevin Coughlin // heuristics to suppress warnings in some cases) but will not warn if the
24977942db0SDevin Coughlin // invariant has already been violated along the path (either directly or
25077942db0SDevin Coughlin // indirectly). As a practical matter, this prevents the analyzer from
25177942db0SDevin Coughlin // (1) warning on defensive code paths where a nullability precondition is
25277942db0SDevin Coughlin // determined to have been violated, (2) warning additional times after an
25377942db0SDevin Coughlin // initial direct violation has been discovered, and (3) warning after a direct
25477942db0SDevin Coughlin // violation that has been implicitly or explicitly suppressed (for
25577942db0SDevin Coughlin // example, with a cast of NULL to _Nonnull). In essence, once an invariant
2562a8c18d9SAlexander Kornienko // violation is detected on a path, this checker will be essentially turned off
25777942db0SDevin Coughlin // for the rest of the analysis
25877942db0SDevin Coughlin //
25977942db0SDevin Coughlin // The analyzer takes this approach (rather than generating a sink node) to
26077942db0SDevin Coughlin // ensure coverage of defensive paths, which may be important for backwards
26177942db0SDevin Coughlin // compatibility in codebases that were developed without nullability in mind.
26277942db0SDevin Coughlin REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
263b47128aaSGabor Horvath 
26428690925SGabor Horvath enum class NullConstraint { IsNull, IsNotNull, Unknown };
26528690925SGabor Horvath 
getNullConstraint(DefinedOrUnknownSVal Val,ProgramStateRef State)26628690925SGabor Horvath static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
26728690925SGabor Horvath                                         ProgramStateRef State) {
26828690925SGabor Horvath   ConditionTruthVal Nullness = State->isNull(Val);
26928690925SGabor Horvath   if (Nullness.isConstrainedFalse())
27028690925SGabor Horvath     return NullConstraint::IsNotNull;
27128690925SGabor Horvath   if (Nullness.isConstrainedTrue())
27228690925SGabor Horvath     return NullConstraint::IsNull;
27328690925SGabor Horvath   return NullConstraint::Unknown;
27428690925SGabor Horvath }
27528690925SGabor Horvath 
2762930735cSGabor Horvath const SymbolicRegion *
getTrackRegion(SVal Val,bool CheckSuperRegion) const2772930735cSGabor Horvath NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
2782930735cSGabor Horvath   if (!NeedTracking)
2792930735cSGabor Horvath     return nullptr;
2802930735cSGabor Horvath 
28128690925SGabor Horvath   auto RegionSVal = Val.getAs<loc::MemRegionVal>();
28228690925SGabor Horvath   if (!RegionSVal)
28328690925SGabor Horvath     return nullptr;
28428690925SGabor Horvath 
28528690925SGabor Horvath   const MemRegion *Region = RegionSVal->getRegion();
28628690925SGabor Horvath 
28728690925SGabor Horvath   if (CheckSuperRegion) {
28828690925SGabor Horvath     if (auto FieldReg = Region->getAs<FieldRegion>())
28928690925SGabor Horvath       return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
2903943adb5SGabor Horvath     if (auto ElementReg = Region->getAs<ElementRegion>())
29128690925SGabor Horvath       return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
29228690925SGabor Horvath   }
29328690925SGabor Horvath 
29428690925SGabor Horvath   return dyn_cast<SymbolicRegion>(Region);
29528690925SGabor Horvath }
29628690925SGabor Horvath 
VisitNode(const ExplodedNode * N,BugReporterContext & BRC,PathSensitiveBugReport & BR)2976d716ef1SKristof Umann PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
2982f169e7cSArtem Dergachev     const ExplodedNode *N, BugReporterContext &BRC,
2992f169e7cSArtem Dergachev     PathSensitiveBugReport &BR) {
3003943adb5SGabor Horvath   ProgramStateRef State = N->getState();
301c82d457dSGeorge Karpenkov   ProgramStateRef StatePrev = N->getFirstPred()->getState();
30228690925SGabor Horvath 
3033943adb5SGabor Horvath   const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
30428690925SGabor Horvath   const NullabilityState *TrackedNullabPrev =
3053943adb5SGabor Horvath       StatePrev->get<NullabilityMap>(Region);
30628690925SGabor Horvath   if (!TrackedNullab)
30728690925SGabor Horvath     return nullptr;
30828690925SGabor Horvath 
30928690925SGabor Horvath   if (TrackedNullabPrev &&
31028690925SGabor Horvath       TrackedNullabPrev->getValue() == TrackedNullab->getValue())
31128690925SGabor Horvath     return nullptr;
31228690925SGabor Horvath 
31328690925SGabor Horvath   // Retrieve the associated statement.
31428690925SGabor Horvath   const Stmt *S = TrackedNullab->getNullabilitySource();
315f2ceec48SStephen Kelly   if (!S || S->getBeginLoc().isInvalid()) {
3166b85f8e9SArtem Dergachev     S = N->getStmtForDiagnostics();
31728690925SGabor Horvath   }
31828690925SGabor Horvath 
31928690925SGabor Horvath   if (!S)
32028690925SGabor Horvath     return nullptr;
32128690925SGabor Horvath 
32228690925SGabor Horvath   std::string InfoText =
32328690925SGabor Horvath       (llvm::Twine("Nullability '") +
324c894ac81SDevin Coughlin        getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
32528690925SGabor Horvath           .str();
32628690925SGabor Horvath 
32728690925SGabor Horvath   // Generate the extra diagnostic.
32828690925SGabor Horvath   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
32928690925SGabor Horvath                              N->getLocationContext());
3308535b8ecSArtem Dergachev   return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
33128690925SGabor Horvath }
33228690925SGabor Horvath 
333cf439edaSArtem Dergachev /// Returns true when the value stored at the given location has been
334cf439edaSArtem Dergachev /// constrained to null after being passed through an object of nonnnull type.
checkValueAtLValForInvariantViolation(ProgramStateRef State,SVal LV,QualType T)335b2d2a018SDevin Coughlin static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
336b2d2a018SDevin Coughlin                                                   SVal LV, QualType T) {
337b2d2a018SDevin Coughlin   if (getNullabilityAnnotation(T) != Nullability::Nonnull)
338b2d2a018SDevin Coughlin     return false;
339b2d2a018SDevin Coughlin 
340b2d2a018SDevin Coughlin   auto RegionVal = LV.getAs<loc::MemRegionVal>();
341b2d2a018SDevin Coughlin   if (!RegionVal)
342b2d2a018SDevin Coughlin     return false;
343b2d2a018SDevin Coughlin 
344cf439edaSArtem Dergachev   // If the value was constrained to null *after* it was passed through that
345cf439edaSArtem Dergachev   // location, it could not have been a concrete pointer *when* it was passed.
346cf439edaSArtem Dergachev   // In that case we would have handled the situation when the value was
347cf439edaSArtem Dergachev   // bound to that location, by emitting (or not emitting) a report.
348cf439edaSArtem Dergachev   // Therefore we are only interested in symbolic regions that can be either
349cf439edaSArtem Dergachev   // null or non-null depending on the value of their respective symbol.
350cf439edaSArtem Dergachev   auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
351cf439edaSArtem Dergachev   if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
352b2d2a018SDevin Coughlin     return false;
353b2d2a018SDevin Coughlin 
354b2d2a018SDevin Coughlin   if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
355b2d2a018SDevin Coughlin     return true;
356b2d2a018SDevin Coughlin 
357b2d2a018SDevin Coughlin   return false;
358b2d2a018SDevin Coughlin }
359b2d2a018SDevin Coughlin 
360b47128aaSGabor Horvath static bool
checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl * > Params,ProgramStateRef State,const LocationContext * LocCtxt)361b2d2a018SDevin Coughlin checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
362b47128aaSGabor Horvath                                     ProgramStateRef State,
363b47128aaSGabor Horvath                                     const LocationContext *LocCtxt) {
364b47128aaSGabor Horvath   for (const auto *ParamDecl : Params) {
365b47128aaSGabor Horvath     if (ParamDecl->isParameterPack())
366b47128aaSGabor Horvath       break;
367b47128aaSGabor Horvath 
368b2d2a018SDevin Coughlin     SVal LV = State->getLValue(ParamDecl, LocCtxt);
369b2d2a018SDevin Coughlin     if (checkValueAtLValForInvariantViolation(State, LV,
370b2d2a018SDevin Coughlin                                               ParamDecl->getType())) {
371b2d2a018SDevin Coughlin       return true;
372b2d2a018SDevin Coughlin     }
373b2d2a018SDevin Coughlin   }
374b2d2a018SDevin Coughlin   return false;
375b2d2a018SDevin Coughlin }
376b47128aaSGabor Horvath 
377b2d2a018SDevin Coughlin static bool
checkSelfIvarsForInvariantViolation(ProgramStateRef State,const LocationContext * LocCtxt)378b2d2a018SDevin Coughlin checkSelfIvarsForInvariantViolation(ProgramStateRef State,
379b2d2a018SDevin Coughlin                                     const LocationContext *LocCtxt) {
380b2d2a018SDevin Coughlin   auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
381b2d2a018SDevin Coughlin   if (!MD || !MD->isInstanceMethod())
382b2d2a018SDevin Coughlin     return false;
383b47128aaSGabor Horvath 
384b2d2a018SDevin Coughlin   const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
385b2d2a018SDevin Coughlin   if (!SelfDecl)
386b2d2a018SDevin Coughlin     return false;
387b47128aaSGabor Horvath 
388b2d2a018SDevin Coughlin   SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
389b2d2a018SDevin Coughlin 
390b2d2a018SDevin Coughlin   const ObjCObjectPointerType *SelfType =
391b2d2a018SDevin Coughlin       dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
392b2d2a018SDevin Coughlin   if (!SelfType)
393b2d2a018SDevin Coughlin     return false;
394b2d2a018SDevin Coughlin 
395b2d2a018SDevin Coughlin   const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
396b2d2a018SDevin Coughlin   if (!ID)
397b2d2a018SDevin Coughlin     return false;
398b2d2a018SDevin Coughlin 
399b2d2a018SDevin Coughlin   for (const auto *IvarDecl : ID->ivars()) {
400b2d2a018SDevin Coughlin     SVal LV = State->getLValue(IvarDecl, SelfVal);
401b2d2a018SDevin Coughlin     if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
402b47128aaSGabor Horvath       return true;
403b47128aaSGabor Horvath     }
404b47128aaSGabor Horvath   }
405b47128aaSGabor Horvath   return false;
406b47128aaSGabor Horvath }
407b47128aaSGabor Horvath 
checkInvariantViolation(ProgramStateRef State,ExplodedNode * N,CheckerContext & C)40877942db0SDevin Coughlin static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
409b47128aaSGabor Horvath                                     CheckerContext &C) {
41077942db0SDevin Coughlin   if (State->get<InvariantViolated>())
411b47128aaSGabor Horvath     return true;
412b47128aaSGabor Horvath 
413b47128aaSGabor Horvath   const LocationContext *LocCtxt = C.getLocationContext();
414b47128aaSGabor Horvath   const Decl *D = LocCtxt->getDecl();
415b47128aaSGabor Horvath   if (!D)
416b47128aaSGabor Horvath     return false;
417b47128aaSGabor Horvath 
418851da71cSDevin Coughlin   ArrayRef<ParmVarDecl*> Params;
419851da71cSDevin Coughlin   if (const auto *BD = dyn_cast<BlockDecl>(D))
420851da71cSDevin Coughlin     Params = BD->parameters();
421851da71cSDevin Coughlin   else if (const auto *FD = dyn_cast<FunctionDecl>(D))
422851da71cSDevin Coughlin     Params = FD->parameters();
423851da71cSDevin Coughlin   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
424851da71cSDevin Coughlin     Params = MD->parameters();
425851da71cSDevin Coughlin   else
426b47128aaSGabor Horvath     return false;
427b47128aaSGabor Horvath 
428b2d2a018SDevin Coughlin   if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
429b2d2a018SDevin Coughlin       checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
430b47128aaSGabor Horvath     if (!N->isSink())
43177942db0SDevin Coughlin       C.addTransition(State->set<InvariantViolated>(true), N);
432b47128aaSGabor Horvath     return true;
433b47128aaSGabor Horvath   }
434b47128aaSGabor Horvath   return false;
435b47128aaSGabor Horvath }
436b47128aaSGabor Horvath 
reportBugIfInvariantHolds(StringRef Msg,ErrorKind Error,CheckKind CK,ExplodedNode * N,const MemRegion * Region,CheckerContext & C,const Stmt * ValueExpr,bool SuppressPath) const437e4e1080aSKirstóf Umann void NullabilityChecker::reportBugIfInvariantHolds(
438e4e1080aSKirstóf Umann     StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
439e4e1080aSKirstóf Umann     const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
440e4e1080aSKirstóf Umann     bool SuppressPath) const {
441b47128aaSGabor Horvath   ProgramStateRef OriginalState = N->getState();
442b47128aaSGabor Horvath 
44377942db0SDevin Coughlin   if (checkInvariantViolation(OriginalState, N, C))
444b47128aaSGabor Horvath     return;
445b47128aaSGabor Horvath   if (SuppressPath) {
44677942db0SDevin Coughlin     OriginalState = OriginalState->set<InvariantViolated>(true);
447b47128aaSGabor Horvath     N = C.addTransition(OriginalState, N);
448b47128aaSGabor Horvath   }
449b47128aaSGabor Horvath 
450e4e1080aSKirstóf Umann   reportBug(Msg, Error, CK, N, Region, C.getBugReporter(), ValueExpr);
451b47128aaSGabor Horvath }
452b47128aaSGabor Horvath 
45328690925SGabor Horvath /// Cleaning up the program state.
checkDeadSymbols(SymbolReaper & SR,CheckerContext & C) const45428690925SGabor Horvath void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
45528690925SGabor Horvath                                           CheckerContext &C) const {
45628690925SGabor Horvath   ProgramStateRef State = C.getState();
45728690925SGabor Horvath   NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
45828690925SGabor Horvath   for (NullabilityMapTy::iterator I = Nullabilities.begin(),
45928690925SGabor Horvath                                   E = Nullabilities.end();
46028690925SGabor Horvath        I != E; ++I) {
461be87d5bbSGabor Horvath     const auto *Region = I->first->getAs<SymbolicRegion>();
462be87d5bbSGabor Horvath     assert(Region && "Non-symbolic region is tracked.");
463be87d5bbSGabor Horvath     if (SR.isDead(Region->getSymbol())) {
46428690925SGabor Horvath       State = State->remove<NullabilityMap>(I->first);
46528690925SGabor Horvath     }
46628690925SGabor Horvath   }
467b47128aaSGabor Horvath   // When one of the nonnull arguments are constrained to be null, nullability
468b47128aaSGabor Horvath   // preconditions are violated. It is not enough to check this only when we
469b47128aaSGabor Horvath   // actually report an error, because at that time interesting symbols might be
470b47128aaSGabor Horvath   // reaped.
47177942db0SDevin Coughlin   if (checkInvariantViolation(State, C.getPredecessor(), C))
472b47128aaSGabor Horvath     return;
473b47128aaSGabor Horvath   C.addTransition(State);
47428690925SGabor Horvath }
47528690925SGabor Horvath 
47628690925SGabor Horvath /// This callback triggers when a pointer is dereferenced and the analyzer does
47728690925SGabor Horvath /// not know anything about the value of that pointer. When that pointer is
47828690925SGabor Horvath /// nullable, this code emits a warning.
checkEvent(ImplicitNullDerefEvent Event) const47928690925SGabor Horvath void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
48077942db0SDevin Coughlin   if (Event.SinkNode->getState()->get<InvariantViolated>())
481b47128aaSGabor Horvath     return;
482b47128aaSGabor Horvath 
48328690925SGabor Horvath   const MemRegion *Region =
48449a3ad21SRui Ueyama       getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
48528690925SGabor Horvath   if (!Region)
48628690925SGabor Horvath     return;
48728690925SGabor Horvath 
48828690925SGabor Horvath   ProgramStateRef State = Event.SinkNode->getState();
48928690925SGabor Horvath   const NullabilityState *TrackedNullability =
49028690925SGabor Horvath       State->get<NullabilityMap>(Region);
49128690925SGabor Horvath 
49228690925SGabor Horvath   if (!TrackedNullability)
49328690925SGabor Horvath     return;
49428690925SGabor Horvath 
495e4e1080aSKirstóf Umann   if (ChecksEnabled[CK_NullableDereferenced] &&
49628690925SGabor Horvath       TrackedNullability->getValue() == Nullability::Nullable) {
49728690925SGabor Horvath     BugReporter &BR = *Event.BR;
498b47128aaSGabor Horvath     // Do not suppress errors on defensive code paths, because dereferencing
499b47128aaSGabor Horvath     // a nullable pointer is always an error.
5008d3ad6b6SGabor Horvath     if (Event.IsDirectDereference)
501ad9e7ea6SAnna Zaks       reportBug("Nullable pointer is dereferenced",
502e4e1080aSKirstóf Umann                 ErrorKind::NullableDereferenced, CK_NullableDereferenced,
503e4e1080aSKirstóf Umann                 Event.SinkNode, Region, BR);
504ad9e7ea6SAnna Zaks     else {
505ad9e7ea6SAnna Zaks       reportBug("Nullable pointer is passed to a callee that requires a "
506e4e1080aSKirstóf Umann                 "non-null",
507e4e1080aSKirstóf Umann                 ErrorKind::NullablePassedToNonnull, CK_NullableDereferenced,
508ad9e7ea6SAnna Zaks                 Event.SinkNode, Region, BR);
509ad9e7ea6SAnna Zaks     }
51028690925SGabor Horvath   }
51128690925SGabor Horvath }
51228690925SGabor Horvath 
51309a1f090SValeriy Savchenko // Whenever we see a load from a typed memory region that's been annotated as
51409a1f090SValeriy Savchenko // 'nonnull', we want to trust the user on that and assume that it is is indeed
51509a1f090SValeriy Savchenko // non-null.
51609a1f090SValeriy Savchenko //
51709a1f090SValeriy Savchenko // We do so even if the value is known to have been assigned to null.
51809a1f090SValeriy Savchenko // The user should be warned on assigning the null value to a non-null pointer
51909a1f090SValeriy Savchenko // as opposed to warning on the later dereference of this pointer.
52009a1f090SValeriy Savchenko //
52109a1f090SValeriy Savchenko // \code
52209a1f090SValeriy Savchenko //   int * _Nonnull var = 0; // we want to warn the user here...
52309a1f090SValeriy Savchenko //   // . . .
52409a1f090SValeriy Savchenko //   *var = 42;              // ...and not here
52509a1f090SValeriy Savchenko // \endcode
checkLocation(SVal Location,bool IsLoad,const Stmt * S,CheckerContext & Context) const52609a1f090SValeriy Savchenko void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
52709a1f090SValeriy Savchenko                                        const Stmt *S,
52809a1f090SValeriy Savchenko                                        CheckerContext &Context) const {
52909a1f090SValeriy Savchenko   // We should care only about loads.
53009a1f090SValeriy Savchenko   // The main idea is to add a constraint whenever we're loading a value from
53109a1f090SValeriy Savchenko   // an annotated pointer type.
53209a1f090SValeriy Savchenko   if (!IsLoad)
53309a1f090SValeriy Savchenko     return;
53409a1f090SValeriy Savchenko 
53509a1f090SValeriy Savchenko   // Annotations that we want to consider make sense only for types.
53609a1f090SValeriy Savchenko   const auto *Region =
53709a1f090SValeriy Savchenko       dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
53809a1f090SValeriy Savchenko   if (!Region)
53909a1f090SValeriy Savchenko     return;
54009a1f090SValeriy Savchenko 
54109a1f090SValeriy Savchenko   ProgramStateRef State = Context.getState();
54209a1f090SValeriy Savchenko 
54309a1f090SValeriy Savchenko   auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
54409a1f090SValeriy Savchenko   if (!StoredVal)
54509a1f090SValeriy Savchenko     return;
54609a1f090SValeriy Savchenko 
54709a1f090SValeriy Savchenko   Nullability NullabilityOfTheLoadedValue =
54809a1f090SValeriy Savchenko       getNullabilityAnnotation(Region->getValueType());
54909a1f090SValeriy Savchenko 
55009a1f090SValeriy Savchenko   if (NullabilityOfTheLoadedValue == Nullability::Nonnull) {
55109a1f090SValeriy Savchenko     // It doesn't matter what we think about this particular pointer, it should
55209a1f090SValeriy Savchenko     // be considered non-null as annotated by the developer.
55309a1f090SValeriy Savchenko     if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
55409a1f090SValeriy Savchenko       Context.addTransition(NewState);
55509a1f090SValeriy Savchenko     }
55609a1f090SValeriy Savchenko   }
55709a1f090SValeriy Savchenko }
55809a1f090SValeriy Savchenko 
5595a3843e5SDevin Coughlin /// Find the outermost subexpression of E that is not an implicit cast.
5605a3843e5SDevin Coughlin /// This looks through the implicit casts to _Nonnull that ARC adds to
5615a3843e5SDevin Coughlin /// return expressions of ObjC types when the return type of the function or
5625a3843e5SDevin Coughlin /// method is non-null but the express is not.
lookThroughImplicitCasts(const Expr * E)5635a3843e5SDevin Coughlin static const Expr *lookThroughImplicitCasts(const Expr *E) {
5647ea64ae3SNico Weber   return E->IgnoreImpCasts();
5655a3843e5SDevin Coughlin }
5665a3843e5SDevin Coughlin 
56728690925SGabor Horvath /// This method check when nullable pointer or null value is returned from a
56828690925SGabor Horvath /// function that has nonnull return type.
checkPreStmt(const ReturnStmt * S,CheckerContext & C) const56928690925SGabor Horvath void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
57028690925SGabor Horvath                                       CheckerContext &C) const {
57128690925SGabor Horvath   auto RetExpr = S->getRetValue();
57228690925SGabor Horvath   if (!RetExpr)
57328690925SGabor Horvath     return;
57428690925SGabor Horvath 
57528690925SGabor Horvath   if (!RetExpr->getType()->isAnyPointerType())
57628690925SGabor Horvath     return;
57728690925SGabor Horvath 
57828690925SGabor Horvath   ProgramStateRef State = C.getState();
57977942db0SDevin Coughlin   if (State->get<InvariantViolated>())
580b47128aaSGabor Horvath     return;
581b47128aaSGabor Horvath 
582d703ec94SGeorge Karpenkov   auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
58328690925SGabor Horvath   if (!RetSVal)
58428690925SGabor Horvath     return;
58528690925SGabor Horvath 
586de21767aSDevin Coughlin   bool InSuppressedMethodFamily = false;
5874a330201SDevin Coughlin 
588851da71cSDevin Coughlin   QualType RequiredRetType;
58928690925SGabor Horvath   AnalysisDeclContext *DeclCtxt =
59028690925SGabor Horvath       C.getLocationContext()->getAnalysisDeclContext();
591851da71cSDevin Coughlin   const Decl *D = DeclCtxt->getDecl();
5924a330201SDevin Coughlin   if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
593de21767aSDevin Coughlin     // HACK: This is a big hammer to avoid warning when there are defensive
594de21767aSDevin Coughlin     // nil checks in -init and -copy methods. We should add more sophisticated
595de21767aSDevin Coughlin     // logic here to suppress on common defensive idioms but still
596de21767aSDevin Coughlin     // warn when there is a likely problem.
597de21767aSDevin Coughlin     ObjCMethodFamily Family = MD->getMethodFamily();
598de21767aSDevin Coughlin     if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
599de21767aSDevin Coughlin       InSuppressedMethodFamily = true;
600de21767aSDevin Coughlin 
601851da71cSDevin Coughlin     RequiredRetType = MD->getReturnType();
6024a330201SDevin Coughlin   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
603851da71cSDevin Coughlin     RequiredRetType = FD->getReturnType();
6044a330201SDevin Coughlin   } else {
60528690925SGabor Horvath     return;
6064a330201SDevin Coughlin   }
60728690925SGabor Horvath 
60828690925SGabor Horvath   NullConstraint Nullness = getNullConstraint(*RetSVal, State);
60928690925SGabor Horvath 
610851da71cSDevin Coughlin   Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
61128690925SGabor Horvath 
612755baa40SDevin Coughlin   // If the returned value is null but the type of the expression
613755baa40SDevin Coughlin   // generating it is nonnull then we will suppress the diagnostic.
614755baa40SDevin Coughlin   // This enables explicit suppression when returning a nil literal in a
615755baa40SDevin Coughlin   // function with a _Nonnull return type:
616755baa40SDevin Coughlin   //    return (NSString * _Nonnull)0;
617755baa40SDevin Coughlin   Nullability RetExprTypeLevelNullability =
6185a3843e5SDevin Coughlin         getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
619755baa40SDevin Coughlin 
62077942db0SDevin Coughlin   bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
62177942db0SDevin Coughlin                                   Nullness == NullConstraint::IsNull);
622e4e1080aSKirstóf Umann   if (ChecksEnabled[CK_NullReturnedFromNonnull] && NullReturnedFromNonNull &&
623755baa40SDevin Coughlin       RetExprTypeLevelNullability != Nullability::Nonnull &&
624e4e1080aSKirstóf Umann       !InSuppressedMethodFamily && C.getLocationContext()->inTopFrame()) {
62528690925SGabor Horvath     static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
626e39bd407SDevin Coughlin     ExplodedNode *N = C.generateErrorNode(State, &Tag);
627e39bd407SDevin Coughlin     if (!N)
628e39bd407SDevin Coughlin       return;
629ad9e7ea6SAnna Zaks 
630ad9e7ea6SAnna Zaks     SmallString<256> SBuf;
631ad9e7ea6SAnna Zaks     llvm::raw_svector_ostream OS(SBuf);
6326d4e76b9SAnna Zaks     OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
6336d4e76b9SAnna Zaks     OS << " returned from a " << C.getDeclDescription(D) <<
634ad9e7ea6SAnna Zaks           " that is expected to return a non-null value";
635e4e1080aSKirstóf Umann     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
636e4e1080aSKirstóf Umann                               CK_NullReturnedFromNonnull, N, nullptr, C,
637b47128aaSGabor Horvath                               RetExpr);
63828690925SGabor Horvath     return;
63928690925SGabor Horvath   }
64028690925SGabor Horvath 
64177942db0SDevin Coughlin   // If null was returned from a non-null function, mark the nullability
64277942db0SDevin Coughlin   // invariant as violated even if the diagnostic was suppressed.
64377942db0SDevin Coughlin   if (NullReturnedFromNonNull) {
64477942db0SDevin Coughlin     State = State->set<InvariantViolated>(true);
64577942db0SDevin Coughlin     C.addTransition(State);
64677942db0SDevin Coughlin     return;
64777942db0SDevin Coughlin   }
64877942db0SDevin Coughlin 
64928690925SGabor Horvath   const MemRegion *Region = getTrackRegion(*RetSVal);
65028690925SGabor Horvath   if (!Region)
65128690925SGabor Horvath     return;
65228690925SGabor Horvath 
65328690925SGabor Horvath   const NullabilityState *TrackedNullability =
65428690925SGabor Horvath       State->get<NullabilityMap>(Region);
65528690925SGabor Horvath   if (TrackedNullability) {
65628690925SGabor Horvath     Nullability TrackedNullabValue = TrackedNullability->getValue();
657e4e1080aSKirstóf Umann     if (ChecksEnabled[CK_NullableReturnedFromNonnull] &&
65828690925SGabor Horvath         Nullness != NullConstraint::IsNotNull &&
65928690925SGabor Horvath         TrackedNullabValue == Nullability::Nullable &&
660755baa40SDevin Coughlin         RequiredNullability == Nullability::Nonnull) {
66128690925SGabor Horvath       static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
66228690925SGabor Horvath       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
663ad9e7ea6SAnna Zaks 
664ad9e7ea6SAnna Zaks       SmallString<256> SBuf;
665ad9e7ea6SAnna Zaks       llvm::raw_svector_ostream OS(SBuf);
666ad9e7ea6SAnna Zaks       OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
667ad9e7ea6SAnna Zaks             " that is expected to return a non-null value";
668ad9e7ea6SAnna Zaks 
669e4e1080aSKirstóf Umann       reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
670e4e1080aSKirstóf Umann                                 CK_NullableReturnedFromNonnull, N, Region, C);
67128690925SGabor Horvath     }
67228690925SGabor Horvath     return;
67328690925SGabor Horvath   }
674755baa40SDevin Coughlin   if (RequiredNullability == Nullability::Nullable) {
67528690925SGabor Horvath     State = State->set<NullabilityMap>(Region,
676755baa40SDevin Coughlin                                        NullabilityState(RequiredNullability,
677755baa40SDevin Coughlin                                                         S));
67828690925SGabor Horvath     C.addTransition(State);
67928690925SGabor Horvath   }
68028690925SGabor Horvath }
68128690925SGabor Horvath 
68228690925SGabor Horvath /// This callback warns when a nullable pointer or a null value is passed to a
68328690925SGabor Horvath /// function that expects its argument to be nonnull.
checkPreCall(const CallEvent & Call,CheckerContext & C) const68428690925SGabor Horvath void NullabilityChecker::checkPreCall(const CallEvent &Call,
68528690925SGabor Horvath                                       CheckerContext &C) const {
68628690925SGabor Horvath   if (!Call.getDecl())
68728690925SGabor Horvath     return;
68828690925SGabor Horvath 
68928690925SGabor Horvath   ProgramStateRef State = C.getState();
69077942db0SDevin Coughlin   if (State->get<InvariantViolated>())
691b47128aaSGabor Horvath     return;
692b47128aaSGabor Horvath 
69328690925SGabor Horvath   ProgramStateRef OrigState = State;
69428690925SGabor Horvath 
69528690925SGabor Horvath   unsigned Idx = 0;
69628690925SGabor Horvath   for (const ParmVarDecl *Param : Call.parameters()) {
69728690925SGabor Horvath     if (Param->isParameterPack())
69828690925SGabor Horvath       break;
69928690925SGabor Horvath 
700e4224cc9SDevin Coughlin     if (Idx >= Call.getNumArgs())
701e4224cc9SDevin Coughlin       break;
702e4224cc9SDevin Coughlin 
703e4224cc9SDevin Coughlin     const Expr *ArgExpr = Call.getArgExpr(Idx);
70428690925SGabor Horvath     auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
70528690925SGabor Horvath     if (!ArgSVal)
70628690925SGabor Horvath       continue;
70728690925SGabor Horvath 
70828690925SGabor Horvath     if (!Param->getType()->isAnyPointerType() &&
70928690925SGabor Horvath         !Param->getType()->isReferenceType())
71028690925SGabor Horvath       continue;
71128690925SGabor Horvath 
71228690925SGabor Horvath     NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
71328690925SGabor Horvath 
714755baa40SDevin Coughlin     Nullability RequiredNullability =
715755baa40SDevin Coughlin         getNullabilityAnnotation(Param->getType());
716755baa40SDevin Coughlin     Nullability ArgExprTypeLevelNullability =
71728690925SGabor Horvath         getNullabilityAnnotation(ArgExpr->getType());
71828690925SGabor Horvath 
719ad9e7ea6SAnna Zaks     unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
720ad9e7ea6SAnna Zaks 
721e4e1080aSKirstóf Umann     if (ChecksEnabled[CK_NullPassedToNonnull] &&
722e4e1080aSKirstóf Umann         Nullness == NullConstraint::IsNull &&
723755baa40SDevin Coughlin         ArgExprTypeLevelNullability != Nullability::Nonnull &&
724a1d9d75aSDevin Coughlin         RequiredNullability == Nullability::Nonnull &&
725a1d9d75aSDevin Coughlin         isDiagnosableCall(Call)) {
726e39bd407SDevin Coughlin       ExplodedNode *N = C.generateErrorNode(State);
727e39bd407SDevin Coughlin       if (!N)
728e39bd407SDevin Coughlin         return;
7296d4e76b9SAnna Zaks 
730ad9e7ea6SAnna Zaks       SmallString<256> SBuf;
731ad9e7ea6SAnna Zaks       llvm::raw_svector_ostream OS(SBuf);
7326d4e76b9SAnna Zaks       OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
7336d4e76b9SAnna Zaks       OS << " passed to a callee that requires a non-null " << ParamIdx
734ad9e7ea6SAnna Zaks          << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
735e4e1080aSKirstóf Umann       reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
736e4e1080aSKirstóf Umann                                 CK_NullPassedToNonnull, N, nullptr, C, ArgExpr,
737e4e1080aSKirstóf Umann                                 /*SuppressPath=*/false);
73828690925SGabor Horvath       return;
73928690925SGabor Horvath     }
74028690925SGabor Horvath 
74128690925SGabor Horvath     const MemRegion *Region = getTrackRegion(*ArgSVal);
74228690925SGabor Horvath     if (!Region)
74328690925SGabor Horvath       continue;
74428690925SGabor Horvath 
74528690925SGabor Horvath     const NullabilityState *TrackedNullability =
74628690925SGabor Horvath         State->get<NullabilityMap>(Region);
74728690925SGabor Horvath 
74828690925SGabor Horvath     if (TrackedNullability) {
74928690925SGabor Horvath       if (Nullness == NullConstraint::IsNotNull ||
75028690925SGabor Horvath           TrackedNullability->getValue() != Nullability::Nullable)
75128690925SGabor Horvath         continue;
75228690925SGabor Horvath 
753e4e1080aSKirstóf Umann       if (ChecksEnabled[CK_NullablePassedToNonnull] &&
754a1d9d75aSDevin Coughlin           RequiredNullability == Nullability::Nonnull &&
755a1d9d75aSDevin Coughlin           isDiagnosableCall(Call)) {
756b47128aaSGabor Horvath         ExplodedNode *N = C.addTransition(State);
757ad9e7ea6SAnna Zaks         SmallString<256> SBuf;
758ad9e7ea6SAnna Zaks         llvm::raw_svector_ostream OS(SBuf);
759ad9e7ea6SAnna Zaks         OS << "Nullable pointer is passed to a callee that requires a non-null "
760ad9e7ea6SAnna Zaks            << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
761e4e1080aSKirstóf Umann         reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
762e4e1080aSKirstóf Umann                                   CK_NullablePassedToNonnull, N, Region, C,
763e4e1080aSKirstóf Umann                                   ArgExpr, /*SuppressPath=*/true);
76428690925SGabor Horvath         return;
76528690925SGabor Horvath       }
766e4e1080aSKirstóf Umann       if (ChecksEnabled[CK_NullableDereferenced] &&
76728690925SGabor Horvath           Param->getType()->isReferenceType()) {
768b47128aaSGabor Horvath         ExplodedNode *N = C.addTransition(State);
76977942db0SDevin Coughlin         reportBugIfInvariantHolds("Nullable pointer is dereferenced",
770e4e1080aSKirstóf Umann                                   ErrorKind::NullableDereferenced,
771e4e1080aSKirstóf Umann                                   CK_NullableDereferenced, N, Region, C,
772e4e1080aSKirstóf Umann                                   ArgExpr, /*SuppressPath=*/true);
77328690925SGabor Horvath         return;
77428690925SGabor Horvath       }
77528690925SGabor Horvath       continue;
77628690925SGabor Horvath     }
77728690925SGabor Horvath   }
77828690925SGabor Horvath   if (State != OrigState)
77928690925SGabor Horvath     C.addTransition(State);
78028690925SGabor Horvath }
78128690925SGabor Horvath 
78228690925SGabor Horvath /// Suppress the nullability warnings for some functions.
checkPostCall(const CallEvent & Call,CheckerContext & C) const78328690925SGabor Horvath void NullabilityChecker::checkPostCall(const CallEvent &Call,
78428690925SGabor Horvath                                        CheckerContext &C) const {
78528690925SGabor Horvath   auto Decl = Call.getDecl();
78628690925SGabor Horvath   if (!Decl)
78728690925SGabor Horvath     return;
78828690925SGabor Horvath   // ObjC Messages handles in a different callback.
78928690925SGabor Horvath   if (Call.getKind() == CE_ObjCMessage)
79028690925SGabor Horvath     return;
79128690925SGabor Horvath   const FunctionType *FuncType = Decl->getFunctionType();
79228690925SGabor Horvath   if (!FuncType)
79328690925SGabor Horvath     return;
79428690925SGabor Horvath   QualType ReturnType = FuncType->getReturnType();
79528690925SGabor Horvath   if (!ReturnType->isAnyPointerType())
79628690925SGabor Horvath     return;
797b47128aaSGabor Horvath   ProgramStateRef State = C.getState();
79877942db0SDevin Coughlin   if (State->get<InvariantViolated>())
799b47128aaSGabor Horvath     return;
800b47128aaSGabor Horvath 
80128690925SGabor Horvath   const MemRegion *Region = getTrackRegion(Call.getReturnValue());
80228690925SGabor Horvath   if (!Region)
80328690925SGabor Horvath     return;
80428690925SGabor Horvath 
80528690925SGabor Horvath   // CG headers are misannotated. Do not warn for symbols that are the results
80628690925SGabor Horvath   // of CG calls.
80728690925SGabor Horvath   const SourceManager &SM = C.getSourceManager();
808f2ceec48SStephen Kelly   StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
80928690925SGabor Horvath   if (llvm::sys::path::filename(FilePath).startswith("CG")) {
81028690925SGabor Horvath     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
81128690925SGabor Horvath     C.addTransition(State);
81228690925SGabor Horvath     return;
81328690925SGabor Horvath   }
81428690925SGabor Horvath 
81528690925SGabor Horvath   const NullabilityState *TrackedNullability =
81628690925SGabor Horvath       State->get<NullabilityMap>(Region);
81728690925SGabor Horvath 
81828690925SGabor Horvath   if (!TrackedNullability &&
81928690925SGabor Horvath       getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
82028690925SGabor Horvath     State = State->set<NullabilityMap>(Region, Nullability::Nullable);
82128690925SGabor Horvath     C.addTransition(State);
82228690925SGabor Horvath   }
82328690925SGabor Horvath }
82428690925SGabor Horvath 
getReceiverNullability(const ObjCMethodCall & M,ProgramStateRef State)82528690925SGabor Horvath static Nullability getReceiverNullability(const ObjCMethodCall &M,
82628690925SGabor Horvath                                           ProgramStateRef State) {
82728690925SGabor Horvath   if (M.isReceiverSelfOrSuper()) {
82828690925SGabor Horvath     // For super and super class receivers we assume that the receiver is
82928690925SGabor Horvath     // nonnull.
8303943adb5SGabor Horvath     return Nullability::Nonnull;
8313943adb5SGabor Horvath   }
83228690925SGabor Horvath   // Otherwise look up nullability in the state.
83328690925SGabor Horvath   SVal Receiver = M.getReceiverSVal();
8343943adb5SGabor Horvath   if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
8353943adb5SGabor Horvath     // If the receiver is constrained to be nonnull, assume that it is nonnull
8363943adb5SGabor Horvath     // regardless of its type.
8373943adb5SGabor Horvath     NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
8383943adb5SGabor Horvath     if (Nullness == NullConstraint::IsNotNull)
8393943adb5SGabor Horvath       return Nullability::Nonnull;
8403943adb5SGabor Horvath   }
84128690925SGabor Horvath   auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
84228690925SGabor Horvath   if (ValueRegionSVal) {
84328690925SGabor Horvath     const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
84428690925SGabor Horvath     assert(SelfRegion);
84528690925SGabor Horvath 
84628690925SGabor Horvath     const NullabilityState *TrackedSelfNullability =
84728690925SGabor Horvath         State->get<NullabilityMap>(SelfRegion);
8483943adb5SGabor Horvath     if (TrackedSelfNullability)
8493943adb5SGabor Horvath       return TrackedSelfNullability->getValue();
85028690925SGabor Horvath   }
8513943adb5SGabor Horvath   return Nullability::Unspecified;
85228690925SGabor Horvath }
85328690925SGabor Horvath 
85428690925SGabor Horvath /// Calculate the nullability of the result of a message expr based on the
85528690925SGabor Horvath /// nullability of the receiver, the nullability of the return value, and the
85628690925SGabor Horvath /// constraints.
checkPostObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const85728690925SGabor Horvath void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
85828690925SGabor Horvath                                               CheckerContext &C) const {
85928690925SGabor Horvath   auto Decl = M.getDecl();
86028690925SGabor Horvath   if (!Decl)
86128690925SGabor Horvath     return;
86228690925SGabor Horvath   QualType RetType = Decl->getReturnType();
86328690925SGabor Horvath   if (!RetType->isAnyPointerType())
86428690925SGabor Horvath     return;
86528690925SGabor Horvath 
866b47128aaSGabor Horvath   ProgramStateRef State = C.getState();
86777942db0SDevin Coughlin   if (State->get<InvariantViolated>())
868b47128aaSGabor Horvath     return;
869b47128aaSGabor Horvath 
87028690925SGabor Horvath   const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
87128690925SGabor Horvath   if (!ReturnRegion)
87228690925SGabor Horvath     return;
87328690925SGabor Horvath 
87428690925SGabor Horvath   auto Interface = Decl->getClassInterface();
87528690925SGabor Horvath   auto Name = Interface ? Interface->getName() : "";
87628690925SGabor Horvath   // In order to reduce the noise in the diagnostics generated by this checker,
87728690925SGabor Horvath   // some framework and programming style based heuristics are used. These
87828690925SGabor Horvath   // heuristics are for Cocoa APIs which have NS prefix.
87928690925SGabor Horvath   if (Name.startswith("NS")) {
88028690925SGabor Horvath     // Developers rely on dynamic invariants such as an item should be available
88128690925SGabor Horvath     // in a collection, or a collection is not empty often. Those invariants can
88228690925SGabor Horvath     // not be inferred by any static analysis tool. To not to bother the users
88328690925SGabor Horvath     // with too many false positives, every item retrieval function should be
88428690925SGabor Horvath     // ignored for collections. The instance methods of dictionaries in Cocoa
88528690925SGabor Horvath     // are either item retrieval related or not interesting nullability wise.
88628690925SGabor Horvath     // Using this fact, to keep the code easier to read just ignore the return
88728690925SGabor Horvath     // value of every instance method of dictionaries.
8882301c5abSGeorge Karpenkov     if (M.isInstanceMessage() && Name.contains("Dictionary")) {
88928690925SGabor Horvath       State =
89028690925SGabor Horvath           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
89128690925SGabor Horvath       C.addTransition(State);
89228690925SGabor Horvath       return;
89328690925SGabor Horvath     }
89428690925SGabor Horvath     // For similar reasons ignore some methods of Cocoa arrays.
89528690925SGabor Horvath     StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
8962301c5abSGeorge Karpenkov     if (Name.contains("Array") &&
89728690925SGabor Horvath         (FirstSelectorSlot == "firstObject" ||
89828690925SGabor Horvath          FirstSelectorSlot == "lastObject")) {
89928690925SGabor Horvath       State =
90028690925SGabor Horvath           State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
90128690925SGabor Horvath       C.addTransition(State);
90228690925SGabor Horvath       return;
90328690925SGabor Horvath     }
90428690925SGabor Horvath 
90528690925SGabor Horvath     // Encoding related methods of string should not fail when lossless
90628690925SGabor Horvath     // encodings are used. Using lossless encodings is so frequent that ignoring
90728690925SGabor Horvath     // this class of methods reduced the emitted diagnostics by about 30% on
90828690925SGabor Horvath     // some projects (and all of that was false positives).
9092301c5abSGeorge Karpenkov     if (Name.contains("String")) {
91028690925SGabor Horvath       for (auto Param : M.parameters()) {
91128690925SGabor Horvath         if (Param->getName() == "encoding") {
91228690925SGabor Horvath           State = State->set<NullabilityMap>(ReturnRegion,
91328690925SGabor Horvath                                              Nullability::Contradicted);
91428690925SGabor Horvath           C.addTransition(State);
91528690925SGabor Horvath           return;
91628690925SGabor Horvath         }
91728690925SGabor Horvath       }
91828690925SGabor Horvath     }
91928690925SGabor Horvath   }
92028690925SGabor Horvath 
92128690925SGabor Horvath   const ObjCMessageExpr *Message = M.getOriginExpr();
92228690925SGabor Horvath   Nullability SelfNullability = getReceiverNullability(M, State);
92328690925SGabor Horvath 
92428690925SGabor Horvath   const NullabilityState *NullabilityOfReturn =
92528690925SGabor Horvath       State->get<NullabilityMap>(ReturnRegion);
92628690925SGabor Horvath 
92728690925SGabor Horvath   if (NullabilityOfReturn) {
92828690925SGabor Horvath     // When we have a nullability tracked for the return value, the nullability
92928690925SGabor Horvath     // of the expression will be the most nullable of the receiver and the
93028690925SGabor Horvath     // return value.
93128690925SGabor Horvath     Nullability RetValTracked = NullabilityOfReturn->getValue();
93228690925SGabor Horvath     Nullability ComputedNullab =
93328690925SGabor Horvath         getMostNullable(RetValTracked, SelfNullability);
93428690925SGabor Horvath     if (ComputedNullab != RetValTracked &&
93528690925SGabor Horvath         ComputedNullab != Nullability::Unspecified) {
93628690925SGabor Horvath       const Stmt *NullabilitySource =
93728690925SGabor Horvath           ComputedNullab == RetValTracked
93828690925SGabor Horvath               ? NullabilityOfReturn->getNullabilitySource()
93928690925SGabor Horvath               : Message->getInstanceReceiver();
94028690925SGabor Horvath       State = State->set<NullabilityMap>(
94128690925SGabor Horvath           ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
94228690925SGabor Horvath       C.addTransition(State);
94328690925SGabor Horvath     }
94428690925SGabor Horvath     return;
94528690925SGabor Horvath   }
94628690925SGabor Horvath 
94728690925SGabor Horvath   // No tracked information. Use static type information for return value.
94828690925SGabor Horvath   Nullability RetNullability = getNullabilityAnnotation(RetType);
94928690925SGabor Horvath 
95028690925SGabor Horvath   // Properties might be computed. For this reason the static analyzer creates a
95128690925SGabor Horvath   // new symbol each time an unknown property  is read. To avoid false pozitives
95228690925SGabor Horvath   // do not treat unknown properties as nullable, even when they explicitly
95328690925SGabor Horvath   // marked nullable.
95428690925SGabor Horvath   if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
95528690925SGabor Horvath     RetNullability = Nullability::Nonnull;
95628690925SGabor Horvath 
95728690925SGabor Horvath   Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
95828690925SGabor Horvath   if (ComputedNullab == Nullability::Nullable) {
95928690925SGabor Horvath     const Stmt *NullabilitySource = ComputedNullab == RetNullability
96028690925SGabor Horvath                                         ? Message
96128690925SGabor Horvath                                         : Message->getInstanceReceiver();
96228690925SGabor Horvath     State = State->set<NullabilityMap>(
96328690925SGabor Horvath         ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
96428690925SGabor Horvath     C.addTransition(State);
96528690925SGabor Horvath   }
96628690925SGabor Horvath }
96728690925SGabor Horvath 
96828690925SGabor Horvath /// Explicit casts are trusted. If there is a disagreement in the nullability
96928690925SGabor Horvath /// annotations in the destination and the source or '0' is casted to nonnull
97028690925SGabor Horvath /// track the value as having contraditory nullability. This will allow users to
97128690925SGabor Horvath /// suppress warnings.
checkPostStmt(const ExplicitCastExpr * CE,CheckerContext & C) const97228690925SGabor Horvath void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
97328690925SGabor Horvath                                        CheckerContext &C) const {
97428690925SGabor Horvath   QualType OriginType = CE->getSubExpr()->getType();
97528690925SGabor Horvath   QualType DestType = CE->getType();
97628690925SGabor Horvath   if (!OriginType->isAnyPointerType())
97728690925SGabor Horvath     return;
97828690925SGabor Horvath   if (!DestType->isAnyPointerType())
97928690925SGabor Horvath     return;
98028690925SGabor Horvath 
981b47128aaSGabor Horvath   ProgramStateRef State = C.getState();
98277942db0SDevin Coughlin   if (State->get<InvariantViolated>())
983b47128aaSGabor Horvath     return;
984b47128aaSGabor Horvath 
98528690925SGabor Horvath   Nullability DestNullability = getNullabilityAnnotation(DestType);
98628690925SGabor Horvath 
98728690925SGabor Horvath   // No explicit nullability in the destination type, so this cast does not
98828690925SGabor Horvath   // change the nullability.
98928690925SGabor Horvath   if (DestNullability == Nullability::Unspecified)
99028690925SGabor Horvath     return;
99128690925SGabor Horvath 
992d703ec94SGeorge Karpenkov   auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
99328690925SGabor Horvath   const MemRegion *Region = getTrackRegion(*RegionSVal);
99428690925SGabor Horvath   if (!Region)
99528690925SGabor Horvath     return;
99628690925SGabor Horvath 
99728690925SGabor Horvath   // When 0 is converted to nonnull mark it as contradicted.
99828690925SGabor Horvath   if (DestNullability == Nullability::Nonnull) {
99928690925SGabor Horvath     NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
100028690925SGabor Horvath     if (Nullness == NullConstraint::IsNull) {
100128690925SGabor Horvath       State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
100228690925SGabor Horvath       C.addTransition(State);
100328690925SGabor Horvath       return;
100428690925SGabor Horvath     }
100528690925SGabor Horvath   }
100628690925SGabor Horvath 
100728690925SGabor Horvath   const NullabilityState *TrackedNullability =
100828690925SGabor Horvath       State->get<NullabilityMap>(Region);
100928690925SGabor Horvath 
101028690925SGabor Horvath   if (!TrackedNullability) {
101128690925SGabor Horvath     if (DestNullability != Nullability::Nullable)
101228690925SGabor Horvath       return;
101328690925SGabor Horvath     State = State->set<NullabilityMap>(Region,
101428690925SGabor Horvath                                        NullabilityState(DestNullability, CE));
101528690925SGabor Horvath     C.addTransition(State);
101628690925SGabor Horvath     return;
101728690925SGabor Horvath   }
101828690925SGabor Horvath 
101928690925SGabor Horvath   if (TrackedNullability->getValue() != DestNullability &&
102028690925SGabor Horvath       TrackedNullability->getValue() != Nullability::Contradicted) {
102128690925SGabor Horvath     State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
102228690925SGabor Horvath     C.addTransition(State);
102328690925SGabor Horvath   }
102428690925SGabor Horvath }
102528690925SGabor Horvath 
1026c1986638SDevin Coughlin /// For a given statement performing a bind, attempt to syntactically
1027c1986638SDevin Coughlin /// match the expression resulting in the bound value.
matchValueExprForBind(const Stmt * S)1028c1986638SDevin Coughlin static const Expr * matchValueExprForBind(const Stmt *S) {
1029c1986638SDevin Coughlin   // For `x = e` the value expression is the right-hand side.
1030c1986638SDevin Coughlin   if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
1031c1986638SDevin Coughlin     if (BinOp->getOpcode() == BO_Assign)
1032c1986638SDevin Coughlin       return BinOp->getRHS();
1033c1986638SDevin Coughlin   }
1034c1986638SDevin Coughlin 
1035c1986638SDevin Coughlin   // For `int x = e` the value expression is the initializer.
1036c1986638SDevin Coughlin   if (auto *DS = dyn_cast<DeclStmt>(S))  {
1037c1986638SDevin Coughlin     if (DS->isSingleDecl()) {
1038c1986638SDevin Coughlin       auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1039c1986638SDevin Coughlin       if (!VD)
1040c1986638SDevin Coughlin         return nullptr;
1041c1986638SDevin Coughlin 
1042c1986638SDevin Coughlin       if (const Expr *Init = VD->getInit())
1043c1986638SDevin Coughlin         return Init;
1044c1986638SDevin Coughlin     }
1045c1986638SDevin Coughlin   }
1046c1986638SDevin Coughlin 
1047c1986638SDevin Coughlin   return nullptr;
1048c1986638SDevin Coughlin }
1049c1986638SDevin Coughlin 
10503ab8b2e7SDevin Coughlin /// Returns true if \param S is a DeclStmt for a local variable that
10513ab8b2e7SDevin Coughlin /// ObjC automated reference counting initialized with zero.
isARCNilInitializedLocal(CheckerContext & C,const Stmt * S)10523ab8b2e7SDevin Coughlin static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
10533ab8b2e7SDevin Coughlin   // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
10543ab8b2e7SDevin Coughlin   // prevents false positives when a _Nonnull local variable cannot be
10553ab8b2e7SDevin Coughlin   // initialized with an initialization expression:
10563ab8b2e7SDevin Coughlin   //    NSString * _Nonnull s; // no-warning
10573ab8b2e7SDevin Coughlin   //    @autoreleasepool {
10583ab8b2e7SDevin Coughlin   //      s = ...
10593ab8b2e7SDevin Coughlin   //    }
10603ab8b2e7SDevin Coughlin   //
10613ab8b2e7SDevin Coughlin   // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
10623ab8b2e7SDevin Coughlin   // uninitialized in Sema's UninitializedValues analysis to warn when a use of
10633ab8b2e7SDevin Coughlin   // the zero-initialized definition will unexpectedly yield nil.
10643ab8b2e7SDevin Coughlin 
10653ab8b2e7SDevin Coughlin   // Locals are only zero-initialized when automated reference counting
10663ab8b2e7SDevin Coughlin   // is turned on.
10673ab8b2e7SDevin Coughlin   if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
10683ab8b2e7SDevin Coughlin     return false;
10693ab8b2e7SDevin Coughlin 
10703ab8b2e7SDevin Coughlin   auto *DS = dyn_cast<DeclStmt>(S);
10713ab8b2e7SDevin Coughlin   if (!DS || !DS->isSingleDecl())
10723ab8b2e7SDevin Coughlin     return false;
10733ab8b2e7SDevin Coughlin 
10743ab8b2e7SDevin Coughlin   auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
10753ab8b2e7SDevin Coughlin   if (!VD)
10763ab8b2e7SDevin Coughlin     return false;
10773ab8b2e7SDevin Coughlin 
10783ab8b2e7SDevin Coughlin   // Sema only zero-initializes locals with ObjCLifetimes.
10793ab8b2e7SDevin Coughlin   if(!VD->getType().getQualifiers().hasObjCLifetime())
10803ab8b2e7SDevin Coughlin     return false;
10813ab8b2e7SDevin Coughlin 
10823ab8b2e7SDevin Coughlin   const Expr *Init = VD->getInit();
10833ab8b2e7SDevin Coughlin   assert(Init && "ObjC local under ARC without initializer");
10843ab8b2e7SDevin Coughlin 
10853ab8b2e7SDevin Coughlin   // Return false if the local is explicitly initialized (e.g., with '= nil').
10863ab8b2e7SDevin Coughlin   if (!isa<ImplicitValueInitExpr>(Init))
10873ab8b2e7SDevin Coughlin     return false;
10883ab8b2e7SDevin Coughlin 
10893ab8b2e7SDevin Coughlin   return true;
10903ab8b2e7SDevin Coughlin }
10913ab8b2e7SDevin Coughlin 
109228690925SGabor Horvath /// Propagate the nullability information through binds and warn when nullable
109328690925SGabor Horvath /// pointer or null symbol is assigned to a pointer with a nonnull type.
checkBind(SVal L,SVal V,const Stmt * S,CheckerContext & C) const109428690925SGabor Horvath void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
109528690925SGabor Horvath                                    CheckerContext &C) const {
109628690925SGabor Horvath   const TypedValueRegion *TVR =
109728690925SGabor Horvath       dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
109828690925SGabor Horvath   if (!TVR)
109928690925SGabor Horvath     return;
110028690925SGabor Horvath 
110128690925SGabor Horvath   QualType LocType = TVR->getValueType();
110228690925SGabor Horvath   if (!LocType->isAnyPointerType())
110328690925SGabor Horvath     return;
110428690925SGabor Horvath 
1105b47128aaSGabor Horvath   ProgramStateRef State = C.getState();
110677942db0SDevin Coughlin   if (State->get<InvariantViolated>())
1107b47128aaSGabor Horvath     return;
1108b47128aaSGabor Horvath 
110928690925SGabor Horvath   auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
111028690925SGabor Horvath   if (!ValDefOrUnknown)
111128690925SGabor Horvath     return;
111228690925SGabor Horvath 
111328690925SGabor Horvath   NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
111428690925SGabor Horvath 
111528690925SGabor Horvath   Nullability ValNullability = Nullability::Unspecified;
111628690925SGabor Horvath   if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
111728690925SGabor Horvath     ValNullability = getNullabilityAnnotation(Sym->getType());
111828690925SGabor Horvath 
111928690925SGabor Horvath   Nullability LocNullability = getNullabilityAnnotation(LocType);
11204ac12425SDevin Coughlin 
11214ac12425SDevin Coughlin   // If the type of the RHS expression is nonnull, don't warn. This
11224ac12425SDevin Coughlin   // enables explicit suppression with a cast to nonnull.
11234ac12425SDevin Coughlin   Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
11244ac12425SDevin Coughlin   const Expr *ValueExpr = matchValueExprForBind(S);
11254ac12425SDevin Coughlin   if (ValueExpr) {
11264ac12425SDevin Coughlin     ValueExprTypeLevelNullability =
11274ac12425SDevin Coughlin       getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
11284ac12425SDevin Coughlin   }
11294ac12425SDevin Coughlin 
11304ac12425SDevin Coughlin   bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
11314ac12425SDevin Coughlin                                 RhsNullness == NullConstraint::IsNull);
1132e4e1080aSKirstóf Umann   if (ChecksEnabled[CK_NullPassedToNonnull] && NullAssignedToNonNull &&
113328690925SGabor Horvath       ValNullability != Nullability::Nonnull &&
11344ac12425SDevin Coughlin       ValueExprTypeLevelNullability != Nullability::Nonnull &&
11353ab8b2e7SDevin Coughlin       !isARCNilInitializedLocal(C, S)) {
113628690925SGabor Horvath     static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
1137e39bd407SDevin Coughlin     ExplodedNode *N = C.generateErrorNode(State, &Tag);
1138e39bd407SDevin Coughlin     if (!N)
1139e39bd407SDevin Coughlin       return;
1140c1986638SDevin Coughlin 
11414ac12425SDevin Coughlin 
11424ac12425SDevin Coughlin     const Stmt *ValueStmt = S;
11434ac12425SDevin Coughlin     if (ValueExpr)
11444ac12425SDevin Coughlin       ValueStmt = ValueExpr;
1145c1986638SDevin Coughlin 
11466d4e76b9SAnna Zaks     SmallString<256> SBuf;
11476d4e76b9SAnna Zaks     llvm::raw_svector_ostream OS(SBuf);
11486d4e76b9SAnna Zaks     OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
11496d4e76b9SAnna Zaks     OS << " assigned to a pointer which is expected to have non-null value";
1150e4e1080aSKirstóf Umann     reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
1151e4e1080aSKirstóf Umann                               CK_NullPassedToNonnull, N, nullptr, C, ValueStmt);
115228690925SGabor Horvath     return;
115328690925SGabor Horvath   }
11544ac12425SDevin Coughlin 
11554ac12425SDevin Coughlin   // If null was returned from a non-null function, mark the nullability
11564ac12425SDevin Coughlin   // invariant as violated even if the diagnostic was suppressed.
11574ac12425SDevin Coughlin   if (NullAssignedToNonNull) {
11584ac12425SDevin Coughlin     State = State->set<InvariantViolated>(true);
11594ac12425SDevin Coughlin     C.addTransition(State);
11604ac12425SDevin Coughlin     return;
11614ac12425SDevin Coughlin   }
11624ac12425SDevin Coughlin 
116328690925SGabor Horvath   // Intentionally missing case: '0' is bound to a reference. It is handled by
116428690925SGabor Horvath   // the DereferenceChecker.
116528690925SGabor Horvath 
116628690925SGabor Horvath   const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
116728690925SGabor Horvath   if (!ValueRegion)
116828690925SGabor Horvath     return;
116928690925SGabor Horvath 
117028690925SGabor Horvath   const NullabilityState *TrackedNullability =
117128690925SGabor Horvath       State->get<NullabilityMap>(ValueRegion);
117228690925SGabor Horvath 
117328690925SGabor Horvath   if (TrackedNullability) {
117428690925SGabor Horvath     if (RhsNullness == NullConstraint::IsNotNull ||
117528690925SGabor Horvath         TrackedNullability->getValue() != Nullability::Nullable)
117628690925SGabor Horvath       return;
1177e4e1080aSKirstóf Umann     if (ChecksEnabled[CK_NullablePassedToNonnull] &&
117828690925SGabor Horvath         LocNullability == Nullability::Nonnull) {
117928690925SGabor Horvath       static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
118028690925SGabor Horvath       ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
118177942db0SDevin Coughlin       reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
1182ad9e7ea6SAnna Zaks                                 "which is expected to have non-null value",
1183e4e1080aSKirstóf Umann                                 ErrorKind::NullableAssignedToNonnull,
1184e4e1080aSKirstóf Umann                                 CK_NullablePassedToNonnull, N, ValueRegion, C);
118528690925SGabor Horvath     }
118628690925SGabor Horvath     return;
118728690925SGabor Horvath   }
118828690925SGabor Horvath 
118928690925SGabor Horvath   const auto *BinOp = dyn_cast<BinaryOperator>(S);
119028690925SGabor Horvath 
119128690925SGabor Horvath   if (ValNullability == Nullability::Nullable) {
119228690925SGabor Horvath     // Trust the static information of the value more than the static
119328690925SGabor Horvath     // information on the location.
119428690925SGabor Horvath     const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
119528690925SGabor Horvath     State = State->set<NullabilityMap>(
119628690925SGabor Horvath         ValueRegion, NullabilityState(ValNullability, NullabilitySource));
119728690925SGabor Horvath     C.addTransition(State);
119828690925SGabor Horvath     return;
119928690925SGabor Horvath   }
120028690925SGabor Horvath 
120128690925SGabor Horvath   if (LocNullability == Nullability::Nullable) {
120228690925SGabor Horvath     const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
120328690925SGabor Horvath     State = State->set<NullabilityMap>(
120428690925SGabor Horvath         ValueRegion, NullabilityState(LocNullability, NullabilitySource));
120528690925SGabor Horvath     C.addTransition(State);
120628690925SGabor Horvath   }
120728690925SGabor Horvath }
120828690925SGabor Horvath 
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const120928690925SGabor Horvath void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
121028690925SGabor Horvath                                     const char *NL, const char *Sep) const {
121128690925SGabor Horvath 
121228690925SGabor Horvath   NullabilityMapTy B = State->get<NullabilityMap>();
121328690925SGabor Horvath 
1214cf439edaSArtem Dergachev   if (State->get<InvariantViolated>())
1215cf439edaSArtem Dergachev     Out << Sep << NL
1216cf439edaSArtem Dergachev         << "Nullability invariant was violated, warnings suppressed." << NL;
1217cf439edaSArtem Dergachev 
121828690925SGabor Horvath   if (B.isEmpty())
121928690925SGabor Horvath     return;
122028690925SGabor Horvath 
1221cf439edaSArtem Dergachev   if (!State->get<InvariantViolated>())
122228690925SGabor Horvath     Out << Sep << NL;
122328690925SGabor Horvath 
122428690925SGabor Horvath   for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
122528690925SGabor Horvath     Out << I->first << " : ";
122628690925SGabor Horvath     I->second.print(Out);
122728690925SGabor Horvath     Out << NL;
122828690925SGabor Horvath   }
122928690925SGabor Horvath }
123028690925SGabor Horvath 
registerNullabilityBase(CheckerManager & mgr)12318fd74ebfSKristof Umann void ento::registerNullabilityBase(CheckerManager &mgr) {
12328fd74ebfSKristof Umann   mgr.registerChecker<NullabilityChecker>();
12338fd74ebfSKristof Umann }
12348fd74ebfSKristof Umann 
shouldRegisterNullabilityBase(const CheckerManager & mgr)1235bda3dd0dSKirstóf Umann bool ento::shouldRegisterNullabilityBase(const CheckerManager &mgr) {
12368fd74ebfSKristof Umann   return true;
12378fd74ebfSKristof Umann }
12388fd74ebfSKristof Umann 
12392930735cSGabor Horvath #define REGISTER_CHECKER(name, trackingRequired)                               \
124028690925SGabor Horvath   void ento::register##name##Checker(CheckerManager &mgr) {                    \
1241204bf2bbSKristof Umann     NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>();        \
1242e4e1080aSKirstóf Umann     checker->ChecksEnabled[NullabilityChecker::CK_##name] = true;              \
1243e4e1080aSKirstóf Umann     checker->CheckNames[NullabilityChecker::CK_##name] =                       \
1244e4e1080aSKirstóf Umann         mgr.getCurrentCheckerName();                                           \
12452930735cSGabor Horvath     checker->NeedTracking = checker->NeedTracking || trackingRequired;         \
1246a1d9d75aSDevin Coughlin     checker->NoDiagnoseCallsToSystemHeaders =                                  \
1247a1d9d75aSDevin Coughlin         checker->NoDiagnoseCallsToSystemHeaders ||                             \
12480a1f91c8SKristof Umann         mgr.getAnalyzerOptions().getCheckerBooleanOption(                      \
124983cc1b35SKristof Umann             checker, "NoDiagnoseCallsToSystemHeaders", true);                  \
1250058a7a45SKristof Umann   }                                                                            \
1251058a7a45SKristof Umann                                                                                \
1252bda3dd0dSKirstóf Umann   bool ento::shouldRegister##name##Checker(const CheckerManager &mgr) {        \
1253058a7a45SKristof Umann     return true;                                                               \
125428690925SGabor Horvath   }
125528690925SGabor Horvath 
12562930735cSGabor Horvath // The checks are likely to be turned on by default and it is possible to do
12572930735cSGabor Horvath // them without tracking any nullability related information. As an optimization
12582930735cSGabor Horvath // no nullability information will be tracked when only these two checks are
12592930735cSGabor Horvath // enables.
12602930735cSGabor Horvath REGISTER_CHECKER(NullPassedToNonnull, false)
12612930735cSGabor Horvath REGISTER_CHECKER(NullReturnedFromNonnull, false)
12622930735cSGabor Horvath 
12632930735cSGabor Horvath REGISTER_CHECKER(NullableDereferenced, true)
12642930735cSGabor Horvath REGISTER_CHECKER(NullablePassedToNonnull, true)
12652930735cSGabor Horvath REGISTER_CHECKER(NullableReturnedFromNonnull, true)
1266