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