1*0b57cec5SDimitry Andric //===-- NullabilityChecker.cpp - Nullability checker ----------------------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This checker tries to find nullability violations. There are several kinds of 10*0b57cec5SDimitry Andric // possible violations: 11*0b57cec5SDimitry Andric // * Null pointer is passed to a pointer which has a _Nonnull type. 12*0b57cec5SDimitry Andric // * Null pointer is returned from a function which has a _Nonnull return type. 13*0b57cec5SDimitry Andric // * Nullable pointer is passed to a pointer which has a _Nonnull type. 14*0b57cec5SDimitry Andric // * Nullable pointer is returned from a function which has a _Nonnull return 15*0b57cec5SDimitry Andric // type. 16*0b57cec5SDimitry Andric // * Nullable pointer is dereferenced. 17*0b57cec5SDimitry Andric // 18*0b57cec5SDimitry Andric // This checker propagates the nullability information of the pointers and looks 19*0b57cec5SDimitry Andric // for the patterns that are described above. Explicit casts are trusted and are 20*0b57cec5SDimitry Andric // considered a way to suppress false positives for this checker. The other way 21*0b57cec5SDimitry Andric // to suppress warnings would be to add asserts or guarding if statements to the 22*0b57cec5SDimitry Andric // code. In addition to the nullability propagation this checker also uses some 23*0b57cec5SDimitry Andric // heuristics to suppress potential false positives. 24*0b57cec5SDimitry Andric // 25*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 26*0b57cec5SDimitry Andric 27*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" 28*0b57cec5SDimitry Andric 29*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 30*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h" 31*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h" 32*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h" 33*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 34*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 35*0b57cec5SDimitry Andric 36*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h" 37*0b57cec5SDimitry Andric #include "llvm/Support/Path.h" 38*0b57cec5SDimitry Andric 39*0b57cec5SDimitry Andric using namespace clang; 40*0b57cec5SDimitry Andric using namespace ento; 41*0b57cec5SDimitry Andric 42*0b57cec5SDimitry Andric namespace { 43*0b57cec5SDimitry Andric 44*0b57cec5SDimitry Andric /// Returns the most nullable nullability. This is used for message expressions 45*0b57cec5SDimitry Andric /// like [receiver method], where the nullability of this expression is either 46*0b57cec5SDimitry Andric /// the nullability of the receiver or the nullability of the return type of the 47*0b57cec5SDimitry Andric /// method, depending on which is more nullable. Contradicted is considered to 48*0b57cec5SDimitry Andric /// be the most nullable, to avoid false positive results. 49*0b57cec5SDimitry Andric Nullability getMostNullable(Nullability Lhs, Nullability Rhs) { 50*0b57cec5SDimitry Andric return static_cast<Nullability>( 51*0b57cec5SDimitry Andric std::min(static_cast<char>(Lhs), static_cast<char>(Rhs))); 52*0b57cec5SDimitry Andric } 53*0b57cec5SDimitry Andric 54*0b57cec5SDimitry Andric const char *getNullabilityString(Nullability Nullab) { 55*0b57cec5SDimitry Andric switch (Nullab) { 56*0b57cec5SDimitry Andric case Nullability::Contradicted: 57*0b57cec5SDimitry Andric return "contradicted"; 58*0b57cec5SDimitry Andric case Nullability::Nullable: 59*0b57cec5SDimitry Andric return "nullable"; 60*0b57cec5SDimitry Andric case Nullability::Unspecified: 61*0b57cec5SDimitry Andric return "unspecified"; 62*0b57cec5SDimitry Andric case Nullability::Nonnull: 63*0b57cec5SDimitry Andric return "nonnull"; 64*0b57cec5SDimitry Andric } 65*0b57cec5SDimitry Andric llvm_unreachable("Unexpected enumeration."); 66*0b57cec5SDimitry Andric return ""; 67*0b57cec5SDimitry Andric } 68*0b57cec5SDimitry Andric 69*0b57cec5SDimitry Andric // These enums are used as an index to ErrorMessages array. 70*0b57cec5SDimitry Andric enum class ErrorKind : int { 71*0b57cec5SDimitry Andric NilAssignedToNonnull, 72*0b57cec5SDimitry Andric NilPassedToNonnull, 73*0b57cec5SDimitry Andric NilReturnedToNonnull, 74*0b57cec5SDimitry Andric NullableAssignedToNonnull, 75*0b57cec5SDimitry Andric NullableReturnedToNonnull, 76*0b57cec5SDimitry Andric NullableDereferenced, 77*0b57cec5SDimitry Andric NullablePassedToNonnull 78*0b57cec5SDimitry Andric }; 79*0b57cec5SDimitry Andric 80*0b57cec5SDimitry Andric class NullabilityChecker 81*0b57cec5SDimitry Andric : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>, 82*0b57cec5SDimitry Andric check::PostCall, check::PostStmt<ExplicitCastExpr>, 83*0b57cec5SDimitry Andric check::PostObjCMessage, check::DeadSymbols, 84*0b57cec5SDimitry Andric check::Event<ImplicitNullDerefEvent>> { 85*0b57cec5SDimitry Andric mutable std::unique_ptr<BugType> BT; 86*0b57cec5SDimitry Andric 87*0b57cec5SDimitry Andric public: 88*0b57cec5SDimitry Andric // If true, the checker will not diagnose nullabilility issues for calls 89*0b57cec5SDimitry Andric // to system headers. This option is motivated by the observation that large 90*0b57cec5SDimitry Andric // projects may have many nullability warnings. These projects may 91*0b57cec5SDimitry Andric // find warnings about nullability annotations that they have explicitly 92*0b57cec5SDimitry Andric // added themselves higher priority to fix than warnings on calls to system 93*0b57cec5SDimitry Andric // libraries. 94*0b57cec5SDimitry Andric DefaultBool NoDiagnoseCallsToSystemHeaders; 95*0b57cec5SDimitry Andric 96*0b57cec5SDimitry Andric void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const; 97*0b57cec5SDimitry Andric void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const; 98*0b57cec5SDimitry Andric void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 99*0b57cec5SDimitry Andric void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const; 100*0b57cec5SDimitry Andric void checkPostCall(const CallEvent &Call, CheckerContext &C) const; 101*0b57cec5SDimitry Andric void checkPreCall(const CallEvent &Call, CheckerContext &C) const; 102*0b57cec5SDimitry Andric void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; 103*0b57cec5SDimitry Andric void checkEvent(ImplicitNullDerefEvent Event) const; 104*0b57cec5SDimitry Andric 105*0b57cec5SDimitry Andric void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, 106*0b57cec5SDimitry Andric const char *Sep) const override; 107*0b57cec5SDimitry Andric 108*0b57cec5SDimitry Andric struct NullabilityChecksFilter { 109*0b57cec5SDimitry Andric DefaultBool CheckNullPassedToNonnull; 110*0b57cec5SDimitry Andric DefaultBool CheckNullReturnedFromNonnull; 111*0b57cec5SDimitry Andric DefaultBool CheckNullableDereferenced; 112*0b57cec5SDimitry Andric DefaultBool CheckNullablePassedToNonnull; 113*0b57cec5SDimitry Andric DefaultBool CheckNullableReturnedFromNonnull; 114*0b57cec5SDimitry Andric 115*0b57cec5SDimitry Andric CheckName CheckNameNullPassedToNonnull; 116*0b57cec5SDimitry Andric CheckName CheckNameNullReturnedFromNonnull; 117*0b57cec5SDimitry Andric CheckName CheckNameNullableDereferenced; 118*0b57cec5SDimitry Andric CheckName CheckNameNullablePassedToNonnull; 119*0b57cec5SDimitry Andric CheckName CheckNameNullableReturnedFromNonnull; 120*0b57cec5SDimitry Andric }; 121*0b57cec5SDimitry Andric 122*0b57cec5SDimitry Andric NullabilityChecksFilter Filter; 123*0b57cec5SDimitry Andric // When set to false no nullability information will be tracked in 124*0b57cec5SDimitry Andric // NullabilityMap. It is possible to catch errors like passing a null pointer 125*0b57cec5SDimitry Andric // to a callee that expects nonnull argument without the information that is 126*0b57cec5SDimitry Andric // stroed in the NullabilityMap. This is an optimization. 127*0b57cec5SDimitry Andric DefaultBool NeedTracking; 128*0b57cec5SDimitry Andric 129*0b57cec5SDimitry Andric private: 130*0b57cec5SDimitry Andric class NullabilityBugVisitor : public BugReporterVisitor { 131*0b57cec5SDimitry Andric public: 132*0b57cec5SDimitry Andric NullabilityBugVisitor(const MemRegion *M) : Region(M) {} 133*0b57cec5SDimitry Andric 134*0b57cec5SDimitry Andric void Profile(llvm::FoldingSetNodeID &ID) const override { 135*0b57cec5SDimitry Andric static int X = 0; 136*0b57cec5SDimitry Andric ID.AddPointer(&X); 137*0b57cec5SDimitry Andric ID.AddPointer(Region); 138*0b57cec5SDimitry Andric } 139*0b57cec5SDimitry Andric 140*0b57cec5SDimitry Andric std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N, 141*0b57cec5SDimitry Andric BugReporterContext &BRC, 142*0b57cec5SDimitry Andric BugReport &BR) override; 143*0b57cec5SDimitry Andric 144*0b57cec5SDimitry Andric private: 145*0b57cec5SDimitry Andric // The tracked region. 146*0b57cec5SDimitry Andric const MemRegion *Region; 147*0b57cec5SDimitry Andric }; 148*0b57cec5SDimitry Andric 149*0b57cec5SDimitry Andric /// When any of the nonnull arguments of the analyzed function is null, do not 150*0b57cec5SDimitry Andric /// report anything and turn off the check. 151*0b57cec5SDimitry Andric /// 152*0b57cec5SDimitry Andric /// When \p SuppressPath is set to true, no more bugs will be reported on this 153*0b57cec5SDimitry Andric /// path by this checker. 154*0b57cec5SDimitry Andric void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, 155*0b57cec5SDimitry Andric ExplodedNode *N, const MemRegion *Region, 156*0b57cec5SDimitry Andric CheckerContext &C, 157*0b57cec5SDimitry Andric const Stmt *ValueExpr = nullptr, 158*0b57cec5SDimitry Andric bool SuppressPath = false) const; 159*0b57cec5SDimitry Andric 160*0b57cec5SDimitry Andric void reportBug(StringRef Msg, ErrorKind Error, ExplodedNode *N, 161*0b57cec5SDimitry Andric const MemRegion *Region, BugReporter &BR, 162*0b57cec5SDimitry Andric const Stmt *ValueExpr = nullptr) const { 163*0b57cec5SDimitry Andric if (!BT) 164*0b57cec5SDimitry Andric BT.reset(new BugType(this, "Nullability", categories::MemoryError)); 165*0b57cec5SDimitry Andric 166*0b57cec5SDimitry Andric auto R = llvm::make_unique<BugReport>(*BT, Msg, N); 167*0b57cec5SDimitry Andric if (Region) { 168*0b57cec5SDimitry Andric R->markInteresting(Region); 169*0b57cec5SDimitry Andric R->addVisitor(llvm::make_unique<NullabilityBugVisitor>(Region)); 170*0b57cec5SDimitry Andric } 171*0b57cec5SDimitry Andric if (ValueExpr) { 172*0b57cec5SDimitry Andric R->addRange(ValueExpr->getSourceRange()); 173*0b57cec5SDimitry Andric if (Error == ErrorKind::NilAssignedToNonnull || 174*0b57cec5SDimitry Andric Error == ErrorKind::NilPassedToNonnull || 175*0b57cec5SDimitry Andric Error == ErrorKind::NilReturnedToNonnull) 176*0b57cec5SDimitry Andric if (const auto *Ex = dyn_cast<Expr>(ValueExpr)) 177*0b57cec5SDimitry Andric bugreporter::trackExpressionValue(N, Ex, *R); 178*0b57cec5SDimitry Andric } 179*0b57cec5SDimitry Andric BR.emitReport(std::move(R)); 180*0b57cec5SDimitry Andric } 181*0b57cec5SDimitry Andric 182*0b57cec5SDimitry Andric /// If an SVal wraps a region that should be tracked, it will return a pointer 183*0b57cec5SDimitry Andric /// to the wrapped region. Otherwise it will return a nullptr. 184*0b57cec5SDimitry Andric const SymbolicRegion *getTrackRegion(SVal Val, 185*0b57cec5SDimitry Andric bool CheckSuperRegion = false) const; 186*0b57cec5SDimitry Andric 187*0b57cec5SDimitry Andric /// Returns true if the call is diagnosable in the current analyzer 188*0b57cec5SDimitry Andric /// configuration. 189*0b57cec5SDimitry Andric bool isDiagnosableCall(const CallEvent &Call) const { 190*0b57cec5SDimitry Andric if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader()) 191*0b57cec5SDimitry Andric return false; 192*0b57cec5SDimitry Andric 193*0b57cec5SDimitry Andric return true; 194*0b57cec5SDimitry Andric } 195*0b57cec5SDimitry Andric }; 196*0b57cec5SDimitry Andric 197*0b57cec5SDimitry Andric class NullabilityState { 198*0b57cec5SDimitry Andric public: 199*0b57cec5SDimitry Andric NullabilityState(Nullability Nullab, const Stmt *Source = nullptr) 200*0b57cec5SDimitry Andric : Nullab(Nullab), Source(Source) {} 201*0b57cec5SDimitry Andric 202*0b57cec5SDimitry Andric const Stmt *getNullabilitySource() const { return Source; } 203*0b57cec5SDimitry Andric 204*0b57cec5SDimitry Andric Nullability getValue() const { return Nullab; } 205*0b57cec5SDimitry Andric 206*0b57cec5SDimitry Andric void Profile(llvm::FoldingSetNodeID &ID) const { 207*0b57cec5SDimitry Andric ID.AddInteger(static_cast<char>(Nullab)); 208*0b57cec5SDimitry Andric ID.AddPointer(Source); 209*0b57cec5SDimitry Andric } 210*0b57cec5SDimitry Andric 211*0b57cec5SDimitry Andric void print(raw_ostream &Out) const { 212*0b57cec5SDimitry Andric Out << getNullabilityString(Nullab) << "\n"; 213*0b57cec5SDimitry Andric } 214*0b57cec5SDimitry Andric 215*0b57cec5SDimitry Andric private: 216*0b57cec5SDimitry Andric Nullability Nullab; 217*0b57cec5SDimitry Andric // Source is the expression which determined the nullability. For example in a 218*0b57cec5SDimitry Andric // message like [nullable nonnull_returning] has nullable nullability, because 219*0b57cec5SDimitry Andric // the receiver is nullable. Here the receiver will be the source of the 220*0b57cec5SDimitry Andric // nullability. This is useful information when the diagnostics are generated. 221*0b57cec5SDimitry Andric const Stmt *Source; 222*0b57cec5SDimitry Andric }; 223*0b57cec5SDimitry Andric 224*0b57cec5SDimitry Andric bool operator==(NullabilityState Lhs, NullabilityState Rhs) { 225*0b57cec5SDimitry Andric return Lhs.getValue() == Rhs.getValue() && 226*0b57cec5SDimitry Andric Lhs.getNullabilitySource() == Rhs.getNullabilitySource(); 227*0b57cec5SDimitry Andric } 228*0b57cec5SDimitry Andric 229*0b57cec5SDimitry Andric } // end anonymous namespace 230*0b57cec5SDimitry Andric 231*0b57cec5SDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *, 232*0b57cec5SDimitry Andric NullabilityState) 233*0b57cec5SDimitry Andric 234*0b57cec5SDimitry Andric // We say "the nullability type invariant is violated" when a location with a 235*0b57cec5SDimitry Andric // non-null type contains NULL or a function with a non-null return type returns 236*0b57cec5SDimitry Andric // NULL. Violations of the nullability type invariant can be detected either 237*0b57cec5SDimitry Andric // directly (for example, when NULL is passed as an argument to a nonnull 238*0b57cec5SDimitry Andric // parameter) or indirectly (for example, when, inside a function, the 239*0b57cec5SDimitry Andric // programmer defensively checks whether a nonnull parameter contains NULL and 240*0b57cec5SDimitry Andric // finds that it does). 241*0b57cec5SDimitry Andric // 242*0b57cec5SDimitry Andric // As a matter of policy, the nullability checker typically warns on direct 243*0b57cec5SDimitry Andric // violations of the nullability invariant (although it uses various 244*0b57cec5SDimitry Andric // heuristics to suppress warnings in some cases) but will not warn if the 245*0b57cec5SDimitry Andric // invariant has already been violated along the path (either directly or 246*0b57cec5SDimitry Andric // indirectly). As a practical matter, this prevents the analyzer from 247*0b57cec5SDimitry Andric // (1) warning on defensive code paths where a nullability precondition is 248*0b57cec5SDimitry Andric // determined to have been violated, (2) warning additional times after an 249*0b57cec5SDimitry Andric // initial direct violation has been discovered, and (3) warning after a direct 250*0b57cec5SDimitry Andric // violation that has been implicitly or explicitly suppressed (for 251*0b57cec5SDimitry Andric // example, with a cast of NULL to _Nonnull). In essence, once an invariant 252*0b57cec5SDimitry Andric // violation is detected on a path, this checker will be essentially turned off 253*0b57cec5SDimitry Andric // for the rest of the analysis 254*0b57cec5SDimitry Andric // 255*0b57cec5SDimitry Andric // The analyzer takes this approach (rather than generating a sink node) to 256*0b57cec5SDimitry Andric // ensure coverage of defensive paths, which may be important for backwards 257*0b57cec5SDimitry Andric // compatibility in codebases that were developed without nullability in mind. 258*0b57cec5SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool) 259*0b57cec5SDimitry Andric 260*0b57cec5SDimitry Andric enum class NullConstraint { IsNull, IsNotNull, Unknown }; 261*0b57cec5SDimitry Andric 262*0b57cec5SDimitry Andric static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val, 263*0b57cec5SDimitry Andric ProgramStateRef State) { 264*0b57cec5SDimitry Andric ConditionTruthVal Nullness = State->isNull(Val); 265*0b57cec5SDimitry Andric if (Nullness.isConstrainedFalse()) 266*0b57cec5SDimitry Andric return NullConstraint::IsNotNull; 267*0b57cec5SDimitry Andric if (Nullness.isConstrainedTrue()) 268*0b57cec5SDimitry Andric return NullConstraint::IsNull; 269*0b57cec5SDimitry Andric return NullConstraint::Unknown; 270*0b57cec5SDimitry Andric } 271*0b57cec5SDimitry Andric 272*0b57cec5SDimitry Andric const SymbolicRegion * 273*0b57cec5SDimitry Andric NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const { 274*0b57cec5SDimitry Andric if (!NeedTracking) 275*0b57cec5SDimitry Andric return nullptr; 276*0b57cec5SDimitry Andric 277*0b57cec5SDimitry Andric auto RegionSVal = Val.getAs<loc::MemRegionVal>(); 278*0b57cec5SDimitry Andric if (!RegionSVal) 279*0b57cec5SDimitry Andric return nullptr; 280*0b57cec5SDimitry Andric 281*0b57cec5SDimitry Andric const MemRegion *Region = RegionSVal->getRegion(); 282*0b57cec5SDimitry Andric 283*0b57cec5SDimitry Andric if (CheckSuperRegion) { 284*0b57cec5SDimitry Andric if (auto FieldReg = Region->getAs<FieldRegion>()) 285*0b57cec5SDimitry Andric return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion()); 286*0b57cec5SDimitry Andric if (auto ElementReg = Region->getAs<ElementRegion>()) 287*0b57cec5SDimitry Andric return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion()); 288*0b57cec5SDimitry Andric } 289*0b57cec5SDimitry Andric 290*0b57cec5SDimitry Andric return dyn_cast<SymbolicRegion>(Region); 291*0b57cec5SDimitry Andric } 292*0b57cec5SDimitry Andric 293*0b57cec5SDimitry Andric std::shared_ptr<PathDiagnosticPiece> 294*0b57cec5SDimitry Andric NullabilityChecker::NullabilityBugVisitor::VisitNode(const ExplodedNode *N, 295*0b57cec5SDimitry Andric BugReporterContext &BRC, 296*0b57cec5SDimitry Andric BugReport &BR) { 297*0b57cec5SDimitry Andric ProgramStateRef State = N->getState(); 298*0b57cec5SDimitry Andric ProgramStateRef StatePrev = N->getFirstPred()->getState(); 299*0b57cec5SDimitry Andric 300*0b57cec5SDimitry Andric const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region); 301*0b57cec5SDimitry Andric const NullabilityState *TrackedNullabPrev = 302*0b57cec5SDimitry Andric StatePrev->get<NullabilityMap>(Region); 303*0b57cec5SDimitry Andric if (!TrackedNullab) 304*0b57cec5SDimitry Andric return nullptr; 305*0b57cec5SDimitry Andric 306*0b57cec5SDimitry Andric if (TrackedNullabPrev && 307*0b57cec5SDimitry Andric TrackedNullabPrev->getValue() == TrackedNullab->getValue()) 308*0b57cec5SDimitry Andric return nullptr; 309*0b57cec5SDimitry Andric 310*0b57cec5SDimitry Andric // Retrieve the associated statement. 311*0b57cec5SDimitry Andric const Stmt *S = TrackedNullab->getNullabilitySource(); 312*0b57cec5SDimitry Andric if (!S || S->getBeginLoc().isInvalid()) { 313*0b57cec5SDimitry Andric S = PathDiagnosticLocation::getStmt(N); 314*0b57cec5SDimitry Andric } 315*0b57cec5SDimitry Andric 316*0b57cec5SDimitry Andric if (!S) 317*0b57cec5SDimitry Andric return nullptr; 318*0b57cec5SDimitry Andric 319*0b57cec5SDimitry Andric std::string InfoText = 320*0b57cec5SDimitry Andric (llvm::Twine("Nullability '") + 321*0b57cec5SDimitry Andric getNullabilityString(TrackedNullab->getValue()) + "' is inferred") 322*0b57cec5SDimitry Andric .str(); 323*0b57cec5SDimitry Andric 324*0b57cec5SDimitry Andric // Generate the extra diagnostic. 325*0b57cec5SDimitry Andric PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 326*0b57cec5SDimitry Andric N->getLocationContext()); 327*0b57cec5SDimitry Andric return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true, 328*0b57cec5SDimitry Andric nullptr); 329*0b57cec5SDimitry Andric } 330*0b57cec5SDimitry Andric 331*0b57cec5SDimitry Andric /// Returns true when the value stored at the given location has been 332*0b57cec5SDimitry Andric /// constrained to null after being passed through an object of nonnnull type. 333*0b57cec5SDimitry Andric static bool checkValueAtLValForInvariantViolation(ProgramStateRef State, 334*0b57cec5SDimitry Andric SVal LV, QualType T) { 335*0b57cec5SDimitry Andric if (getNullabilityAnnotation(T) != Nullability::Nonnull) 336*0b57cec5SDimitry Andric return false; 337*0b57cec5SDimitry Andric 338*0b57cec5SDimitry Andric auto RegionVal = LV.getAs<loc::MemRegionVal>(); 339*0b57cec5SDimitry Andric if (!RegionVal) 340*0b57cec5SDimitry Andric return false; 341*0b57cec5SDimitry Andric 342*0b57cec5SDimitry Andric // If the value was constrained to null *after* it was passed through that 343*0b57cec5SDimitry Andric // location, it could not have been a concrete pointer *when* it was passed. 344*0b57cec5SDimitry Andric // In that case we would have handled the situation when the value was 345*0b57cec5SDimitry Andric // bound to that location, by emitting (or not emitting) a report. 346*0b57cec5SDimitry Andric // Therefore we are only interested in symbolic regions that can be either 347*0b57cec5SDimitry Andric // null or non-null depending on the value of their respective symbol. 348*0b57cec5SDimitry Andric auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>(); 349*0b57cec5SDimitry Andric if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion())) 350*0b57cec5SDimitry Andric return false; 351*0b57cec5SDimitry Andric 352*0b57cec5SDimitry Andric if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull) 353*0b57cec5SDimitry Andric return true; 354*0b57cec5SDimitry Andric 355*0b57cec5SDimitry Andric return false; 356*0b57cec5SDimitry Andric } 357*0b57cec5SDimitry Andric 358*0b57cec5SDimitry Andric static bool 359*0b57cec5SDimitry Andric checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params, 360*0b57cec5SDimitry Andric ProgramStateRef State, 361*0b57cec5SDimitry Andric const LocationContext *LocCtxt) { 362*0b57cec5SDimitry Andric for (const auto *ParamDecl : Params) { 363*0b57cec5SDimitry Andric if (ParamDecl->isParameterPack()) 364*0b57cec5SDimitry Andric break; 365*0b57cec5SDimitry Andric 366*0b57cec5SDimitry Andric SVal LV = State->getLValue(ParamDecl, LocCtxt); 367*0b57cec5SDimitry Andric if (checkValueAtLValForInvariantViolation(State, LV, 368*0b57cec5SDimitry Andric ParamDecl->getType())) { 369*0b57cec5SDimitry Andric return true; 370*0b57cec5SDimitry Andric } 371*0b57cec5SDimitry Andric } 372*0b57cec5SDimitry Andric return false; 373*0b57cec5SDimitry Andric } 374*0b57cec5SDimitry Andric 375*0b57cec5SDimitry Andric static bool 376*0b57cec5SDimitry Andric checkSelfIvarsForInvariantViolation(ProgramStateRef State, 377*0b57cec5SDimitry Andric const LocationContext *LocCtxt) { 378*0b57cec5SDimitry Andric auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl()); 379*0b57cec5SDimitry Andric if (!MD || !MD->isInstanceMethod()) 380*0b57cec5SDimitry Andric return false; 381*0b57cec5SDimitry Andric 382*0b57cec5SDimitry Andric const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl(); 383*0b57cec5SDimitry Andric if (!SelfDecl) 384*0b57cec5SDimitry Andric return false; 385*0b57cec5SDimitry Andric 386*0b57cec5SDimitry Andric SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt)); 387*0b57cec5SDimitry Andric 388*0b57cec5SDimitry Andric const ObjCObjectPointerType *SelfType = 389*0b57cec5SDimitry Andric dyn_cast<ObjCObjectPointerType>(SelfDecl->getType()); 390*0b57cec5SDimitry Andric if (!SelfType) 391*0b57cec5SDimitry Andric return false; 392*0b57cec5SDimitry Andric 393*0b57cec5SDimitry Andric const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl(); 394*0b57cec5SDimitry Andric if (!ID) 395*0b57cec5SDimitry Andric return false; 396*0b57cec5SDimitry Andric 397*0b57cec5SDimitry Andric for (const auto *IvarDecl : ID->ivars()) { 398*0b57cec5SDimitry Andric SVal LV = State->getLValue(IvarDecl, SelfVal); 399*0b57cec5SDimitry Andric if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) { 400*0b57cec5SDimitry Andric return true; 401*0b57cec5SDimitry Andric } 402*0b57cec5SDimitry Andric } 403*0b57cec5SDimitry Andric return false; 404*0b57cec5SDimitry Andric } 405*0b57cec5SDimitry Andric 406*0b57cec5SDimitry Andric static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N, 407*0b57cec5SDimitry Andric CheckerContext &C) { 408*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 409*0b57cec5SDimitry Andric return true; 410*0b57cec5SDimitry Andric 411*0b57cec5SDimitry Andric const LocationContext *LocCtxt = C.getLocationContext(); 412*0b57cec5SDimitry Andric const Decl *D = LocCtxt->getDecl(); 413*0b57cec5SDimitry Andric if (!D) 414*0b57cec5SDimitry Andric return false; 415*0b57cec5SDimitry Andric 416*0b57cec5SDimitry Andric ArrayRef<ParmVarDecl*> Params; 417*0b57cec5SDimitry Andric if (const auto *BD = dyn_cast<BlockDecl>(D)) 418*0b57cec5SDimitry Andric Params = BD->parameters(); 419*0b57cec5SDimitry Andric else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 420*0b57cec5SDimitry Andric Params = FD->parameters(); 421*0b57cec5SDimitry Andric else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 422*0b57cec5SDimitry Andric Params = MD->parameters(); 423*0b57cec5SDimitry Andric else 424*0b57cec5SDimitry Andric return false; 425*0b57cec5SDimitry Andric 426*0b57cec5SDimitry Andric if (checkParamsForPreconditionViolation(Params, State, LocCtxt) || 427*0b57cec5SDimitry Andric checkSelfIvarsForInvariantViolation(State, LocCtxt)) { 428*0b57cec5SDimitry Andric if (!N->isSink()) 429*0b57cec5SDimitry Andric C.addTransition(State->set<InvariantViolated>(true), N); 430*0b57cec5SDimitry Andric return true; 431*0b57cec5SDimitry Andric } 432*0b57cec5SDimitry Andric return false; 433*0b57cec5SDimitry Andric } 434*0b57cec5SDimitry Andric 435*0b57cec5SDimitry Andric void NullabilityChecker::reportBugIfInvariantHolds(StringRef Msg, 436*0b57cec5SDimitry Andric ErrorKind Error, ExplodedNode *N, const MemRegion *Region, 437*0b57cec5SDimitry Andric CheckerContext &C, const Stmt *ValueExpr, bool SuppressPath) const { 438*0b57cec5SDimitry Andric ProgramStateRef OriginalState = N->getState(); 439*0b57cec5SDimitry Andric 440*0b57cec5SDimitry Andric if (checkInvariantViolation(OriginalState, N, C)) 441*0b57cec5SDimitry Andric return; 442*0b57cec5SDimitry Andric if (SuppressPath) { 443*0b57cec5SDimitry Andric OriginalState = OriginalState->set<InvariantViolated>(true); 444*0b57cec5SDimitry Andric N = C.addTransition(OriginalState, N); 445*0b57cec5SDimitry Andric } 446*0b57cec5SDimitry Andric 447*0b57cec5SDimitry Andric reportBug(Msg, Error, N, Region, C.getBugReporter(), ValueExpr); 448*0b57cec5SDimitry Andric } 449*0b57cec5SDimitry Andric 450*0b57cec5SDimitry Andric /// Cleaning up the program state. 451*0b57cec5SDimitry Andric void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR, 452*0b57cec5SDimitry Andric CheckerContext &C) const { 453*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 454*0b57cec5SDimitry Andric NullabilityMapTy Nullabilities = State->get<NullabilityMap>(); 455*0b57cec5SDimitry Andric for (NullabilityMapTy::iterator I = Nullabilities.begin(), 456*0b57cec5SDimitry Andric E = Nullabilities.end(); 457*0b57cec5SDimitry Andric I != E; ++I) { 458*0b57cec5SDimitry Andric const auto *Region = I->first->getAs<SymbolicRegion>(); 459*0b57cec5SDimitry Andric assert(Region && "Non-symbolic region is tracked."); 460*0b57cec5SDimitry Andric if (SR.isDead(Region->getSymbol())) { 461*0b57cec5SDimitry Andric State = State->remove<NullabilityMap>(I->first); 462*0b57cec5SDimitry Andric } 463*0b57cec5SDimitry Andric } 464*0b57cec5SDimitry Andric // When one of the nonnull arguments are constrained to be null, nullability 465*0b57cec5SDimitry Andric // preconditions are violated. It is not enough to check this only when we 466*0b57cec5SDimitry Andric // actually report an error, because at that time interesting symbols might be 467*0b57cec5SDimitry Andric // reaped. 468*0b57cec5SDimitry Andric if (checkInvariantViolation(State, C.getPredecessor(), C)) 469*0b57cec5SDimitry Andric return; 470*0b57cec5SDimitry Andric C.addTransition(State); 471*0b57cec5SDimitry Andric } 472*0b57cec5SDimitry Andric 473*0b57cec5SDimitry Andric /// This callback triggers when a pointer is dereferenced and the analyzer does 474*0b57cec5SDimitry Andric /// not know anything about the value of that pointer. When that pointer is 475*0b57cec5SDimitry Andric /// nullable, this code emits a warning. 476*0b57cec5SDimitry Andric void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const { 477*0b57cec5SDimitry Andric if (Event.SinkNode->getState()->get<InvariantViolated>()) 478*0b57cec5SDimitry Andric return; 479*0b57cec5SDimitry Andric 480*0b57cec5SDimitry Andric const MemRegion *Region = 481*0b57cec5SDimitry Andric getTrackRegion(Event.Location, /*CheckSuperRegion=*/true); 482*0b57cec5SDimitry Andric if (!Region) 483*0b57cec5SDimitry Andric return; 484*0b57cec5SDimitry Andric 485*0b57cec5SDimitry Andric ProgramStateRef State = Event.SinkNode->getState(); 486*0b57cec5SDimitry Andric const NullabilityState *TrackedNullability = 487*0b57cec5SDimitry Andric State->get<NullabilityMap>(Region); 488*0b57cec5SDimitry Andric 489*0b57cec5SDimitry Andric if (!TrackedNullability) 490*0b57cec5SDimitry Andric return; 491*0b57cec5SDimitry Andric 492*0b57cec5SDimitry Andric if (Filter.CheckNullableDereferenced && 493*0b57cec5SDimitry Andric TrackedNullability->getValue() == Nullability::Nullable) { 494*0b57cec5SDimitry Andric BugReporter &BR = *Event.BR; 495*0b57cec5SDimitry Andric // Do not suppress errors on defensive code paths, because dereferencing 496*0b57cec5SDimitry Andric // a nullable pointer is always an error. 497*0b57cec5SDimitry Andric if (Event.IsDirectDereference) 498*0b57cec5SDimitry Andric reportBug("Nullable pointer is dereferenced", 499*0b57cec5SDimitry Andric ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR); 500*0b57cec5SDimitry Andric else { 501*0b57cec5SDimitry Andric reportBug("Nullable pointer is passed to a callee that requires a " 502*0b57cec5SDimitry Andric "non-null", ErrorKind::NullablePassedToNonnull, 503*0b57cec5SDimitry Andric Event.SinkNode, Region, BR); 504*0b57cec5SDimitry Andric } 505*0b57cec5SDimitry Andric } 506*0b57cec5SDimitry Andric } 507*0b57cec5SDimitry Andric 508*0b57cec5SDimitry Andric /// Find the outermost subexpression of E that is not an implicit cast. 509*0b57cec5SDimitry Andric /// This looks through the implicit casts to _Nonnull that ARC adds to 510*0b57cec5SDimitry Andric /// return expressions of ObjC types when the return type of the function or 511*0b57cec5SDimitry Andric /// method is non-null but the express is not. 512*0b57cec5SDimitry Andric static const Expr *lookThroughImplicitCasts(const Expr *E) { 513*0b57cec5SDimitry Andric assert(E); 514*0b57cec5SDimitry Andric 515*0b57cec5SDimitry Andric while (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 516*0b57cec5SDimitry Andric E = ICE->getSubExpr(); 517*0b57cec5SDimitry Andric } 518*0b57cec5SDimitry Andric 519*0b57cec5SDimitry Andric return E; 520*0b57cec5SDimitry Andric } 521*0b57cec5SDimitry Andric 522*0b57cec5SDimitry Andric /// This method check when nullable pointer or null value is returned from a 523*0b57cec5SDimitry Andric /// function that has nonnull return type. 524*0b57cec5SDimitry Andric void NullabilityChecker::checkPreStmt(const ReturnStmt *S, 525*0b57cec5SDimitry Andric CheckerContext &C) const { 526*0b57cec5SDimitry Andric auto RetExpr = S->getRetValue(); 527*0b57cec5SDimitry Andric if (!RetExpr) 528*0b57cec5SDimitry Andric return; 529*0b57cec5SDimitry Andric 530*0b57cec5SDimitry Andric if (!RetExpr->getType()->isAnyPointerType()) 531*0b57cec5SDimitry Andric return; 532*0b57cec5SDimitry Andric 533*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 534*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 535*0b57cec5SDimitry Andric return; 536*0b57cec5SDimitry Andric 537*0b57cec5SDimitry Andric auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>(); 538*0b57cec5SDimitry Andric if (!RetSVal) 539*0b57cec5SDimitry Andric return; 540*0b57cec5SDimitry Andric 541*0b57cec5SDimitry Andric bool InSuppressedMethodFamily = false; 542*0b57cec5SDimitry Andric 543*0b57cec5SDimitry Andric QualType RequiredRetType; 544*0b57cec5SDimitry Andric AnalysisDeclContext *DeclCtxt = 545*0b57cec5SDimitry Andric C.getLocationContext()->getAnalysisDeclContext(); 546*0b57cec5SDimitry Andric const Decl *D = DeclCtxt->getDecl(); 547*0b57cec5SDimitry Andric if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 548*0b57cec5SDimitry Andric // HACK: This is a big hammer to avoid warning when there are defensive 549*0b57cec5SDimitry Andric // nil checks in -init and -copy methods. We should add more sophisticated 550*0b57cec5SDimitry Andric // logic here to suppress on common defensive idioms but still 551*0b57cec5SDimitry Andric // warn when there is a likely problem. 552*0b57cec5SDimitry Andric ObjCMethodFamily Family = MD->getMethodFamily(); 553*0b57cec5SDimitry Andric if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family) 554*0b57cec5SDimitry Andric InSuppressedMethodFamily = true; 555*0b57cec5SDimitry Andric 556*0b57cec5SDimitry Andric RequiredRetType = MD->getReturnType(); 557*0b57cec5SDimitry Andric } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 558*0b57cec5SDimitry Andric RequiredRetType = FD->getReturnType(); 559*0b57cec5SDimitry Andric } else { 560*0b57cec5SDimitry Andric return; 561*0b57cec5SDimitry Andric } 562*0b57cec5SDimitry Andric 563*0b57cec5SDimitry Andric NullConstraint Nullness = getNullConstraint(*RetSVal, State); 564*0b57cec5SDimitry Andric 565*0b57cec5SDimitry Andric Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType); 566*0b57cec5SDimitry Andric 567*0b57cec5SDimitry Andric // If the returned value is null but the type of the expression 568*0b57cec5SDimitry Andric // generating it is nonnull then we will suppress the diagnostic. 569*0b57cec5SDimitry Andric // This enables explicit suppression when returning a nil literal in a 570*0b57cec5SDimitry Andric // function with a _Nonnull return type: 571*0b57cec5SDimitry Andric // return (NSString * _Nonnull)0; 572*0b57cec5SDimitry Andric Nullability RetExprTypeLevelNullability = 573*0b57cec5SDimitry Andric getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType()); 574*0b57cec5SDimitry Andric 575*0b57cec5SDimitry Andric bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull && 576*0b57cec5SDimitry Andric Nullness == NullConstraint::IsNull); 577*0b57cec5SDimitry Andric if (Filter.CheckNullReturnedFromNonnull && 578*0b57cec5SDimitry Andric NullReturnedFromNonNull && 579*0b57cec5SDimitry Andric RetExprTypeLevelNullability != Nullability::Nonnull && 580*0b57cec5SDimitry Andric !InSuppressedMethodFamily && 581*0b57cec5SDimitry Andric C.getLocationContext()->inTopFrame()) { 582*0b57cec5SDimitry Andric static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull"); 583*0b57cec5SDimitry Andric ExplodedNode *N = C.generateErrorNode(State, &Tag); 584*0b57cec5SDimitry Andric if (!N) 585*0b57cec5SDimitry Andric return; 586*0b57cec5SDimitry Andric 587*0b57cec5SDimitry Andric SmallString<256> SBuf; 588*0b57cec5SDimitry Andric llvm::raw_svector_ostream OS(SBuf); 589*0b57cec5SDimitry Andric OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null"); 590*0b57cec5SDimitry Andric OS << " returned from a " << C.getDeclDescription(D) << 591*0b57cec5SDimitry Andric " that is expected to return a non-null value"; 592*0b57cec5SDimitry Andric reportBugIfInvariantHolds(OS.str(), 593*0b57cec5SDimitry Andric ErrorKind::NilReturnedToNonnull, N, nullptr, C, 594*0b57cec5SDimitry Andric RetExpr); 595*0b57cec5SDimitry Andric return; 596*0b57cec5SDimitry Andric } 597*0b57cec5SDimitry Andric 598*0b57cec5SDimitry Andric // If null was returned from a non-null function, mark the nullability 599*0b57cec5SDimitry Andric // invariant as violated even if the diagnostic was suppressed. 600*0b57cec5SDimitry Andric if (NullReturnedFromNonNull) { 601*0b57cec5SDimitry Andric State = State->set<InvariantViolated>(true); 602*0b57cec5SDimitry Andric C.addTransition(State); 603*0b57cec5SDimitry Andric return; 604*0b57cec5SDimitry Andric } 605*0b57cec5SDimitry Andric 606*0b57cec5SDimitry Andric const MemRegion *Region = getTrackRegion(*RetSVal); 607*0b57cec5SDimitry Andric if (!Region) 608*0b57cec5SDimitry Andric return; 609*0b57cec5SDimitry Andric 610*0b57cec5SDimitry Andric const NullabilityState *TrackedNullability = 611*0b57cec5SDimitry Andric State->get<NullabilityMap>(Region); 612*0b57cec5SDimitry Andric if (TrackedNullability) { 613*0b57cec5SDimitry Andric Nullability TrackedNullabValue = TrackedNullability->getValue(); 614*0b57cec5SDimitry Andric if (Filter.CheckNullableReturnedFromNonnull && 615*0b57cec5SDimitry Andric Nullness != NullConstraint::IsNotNull && 616*0b57cec5SDimitry Andric TrackedNullabValue == Nullability::Nullable && 617*0b57cec5SDimitry Andric RequiredNullability == Nullability::Nonnull) { 618*0b57cec5SDimitry Andric static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull"); 619*0b57cec5SDimitry Andric ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag); 620*0b57cec5SDimitry Andric 621*0b57cec5SDimitry Andric SmallString<256> SBuf; 622*0b57cec5SDimitry Andric llvm::raw_svector_ostream OS(SBuf); 623*0b57cec5SDimitry Andric OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) << 624*0b57cec5SDimitry Andric " that is expected to return a non-null value"; 625*0b57cec5SDimitry Andric 626*0b57cec5SDimitry Andric reportBugIfInvariantHolds(OS.str(), 627*0b57cec5SDimitry Andric ErrorKind::NullableReturnedToNonnull, N, 628*0b57cec5SDimitry Andric Region, C); 629*0b57cec5SDimitry Andric } 630*0b57cec5SDimitry Andric return; 631*0b57cec5SDimitry Andric } 632*0b57cec5SDimitry Andric if (RequiredNullability == Nullability::Nullable) { 633*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(Region, 634*0b57cec5SDimitry Andric NullabilityState(RequiredNullability, 635*0b57cec5SDimitry Andric S)); 636*0b57cec5SDimitry Andric C.addTransition(State); 637*0b57cec5SDimitry Andric } 638*0b57cec5SDimitry Andric } 639*0b57cec5SDimitry Andric 640*0b57cec5SDimitry Andric /// This callback warns when a nullable pointer or a null value is passed to a 641*0b57cec5SDimitry Andric /// function that expects its argument to be nonnull. 642*0b57cec5SDimitry Andric void NullabilityChecker::checkPreCall(const CallEvent &Call, 643*0b57cec5SDimitry Andric CheckerContext &C) const { 644*0b57cec5SDimitry Andric if (!Call.getDecl()) 645*0b57cec5SDimitry Andric return; 646*0b57cec5SDimitry Andric 647*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 648*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 649*0b57cec5SDimitry Andric return; 650*0b57cec5SDimitry Andric 651*0b57cec5SDimitry Andric ProgramStateRef OrigState = State; 652*0b57cec5SDimitry Andric 653*0b57cec5SDimitry Andric unsigned Idx = 0; 654*0b57cec5SDimitry Andric for (const ParmVarDecl *Param : Call.parameters()) { 655*0b57cec5SDimitry Andric if (Param->isParameterPack()) 656*0b57cec5SDimitry Andric break; 657*0b57cec5SDimitry Andric 658*0b57cec5SDimitry Andric if (Idx >= Call.getNumArgs()) 659*0b57cec5SDimitry Andric break; 660*0b57cec5SDimitry Andric 661*0b57cec5SDimitry Andric const Expr *ArgExpr = Call.getArgExpr(Idx); 662*0b57cec5SDimitry Andric auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>(); 663*0b57cec5SDimitry Andric if (!ArgSVal) 664*0b57cec5SDimitry Andric continue; 665*0b57cec5SDimitry Andric 666*0b57cec5SDimitry Andric if (!Param->getType()->isAnyPointerType() && 667*0b57cec5SDimitry Andric !Param->getType()->isReferenceType()) 668*0b57cec5SDimitry Andric continue; 669*0b57cec5SDimitry Andric 670*0b57cec5SDimitry Andric NullConstraint Nullness = getNullConstraint(*ArgSVal, State); 671*0b57cec5SDimitry Andric 672*0b57cec5SDimitry Andric Nullability RequiredNullability = 673*0b57cec5SDimitry Andric getNullabilityAnnotation(Param->getType()); 674*0b57cec5SDimitry Andric Nullability ArgExprTypeLevelNullability = 675*0b57cec5SDimitry Andric getNullabilityAnnotation(ArgExpr->getType()); 676*0b57cec5SDimitry Andric 677*0b57cec5SDimitry Andric unsigned ParamIdx = Param->getFunctionScopeIndex() + 1; 678*0b57cec5SDimitry Andric 679*0b57cec5SDimitry Andric if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull && 680*0b57cec5SDimitry Andric ArgExprTypeLevelNullability != Nullability::Nonnull && 681*0b57cec5SDimitry Andric RequiredNullability == Nullability::Nonnull && 682*0b57cec5SDimitry Andric isDiagnosableCall(Call)) { 683*0b57cec5SDimitry Andric ExplodedNode *N = C.generateErrorNode(State); 684*0b57cec5SDimitry Andric if (!N) 685*0b57cec5SDimitry Andric return; 686*0b57cec5SDimitry Andric 687*0b57cec5SDimitry Andric SmallString<256> SBuf; 688*0b57cec5SDimitry Andric llvm::raw_svector_ostream OS(SBuf); 689*0b57cec5SDimitry Andric OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null"); 690*0b57cec5SDimitry Andric OS << " passed to a callee that requires a non-null " << ParamIdx 691*0b57cec5SDimitry Andric << llvm::getOrdinalSuffix(ParamIdx) << " parameter"; 692*0b57cec5SDimitry Andric reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull, N, 693*0b57cec5SDimitry Andric nullptr, C, 694*0b57cec5SDimitry Andric ArgExpr, /*SuppressPath=*/false); 695*0b57cec5SDimitry Andric return; 696*0b57cec5SDimitry Andric } 697*0b57cec5SDimitry Andric 698*0b57cec5SDimitry Andric const MemRegion *Region = getTrackRegion(*ArgSVal); 699*0b57cec5SDimitry Andric if (!Region) 700*0b57cec5SDimitry Andric continue; 701*0b57cec5SDimitry Andric 702*0b57cec5SDimitry Andric const NullabilityState *TrackedNullability = 703*0b57cec5SDimitry Andric State->get<NullabilityMap>(Region); 704*0b57cec5SDimitry Andric 705*0b57cec5SDimitry Andric if (TrackedNullability) { 706*0b57cec5SDimitry Andric if (Nullness == NullConstraint::IsNotNull || 707*0b57cec5SDimitry Andric TrackedNullability->getValue() != Nullability::Nullable) 708*0b57cec5SDimitry Andric continue; 709*0b57cec5SDimitry Andric 710*0b57cec5SDimitry Andric if (Filter.CheckNullablePassedToNonnull && 711*0b57cec5SDimitry Andric RequiredNullability == Nullability::Nonnull && 712*0b57cec5SDimitry Andric isDiagnosableCall(Call)) { 713*0b57cec5SDimitry Andric ExplodedNode *N = C.addTransition(State); 714*0b57cec5SDimitry Andric SmallString<256> SBuf; 715*0b57cec5SDimitry Andric llvm::raw_svector_ostream OS(SBuf); 716*0b57cec5SDimitry Andric OS << "Nullable pointer is passed to a callee that requires a non-null " 717*0b57cec5SDimitry Andric << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter"; 718*0b57cec5SDimitry Andric reportBugIfInvariantHolds(OS.str(), 719*0b57cec5SDimitry Andric ErrorKind::NullablePassedToNonnull, N, 720*0b57cec5SDimitry Andric Region, C, ArgExpr, /*SuppressPath=*/true); 721*0b57cec5SDimitry Andric return; 722*0b57cec5SDimitry Andric } 723*0b57cec5SDimitry Andric if (Filter.CheckNullableDereferenced && 724*0b57cec5SDimitry Andric Param->getType()->isReferenceType()) { 725*0b57cec5SDimitry Andric ExplodedNode *N = C.addTransition(State); 726*0b57cec5SDimitry Andric reportBugIfInvariantHolds("Nullable pointer is dereferenced", 727*0b57cec5SDimitry Andric ErrorKind::NullableDereferenced, N, Region, 728*0b57cec5SDimitry Andric C, ArgExpr, /*SuppressPath=*/true); 729*0b57cec5SDimitry Andric return; 730*0b57cec5SDimitry Andric } 731*0b57cec5SDimitry Andric continue; 732*0b57cec5SDimitry Andric } 733*0b57cec5SDimitry Andric // No tracked nullability yet. 734*0b57cec5SDimitry Andric if (ArgExprTypeLevelNullability != Nullability::Nullable) 735*0b57cec5SDimitry Andric continue; 736*0b57cec5SDimitry Andric State = State->set<NullabilityMap>( 737*0b57cec5SDimitry Andric Region, NullabilityState(ArgExprTypeLevelNullability, ArgExpr)); 738*0b57cec5SDimitry Andric } 739*0b57cec5SDimitry Andric if (State != OrigState) 740*0b57cec5SDimitry Andric C.addTransition(State); 741*0b57cec5SDimitry Andric } 742*0b57cec5SDimitry Andric 743*0b57cec5SDimitry Andric /// Suppress the nullability warnings for some functions. 744*0b57cec5SDimitry Andric void NullabilityChecker::checkPostCall(const CallEvent &Call, 745*0b57cec5SDimitry Andric CheckerContext &C) const { 746*0b57cec5SDimitry Andric auto Decl = Call.getDecl(); 747*0b57cec5SDimitry Andric if (!Decl) 748*0b57cec5SDimitry Andric return; 749*0b57cec5SDimitry Andric // ObjC Messages handles in a different callback. 750*0b57cec5SDimitry Andric if (Call.getKind() == CE_ObjCMessage) 751*0b57cec5SDimitry Andric return; 752*0b57cec5SDimitry Andric const FunctionType *FuncType = Decl->getFunctionType(); 753*0b57cec5SDimitry Andric if (!FuncType) 754*0b57cec5SDimitry Andric return; 755*0b57cec5SDimitry Andric QualType ReturnType = FuncType->getReturnType(); 756*0b57cec5SDimitry Andric if (!ReturnType->isAnyPointerType()) 757*0b57cec5SDimitry Andric return; 758*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 759*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 760*0b57cec5SDimitry Andric return; 761*0b57cec5SDimitry Andric 762*0b57cec5SDimitry Andric const MemRegion *Region = getTrackRegion(Call.getReturnValue()); 763*0b57cec5SDimitry Andric if (!Region) 764*0b57cec5SDimitry Andric return; 765*0b57cec5SDimitry Andric 766*0b57cec5SDimitry Andric // CG headers are misannotated. Do not warn for symbols that are the results 767*0b57cec5SDimitry Andric // of CG calls. 768*0b57cec5SDimitry Andric const SourceManager &SM = C.getSourceManager(); 769*0b57cec5SDimitry Andric StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc())); 770*0b57cec5SDimitry Andric if (llvm::sys::path::filename(FilePath).startswith("CG")) { 771*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(Region, Nullability::Contradicted); 772*0b57cec5SDimitry Andric C.addTransition(State); 773*0b57cec5SDimitry Andric return; 774*0b57cec5SDimitry Andric } 775*0b57cec5SDimitry Andric 776*0b57cec5SDimitry Andric const NullabilityState *TrackedNullability = 777*0b57cec5SDimitry Andric State->get<NullabilityMap>(Region); 778*0b57cec5SDimitry Andric 779*0b57cec5SDimitry Andric if (!TrackedNullability && 780*0b57cec5SDimitry Andric getNullabilityAnnotation(ReturnType) == Nullability::Nullable) { 781*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(Region, Nullability::Nullable); 782*0b57cec5SDimitry Andric C.addTransition(State); 783*0b57cec5SDimitry Andric } 784*0b57cec5SDimitry Andric } 785*0b57cec5SDimitry Andric 786*0b57cec5SDimitry Andric static Nullability getReceiverNullability(const ObjCMethodCall &M, 787*0b57cec5SDimitry Andric ProgramStateRef State) { 788*0b57cec5SDimitry Andric if (M.isReceiverSelfOrSuper()) { 789*0b57cec5SDimitry Andric // For super and super class receivers we assume that the receiver is 790*0b57cec5SDimitry Andric // nonnull. 791*0b57cec5SDimitry Andric return Nullability::Nonnull; 792*0b57cec5SDimitry Andric } 793*0b57cec5SDimitry Andric // Otherwise look up nullability in the state. 794*0b57cec5SDimitry Andric SVal Receiver = M.getReceiverSVal(); 795*0b57cec5SDimitry Andric if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) { 796*0b57cec5SDimitry Andric // If the receiver is constrained to be nonnull, assume that it is nonnull 797*0b57cec5SDimitry Andric // regardless of its type. 798*0b57cec5SDimitry Andric NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State); 799*0b57cec5SDimitry Andric if (Nullness == NullConstraint::IsNotNull) 800*0b57cec5SDimitry Andric return Nullability::Nonnull; 801*0b57cec5SDimitry Andric } 802*0b57cec5SDimitry Andric auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>(); 803*0b57cec5SDimitry Andric if (ValueRegionSVal) { 804*0b57cec5SDimitry Andric const MemRegion *SelfRegion = ValueRegionSVal->getRegion(); 805*0b57cec5SDimitry Andric assert(SelfRegion); 806*0b57cec5SDimitry Andric 807*0b57cec5SDimitry Andric const NullabilityState *TrackedSelfNullability = 808*0b57cec5SDimitry Andric State->get<NullabilityMap>(SelfRegion); 809*0b57cec5SDimitry Andric if (TrackedSelfNullability) 810*0b57cec5SDimitry Andric return TrackedSelfNullability->getValue(); 811*0b57cec5SDimitry Andric } 812*0b57cec5SDimitry Andric return Nullability::Unspecified; 813*0b57cec5SDimitry Andric } 814*0b57cec5SDimitry Andric 815*0b57cec5SDimitry Andric /// Calculate the nullability of the result of a message expr based on the 816*0b57cec5SDimitry Andric /// nullability of the receiver, the nullability of the return value, and the 817*0b57cec5SDimitry Andric /// constraints. 818*0b57cec5SDimitry Andric void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M, 819*0b57cec5SDimitry Andric CheckerContext &C) const { 820*0b57cec5SDimitry Andric auto Decl = M.getDecl(); 821*0b57cec5SDimitry Andric if (!Decl) 822*0b57cec5SDimitry Andric return; 823*0b57cec5SDimitry Andric QualType RetType = Decl->getReturnType(); 824*0b57cec5SDimitry Andric if (!RetType->isAnyPointerType()) 825*0b57cec5SDimitry Andric return; 826*0b57cec5SDimitry Andric 827*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 828*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 829*0b57cec5SDimitry Andric return; 830*0b57cec5SDimitry Andric 831*0b57cec5SDimitry Andric const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue()); 832*0b57cec5SDimitry Andric if (!ReturnRegion) 833*0b57cec5SDimitry Andric return; 834*0b57cec5SDimitry Andric 835*0b57cec5SDimitry Andric auto Interface = Decl->getClassInterface(); 836*0b57cec5SDimitry Andric auto Name = Interface ? Interface->getName() : ""; 837*0b57cec5SDimitry Andric // In order to reduce the noise in the diagnostics generated by this checker, 838*0b57cec5SDimitry Andric // some framework and programming style based heuristics are used. These 839*0b57cec5SDimitry Andric // heuristics are for Cocoa APIs which have NS prefix. 840*0b57cec5SDimitry Andric if (Name.startswith("NS")) { 841*0b57cec5SDimitry Andric // Developers rely on dynamic invariants such as an item should be available 842*0b57cec5SDimitry Andric // in a collection, or a collection is not empty often. Those invariants can 843*0b57cec5SDimitry Andric // not be inferred by any static analysis tool. To not to bother the users 844*0b57cec5SDimitry Andric // with too many false positives, every item retrieval function should be 845*0b57cec5SDimitry Andric // ignored for collections. The instance methods of dictionaries in Cocoa 846*0b57cec5SDimitry Andric // are either item retrieval related or not interesting nullability wise. 847*0b57cec5SDimitry Andric // Using this fact, to keep the code easier to read just ignore the return 848*0b57cec5SDimitry Andric // value of every instance method of dictionaries. 849*0b57cec5SDimitry Andric if (M.isInstanceMessage() && Name.contains("Dictionary")) { 850*0b57cec5SDimitry Andric State = 851*0b57cec5SDimitry Andric State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted); 852*0b57cec5SDimitry Andric C.addTransition(State); 853*0b57cec5SDimitry Andric return; 854*0b57cec5SDimitry Andric } 855*0b57cec5SDimitry Andric // For similar reasons ignore some methods of Cocoa arrays. 856*0b57cec5SDimitry Andric StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0); 857*0b57cec5SDimitry Andric if (Name.contains("Array") && 858*0b57cec5SDimitry Andric (FirstSelectorSlot == "firstObject" || 859*0b57cec5SDimitry Andric FirstSelectorSlot == "lastObject")) { 860*0b57cec5SDimitry Andric State = 861*0b57cec5SDimitry Andric State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted); 862*0b57cec5SDimitry Andric C.addTransition(State); 863*0b57cec5SDimitry Andric return; 864*0b57cec5SDimitry Andric } 865*0b57cec5SDimitry Andric 866*0b57cec5SDimitry Andric // Encoding related methods of string should not fail when lossless 867*0b57cec5SDimitry Andric // encodings are used. Using lossless encodings is so frequent that ignoring 868*0b57cec5SDimitry Andric // this class of methods reduced the emitted diagnostics by about 30% on 869*0b57cec5SDimitry Andric // some projects (and all of that was false positives). 870*0b57cec5SDimitry Andric if (Name.contains("String")) { 871*0b57cec5SDimitry Andric for (auto Param : M.parameters()) { 872*0b57cec5SDimitry Andric if (Param->getName() == "encoding") { 873*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(ReturnRegion, 874*0b57cec5SDimitry Andric Nullability::Contradicted); 875*0b57cec5SDimitry Andric C.addTransition(State); 876*0b57cec5SDimitry Andric return; 877*0b57cec5SDimitry Andric } 878*0b57cec5SDimitry Andric } 879*0b57cec5SDimitry Andric } 880*0b57cec5SDimitry Andric } 881*0b57cec5SDimitry Andric 882*0b57cec5SDimitry Andric const ObjCMessageExpr *Message = M.getOriginExpr(); 883*0b57cec5SDimitry Andric Nullability SelfNullability = getReceiverNullability(M, State); 884*0b57cec5SDimitry Andric 885*0b57cec5SDimitry Andric const NullabilityState *NullabilityOfReturn = 886*0b57cec5SDimitry Andric State->get<NullabilityMap>(ReturnRegion); 887*0b57cec5SDimitry Andric 888*0b57cec5SDimitry Andric if (NullabilityOfReturn) { 889*0b57cec5SDimitry Andric // When we have a nullability tracked for the return value, the nullability 890*0b57cec5SDimitry Andric // of the expression will be the most nullable of the receiver and the 891*0b57cec5SDimitry Andric // return value. 892*0b57cec5SDimitry Andric Nullability RetValTracked = NullabilityOfReturn->getValue(); 893*0b57cec5SDimitry Andric Nullability ComputedNullab = 894*0b57cec5SDimitry Andric getMostNullable(RetValTracked, SelfNullability); 895*0b57cec5SDimitry Andric if (ComputedNullab != RetValTracked && 896*0b57cec5SDimitry Andric ComputedNullab != Nullability::Unspecified) { 897*0b57cec5SDimitry Andric const Stmt *NullabilitySource = 898*0b57cec5SDimitry Andric ComputedNullab == RetValTracked 899*0b57cec5SDimitry Andric ? NullabilityOfReturn->getNullabilitySource() 900*0b57cec5SDimitry Andric : Message->getInstanceReceiver(); 901*0b57cec5SDimitry Andric State = State->set<NullabilityMap>( 902*0b57cec5SDimitry Andric ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource)); 903*0b57cec5SDimitry Andric C.addTransition(State); 904*0b57cec5SDimitry Andric } 905*0b57cec5SDimitry Andric return; 906*0b57cec5SDimitry Andric } 907*0b57cec5SDimitry Andric 908*0b57cec5SDimitry Andric // No tracked information. Use static type information for return value. 909*0b57cec5SDimitry Andric Nullability RetNullability = getNullabilityAnnotation(RetType); 910*0b57cec5SDimitry Andric 911*0b57cec5SDimitry Andric // Properties might be computed. For this reason the static analyzer creates a 912*0b57cec5SDimitry Andric // new symbol each time an unknown property is read. To avoid false pozitives 913*0b57cec5SDimitry Andric // do not treat unknown properties as nullable, even when they explicitly 914*0b57cec5SDimitry Andric // marked nullable. 915*0b57cec5SDimitry Andric if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined) 916*0b57cec5SDimitry Andric RetNullability = Nullability::Nonnull; 917*0b57cec5SDimitry Andric 918*0b57cec5SDimitry Andric Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability); 919*0b57cec5SDimitry Andric if (ComputedNullab == Nullability::Nullable) { 920*0b57cec5SDimitry Andric const Stmt *NullabilitySource = ComputedNullab == RetNullability 921*0b57cec5SDimitry Andric ? Message 922*0b57cec5SDimitry Andric : Message->getInstanceReceiver(); 923*0b57cec5SDimitry Andric State = State->set<NullabilityMap>( 924*0b57cec5SDimitry Andric ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource)); 925*0b57cec5SDimitry Andric C.addTransition(State); 926*0b57cec5SDimitry Andric } 927*0b57cec5SDimitry Andric } 928*0b57cec5SDimitry Andric 929*0b57cec5SDimitry Andric /// Explicit casts are trusted. If there is a disagreement in the nullability 930*0b57cec5SDimitry Andric /// annotations in the destination and the source or '0' is casted to nonnull 931*0b57cec5SDimitry Andric /// track the value as having contraditory nullability. This will allow users to 932*0b57cec5SDimitry Andric /// suppress warnings. 933*0b57cec5SDimitry Andric void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE, 934*0b57cec5SDimitry Andric CheckerContext &C) const { 935*0b57cec5SDimitry Andric QualType OriginType = CE->getSubExpr()->getType(); 936*0b57cec5SDimitry Andric QualType DestType = CE->getType(); 937*0b57cec5SDimitry Andric if (!OriginType->isAnyPointerType()) 938*0b57cec5SDimitry Andric return; 939*0b57cec5SDimitry Andric if (!DestType->isAnyPointerType()) 940*0b57cec5SDimitry Andric return; 941*0b57cec5SDimitry Andric 942*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 943*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 944*0b57cec5SDimitry Andric return; 945*0b57cec5SDimitry Andric 946*0b57cec5SDimitry Andric Nullability DestNullability = getNullabilityAnnotation(DestType); 947*0b57cec5SDimitry Andric 948*0b57cec5SDimitry Andric // No explicit nullability in the destination type, so this cast does not 949*0b57cec5SDimitry Andric // change the nullability. 950*0b57cec5SDimitry Andric if (DestNullability == Nullability::Unspecified) 951*0b57cec5SDimitry Andric return; 952*0b57cec5SDimitry Andric 953*0b57cec5SDimitry Andric auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>(); 954*0b57cec5SDimitry Andric const MemRegion *Region = getTrackRegion(*RegionSVal); 955*0b57cec5SDimitry Andric if (!Region) 956*0b57cec5SDimitry Andric return; 957*0b57cec5SDimitry Andric 958*0b57cec5SDimitry Andric // When 0 is converted to nonnull mark it as contradicted. 959*0b57cec5SDimitry Andric if (DestNullability == Nullability::Nonnull) { 960*0b57cec5SDimitry Andric NullConstraint Nullness = getNullConstraint(*RegionSVal, State); 961*0b57cec5SDimitry Andric if (Nullness == NullConstraint::IsNull) { 962*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(Region, Nullability::Contradicted); 963*0b57cec5SDimitry Andric C.addTransition(State); 964*0b57cec5SDimitry Andric return; 965*0b57cec5SDimitry Andric } 966*0b57cec5SDimitry Andric } 967*0b57cec5SDimitry Andric 968*0b57cec5SDimitry Andric const NullabilityState *TrackedNullability = 969*0b57cec5SDimitry Andric State->get<NullabilityMap>(Region); 970*0b57cec5SDimitry Andric 971*0b57cec5SDimitry Andric if (!TrackedNullability) { 972*0b57cec5SDimitry Andric if (DestNullability != Nullability::Nullable) 973*0b57cec5SDimitry Andric return; 974*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(Region, 975*0b57cec5SDimitry Andric NullabilityState(DestNullability, CE)); 976*0b57cec5SDimitry Andric C.addTransition(State); 977*0b57cec5SDimitry Andric return; 978*0b57cec5SDimitry Andric } 979*0b57cec5SDimitry Andric 980*0b57cec5SDimitry Andric if (TrackedNullability->getValue() != DestNullability && 981*0b57cec5SDimitry Andric TrackedNullability->getValue() != Nullability::Contradicted) { 982*0b57cec5SDimitry Andric State = State->set<NullabilityMap>(Region, Nullability::Contradicted); 983*0b57cec5SDimitry Andric C.addTransition(State); 984*0b57cec5SDimitry Andric } 985*0b57cec5SDimitry Andric } 986*0b57cec5SDimitry Andric 987*0b57cec5SDimitry Andric /// For a given statement performing a bind, attempt to syntactically 988*0b57cec5SDimitry Andric /// match the expression resulting in the bound value. 989*0b57cec5SDimitry Andric static const Expr * matchValueExprForBind(const Stmt *S) { 990*0b57cec5SDimitry Andric // For `x = e` the value expression is the right-hand side. 991*0b57cec5SDimitry Andric if (auto *BinOp = dyn_cast<BinaryOperator>(S)) { 992*0b57cec5SDimitry Andric if (BinOp->getOpcode() == BO_Assign) 993*0b57cec5SDimitry Andric return BinOp->getRHS(); 994*0b57cec5SDimitry Andric } 995*0b57cec5SDimitry Andric 996*0b57cec5SDimitry Andric // For `int x = e` the value expression is the initializer. 997*0b57cec5SDimitry Andric if (auto *DS = dyn_cast<DeclStmt>(S)) { 998*0b57cec5SDimitry Andric if (DS->isSingleDecl()) { 999*0b57cec5SDimitry Andric auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 1000*0b57cec5SDimitry Andric if (!VD) 1001*0b57cec5SDimitry Andric return nullptr; 1002*0b57cec5SDimitry Andric 1003*0b57cec5SDimitry Andric if (const Expr *Init = VD->getInit()) 1004*0b57cec5SDimitry Andric return Init; 1005*0b57cec5SDimitry Andric } 1006*0b57cec5SDimitry Andric } 1007*0b57cec5SDimitry Andric 1008*0b57cec5SDimitry Andric return nullptr; 1009*0b57cec5SDimitry Andric } 1010*0b57cec5SDimitry Andric 1011*0b57cec5SDimitry Andric /// Returns true if \param S is a DeclStmt for a local variable that 1012*0b57cec5SDimitry Andric /// ObjC automated reference counting initialized with zero. 1013*0b57cec5SDimitry Andric static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) { 1014*0b57cec5SDimitry Andric // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This 1015*0b57cec5SDimitry Andric // prevents false positives when a _Nonnull local variable cannot be 1016*0b57cec5SDimitry Andric // initialized with an initialization expression: 1017*0b57cec5SDimitry Andric // NSString * _Nonnull s; // no-warning 1018*0b57cec5SDimitry Andric // @autoreleasepool { 1019*0b57cec5SDimitry Andric // s = ... 1020*0b57cec5SDimitry Andric // } 1021*0b57cec5SDimitry Andric // 1022*0b57cec5SDimitry Andric // FIXME: We should treat implicitly zero-initialized _Nonnull locals as 1023*0b57cec5SDimitry Andric // uninitialized in Sema's UninitializedValues analysis to warn when a use of 1024*0b57cec5SDimitry Andric // the zero-initialized definition will unexpectedly yield nil. 1025*0b57cec5SDimitry Andric 1026*0b57cec5SDimitry Andric // Locals are only zero-initialized when automated reference counting 1027*0b57cec5SDimitry Andric // is turned on. 1028*0b57cec5SDimitry Andric if (!C.getASTContext().getLangOpts().ObjCAutoRefCount) 1029*0b57cec5SDimitry Andric return false; 1030*0b57cec5SDimitry Andric 1031*0b57cec5SDimitry Andric auto *DS = dyn_cast<DeclStmt>(S); 1032*0b57cec5SDimitry Andric if (!DS || !DS->isSingleDecl()) 1033*0b57cec5SDimitry Andric return false; 1034*0b57cec5SDimitry Andric 1035*0b57cec5SDimitry Andric auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 1036*0b57cec5SDimitry Andric if (!VD) 1037*0b57cec5SDimitry Andric return false; 1038*0b57cec5SDimitry Andric 1039*0b57cec5SDimitry Andric // Sema only zero-initializes locals with ObjCLifetimes. 1040*0b57cec5SDimitry Andric if(!VD->getType().getQualifiers().hasObjCLifetime()) 1041*0b57cec5SDimitry Andric return false; 1042*0b57cec5SDimitry Andric 1043*0b57cec5SDimitry Andric const Expr *Init = VD->getInit(); 1044*0b57cec5SDimitry Andric assert(Init && "ObjC local under ARC without initializer"); 1045*0b57cec5SDimitry Andric 1046*0b57cec5SDimitry Andric // Return false if the local is explicitly initialized (e.g., with '= nil'). 1047*0b57cec5SDimitry Andric if (!isa<ImplicitValueInitExpr>(Init)) 1048*0b57cec5SDimitry Andric return false; 1049*0b57cec5SDimitry Andric 1050*0b57cec5SDimitry Andric return true; 1051*0b57cec5SDimitry Andric } 1052*0b57cec5SDimitry Andric 1053*0b57cec5SDimitry Andric /// Propagate the nullability information through binds and warn when nullable 1054*0b57cec5SDimitry Andric /// pointer or null symbol is assigned to a pointer with a nonnull type. 1055*0b57cec5SDimitry Andric void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S, 1056*0b57cec5SDimitry Andric CheckerContext &C) const { 1057*0b57cec5SDimitry Andric const TypedValueRegion *TVR = 1058*0b57cec5SDimitry Andric dyn_cast_or_null<TypedValueRegion>(L.getAsRegion()); 1059*0b57cec5SDimitry Andric if (!TVR) 1060*0b57cec5SDimitry Andric return; 1061*0b57cec5SDimitry Andric 1062*0b57cec5SDimitry Andric QualType LocType = TVR->getValueType(); 1063*0b57cec5SDimitry Andric if (!LocType->isAnyPointerType()) 1064*0b57cec5SDimitry Andric return; 1065*0b57cec5SDimitry Andric 1066*0b57cec5SDimitry Andric ProgramStateRef State = C.getState(); 1067*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 1068*0b57cec5SDimitry Andric return; 1069*0b57cec5SDimitry Andric 1070*0b57cec5SDimitry Andric auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>(); 1071*0b57cec5SDimitry Andric if (!ValDefOrUnknown) 1072*0b57cec5SDimitry Andric return; 1073*0b57cec5SDimitry Andric 1074*0b57cec5SDimitry Andric NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State); 1075*0b57cec5SDimitry Andric 1076*0b57cec5SDimitry Andric Nullability ValNullability = Nullability::Unspecified; 1077*0b57cec5SDimitry Andric if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol()) 1078*0b57cec5SDimitry Andric ValNullability = getNullabilityAnnotation(Sym->getType()); 1079*0b57cec5SDimitry Andric 1080*0b57cec5SDimitry Andric Nullability LocNullability = getNullabilityAnnotation(LocType); 1081*0b57cec5SDimitry Andric 1082*0b57cec5SDimitry Andric // If the type of the RHS expression is nonnull, don't warn. This 1083*0b57cec5SDimitry Andric // enables explicit suppression with a cast to nonnull. 1084*0b57cec5SDimitry Andric Nullability ValueExprTypeLevelNullability = Nullability::Unspecified; 1085*0b57cec5SDimitry Andric const Expr *ValueExpr = matchValueExprForBind(S); 1086*0b57cec5SDimitry Andric if (ValueExpr) { 1087*0b57cec5SDimitry Andric ValueExprTypeLevelNullability = 1088*0b57cec5SDimitry Andric getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType()); 1089*0b57cec5SDimitry Andric } 1090*0b57cec5SDimitry Andric 1091*0b57cec5SDimitry Andric bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull && 1092*0b57cec5SDimitry Andric RhsNullness == NullConstraint::IsNull); 1093*0b57cec5SDimitry Andric if (Filter.CheckNullPassedToNonnull && 1094*0b57cec5SDimitry Andric NullAssignedToNonNull && 1095*0b57cec5SDimitry Andric ValNullability != Nullability::Nonnull && 1096*0b57cec5SDimitry Andric ValueExprTypeLevelNullability != Nullability::Nonnull && 1097*0b57cec5SDimitry Andric !isARCNilInitializedLocal(C, S)) { 1098*0b57cec5SDimitry Andric static CheckerProgramPointTag Tag(this, "NullPassedToNonnull"); 1099*0b57cec5SDimitry Andric ExplodedNode *N = C.generateErrorNode(State, &Tag); 1100*0b57cec5SDimitry Andric if (!N) 1101*0b57cec5SDimitry Andric return; 1102*0b57cec5SDimitry Andric 1103*0b57cec5SDimitry Andric 1104*0b57cec5SDimitry Andric const Stmt *ValueStmt = S; 1105*0b57cec5SDimitry Andric if (ValueExpr) 1106*0b57cec5SDimitry Andric ValueStmt = ValueExpr; 1107*0b57cec5SDimitry Andric 1108*0b57cec5SDimitry Andric SmallString<256> SBuf; 1109*0b57cec5SDimitry Andric llvm::raw_svector_ostream OS(SBuf); 1110*0b57cec5SDimitry Andric OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null"); 1111*0b57cec5SDimitry Andric OS << " assigned to a pointer which is expected to have non-null value"; 1112*0b57cec5SDimitry Andric reportBugIfInvariantHolds(OS.str(), 1113*0b57cec5SDimitry Andric ErrorKind::NilAssignedToNonnull, N, nullptr, C, 1114*0b57cec5SDimitry Andric ValueStmt); 1115*0b57cec5SDimitry Andric return; 1116*0b57cec5SDimitry Andric } 1117*0b57cec5SDimitry Andric 1118*0b57cec5SDimitry Andric // If null was returned from a non-null function, mark the nullability 1119*0b57cec5SDimitry Andric // invariant as violated even if the diagnostic was suppressed. 1120*0b57cec5SDimitry Andric if (NullAssignedToNonNull) { 1121*0b57cec5SDimitry Andric State = State->set<InvariantViolated>(true); 1122*0b57cec5SDimitry Andric C.addTransition(State); 1123*0b57cec5SDimitry Andric return; 1124*0b57cec5SDimitry Andric } 1125*0b57cec5SDimitry Andric 1126*0b57cec5SDimitry Andric // Intentionally missing case: '0' is bound to a reference. It is handled by 1127*0b57cec5SDimitry Andric // the DereferenceChecker. 1128*0b57cec5SDimitry Andric 1129*0b57cec5SDimitry Andric const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown); 1130*0b57cec5SDimitry Andric if (!ValueRegion) 1131*0b57cec5SDimitry Andric return; 1132*0b57cec5SDimitry Andric 1133*0b57cec5SDimitry Andric const NullabilityState *TrackedNullability = 1134*0b57cec5SDimitry Andric State->get<NullabilityMap>(ValueRegion); 1135*0b57cec5SDimitry Andric 1136*0b57cec5SDimitry Andric if (TrackedNullability) { 1137*0b57cec5SDimitry Andric if (RhsNullness == NullConstraint::IsNotNull || 1138*0b57cec5SDimitry Andric TrackedNullability->getValue() != Nullability::Nullable) 1139*0b57cec5SDimitry Andric return; 1140*0b57cec5SDimitry Andric if (Filter.CheckNullablePassedToNonnull && 1141*0b57cec5SDimitry Andric LocNullability == Nullability::Nonnull) { 1142*0b57cec5SDimitry Andric static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull"); 1143*0b57cec5SDimitry Andric ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag); 1144*0b57cec5SDimitry Andric reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer " 1145*0b57cec5SDimitry Andric "which is expected to have non-null value", 1146*0b57cec5SDimitry Andric ErrorKind::NullableAssignedToNonnull, N, 1147*0b57cec5SDimitry Andric ValueRegion, C); 1148*0b57cec5SDimitry Andric } 1149*0b57cec5SDimitry Andric return; 1150*0b57cec5SDimitry Andric } 1151*0b57cec5SDimitry Andric 1152*0b57cec5SDimitry Andric const auto *BinOp = dyn_cast<BinaryOperator>(S); 1153*0b57cec5SDimitry Andric 1154*0b57cec5SDimitry Andric if (ValNullability == Nullability::Nullable) { 1155*0b57cec5SDimitry Andric // Trust the static information of the value more than the static 1156*0b57cec5SDimitry Andric // information on the location. 1157*0b57cec5SDimitry Andric const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S; 1158*0b57cec5SDimitry Andric State = State->set<NullabilityMap>( 1159*0b57cec5SDimitry Andric ValueRegion, NullabilityState(ValNullability, NullabilitySource)); 1160*0b57cec5SDimitry Andric C.addTransition(State); 1161*0b57cec5SDimitry Andric return; 1162*0b57cec5SDimitry Andric } 1163*0b57cec5SDimitry Andric 1164*0b57cec5SDimitry Andric if (LocNullability == Nullability::Nullable) { 1165*0b57cec5SDimitry Andric const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S; 1166*0b57cec5SDimitry Andric State = State->set<NullabilityMap>( 1167*0b57cec5SDimitry Andric ValueRegion, NullabilityState(LocNullability, NullabilitySource)); 1168*0b57cec5SDimitry Andric C.addTransition(State); 1169*0b57cec5SDimitry Andric } 1170*0b57cec5SDimitry Andric } 1171*0b57cec5SDimitry Andric 1172*0b57cec5SDimitry Andric void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State, 1173*0b57cec5SDimitry Andric const char *NL, const char *Sep) const { 1174*0b57cec5SDimitry Andric 1175*0b57cec5SDimitry Andric NullabilityMapTy B = State->get<NullabilityMap>(); 1176*0b57cec5SDimitry Andric 1177*0b57cec5SDimitry Andric if (State->get<InvariantViolated>()) 1178*0b57cec5SDimitry Andric Out << Sep << NL 1179*0b57cec5SDimitry Andric << "Nullability invariant was violated, warnings suppressed." << NL; 1180*0b57cec5SDimitry Andric 1181*0b57cec5SDimitry Andric if (B.isEmpty()) 1182*0b57cec5SDimitry Andric return; 1183*0b57cec5SDimitry Andric 1184*0b57cec5SDimitry Andric if (!State->get<InvariantViolated>()) 1185*0b57cec5SDimitry Andric Out << Sep << NL; 1186*0b57cec5SDimitry Andric 1187*0b57cec5SDimitry Andric for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { 1188*0b57cec5SDimitry Andric Out << I->first << " : "; 1189*0b57cec5SDimitry Andric I->second.print(Out); 1190*0b57cec5SDimitry Andric Out << NL; 1191*0b57cec5SDimitry Andric } 1192*0b57cec5SDimitry Andric } 1193*0b57cec5SDimitry Andric 1194*0b57cec5SDimitry Andric void ento::registerNullabilityBase(CheckerManager &mgr) { 1195*0b57cec5SDimitry Andric mgr.registerChecker<NullabilityChecker>(); 1196*0b57cec5SDimitry Andric } 1197*0b57cec5SDimitry Andric 1198*0b57cec5SDimitry Andric bool ento::shouldRegisterNullabilityBase(const LangOptions &LO) { 1199*0b57cec5SDimitry Andric return true; 1200*0b57cec5SDimitry Andric } 1201*0b57cec5SDimitry Andric 1202*0b57cec5SDimitry Andric #define REGISTER_CHECKER(name, trackingRequired) \ 1203*0b57cec5SDimitry Andric void ento::register##name##Checker(CheckerManager &mgr) { \ 1204*0b57cec5SDimitry Andric NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>(); \ 1205*0b57cec5SDimitry Andric checker->Filter.Check##name = true; \ 1206*0b57cec5SDimitry Andric checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \ 1207*0b57cec5SDimitry Andric checker->NeedTracking = checker->NeedTracking || trackingRequired; \ 1208*0b57cec5SDimitry Andric checker->NoDiagnoseCallsToSystemHeaders = \ 1209*0b57cec5SDimitry Andric checker->NoDiagnoseCallsToSystemHeaders || \ 1210*0b57cec5SDimitry Andric mgr.getAnalyzerOptions().getCheckerBooleanOption( \ 1211*0b57cec5SDimitry Andric checker, "NoDiagnoseCallsToSystemHeaders", true); \ 1212*0b57cec5SDimitry Andric } \ 1213*0b57cec5SDimitry Andric \ 1214*0b57cec5SDimitry Andric bool ento::shouldRegister##name##Checker(const LangOptions &LO) { \ 1215*0b57cec5SDimitry Andric return true; \ 1216*0b57cec5SDimitry Andric } 1217*0b57cec5SDimitry Andric 1218*0b57cec5SDimitry Andric // The checks are likely to be turned on by default and it is possible to do 1219*0b57cec5SDimitry Andric // them without tracking any nullability related information. As an optimization 1220*0b57cec5SDimitry Andric // no nullability information will be tracked when only these two checks are 1221*0b57cec5SDimitry Andric // enables. 1222*0b57cec5SDimitry Andric REGISTER_CHECKER(NullPassedToNonnull, false) 1223*0b57cec5SDimitry Andric REGISTER_CHECKER(NullReturnedFromNonnull, false) 1224*0b57cec5SDimitry Andric 1225*0b57cec5SDimitry Andric REGISTER_CHECKER(NullableDereferenced, true) 1226*0b57cec5SDimitry Andric REGISTER_CHECKER(NullablePassedToNonnull, true) 1227*0b57cec5SDimitry Andric REGISTER_CHECKER(NullableReturnedFromNonnull, true) 1228