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