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