1 //== Nullabilityhecker.cpp - Nullability checker ----------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
17 // * Nullable pointer is dereferenced.
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.
26 //===----------------------------------------------------------------------===//
28 #include "ClangSACheckers.h"
29 #include "llvm/Support/Path.h"
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/CheckerContext.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
36 using namespace clang;
40 // Do not reorder! The getMostNullable method relies on the order.
41 // Optimization: Most pointers expected to be unspecified. When a symbol has an
42 // unspecified or nonnull type non of the rules would indicate any problem for
43 // that symbol. For this reason only nullable and contradicted nullability are
44 // stored for a symbol. When a symbol is already contradicted, it can not be
45 // casted back to nullable.
46 enum class Nullability : char {
47 Contradicted, // Tracked nullability is contradicted by an explicit cast. Do
48 // not report any nullability related issue for this symbol.
49 // This nullability is propagated agressively to avoid false
50 // positive results. See the comment on getMostNullable method.
56 /// Returns the most nullable nullability. This is used for message expressions
57 /// like [reciever method], where the nullability of this expression is either
58 /// the nullability of the receiver or the nullability of the return type of the
59 /// method, depending on which is more nullable. Contradicted is considered to
60 /// be the most nullable, to avoid false positive results.
61 Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
62 return static_cast<Nullability>(
63 std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
66 const char *getNullabilityString(Nullability Nullab) {
68 case Nullability::Contradicted:
69 return "contradicted";
70 case Nullability::Nullable:
72 case Nullability::Unspecified:
74 case Nullability::Nonnull:
77 llvm_unreachable("Unexpected enumeration.");
81 // These enums are used as an index to ErrorMessages array.
82 enum class ErrorKind : int {
86 NullableAssignedToNonnull,
87 NullableReturnedToNonnull,
89 NullablePassedToNonnull
92 const char *const ErrorMessages[] = {
93 "Null is assigned to a pointer which is expected to have non-null value",
94 "Null passed to a callee that requires a non-null argument",
95 "Null is returned from a function that is expected to return a non-null "
97 "Nullable pointer is assigned to a pointer which is expected to have "
99 "Nullable pointer is returned from a function that is expected to return a "
101 "Nullable pointer is dereferenced",
102 "Nullable pointer is passed to a callee that requires a non-null argument"};
104 class NullabilityChecker
105 : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
106 check::PostCall, check::PostStmt<ExplicitCastExpr>,
107 check::PostObjCMessage, check::DeadSymbols,
108 check::Event<ImplicitNullDerefEvent>> {
109 mutable std::unique_ptr<BugType> BT;
112 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
113 void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
114 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
115 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
116 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
117 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
118 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
119 void checkEvent(ImplicitNullDerefEvent Event) const;
121 void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
122 const char *Sep) const override;
124 struct NullabilityChecksFilter {
125 DefaultBool CheckNullPassedToNonnull;
126 DefaultBool CheckNullReturnedFromNonnull;
127 DefaultBool CheckNullableDereferenced;
128 DefaultBool CheckNullablePassedToNonnull;
129 DefaultBool CheckNullableReturnedFromNonnull;
131 CheckName CheckNameNullPassedToNonnull;
132 CheckName CheckNameNullReturnedFromNonnull;
133 CheckName CheckNameNullableDereferenced;
134 CheckName CheckNameNullablePassedToNonnull;
135 CheckName CheckNameNullableReturnedFromNonnull;
138 NullabilityChecksFilter Filter;
139 // When set to false no nullability information will be tracked in
140 // NullabilityMap. It is possible to catch errors like passing a null pointer
141 // to a callee that expects nonnull argument without the information that is
142 // stroed in the NullabilityMap. This is an optimization.
143 DefaultBool NeedTracking;
146 class NullabilityBugVisitor
147 : public BugReporterVisitorImpl<NullabilityBugVisitor> {
149 NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
151 void Profile(llvm::FoldingSetNodeID &ID) const override {
154 ID.AddPointer(Region);
157 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
158 const ExplodedNode *PrevN,
159 BugReporterContext &BRC,
160 BugReport &BR) override;
163 // The tracked region.
164 const MemRegion *Region;
167 /// When any of the nonnull arguments of the analyzed function is null, do not
168 /// report anything and turn off the check.
170 /// When \p SuppressPath is set to true, no more bugs will be reported on this
171 /// path by this checker.
172 void reportBugIfPreconditionHolds(ErrorKind Error, ExplodedNode *N,
173 const MemRegion *Region, CheckerContext &C,
174 const Stmt *ValueExpr = nullptr,
175 bool SuppressPath = false) const;
177 void reportBug(ErrorKind Error, ExplodedNode *N, const MemRegion *Region,
178 BugReporter &BR, const Stmt *ValueExpr = nullptr) const {
180 BT.reset(new BugType(this, "Nullability", "Memory error"));
181 const char *Msg = ErrorMessages[static_cast<int>(Error)];
182 std::unique_ptr<BugReport> R(new BugReport(*BT, Msg, N));
184 R->markInteresting(Region);
185 R->addVisitor(llvm::make_unique<NullabilityBugVisitor>(Region));
188 R->addRange(ValueExpr->getSourceRange());
189 if (Error == ErrorKind::NilAssignedToNonnull ||
190 Error == ErrorKind::NilPassedToNonnull ||
191 Error == ErrorKind::NilReturnedToNonnull)
192 bugreporter::trackNullOrUndefValue(N, ValueExpr, *R);
194 BR.emitReport(std::move(R));
197 /// If an SVal wraps a region that should be tracked, it will return a pointer
198 /// to the wrapped region. Otherwise it will return a nullptr.
199 const SymbolicRegion *getTrackRegion(SVal Val,
200 bool CheckSuperRegion = false) const;
203 class NullabilityState {
205 NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
206 : Nullab(Nullab), Source(Source) {}
208 const Stmt *getNullabilitySource() const { return Source; }
210 Nullability getValue() const { return Nullab; }
212 void Profile(llvm::FoldingSetNodeID &ID) const {
213 ID.AddInteger(static_cast<char>(Nullab));
214 ID.AddPointer(Source);
217 void print(raw_ostream &Out) const {
218 Out << getNullabilityString(Nullab) << "\n";
223 // Source is the expression which determined the nullability. For example in a
224 // message like [nullable nonnull_returning] has nullable nullability, because
225 // the receiver is nullable. Here the receiver will be the source of the
226 // nullability. This is useful information when the diagnostics are generated.
230 bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
231 return Lhs.getValue() == Rhs.getValue() &&
232 Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
235 } // end anonymous namespace
237 REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
240 // If the nullability precondition of a function is violated, we should not
241 // report nullability related issues on that path. For this reason once a
242 // precondition is not met on a path, this checker will be esentially turned off
243 // for the rest of the analysis. We do not want to generate a sink node however,
244 // so this checker would not lead to reduced coverage.
245 REGISTER_TRAIT_WITH_PROGRAMSTATE(PreconditionViolated, bool)
247 enum class NullConstraint { IsNull, IsNotNull, Unknown };
249 static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
250 ProgramStateRef State) {
251 ConditionTruthVal Nullness = State->isNull(Val);
252 if (Nullness.isConstrainedFalse())
253 return NullConstraint::IsNotNull;
254 if (Nullness.isConstrainedTrue())
255 return NullConstraint::IsNull;
256 return NullConstraint::Unknown;
259 const SymbolicRegion *
260 NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
264 auto RegionSVal = Val.getAs<loc::MemRegionVal>();
268 const MemRegion *Region = RegionSVal->getRegion();
270 if (CheckSuperRegion) {
271 if (auto FieldReg = Region->getAs<FieldRegion>())
272 return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
273 if (auto ElementReg = Region->getAs<ElementRegion>())
274 return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
277 return dyn_cast<SymbolicRegion>(Region);
280 PathDiagnosticPiece *NullabilityChecker::NullabilityBugVisitor::VisitNode(
281 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
283 ProgramStateRef State = N->getState();
284 ProgramStateRef StatePrev = PrevN->getState();
286 const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
287 const NullabilityState *TrackedNullabPrev =
288 StatePrev->get<NullabilityMap>(Region);
292 if (TrackedNullabPrev &&
293 TrackedNullabPrev->getValue() == TrackedNullab->getValue())
296 // Retrieve the associated statement.
297 const Stmt *S = TrackedNullab->getNullabilitySource();
299 ProgramPoint ProgLoc = N->getLocation();
300 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
308 std::string InfoText =
309 (llvm::Twine("Nullability '") +
310 getNullabilityString(TrackedNullab->getValue()) + "' is infered")
313 // Generate the extra diagnostic.
314 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
315 N->getLocationContext());
316 return new PathDiagnosticEventPiece(Pos, InfoText, true, nullptr);
319 static Nullability getNullabilityAnnotation(QualType Type) {
320 const auto *AttrType = Type->getAs<AttributedType>();
322 return Nullability::Unspecified;
323 if (AttrType->getAttrKind() == AttributedType::attr_nullable)
324 return Nullability::Nullable;
325 else if (AttrType->getAttrKind() == AttributedType::attr_nonnull)
326 return Nullability::Nonnull;
327 return Nullability::Unspecified;
330 template <typename ParamVarDeclRange>
332 checkParamsForPreconditionViolation(const ParamVarDeclRange &Params,
333 ProgramStateRef State,
334 const LocationContext *LocCtxt) {
335 for (const auto *ParamDecl : Params) {
336 if (ParamDecl->isParameterPack())
339 if (getNullabilityAnnotation(ParamDecl->getType()) != Nullability::Nonnull)
342 auto RegVal = State->getLValue(ParamDecl, LocCtxt)
343 .template getAs<loc::MemRegionVal>();
347 auto ParamValue = State->getSVal(RegVal->getRegion())
348 .template getAs<DefinedOrUnknownSVal>();
352 if (getNullConstraint(*ParamValue, State) == NullConstraint::IsNull) {
359 static bool checkPreconditionViolation(ProgramStateRef State, ExplodedNode *N,
361 if (State->get<PreconditionViolated>())
364 const LocationContext *LocCtxt = C.getLocationContext();
365 const Decl *D = LocCtxt->getDecl();
369 if (const auto *BlockD = dyn_cast<BlockDecl>(D)) {
370 if (checkParamsForPreconditionViolation(BlockD->parameters(), State,
373 C.addTransition(State->set<PreconditionViolated>(true), N);
379 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
380 if (checkParamsForPreconditionViolation(FuncDecl->parameters(), State,
383 C.addTransition(State->set<PreconditionViolated>(true), N);
391 void NullabilityChecker::reportBugIfPreconditionHolds(
392 ErrorKind Error, ExplodedNode *N, const MemRegion *Region,
393 CheckerContext &C, const Stmt *ValueExpr, bool SuppressPath) const {
394 ProgramStateRef OriginalState = N->getState();
396 if (checkPreconditionViolation(OriginalState, N, C))
399 OriginalState = OriginalState->set<PreconditionViolated>(true);
400 N = C.addTransition(OriginalState, N);
403 reportBug(Error, N, Region, C.getBugReporter(), ValueExpr);
406 /// Cleaning up the program state.
407 void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
408 CheckerContext &C) const {
409 ProgramStateRef State = C.getState();
410 NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
411 for (NullabilityMapTy::iterator I = Nullabilities.begin(),
412 E = Nullabilities.end();
414 if (!SR.isLiveRegion(I->first)) {
415 State = State->remove<NullabilityMap>(I->first);
418 // When one of the nonnull arguments are constrained to be null, nullability
419 // preconditions are violated. It is not enough to check this only when we
420 // actually report an error, because at that time interesting symbols might be
422 if (checkPreconditionViolation(State, C.getPredecessor(), C))
424 C.addTransition(State);
427 /// This callback triggers when a pointer is dereferenced and the analyzer does
428 /// not know anything about the value of that pointer. When that pointer is
429 /// nullable, this code emits a warning.
430 void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
431 if (Event.SinkNode->getState()->get<PreconditionViolated>())
434 const MemRegion *Region =
435 getTrackRegion(Event.Location, /*CheckSuperregion=*/true);
439 ProgramStateRef State = Event.SinkNode->getState();
440 const NullabilityState *TrackedNullability =
441 State->get<NullabilityMap>(Region);
443 if (!TrackedNullability)
446 if (Filter.CheckNullableDereferenced &&
447 TrackedNullability->getValue() == Nullability::Nullable) {
448 BugReporter &BR = *Event.BR;
449 // Do not suppress errors on defensive code paths, because dereferencing
450 // a nullable pointer is always an error.
451 if (Event.IsDirectDereference)
452 reportBug(ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR);
454 reportBug(ErrorKind::NullablePassedToNonnull, Event.SinkNode, Region, BR);
458 /// This method check when nullable pointer or null value is returned from a
459 /// function that has nonnull return type.
461 /// TODO: when nullability preconditons are violated, it is ok to violate the
462 /// nullability postconditons (i.e.: when one of the nonnull parameters are null
463 /// this check should not report any nullability related issue).
464 void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
465 CheckerContext &C) const {
466 auto RetExpr = S->getRetValue();
470 if (!RetExpr->getType()->isAnyPointerType())
473 ProgramStateRef State = C.getState();
474 if (State->get<PreconditionViolated>())
478 State->getSVal(S, C.getLocationContext()).getAs<DefinedOrUnknownSVal>();
482 AnalysisDeclContext *DeclCtxt =
483 C.getLocationContext()->getAnalysisDeclContext();
484 const FunctionType *FuncType = DeclCtxt->getDecl()->getFunctionType();
488 NullConstraint Nullness = getNullConstraint(*RetSVal, State);
490 Nullability StaticNullability =
491 getNullabilityAnnotation(FuncType->getReturnType());
493 if (Filter.CheckNullReturnedFromNonnull &&
494 Nullness == NullConstraint::IsNull &&
495 StaticNullability == Nullability::Nonnull) {
496 static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
497 ExplodedNode *N = C.generateSink(State, C.getPredecessor(), &Tag);
498 reportBugIfPreconditionHolds(ErrorKind::NilReturnedToNonnull, N, nullptr, C,
503 const MemRegion *Region = getTrackRegion(*RetSVal);
507 const NullabilityState *TrackedNullability =
508 State->get<NullabilityMap>(Region);
509 if (TrackedNullability) {
510 Nullability TrackedNullabValue = TrackedNullability->getValue();
511 if (Filter.CheckNullableReturnedFromNonnull &&
512 Nullness != NullConstraint::IsNotNull &&
513 TrackedNullabValue == Nullability::Nullable &&
514 StaticNullability == Nullability::Nonnull) {
515 static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
516 ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
517 reportBugIfPreconditionHolds(ErrorKind::NullableReturnedToNonnull, N,
522 if (StaticNullability == Nullability::Nullable) {
523 State = State->set<NullabilityMap>(Region,
524 NullabilityState(StaticNullability, S));
525 C.addTransition(State);
529 /// This callback warns when a nullable pointer or a null value is passed to a
530 /// function that expects its argument to be nonnull.
531 void NullabilityChecker::checkPreCall(const CallEvent &Call,
532 CheckerContext &C) const {
536 ProgramStateRef State = C.getState();
537 if (State->get<PreconditionViolated>())
540 ProgramStateRef OrigState = State;
543 for (const ParmVarDecl *Param : Call.parameters()) {
544 if (Param->isParameterPack())
547 const Expr *ArgExpr = nullptr;
548 if (Idx < Call.getNumArgs())
549 ArgExpr = Call.getArgExpr(Idx);
550 auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
554 if (!Param->getType()->isAnyPointerType() &&
555 !Param->getType()->isReferenceType())
558 NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
560 Nullability ParamNullability = getNullabilityAnnotation(Param->getType());
561 Nullability ArgStaticNullability =
562 getNullabilityAnnotation(ArgExpr->getType());
564 if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull &&
565 ArgStaticNullability != Nullability::Nonnull &&
566 ParamNullability == Nullability::Nonnull) {
567 ExplodedNode *N = C.generateSink(State);
568 reportBugIfPreconditionHolds(ErrorKind::NilPassedToNonnull, N, nullptr, C,
573 const MemRegion *Region = getTrackRegion(*ArgSVal);
577 const NullabilityState *TrackedNullability =
578 State->get<NullabilityMap>(Region);
580 if (TrackedNullability) {
581 if (Nullness == NullConstraint::IsNotNull ||
582 TrackedNullability->getValue() != Nullability::Nullable)
585 if (Filter.CheckNullablePassedToNonnull &&
586 ParamNullability == Nullability::Nonnull) {
587 ExplodedNode *N = C.addTransition(State);
588 reportBugIfPreconditionHolds(ErrorKind::NullablePassedToNonnull, N,
589 Region, C, ArgExpr, /*SuppressPath=*/true);
592 if (Filter.CheckNullableDereferenced &&
593 Param->getType()->isReferenceType()) {
594 ExplodedNode *N = C.addTransition(State);
595 reportBugIfPreconditionHolds(ErrorKind::NullableDereferenced, N, Region,
596 C, ArgExpr, /*SuppressPath=*/true);
601 // No tracked nullability yet.
602 if (ArgStaticNullability != Nullability::Nullable)
604 State = State->set<NullabilityMap>(
605 Region, NullabilityState(ArgStaticNullability, ArgExpr));
607 if (State != OrigState)
608 C.addTransition(State);
611 /// Suppress the nullability warnings for some functions.
612 void NullabilityChecker::checkPostCall(const CallEvent &Call,
613 CheckerContext &C) const {
614 auto Decl = Call.getDecl();
617 // ObjC Messages handles in a different callback.
618 if (Call.getKind() == CE_ObjCMessage)
620 const FunctionType *FuncType = Decl->getFunctionType();
623 QualType ReturnType = FuncType->getReturnType();
624 if (!ReturnType->isAnyPointerType())
626 ProgramStateRef State = C.getState();
627 if (State->get<PreconditionViolated>())
630 const MemRegion *Region = getTrackRegion(Call.getReturnValue());
634 // CG headers are misannotated. Do not warn for symbols that are the results
636 const SourceManager &SM = C.getSourceManager();
637 StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getLocStart()));
638 if (llvm::sys::path::filename(FilePath).startswith("CG")) {
639 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
640 C.addTransition(State);
644 const NullabilityState *TrackedNullability =
645 State->get<NullabilityMap>(Region);
647 if (!TrackedNullability &&
648 getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
649 State = State->set<NullabilityMap>(Region, Nullability::Nullable);
650 C.addTransition(State);
654 static Nullability getReceiverNullability(const ObjCMethodCall &M,
655 ProgramStateRef State) {
656 if (M.isReceiverSelfOrSuper()) {
657 // For super and super class receivers we assume that the receiver is
659 return Nullability::Nonnull;
661 // Otherwise look up nullability in the state.
662 SVal Receiver = M.getReceiverSVal();
663 if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
664 // If the receiver is constrained to be nonnull, assume that it is nonnull
665 // regardless of its type.
666 NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
667 if (Nullness == NullConstraint::IsNotNull)
668 return Nullability::Nonnull;
670 auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
671 if (ValueRegionSVal) {
672 const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
675 const NullabilityState *TrackedSelfNullability =
676 State->get<NullabilityMap>(SelfRegion);
677 if (TrackedSelfNullability)
678 return TrackedSelfNullability->getValue();
680 return Nullability::Unspecified;
683 /// Calculate the nullability of the result of a message expr based on the
684 /// nullability of the receiver, the nullability of the return value, and the
686 void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
687 CheckerContext &C) const {
688 auto Decl = M.getDecl();
691 QualType RetType = Decl->getReturnType();
692 if (!RetType->isAnyPointerType())
695 ProgramStateRef State = C.getState();
696 if (State->get<PreconditionViolated>())
699 const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
703 auto Interface = Decl->getClassInterface();
704 auto Name = Interface ? Interface->getName() : "";
705 // In order to reduce the noise in the diagnostics generated by this checker,
706 // some framework and programming style based heuristics are used. These
707 // heuristics are for Cocoa APIs which have NS prefix.
708 if (Name.startswith("NS")) {
709 // Developers rely on dynamic invariants such as an item should be available
710 // in a collection, or a collection is not empty often. Those invariants can
711 // not be inferred by any static analysis tool. To not to bother the users
712 // with too many false positives, every item retrieval function should be
713 // ignored for collections. The instance methods of dictionaries in Cocoa
714 // are either item retrieval related or not interesting nullability wise.
715 // Using this fact, to keep the code easier to read just ignore the return
716 // value of every instance method of dictionaries.
717 if (M.isInstanceMessage() && Name.find("Dictionary") != StringRef::npos) {
719 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
720 C.addTransition(State);
723 // For similar reasons ignore some methods of Cocoa arrays.
724 StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
725 if (Name.find("Array") != StringRef::npos &&
726 (FirstSelectorSlot == "firstObject" ||
727 FirstSelectorSlot == "lastObject")) {
729 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
730 C.addTransition(State);
734 // Encoding related methods of string should not fail when lossless
735 // encodings are used. Using lossless encodings is so frequent that ignoring
736 // this class of methods reduced the emitted diagnostics by about 30% on
737 // some projects (and all of that was false positives).
738 if (Name.find("String") != StringRef::npos) {
739 for (auto Param : M.parameters()) {
740 if (Param->getName() == "encoding") {
741 State = State->set<NullabilityMap>(ReturnRegion,
742 Nullability::Contradicted);
743 C.addTransition(State);
750 const ObjCMessageExpr *Message = M.getOriginExpr();
751 Nullability SelfNullability = getReceiverNullability(M, State);
753 const NullabilityState *NullabilityOfReturn =
754 State->get<NullabilityMap>(ReturnRegion);
756 if (NullabilityOfReturn) {
757 // When we have a nullability tracked for the return value, the nullability
758 // of the expression will be the most nullable of the receiver and the
760 Nullability RetValTracked = NullabilityOfReturn->getValue();
761 Nullability ComputedNullab =
762 getMostNullable(RetValTracked, SelfNullability);
763 if (ComputedNullab != RetValTracked &&
764 ComputedNullab != Nullability::Unspecified) {
765 const Stmt *NullabilitySource =
766 ComputedNullab == RetValTracked
767 ? NullabilityOfReturn->getNullabilitySource()
768 : Message->getInstanceReceiver();
769 State = State->set<NullabilityMap>(
770 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
771 C.addTransition(State);
776 // No tracked information. Use static type information for return value.
777 Nullability RetNullability = getNullabilityAnnotation(RetType);
779 // Properties might be computed. For this reason the static analyzer creates a
780 // new symbol each time an unknown property is read. To avoid false pozitives
781 // do not treat unknown properties as nullable, even when they explicitly
783 if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
784 RetNullability = Nullability::Nonnull;
786 Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
787 if (ComputedNullab == Nullability::Nullable) {
788 const Stmt *NullabilitySource = ComputedNullab == RetNullability
790 : Message->getInstanceReceiver();
791 State = State->set<NullabilityMap>(
792 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
793 C.addTransition(State);
797 /// Explicit casts are trusted. If there is a disagreement in the nullability
798 /// annotations in the destination and the source or '0' is casted to nonnull
799 /// track the value as having contraditory nullability. This will allow users to
800 /// suppress warnings.
801 void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
802 CheckerContext &C) const {
803 QualType OriginType = CE->getSubExpr()->getType();
804 QualType DestType = CE->getType();
805 if (!OriginType->isAnyPointerType())
807 if (!DestType->isAnyPointerType())
810 ProgramStateRef State = C.getState();
811 if (State->get<PreconditionViolated>())
814 Nullability DestNullability = getNullabilityAnnotation(DestType);
816 // No explicit nullability in the destination type, so this cast does not
817 // change the nullability.
818 if (DestNullability == Nullability::Unspecified)
822 State->getSVal(CE, C.getLocationContext()).getAs<DefinedOrUnknownSVal>();
823 const MemRegion *Region = getTrackRegion(*RegionSVal);
827 // When 0 is converted to nonnull mark it as contradicted.
828 if (DestNullability == Nullability::Nonnull) {
829 NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
830 if (Nullness == NullConstraint::IsNull) {
831 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
832 C.addTransition(State);
837 const NullabilityState *TrackedNullability =
838 State->get<NullabilityMap>(Region);
840 if (!TrackedNullability) {
841 if (DestNullability != Nullability::Nullable)
843 State = State->set<NullabilityMap>(Region,
844 NullabilityState(DestNullability, CE));
845 C.addTransition(State);
849 if (TrackedNullability->getValue() != DestNullability &&
850 TrackedNullability->getValue() != Nullability::Contradicted) {
851 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
852 C.addTransition(State);
856 /// Propagate the nullability information through binds and warn when nullable
857 /// pointer or null symbol is assigned to a pointer with a nonnull type.
858 void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
859 CheckerContext &C) const {
860 const TypedValueRegion *TVR =
861 dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
865 QualType LocType = TVR->getValueType();
866 if (!LocType->isAnyPointerType())
869 ProgramStateRef State = C.getState();
870 if (State->get<PreconditionViolated>())
873 auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
874 if (!ValDefOrUnknown)
877 NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
879 Nullability ValNullability = Nullability::Unspecified;
880 if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
881 ValNullability = getNullabilityAnnotation(Sym->getType());
883 Nullability LocNullability = getNullabilityAnnotation(LocType);
884 if (Filter.CheckNullPassedToNonnull &&
885 RhsNullness == NullConstraint::IsNull &&
886 ValNullability != Nullability::Nonnull &&
887 LocNullability == Nullability::Nonnull) {
888 static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
889 ExplodedNode *N = C.generateSink(State, C.getPredecessor(), &Tag);
890 reportBugIfPreconditionHolds(ErrorKind::NilAssignedToNonnull, N, nullptr, C,
894 // Intentionally missing case: '0' is bound to a reference. It is handled by
895 // the DereferenceChecker.
897 const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
901 const NullabilityState *TrackedNullability =
902 State->get<NullabilityMap>(ValueRegion);
904 if (TrackedNullability) {
905 if (RhsNullness == NullConstraint::IsNotNull ||
906 TrackedNullability->getValue() != Nullability::Nullable)
908 if (Filter.CheckNullablePassedToNonnull &&
909 LocNullability == Nullability::Nonnull) {
910 static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
911 ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
912 reportBugIfPreconditionHolds(ErrorKind::NullableAssignedToNonnull, N,
918 const auto *BinOp = dyn_cast<BinaryOperator>(S);
920 if (ValNullability == Nullability::Nullable) {
921 // Trust the static information of the value more than the static
922 // information on the location.
923 const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
924 State = State->set<NullabilityMap>(
925 ValueRegion, NullabilityState(ValNullability, NullabilitySource));
926 C.addTransition(State);
930 if (LocNullability == Nullability::Nullable) {
931 const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
932 State = State->set<NullabilityMap>(
933 ValueRegion, NullabilityState(LocNullability, NullabilitySource));
934 C.addTransition(State);
938 void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
939 const char *NL, const char *Sep) const {
941 NullabilityMapTy B = State->get<NullabilityMap>();
948 for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
949 Out << I->first << " : ";
950 I->second.print(Out);
955 #define REGISTER_CHECKER(name, trackingRequired) \
956 void ento::register##name##Checker(CheckerManager &mgr) { \
957 NullabilityChecker *checker = mgr.registerChecker<NullabilityChecker>(); \
958 checker->Filter.Check##name = true; \
959 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
960 checker->NeedTracking = checker->NeedTracking || trackingRequired; \
963 // The checks are likely to be turned on by default and it is possible to do
964 // them without tracking any nullability related information. As an optimization
965 // no nullability information will be tracked when only these two checks are
967 REGISTER_CHECKER(NullPassedToNonnull, false)
968 REGISTER_CHECKER(NullReturnedFromNonnull, false)
970 REGISTER_CHECKER(NullableDereferenced, true)
971 REGISTER_CHECKER(NullablePassedToNonnull, true)
972 REGISTER_CHECKER(NullableReturnedFromNonnull, true)