clang 24.0.0git
NullabilityChecker.cpp
Go to the documentation of this file.
1//===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This checker tries to find nullability violations. There are several kinds of
10// possible violations:
11// * Null pointer is passed to a pointer which has a _Nonnull type.
12// * Null pointer is returned from a function which has a _Nonnull return type.
13// * Nullable pointer is passed to a pointer which has a _Nonnull type.
14// * Nullable pointer is returned from a function which has a _Nonnull return
15// type.
16// * Nullable pointer is dereferenced.
17//
18// This checker propagates the nullability information of the pointers and looks
19// for the patterns that are described above. Explicit casts are trusted and are
20// considered a way to suppress false positives for this checker. The other way
21// to suppress warnings would be to add asserts or guarding if statements to the
22// code. In addition to the nullability propagation this checker also uses some
23// heuristics to suppress potential false positives.
24//
25//===----------------------------------------------------------------------===//
26
28
36
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/Path.h"
40
41using namespace clang;
42using namespace ento;
43
44namespace {
45
46/// Returns the most nullable nullability. This is used for message expressions
47/// like [receiver method], where the nullability of this expression is either
48/// the nullability of the receiver or the nullability of the return type of the
49/// method, depending on which is more nullable. Contradicted is considered to
50/// be the most nullable, to avoid false positive results.
51Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
52 return static_cast<Nullability>(
53 std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
54}
55
56const char *getNullabilityString(Nullability Nullab) {
57 switch (Nullab) {
58 case Nullability::Contradicted:
59 return "contradicted";
60 case Nullability::Nullable:
61 return "nullable";
62 case Nullability::Unspecified:
63 return "unspecified";
64 case Nullability::Nonnull:
65 return "nonnull";
66 }
67 llvm_unreachable("Unexpected enumeration.");
68 return "";
69}
70
71// These enums are used as an index to ErrorMessages array.
72// FIXME: ErrorMessages no longer exists, perhaps remove this as well?
73enum class ErrorKind : int {
74 NilAssignedToNonnull,
75 NilPassedToNonnull,
76 NilReturnedToNonnull,
77 NullableAssignedToNonnull,
78 NullableReturnedToNonnull,
79 NullableDereferenced,
80 NullablePassedToNonnull
81};
82
83class NullabilityChecker
84 : public CheckerFamily<
85 check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
86 check::PostCall, check::PostStmt<ExplicitCastExpr>,
87 check::PostObjCMessage, check::DeadSymbols, eval::Assume,
88 check::Location, check::Event<ImplicitNullDerefEvent>,
89 check::BeginFunction> {
90
91public:
92 // If true, the checker will not diagnose nullabilility issues for calls
93 // to system headers. This option is motivated by the observation that large
94 // projects may have many nullability warnings. These projects may
95 // find warnings about nullability annotations that they have explicitly
96 // added themselves higher priority to fix than warnings on calls to system
97 // libraries.
98 bool NoDiagnoseCallsToSystemHeaders = false;
99
100 void checkBind(SVal L, SVal V, const Stmt *S, bool AtDeclInit,
101 CheckerContext &C) const;
102 void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
103 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
104 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
105 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
106 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
107 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
108 void checkEvent(ImplicitNullDerefEvent Event) const;
109 void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
110 CheckerContext &C) const;
111 void checkBeginFunction(CheckerContext &Ctx) const;
112 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
113 bool Assumption) const;
114
115 void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
116 const char *Sep) const override;
117
118 StringRef getDebugTag() const override { return "NullabilityChecker"; }
119
120 // FIXME: All bug types share the same Description ("Nullability") since the
121 // creation of this checker. We should write more descriptive descriptions...
122 // or just eliminate the Description field if it is meaningless?
123 CheckerFrontendWithBugType NullPassedToNonnull{"Nullability",
125 CheckerFrontendWithBugType NullReturnedFromNonnull{"Nullability",
127 CheckerFrontendWithBugType NullableDereferenced{"Nullability",
129 CheckerFrontendWithBugType NullablePassedToNonnull{"Nullability",
131 CheckerFrontendWithBugType NullableReturnedFromNonnull{
132 "Nullability", categories::MemoryError};
133
134 // When set to false no nullability information will be tracked in
135 // NullabilityMap. It is possible to catch errors like passing a null pointer
136 // to a callee that expects nonnull argument without the information that is
137 // stored in the NullabilityMap. This is an optimization.
138 bool NeedTracking = false;
139
140private:
141 class NullabilityBugVisitor : public BugReporterVisitor {
142 public:
143 NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
144
145 void Profile(llvm::FoldingSetNodeID &ID) const override {
146 static int X = 0;
147 ID.AddPointer(&X);
148 ID.AddPointer(Region);
149 }
150
151 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
152 BugReporterContext &BRC,
153 PathSensitiveBugReport &BR) override;
154
155 private:
156 // The tracked region.
157 const MemRegion *Region;
158 };
159
160 /// When any of the nonnull arguments of the analyzed function is null, do not
161 /// report anything and turn off the check.
162 ///
163 /// When \p SuppressPath is set to true, no more bugs will be reported on this
164 /// path by this checker.
165 void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error,
166 const BugType &BT, ExplodedNode *N,
167 const MemRegion *Region, CheckerContext &C,
168 const Stmt *ValueExpr = nullptr,
169 bool SuppressPath = false) const;
170
171 void reportBug(StringRef Msg, ErrorKind Error, const BugType &BT,
172 ExplodedNode *N, const MemRegion *Region, BugReporter &BR,
173 const Stmt *ValueExpr = nullptr) const {
174 auto R = std::make_unique<PathSensitiveBugReport>(BT, Msg, N);
175 if (Region) {
176 R->markInteresting(Region);
177 R->addVisitor<NullabilityBugVisitor>(Region);
178 }
179 if (ValueExpr) {
180 R->addRange(ValueExpr->getSourceRange());
181 if (Error == ErrorKind::NilAssignedToNonnull ||
182 Error == ErrorKind::NilPassedToNonnull ||
183 Error == ErrorKind::NilReturnedToNonnull)
184 if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
186 }
187 BR.emitReport(std::move(R));
188 }
189
190 /// If an SVal wraps a region that should be tracked, it will return a pointer
191 /// to the wrapped region. Otherwise it will return a nullptr.
192 const SymbolicRegion *getTrackRegion(SVal Val,
193 bool CheckSuperRegion = false) const;
194
195 /// Returns true if the call is diagnosable in the current analyzer
196 /// configuration.
197 bool isDiagnosableCall(const CallEvent &Call) const {
198 if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
199 return false;
200
201 return true;
202 }
203};
204
205class NullabilityState {
206public:
207 NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
208 : Nullab(Nullab), Source(Source) {}
209
210 const Stmt *getNullabilitySource() const { return Source; }
211
212 Nullability getValue() const { return Nullab; }
213
214 void Profile(llvm::FoldingSetNodeID &ID) const {
215 ID.AddInteger(static_cast<char>(Nullab));
216 ID.AddPointer(Source);
217 }
218
219 void print(raw_ostream &Out) const {
220 Out << getNullabilityString(Nullab) << "\n";
221 }
222
223private:
224 Nullability Nullab;
225 // Source is the expression which determined the nullability. For example in a
226 // message like [nullable nonnull_returning] has nullable nullability, because
227 // the receiver is nullable. Here the receiver will be the source of the
228 // nullability. This is useful information when the diagnostics are generated.
229 const Stmt *Source;
230};
231
232bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
233 return Lhs.getValue() == Rhs.getValue() &&
234 Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
235}
236
237// For the purpose of tracking historical property accesses, the key for lookup
238// is an object pointer (could be an instance or a class) paired with the unique
239// identifier for the property being invoked on that object.
240using ObjectPropPair = std::pair<const MemRegion *, const IdentifierInfo *>;
241
242// Metadata associated with the return value from a recorded property access.
243struct ConstrainedPropertyVal {
244 // This will reference the conjured return SVal for some call
245 // of the form [object property]
246 DefinedOrUnknownSVal Value;
247
248 // If the SVal has been determined to be nonnull, that is recorded here
249 bool isConstrainedNonnull;
250
251 ConstrainedPropertyVal(DefinedOrUnknownSVal SV)
252 : Value(SV), isConstrainedNonnull(false) {}
253
254 void Profile(llvm::FoldingSetNodeID &ID) const {
255 Value.Profile(ID);
256 ID.AddInteger(isConstrainedNonnull ? 1 : 0);
257 }
258};
259
260bool operator==(const ConstrainedPropertyVal &Lhs,
261 const ConstrainedPropertyVal &Rhs) {
262 return Lhs.Value == Rhs.Value &&
263 Lhs.isConstrainedNonnull == Rhs.isConstrainedNonnull;
264}
265
266} // end anonymous namespace
267
269 NullabilityState)
271 ConstrainedPropertyVal)
272
273// We say "the nullability type invariant is violated" when a location with a
274// non-null type contains NULL or a function with a non-null return type returns
275// NULL. Violations of the nullability type invariant can be detected either
276// directly (for example, when NULL is passed as an argument to a nonnull
277// parameter) or indirectly (for example, when, inside a function, the
278// programmer defensively checks whether a nonnull parameter contains NULL and
279// finds that it does).
280//
281// As a matter of policy, the nullability checker typically warns on direct
282// violations of the nullability invariant (although it uses various
283// heuristics to suppress warnings in some cases) but will not warn if the
284// invariant has already been violated along the path (either directly or
285// indirectly). As a practical matter, this prevents the analyzer from
286// (1) warning on defensive code paths where a nullability precondition is
287// determined to have been violated, (2) warning additional times after an
288// initial direct violation has been discovered, and (3) warning after a direct
289// violation that has been implicitly or explicitly suppressed (for
290// example, with a cast of NULL to _Nonnull). In essence, once an invariant
291// violation is detected on a path, this checker will be essentially turned off
292// for the rest of the analysis
293//
294// The analyzer takes this approach (rather than generating a sink node) to
295// ensure coverage of defensive paths, which may be important for backwards
296// compatibility in codebases that were developed without nullability in mind.
297REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
298
300
302 ProgramStateRef State) {
303 ConditionTruthVal Nullness = State->isNull(Val);
304 if (Nullness.isConstrainedFalse())
306 if (Nullness.isConstrainedTrue())
309}
310
312 return T->isAnyPointerType() || T->isBlockPointerType();
313}
314
315const SymbolicRegion *
316NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
317 if (!NeedTracking)
318 return nullptr;
319
320 auto RegionSVal = Val.getAs<loc::MemRegionVal>();
321 if (!RegionSVal)
322 return nullptr;
323
324 const MemRegion *Region = RegionSVal->getRegion();
325
326 if (CheckSuperRegion) {
327 if (const SubRegion *FieldReg = Region->getAs<FieldRegion>()) {
328 if (const auto *ER = dyn_cast<ElementRegion>(FieldReg->getSuperRegion()))
329 FieldReg = ER;
330 return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
331 }
332 if (auto ElementReg = Region->getAs<ElementRegion>())
333 return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
334 }
335
336 return dyn_cast<SymbolicRegion>(Region);
337}
338
339PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
340 const ExplodedNode *N, BugReporterContext &BRC,
341 PathSensitiveBugReport &BR) {
342 ProgramStateRef State = N->getState();
343 ProgramStateRef StatePrev = N->getFirstPred()->getState();
344
345 const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
346 const NullabilityState *TrackedNullabPrev =
347 StatePrev->get<NullabilityMap>(Region);
348 if (!TrackedNullab)
349 return nullptr;
350
351 if (TrackedNullabPrev &&
352 TrackedNullabPrev->getValue() == TrackedNullab->getValue())
353 return nullptr;
354
355 // Retrieve the associated statement.
356 const Stmt *S = TrackedNullab->getNullabilitySource();
357 if (!S || S->getBeginLoc().isInvalid()) {
358 S = N->getStmtForDiagnostics();
359 }
360
361 if (!S)
362 return nullptr;
363
364 std::string InfoText =
365 (llvm::Twine("Nullability '") +
366 getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
367 .str();
368
369 // Generate the extra diagnostic.
370 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), N->getStackFrame());
371 return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
372}
373
374/// Returns true when the value stored at the given location has been
375/// constrained to null after being passed through an object of nonnnull type.
377 SVal LV, QualType T) {
378 if (getNullabilityAnnotation(T) != Nullability::Nonnull)
379 return false;
380
381 auto RegionVal = LV.getAs<loc::MemRegionVal>();
382 if (!RegionVal)
383 return false;
384
385 // If the value was constrained to null *after* it was passed through that
386 // location, it could not have been a concrete pointer *when* it was passed.
387 // In that case we would have handled the situation when the value was
388 // bound to that location, by emitting (or not emitting) a report.
389 // Therefore we are only interested in symbolic regions that can be either
390 // null or non-null depending on the value of their respective symbol.
391 auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
392 if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
393 return false;
394
395 if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
396 return true;
397
398 return false;
399}
400
402 ProgramStateRef State,
403 const StackFrame *SF) {
404 for (const auto *ParamDecl : Params) {
405 if (ParamDecl->isParameterPack())
406 break;
407
408 // Only nonnull parameters can violate the precondition; check this before
409 // looking up the region of the parameter.
410 if (getNullabilityAnnotation(ParamDecl->getType()) != Nullability::Nonnull)
411 continue;
412
413 SVal LV = State->getLValue(ParamDecl, SF);
415 ParamDecl->getType())) {
416 return true;
417 }
418 }
419 return false;
420}
421
423 const StackFrame *SF) {
424 auto *MD = dyn_cast<ObjCMethodDecl>(SF->getDecl());
425 if (!MD || !MD->isInstanceMethod())
426 return false;
427
428 const ImplicitParamDecl *SelfDecl = SF->getSelfDecl();
429 if (!SelfDecl)
430 return false;
431
432 SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, SF));
433
434 const ObjCObjectPointerType *SelfType =
435 dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
436 if (!SelfType)
437 return false;
438
439 const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
440 if (!ID)
441 return false;
442
443 auto HasInvariantViolation = [&](const ObjCIvarDecl *IvarDecl) {
444 SVal LV = State->getLValue(IvarDecl, SelfVal);
446 IvarDecl->getType());
447 };
448 return llvm::any_of(ID->ivars(), HasInvariantViolation);
449}
450
452 CheckerContext &C) {
453 if (State->get<InvariantViolated>())
454 return true;
455
456 const StackFrame *SF = C.getStackFrame();
457 const Decl *D = SF->getDecl();
458 if (!D)
459 return false;
460
462 if (const auto *BD = dyn_cast<BlockDecl>(D))
463 Params = BD->parameters();
464 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
465 Params = FD->parameters();
466 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
467 Params = MD->parameters();
468 else
469 return false;
470
471 if (checkParamsForPreconditionViolation(Params, State, SF) ||
473 if (!N->isSink())
474 C.addTransition(State->set<InvariantViolated>(true), N);
475 return true;
476 }
477 return false;
478}
479
480void NullabilityChecker::reportBugIfInvariantHolds(
481 StringRef Msg, ErrorKind Error, const BugType &BT, ExplodedNode *N,
482 const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
483 bool SuppressPath) const {
484 if (!N)
485 return;
486 ProgramStateRef OriginalState = N->getState();
487
488 if (checkInvariantViolation(OriginalState, N, C))
489 return;
490 if (SuppressPath) {
491 OriginalState = OriginalState->set<InvariantViolated>(true);
492 N = C.addTransition(OriginalState, N);
493 if (!N)
494 return;
495 }
496
497 reportBug(Msg, Error, BT, N, Region, C.getBugReporter(), ValueExpr);
498}
499
500/// Cleaning up the program state.
501void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
502 CheckerContext &C) const {
503 ProgramStateRef State = C.getState();
504 NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
505 for (const MemRegion *Reg : llvm::make_first_range(Nullabilities)) {
506 const auto *Region = Reg->getAs<SymbolicRegion>();
507 assert(Region && "Non-symbolic region is tracked.");
508 if (SR.isDead(Region->getSymbol())) {
509 State = State->remove<NullabilityMap>(Reg);
510 }
511 }
512
513 // When an object goes out of scope, we can free the history associated
514 // with any property accesses on that object
515 PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
516 for (ObjectPropPair PropKey : llvm::make_first_range(PropertyAccesses)) {
517 const MemRegion *ReceiverRegion = PropKey.first;
518 if (!SR.isLiveRegion(ReceiverRegion)) {
519 State = State->remove<PropertyAccessesMap>(PropKey);
520 }
521 }
522
523 // When one of the nonnull arguments are constrained to be null, nullability
524 // preconditions are violated. It is not enough to check this only when we
525 // actually report an error, because at that time interesting symbols might be
526 // reaped.
527 if (checkInvariantViolation(State, C.getPredecessor(), C))
528 return;
529 C.addTransition(State);
530}
531
532/// This callback triggers when a pointer is dereferenced and the analyzer does
533/// not know anything about the value of that pointer. When that pointer is
534/// nullable, this code emits a warning.
535void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
536 if (Event.SinkNode->getState()->get<InvariantViolated>())
537 return;
538
539 const MemRegion *Region =
540 getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
541 if (!Region)
542 return;
543
544 ProgramStateRef State = Event.SinkNode->getState();
545 const NullabilityState *TrackedNullability =
546 State->get<NullabilityMap>(Region);
547
548 if (!TrackedNullability)
549 return;
550
551 if (NullableDereferenced.isEnabled() &&
552 TrackedNullability->getValue() == Nullability::Nullable) {
553 BugReporter &BR = *Event.BR;
554 // Do not suppress errors on defensive code paths, because dereferencing
555 // a nullable pointer is always an error.
556 if (Event.IsDirectDereference)
557 reportBug("Nullable pointer is dereferenced",
558 ErrorKind::NullableDereferenced, NullableDereferenced,
559 Event.SinkNode, Region, BR);
560 else {
561 reportBug("Nullable pointer is passed to a callee that requires a "
562 "non-null",
563 ErrorKind::NullablePassedToNonnull, NullableDereferenced,
564 Event.SinkNode, Region, BR);
565 }
566 }
567}
568
569void NullabilityChecker::checkBeginFunction(CheckerContext &C) const {
570 if (!C.inTopFrame())
571 return;
572
573 const StackFrame *SF = C.getStackFrame();
574 auto AbstractCall = AnyCall::forDecl(SF->getDecl());
575 if (!AbstractCall || AbstractCall->parameters().empty())
576 return;
577
578 ProgramStateRef State = C.getState();
579 for (const ParmVarDecl *Param : AbstractCall->parameters()) {
580 if (!isValidPointerType(Param->getType()))
581 continue;
582
583 Nullability RequiredNullability =
584 getNullabilityAnnotation(Param->getType());
585 if (RequiredNullability != Nullability::Nullable)
586 continue;
587
588 const VarRegion *ParamRegion = State->getRegion(Param, SF);
589 const MemRegion *ParamPointeeRegion =
590 State->getSVal(ParamRegion).getAsRegion();
591 if (!ParamPointeeRegion)
592 continue;
593
594 State = State->set<NullabilityMap>(ParamPointeeRegion,
595 NullabilityState(RequiredNullability));
596 }
597 C.addTransition(State);
598}
599
600// Whenever we see a load from a typed memory region that's been annotated as
601// 'nonnull', we want to trust the user on that and assume that it is indeed
602// non-null.
603//
604// We do so even if the value is known to have been assigned to null.
605// The user should be warned on assigning the null value to a non-null pointer
606// as opposed to warning on the later dereference of this pointer.
607//
608// \code
609// int * _Nonnull var = 0; // we want to warn the user here...
610// // . . .
611// *var = 42; // ...and not here
612// \endcode
613void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
614 const Stmt *S,
615 CheckerContext &Context) const {
616 // We should care only about loads.
617 // The main idea is to add a constraint whenever we're loading a value from
618 // an annotated pointer type.
619 if (!IsLoad)
620 return;
621
622 // Annotations that we want to consider make sense only for types.
623 const auto *Region =
624 dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
625 if (!Region)
626 return;
627
628 if (getNullabilityAnnotation(Region->getValueType()) != Nullability::Nonnull)
629 return;
630
631 ProgramStateRef State = Context.getState();
632
633 auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
634 if (!StoredVal)
635 return;
636
637 // It doesn't matter what we think about this particular pointer, it should
638 // be considered non-null as annotated by the developer.
639 if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
640 Context.addTransition(NewState);
641 }
642}
643
644/// Find the outermost subexpression of E that is not an implicit cast.
645/// This looks through the implicit casts to _Nonnull that ARC adds to
646/// return expressions of ObjC types when the return type of the function or
647/// method is non-null but the express is not.
648static const Expr *lookThroughImplicitCasts(const Expr *E) {
649 return E->IgnoreImpCasts();
650}
651
652/// This method check when nullable pointer or null value is returned from a
653/// function that has nonnull return type.
654void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
655 CheckerContext &C) const {
656 auto RetExpr = S->getRetValue();
657 if (!RetExpr)
658 return;
659
660 if (!isValidPointerType(RetExpr->getType()))
661 return;
662
663 ProgramStateRef State = C.getState();
664 if (State->get<InvariantViolated>())
665 return;
666
667 auto RetSVal = C.getSVal(RetExpr).getAs<DefinedOrUnknownSVal>();
668 if (!RetSVal)
669 return;
670
671 bool InSuppressedMethodFamily = false;
672
673 QualType RequiredRetType;
674 AnalysisDeclContext *DeclCtxt = C.getStackFrame()->getAnalysisDeclContext();
675 const Decl *D = DeclCtxt->getDecl();
676 if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
677 // HACK: This is a big hammer to avoid warning when there are defensive
678 // nil checks in -init and -copy methods. We should add more sophisticated
679 // logic here to suppress on common defensive idioms but still
680 // warn when there is a likely problem.
681 ObjCMethodFamily Family = MD->getMethodFamily();
682 if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
683 InSuppressedMethodFamily = true;
684
685 RequiredRetType = MD->getReturnType();
686 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
687 RequiredRetType = FD->getReturnType();
688 } else {
689 return;
690 }
691
692 NullConstraint Nullness = getNullConstraint(*RetSVal, State);
693
694 Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
695 if (const auto *FunDecl = C.getStackFrame()->getDecl();
696 FunDecl && FunDecl->getAttr<ReturnsNonNullAttr>() &&
697 (RequiredNullability == Nullability::Unspecified ||
698 RequiredNullability == Nullability::Nullable)) {
699 // If a function is marked with the returns_nonnull attribute,
700 // the return value must be non-null.
701 RequiredNullability = Nullability::Nonnull;
702 }
703
704 // If the returned value is null but the type of the expression
705 // generating it is nonnull then we will suppress the diagnostic.
706 // This enables explicit suppression when returning a nil literal in a
707 // function with a _Nonnull return type:
708 // return (NSString * _Nonnull)0;
709 Nullability RetExprTypeLevelNullability =
711
712 if (RequiredNullability == Nullability::Nonnull &&
713 Nullness == NullConstraint::IsNull) {
714 if (NullReturnedFromNonnull.isEnabled() &&
715 RetExprTypeLevelNullability != Nullability::Nonnull &&
716 !InSuppressedMethodFamily) {
717 ExplodedNode *N = C.addSink(State);
718 if (!N)
719 return;
720
721 SmallString<256> SBuf;
722 llvm::raw_svector_ostream OS(SBuf);
723 OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
724 OS << " returned from a " << C.getDeclDescription(D)
725 << " that is expected to return a non-null value";
726 reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
727 NullReturnedFromNonnull, N, nullptr, C,
728 RetExpr);
729 return;
730 }
731
732 // If null was returned from a non-null function, mark the nullability
733 // invariant as violated even if the diagnostic was suppressed.
734 State = State->set<InvariantViolated>(true);
735 C.addTransition(State);
736 return;
737 }
738
739 const MemRegion *Region = getTrackRegion(*RetSVal);
740 if (!Region)
741 return;
742
743 const NullabilityState *TrackedNullability =
744 State->get<NullabilityMap>(Region);
745 if (TrackedNullability) {
746 Nullability TrackedNullabValue = TrackedNullability->getValue();
747 if (NullableReturnedFromNonnull.isEnabled() &&
748 Nullness != NullConstraint::IsNotNull &&
749 TrackedNullabValue == Nullability::Nullable &&
750 RequiredNullability == Nullability::Nonnull) {
751 ExplodedNode *N = C.addTransition(State, C.getPredecessor());
752
753 SmallString<256> SBuf;
754 llvm::raw_svector_ostream OS(SBuf);
755 OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
756 " that is expected to return a non-null value";
757
758 reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
759 NullableReturnedFromNonnull, N, Region, C);
760 }
761 return;
762 }
763 if (RequiredNullability == Nullability::Nullable) {
764 State = State->set<NullabilityMap>(Region,
765 NullabilityState(RequiredNullability,
766 S));
767 C.addTransition(State);
768 }
769}
770
771/// This callback warns when a nullable pointer or a null value is passed to a
772/// function that expects its argument to be nonnull.
773void NullabilityChecker::checkPreCall(const CallEvent &Call,
774 CheckerContext &C) const {
775 if (!Call.getDecl())
776 return;
777
778 ProgramStateRef State = C.getState();
779 if (State->get<InvariantViolated>())
780 return;
781
782 ProgramStateRef OrigState = State;
783
784 unsigned Idx = 0;
785 for (const ParmVarDecl *Param : Call.parameters()) {
786 if (Param->isParameterPack())
787 break;
788
789 if (Idx >= Call.getNumArgs())
790 break;
791
792 const Expr *ArgExpr = Call.getArgExpr(Idx);
793 auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
794 if (!ArgSVal)
795 continue;
796
797 if (!isValidPointerType(Param->getType()) &&
798 !Param->getType()->isReferenceType())
799 continue;
800
801 NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
802
803 Nullability RequiredNullability =
804 getNullabilityAnnotation(Param->getType());
805 Nullability ArgExprTypeLevelNullability =
807
808 unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
809
810 if (NullPassedToNonnull.isEnabled() && Nullness == NullConstraint::IsNull &&
811 ArgExprTypeLevelNullability != Nullability::Nonnull &&
812 RequiredNullability == Nullability::Nonnull &&
813 isDiagnosableCall(Call)) {
814 ExplodedNode *N = C.addSink(State);
815 if (!N)
816 return;
817
818 SmallString<256> SBuf;
819 llvm::raw_svector_ostream OS(SBuf);
820 OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
821 OS << " passed to a callee that requires a non-null " << ParamIdx
822 << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
823 reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
824 NullPassedToNonnull, N, nullptr, C, ArgExpr,
825 /*SuppressPath=*/false);
826 return;
827 }
828
829 const MemRegion *Region = getTrackRegion(*ArgSVal);
830 if (!Region)
831 continue;
832
833 const NullabilityState *TrackedNullability =
834 State->get<NullabilityMap>(Region);
835
836 if (TrackedNullability) {
837 if (Nullness == NullConstraint::IsNotNull ||
838 TrackedNullability->getValue() != Nullability::Nullable)
839 continue;
840
841 if (NullablePassedToNonnull.isEnabled() &&
842 RequiredNullability == Nullability::Nonnull &&
843 isDiagnosableCall(Call)) {
844 ExplodedNode *N = C.addTransition(State);
845 SmallString<256> SBuf;
846 llvm::raw_svector_ostream OS(SBuf);
847 OS << "Nullable pointer is passed to a callee that requires a non-null "
848 << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
849 reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
850 NullablePassedToNonnull, N, Region, C,
851 ArgExpr, /*SuppressPath=*/true);
852 return;
853 }
854 if (NullableDereferenced.isEnabled() &&
855 Param->getType()->isReferenceType()) {
856 ExplodedNode *N = C.addTransition(State);
857 reportBugIfInvariantHolds(
858 "Nullable pointer is dereferenced", ErrorKind::NullableDereferenced,
859 NullableDereferenced, N, Region, C, ArgExpr, /*SuppressPath=*/true);
860 return;
861 }
862 continue;
863 }
864 }
865 if (State != OrigState)
866 C.addTransition(State);
867}
868
869/// Suppress the nullability warnings for some functions.
870void NullabilityChecker::checkPostCall(const CallEvent &Call,
871 CheckerContext &C) const {
872 auto Decl = Call.getDecl();
873 if (!Decl)
874 return;
875 // ObjC Messages handles in a different callback.
876 if (Call.getKind() == CE_ObjCMessage)
877 return;
878 const FunctionType *FuncType = Decl->getFunctionType();
879 if (!FuncType)
880 return;
881 QualType ReturnType = FuncType->getReturnType();
882 if (!isValidPointerType(ReturnType))
883 return;
884 ProgramStateRef State = C.getState();
885 if (State->get<InvariantViolated>())
886 return;
887
888 const MemRegion *Region = getTrackRegion(Call.getReturnValue());
889 if (!Region)
890 return;
891
892 // CG headers are misannotated. Do not warn for symbols that are the results
893 // of CG calls.
894 const SourceManager &SM = C.getSourceManager();
895 StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
896 if (llvm::sys::path::filename(FilePath).starts_with("CG")) {
897 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
898 C.addTransition(State);
899 return;
900 }
901
902 const NullabilityState *TrackedNullability =
903 State->get<NullabilityMap>(Region);
904
905 // ObjCMessageExpr gets the actual type through
906 // Sema::getMessageSendResultType, instead of using the return type of
907 // MethodDecl directly. The final type is generated by considering the
908 // nullability of receiver and MethodDecl together. Thus, The type of
909 // ObjCMessageExpr is prefer.
910 if (const Expr *E = Call.getOriginExpr())
911 ReturnType = E->getType();
912
913 if (!TrackedNullability &&
914 getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
915 State = State->set<NullabilityMap>(Region, Nullability::Nullable);
916 C.addTransition(State);
917 }
918}
919
921 ProgramStateRef State) {
922 if (M.isReceiverSelfOrSuper()) {
923 // For super and super class receivers we assume that the receiver is
924 // nonnull.
925 return Nullability::Nonnull;
926 }
927 // Otherwise look up nullability in the state.
928 SVal Receiver = M.getReceiverSVal();
929 if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
930 // If the receiver is constrained to be nonnull, assume that it is nonnull
931 // regardless of its type.
932 NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
933 if (Nullness == NullConstraint::IsNotNull)
934 return Nullability::Nonnull;
935 }
936 auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
937 if (ValueRegionSVal) {
938 const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
939 assert(SelfRegion);
940
941 const NullabilityState *TrackedSelfNullability =
942 State->get<NullabilityMap>(SelfRegion);
943 if (TrackedSelfNullability)
944 return TrackedSelfNullability->getValue();
945 }
946 return Nullability::Unspecified;
947}
948
949// The return value of a property access is typically a temporary value which
950// will not be tracked in a persistent manner by the analyzer. We use
951// evalAssume() in order to immediately record constraints on those temporaries
952// at the time they are imposed (e.g. by a nil-check conditional).
953ProgramStateRef NullabilityChecker::evalAssume(ProgramStateRef State, SVal Cond,
954 bool Assumption) const {
955 PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
956 for (auto [PropKey, PropVal] : PropertyAccesses) {
957 if (!PropVal.isConstrainedNonnull) {
958 ConditionTruthVal IsNonNull = State->isNonNull(PropVal.Value);
959 if (IsNonNull.isConstrainedTrue()) {
960 ConstrainedPropertyVal Replacement = PropVal;
961 Replacement.isConstrainedNonnull = true;
962 State = State->set<PropertyAccessesMap>(PropKey, Replacement);
963 } else if (IsNonNull.isConstrainedFalse()) {
964 // Space optimization: no point in tracking constrained-null cases
965 State = State->remove<PropertyAccessesMap>(PropKey);
966 }
967 }
968 }
969
970 return State;
971}
972
973/// Calculate the nullability of the result of a message expr based on the
974/// nullability of the receiver, the nullability of the return value, and the
975/// constraints.
976void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
977 CheckerContext &C) const {
978 auto Decl = M.getDecl();
979 if (!Decl)
980 return;
981 QualType RetType = Decl->getReturnType();
982 if (!isValidPointerType(RetType))
983 return;
984
985 ProgramStateRef State = C.getState();
986 if (State->get<InvariantViolated>())
987 return;
988
989 const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
990 if (!ReturnRegion)
991 return;
992
993 auto Interface = Decl->getClassInterface();
994 auto Name = Interface ? Interface->getName() : "";
995 // In order to reduce the noise in the diagnostics generated by this checker,
996 // some framework and programming style based heuristics are used. These
997 // heuristics are for Cocoa APIs which have NS prefix.
998 if (Name.starts_with("NS")) {
999 // Developers rely on dynamic invariants such as an item should be available
1000 // in a collection, or a collection is not empty often. Those invariants can
1001 // not be inferred by any static analysis tool. To not to bother the users
1002 // with too many false positives, every item retrieval function should be
1003 // ignored for collections. The instance methods of dictionaries in Cocoa
1004 // are either item retrieval related or not interesting nullability wise.
1005 // Using this fact, to keep the code easier to read just ignore the return
1006 // value of every instance method of dictionaries.
1007 if (M.isInstanceMessage() && Name.contains("Dictionary")) {
1008 State =
1009 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
1010 C.addTransition(State);
1011 return;
1012 }
1013 // For similar reasons ignore some methods of Cocoa arrays.
1014 StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
1015 if (Name.contains("Array") &&
1016 (FirstSelectorSlot == "firstObject" ||
1017 FirstSelectorSlot == "lastObject")) {
1018 State =
1019 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
1020 C.addTransition(State);
1021 return;
1022 }
1023
1024 // Encoding related methods of string should not fail when lossless
1025 // encodings are used. Using lossless encodings is so frequent that ignoring
1026 // this class of methods reduced the emitted diagnostics by about 30% on
1027 // some projects (and all of that was false positives).
1028 if (Name.contains("String")) {
1029 for (auto *Param : M.parameters()) {
1030 if (Param->getName() == "encoding") {
1031 State = State->set<NullabilityMap>(ReturnRegion,
1032 Nullability::Contradicted);
1033 C.addTransition(State);
1034 return;
1035 }
1036 }
1037 }
1038 }
1039
1040 const ObjCMessageExpr *Message = M.getOriginExpr();
1041 Nullability SelfNullability = getReceiverNullability(M, State);
1042
1043 const NullabilityState *NullabilityOfReturn =
1044 State->get<NullabilityMap>(ReturnRegion);
1045
1046 if (NullabilityOfReturn) {
1047 // When we have a nullability tracked for the return value, the nullability
1048 // of the expression will be the most nullable of the receiver and the
1049 // return value.
1050 Nullability RetValTracked = NullabilityOfReturn->getValue();
1051 Nullability ComputedNullab =
1052 getMostNullable(RetValTracked, SelfNullability);
1053 if (ComputedNullab != RetValTracked &&
1054 ComputedNullab != Nullability::Unspecified) {
1055 const Stmt *NullabilitySource =
1056 ComputedNullab == RetValTracked
1057 ? NullabilityOfReturn->getNullabilitySource()
1058 : Message->getInstanceReceiver();
1059 State = State->set<NullabilityMap>(
1060 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
1061 C.addTransition(State);
1062 }
1063 return;
1064 }
1065
1066 // No tracked information. Use static type information for return value.
1067 Nullability RetNullability = getNullabilityAnnotation(Message->getType());
1068
1069 // Properties might be computed, which means the property value could
1070 // theoretically change between calls even in commonly-observed cases like
1071 // this:
1072 //
1073 // if (foo.prop) { // ok, it's nonnull here...
1074 // [bar doStuffWithNonnullVal:foo.prop]; // ...but what about
1075 // here?
1076 // }
1077 //
1078 // If the property is nullable-annotated, a naive analysis would lead to many
1079 // false positives despite the presence of probably-correct nil-checks. To
1080 // reduce the false positive rate, we maintain a history of the most recently
1081 // observed property value. For each property access, if the prior value has
1082 // been constrained to be not nil then we will conservatively assume that the
1083 // next access can be inferred as nonnull.
1084 if (RetNullability != Nullability::Nonnull &&
1085 M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined) {
1086 bool LookupResolved = false;
1087 if (const MemRegion *ReceiverRegion = getTrackRegion(M.getReceiverSVal())) {
1088 if (const IdentifierInfo *Ident =
1090 LookupResolved = true;
1091 ObjectPropPair Key = std::make_pair(ReceiverRegion, Ident);
1092 const ConstrainedPropertyVal *PrevPropVal =
1093 State->get<PropertyAccessesMap>(Key);
1094 if (PrevPropVal && PrevPropVal->isConstrainedNonnull) {
1095 RetNullability = Nullability::Nonnull;
1096 } else {
1097 // If a previous property access was constrained as nonnull, we hold
1098 // on to that constraint (effectively inferring that all subsequent
1099 // accesses on that code path can be inferred as nonnull). If the
1100 // previous property access was *not* constrained as nonnull, then
1101 // let's throw it away in favor of keeping the SVal associated with
1102 // this more recent access.
1103 if (auto ReturnSVal =
1104 M.getReturnValue().getAs<DefinedOrUnknownSVal>()) {
1105 State = State->set<PropertyAccessesMap>(
1106 Key, ConstrainedPropertyVal(*ReturnSVal));
1107 }
1108 }
1109 }
1110 }
1111
1112 if (!LookupResolved) {
1113 // Fallback: err on the side of suppressing the false positive.
1114 RetNullability = Nullability::Nonnull;
1115 }
1116 }
1117
1118 Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
1119 if (ComputedNullab == Nullability::Nullable) {
1120 const Stmt *NullabilitySource = ComputedNullab == RetNullability
1121 ? Message
1122 : Message->getInstanceReceiver();
1123 State = State->set<NullabilityMap>(
1124 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
1125 C.addTransition(State);
1126 }
1127}
1128
1129/// Explicit casts are trusted. If there is a disagreement in the nullability
1130/// annotations in the destination and the source or '0' is casted to nonnull
1131/// track the value as having contraditory nullability. This will allow users to
1132/// suppress warnings.
1133void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
1134 CheckerContext &C) const {
1135 QualType OriginType = CE->getSubExpr()->getType();
1136 QualType DestType = CE->getType();
1137 if (!isValidPointerType(OriginType))
1138 return;
1139 if (!isValidPointerType(DestType))
1140 return;
1141
1142 ProgramStateRef State = C.getState();
1143 if (State->get<InvariantViolated>())
1144 return;
1145
1146 Nullability DestNullability = getNullabilityAnnotation(DestType);
1147
1148 // No explicit nullability in the destination type, so this cast does not
1149 // change the nullability.
1150 if (DestNullability == Nullability::Unspecified)
1151 return;
1152
1153 auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
1154 const MemRegion *Region = getTrackRegion(*RegionSVal);
1155 if (!Region)
1156 return;
1157
1158 // When 0 is converted to nonnull mark it as contradicted.
1159 if (DestNullability == Nullability::Nonnull) {
1160 NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
1161 if (Nullness == NullConstraint::IsNull) {
1162 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1163 C.addTransition(State);
1164 return;
1165 }
1166 }
1167
1168 const NullabilityState *TrackedNullability =
1169 State->get<NullabilityMap>(Region);
1170
1171 if (!TrackedNullability) {
1172 if (DestNullability != Nullability::Nullable)
1173 return;
1174 State = State->set<NullabilityMap>(Region,
1175 NullabilityState(DestNullability, CE));
1176 C.addTransition(State);
1177 return;
1178 }
1179
1180 if (TrackedNullability->getValue() != DestNullability &&
1181 TrackedNullability->getValue() != Nullability::Contradicted) {
1182 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1183 C.addTransition(State);
1184 }
1185}
1186
1187/// For a given statement performing a bind, attempt to syntactically
1188/// match the expression resulting in the bound value.
1189static const Expr * matchValueExprForBind(const Stmt *S) {
1190 // For `x = e` the value expression is the right-hand side.
1191 if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
1192 if (BinOp->getOpcode() == BO_Assign)
1193 return BinOp->getRHS();
1194 }
1195
1196 // For `int x = e` the value expression is the initializer.
1197 if (auto *DS = dyn_cast<DeclStmt>(S)) {
1198 if (DS->isSingleDecl()) {
1199 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1200 if (!VD)
1201 return nullptr;
1202
1203 if (const Expr *Init = VD->getInit())
1204 return Init;
1205 }
1206 }
1207
1208 return nullptr;
1209}
1210
1211/// Returns true if \param S is a DeclStmt for a local variable that
1212/// ObjC automated reference counting initialized with zero.
1214 // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
1215 // prevents false positives when a _Nonnull local variable cannot be
1216 // initialized with an initialization expression:
1217 // NSString * _Nonnull s; // no-warning
1218 // @autoreleasepool {
1219 // s = ...
1220 // }
1221 //
1222 // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
1223 // uninitialized in Sema's UninitializedValues analysis to warn when a use of
1224 // the zero-initialized definition will unexpectedly yield nil.
1225
1226 // Locals are only zero-initialized when automated reference counting
1227 // is turned on.
1228 if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
1229 return false;
1230
1231 auto *DS = dyn_cast<DeclStmt>(S);
1232 if (!DS || !DS->isSingleDecl())
1233 return false;
1234
1235 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1236 if (!VD)
1237 return false;
1238
1239 // Sema only zero-initializes locals with ObjCLifetimes.
1240 if(!VD->getType().getQualifiers().hasObjCLifetime())
1241 return false;
1242
1243 const Expr *Init = VD->getInit();
1244 assert(Init && "ObjC local under ARC without initializer");
1245
1246 // Return false if the local is explicitly initialized (e.g., with '= nil').
1248 return false;
1249
1250 return true;
1251}
1252
1253/// Propagate the nullability information through binds and warn when nullable
1254/// pointer or null symbol is assigned to a pointer with a nonnull type.
1255void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
1256 bool AtDeclInit, CheckerContext &C) const {
1257 const TypedValueRegion *TVR =
1258 dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
1259 if (!TVR)
1260 return;
1261
1262 QualType LocType = TVR->getValueType();
1263 if (!isValidPointerType(LocType))
1264 return;
1265
1266 ProgramStateRef State = C.getState();
1267 if (State->get<InvariantViolated>())
1268 return;
1269
1270 auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
1271 if (!ValDefOrUnknown)
1272 return;
1273
1274 NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
1275
1276 Nullability ValNullability = Nullability::Unspecified;
1277 if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
1278 ValNullability = getNullabilityAnnotation(Sym->getType());
1279
1280 Nullability LocNullability = getNullabilityAnnotation(LocType);
1281
1282 // If the type of the RHS expression is nonnull, don't warn. This
1283 // enables explicit suppression with a cast to nonnull.
1284 Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
1285 const Expr *ValueExpr = matchValueExprForBind(S);
1286 if (ValueExpr) {
1287 ValueExprTypeLevelNullability =
1289 }
1290
1291 bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
1292 RhsNullness == NullConstraint::IsNull);
1293 if (NullPassedToNonnull.isEnabled() && NullAssignedToNonNull &&
1294 ValNullability != Nullability::Nonnull &&
1295 ValueExprTypeLevelNullability != Nullability::Nonnull &&
1297 ExplodedNode *N = C.addSink(State);
1298 if (!N)
1299 return;
1300
1301
1302 const Stmt *ValueStmt = S;
1303 if (ValueExpr)
1304 ValueStmt = ValueExpr;
1305
1306 SmallString<256> SBuf;
1307 llvm::raw_svector_ostream OS(SBuf);
1308 OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
1309 OS << " assigned to a pointer which is expected to have non-null value";
1310 reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
1311 NullPassedToNonnull, N, nullptr, C, ValueStmt);
1312 return;
1313 }
1314
1315 // If null was returned from a non-null function, mark the nullability
1316 // invariant as violated even if the diagnostic was suppressed.
1317 if (NullAssignedToNonNull) {
1318 State = State->set<InvariantViolated>(true);
1319 C.addTransition(State);
1320 return;
1321 }
1322
1323 // Intentionally missing case: '0' is bound to a reference. It is handled by
1324 // the DereferenceChecker.
1325
1326 const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
1327 if (!ValueRegion)
1328 return;
1329
1330 const NullabilityState *TrackedNullability =
1331 State->get<NullabilityMap>(ValueRegion);
1332
1333 if (TrackedNullability) {
1334 if (RhsNullness == NullConstraint::IsNotNull ||
1335 TrackedNullability->getValue() != Nullability::Nullable)
1336 return;
1337 if (NullablePassedToNonnull.isEnabled() &&
1338 LocNullability == Nullability::Nonnull) {
1339 ExplodedNode *N = C.addTransition(State, C.getPredecessor());
1340 reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
1341 "which is expected to have non-null value",
1342 ErrorKind::NullableAssignedToNonnull,
1343 NullablePassedToNonnull, N, ValueRegion, C);
1344 }
1345 return;
1346 }
1347
1348 const auto *BinOp = dyn_cast<BinaryOperator>(S);
1349
1350 if (ValNullability == Nullability::Nullable) {
1351 // Trust the static information of the value more than the static
1352 // information on the location.
1353 const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
1354 State = State->set<NullabilityMap>(
1355 ValueRegion, NullabilityState(ValNullability, NullabilitySource));
1356 C.addTransition(State);
1357 return;
1358 }
1359
1360 if (LocNullability == Nullability::Nullable) {
1361 const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
1362 State = State->set<NullabilityMap>(
1363 ValueRegion, NullabilityState(LocNullability, NullabilitySource));
1364 C.addTransition(State);
1365 }
1366}
1367
1368void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
1369 const char *NL, const char *Sep) const {
1370
1371 NullabilityMapTy B = State->get<NullabilityMap>();
1372
1373 if (State->get<InvariantViolated>())
1374 Out << Sep << NL
1375 << "Nullability invariant was violated, warnings suppressed." << NL;
1376
1377 if (B.isEmpty())
1378 return;
1379
1380 if (!State->get<InvariantViolated>())
1381 Out << Sep << NL;
1382
1383 for (auto [Region, State] : B) {
1384 Out << Region << " : ";
1385 State.print(Out);
1386 Out << NL;
1387 }
1388}
1389
1390// The checker group "nullability" (which consists of the checkers that are
1391// implemented in this file) has a group-level configuration option which
1392// affects all the checkers in the group. As this is a completely unique
1393// remnant of old design (this is the only group option in the analyzer), there
1394// is no machinery to inject the group name from `Checkers.td`, so it is simply
1395// hardcoded here:
1396constexpr llvm::StringLiteral GroupName = "nullability";
1397constexpr llvm::StringLiteral GroupOptName = "NoDiagnoseCallsToSystemHeaders";
1398
1399#define REGISTER_CHECKER(NAME, TRACKING_REQUIRED) \
1400 void ento::register##NAME##Checker(CheckerManager &Mgr) { \
1401 NullabilityChecker *Chk = Mgr.getChecker<NullabilityChecker>(); \
1402 Chk->NAME.enable(Mgr); \
1403 Chk->NeedTracking = Chk->NeedTracking || TRACKING_REQUIRED; \
1404 Chk->NoDiagnoseCallsToSystemHeaders = \
1405 Mgr.getAnalyzerOptions().getCheckerBooleanOption(GroupName, \
1406 GroupOptName, true); \
1407 } \
1408 \
1409 bool ento::shouldRegister##NAME##Checker(const CheckerManager &) { \
1410 return true; \
1411 }
1412
1413// The checks are likely to be turned on by default and it is possible to do
1414// them without tracking any nullability related information. As an optimization
1415// no nullability information will be tracked when only these two checks are
1416// enables.
1417REGISTER_CHECKER(NullPassedToNonnull, false)
1418REGISTER_CHECKER(NullReturnedFromNonnull, false)
1419
1420REGISTER_CHECKER(NullableDereferenced, true)
1421REGISTER_CHECKER(NullablePassedToNonnull, true)
1422REGISTER_CHECKER(NullableReturnedFromNonnull, true)
1423
1424#undef REGISTER_CHECKER
#define V(N, I)
#define REGISTER_CHECKER(name)
TokenType getType() const
Returns the token's type, e.g.
static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx, QualType Ty)
#define X(type, name)
Definition Value.h:97
static bool isValidPointerType(QualType T)
static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val, ProgramStateRef State)
static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S)
Returns true if.
constexpr llvm::StringLiteral GroupOptName
static bool checkValueAtLValForInvariantViolation(ProgramStateRef State, SVal LV, QualType T)
Returns true when the value stored at the given location has been constrained to null after being pas...
static const Expr * matchValueExprForBind(const Stmt *S)
For a given statement performing a bind, attempt to syntactically match the expression resulting in t...
static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N, CheckerContext &C)
constexpr llvm::StringLiteral GroupName
static const Expr * lookThroughImplicitCasts(const Expr *E)
Find the outermost subexpression of E that is not an implicit cast.
static bool checkParamsForPreconditionViolation(ArrayRef< ParmVarDecl * > Params, ProgramStateRef State, const StackFrame *SF)
static bool checkSelfIvarsForInvariantViolation(ProgramStateRef State, const StackFrame *SF)
static Nullability getReceiverNullability(const ObjCMethodCall &M, ProgramStateRef State)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
static std::optional< AnyCall > forDecl(const Decl *D)
If D is a callable (Objective-C method or a function), return a constructed AnyCall object.
Definition AnyCall.h:135
Expr * getSubExpr()
Definition Expr.h:3795
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:114
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3110
QualType getType() const
Definition Expr.h:146
QualType getReturnType() const
Definition TypeBase.h:5186
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
Represents a pointer to an Objective C object.
Definition TypeBase.h:8321
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8373
A (possibly-)qualified type.
Definition TypeBase.h:938
Expr * getRetValue()
Definition Stmt.h:3200
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
It represents a stack frame of the call stack.
const Decl * getDecl() const
const ImplicitParamDecl * getSelfDecl() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isObjCObjectPointerType() const
Definition TypeBase.h:9100
QualType getType() const
Definition Decl.h:725
const SourceManager & getSourceManager() const
virtual void emitReport(std::unique_ptr< BugReport > R)
Add the given report to the set of reports tracked by BugReporter.
SVal getReturnValue() const
Returns the return value of the call.
Checker families (where a single backend class implements multiple related frontends) should derive f...
Definition Checker.h:596
bool isConstrainedFalse() const
Return true if the constraint is perfectly constrained to 'false'.
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
const RegionTy * getAs() const
Definition MemRegion.h:1427
Represents any expression that calls an Objective-C method.
Definition CallEvent.h:1244
const ObjCMethodDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition CallEvent.h:1272
ObjCMessageKind getMessageKind() const
Returns how the message was written in the source (property access, subscript, or explicit message se...
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:1268
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
bool isReceiverSelfOrSuper() const
Checks if the receiver refers to 'self' or 'super'.
Selector getSelector() const
Definition CallEvent.h:1290
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
Definition SVals.cpp:180
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
bool isLiveRegion(const MemRegion *region)
SymbolicRegion - A special, "non-concrete" region.
Definition MemRegion.h:814
virtual QualType getValueType() const =0
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.
Nullability getNullabilityAnnotation(QualType Type)
Get nullability annotation for a given type.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:166
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
bool IsNonNull(InterpState &S)
Definition Interp.h:3174
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
ObjCMethodFamily
A family of Objective-C methods.
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6253
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25