blob: 7d1ca61c97a9c13665b09c27cbd51d176c325d0f [file] [log] [blame]
Gabor Horvath28690922015-08-26 23:17:43 +00001//== 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"
Anna Zaksad9e7ea2016-01-29 18:43:15 +000029
Gabor Horvath28690922015-08-26 23:17:43 +000030#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
31#include "clang/StaticAnalyzer/Core/Checker.h"
32#include "clang/StaticAnalyzer/Core/CheckerManager.h"
George Karpenkov2301c5a2018-03-23 00:16:03 +000033#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
Gabor Horvath28690922015-08-26 23:17:43 +000034#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
35#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
36
Anna Zaksad9e7ea2016-01-29 18:43:15 +000037#include "llvm/ADT/StringExtras.h"
38#include "llvm/Support/Path.h"
39
Gabor Horvath28690922015-08-26 23:17:43 +000040using namespace clang;
41using namespace ento;
42
43namespace {
Gabor Horvath28690922015-08-26 23:17:43 +000044
45/// Returns the most nullable nullability. This is used for message expressions
Simon Pilgrim2c518802017-03-30 14:13:19 +000046/// like [receiver method], where the nullability of this expression is either
Gabor Horvath28690922015-08-26 23:17:43 +000047/// 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.
Gabor Horvath3943adb2015-09-11 16:29:05 +000050Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
Gabor Horvath28690922015-08-26 23:17:43 +000051 return static_cast<Nullability>(
52 std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
53}
54
Gabor Horvath3943adb2015-09-11 16:29:05 +000055const char *getNullabilityString(Nullability Nullab) {
Gabor Horvath28690922015-08-26 23:17:43 +000056 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 }
Gabor Horvath3943adb2015-09-11 16:29:05 +000066 llvm_unreachable("Unexpected enumeration.");
Gabor Horvath28690922015-08-26 23:17:43 +000067 return "";
68}
69
70// These enums are used as an index to ErrorMessages array.
71enum class ErrorKind : int {
72 NilAssignedToNonnull,
73 NilPassedToNonnull,
74 NilReturnedToNonnull,
75 NullableAssignedToNonnull,
76 NullableReturnedToNonnull,
77 NullableDereferenced,
78 NullablePassedToNonnull
79};
80
Gabor Horvath28690922015-08-26 23:17:43 +000081class 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
88public:
Devin Coughlina1d9d752016-03-05 01:32:43 +000089 // 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
Gabor Horvath28690922015-08-26 23:17:43 +000097 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;
Gabor Horvath29307352015-09-14 18:31:34 +0000124 // 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;
Gabor Horvath28690922015-08-26 23:17:43 +0000129
130private:
George Karpenkov70ec1dd2018-06-26 21:12:08 +0000131 class NullabilityBugVisitor : public BugReporterVisitor {
Gabor Horvath28690922015-08-26 23:17:43 +0000132 public:
133 NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
134
135 void Profile(llvm::FoldingSetNodeID &ID) const override {
136 static int X = 0;
137 ID.AddPointer(&X);
138 ID.AddPointer(Region);
139 }
140
David Blaikie0a0c2752017-01-05 17:26:53 +0000141 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
142 const ExplodedNode *PrevN,
143 BugReporterContext &BRC,
144 BugReport &BR) override;
Gabor Horvath28690922015-08-26 23:17:43 +0000145
146 private:
147 // The tracked region.
148 const MemRegion *Region;
149 };
150
Gabor Horvathb47128a2015-09-03 23:16:21 +0000151 /// When any of the nonnull arguments of the analyzed function is null, do not
152 /// report anything and turn off the check.
153 ///
154 /// When \p SuppressPath is set to true, no more bugs will be reported on this
155 /// path by this checker.
Devin Coughlin77942db2016-03-28 20:30:25 +0000156 void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error,
157 ExplodedNode *N, const MemRegion *Region,
158 CheckerContext &C,
159 const Stmt *ValueExpr = nullptr,
160 bool SuppressPath = false) const;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000161
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000162 void reportBug(StringRef Msg, ErrorKind Error, ExplodedNode *N,
163 const MemRegion *Region, BugReporter &BR,
164 const Stmt *ValueExpr = nullptr) const {
Gabor Horvath28690922015-08-26 23:17:43 +0000165 if (!BT)
Artem Dergachevb6a513d2017-05-03 11:47:13 +0000166 BT.reset(new BugType(this, "Nullability", categories::MemoryError));
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000167
168 auto R = llvm::make_unique<BugReport>(*BT, Msg, N);
Gabor Horvath28690922015-08-26 23:17:43 +0000169 if (Region) {
170 R->markInteresting(Region);
171 R->addVisitor(llvm::make_unique<NullabilityBugVisitor>(Region));
172 }
173 if (ValueExpr) {
174 R->addRange(ValueExpr->getSourceRange());
175 if (Error == ErrorKind::NilAssignedToNonnull ||
176 Error == ErrorKind::NilPassedToNonnull ||
177 Error == ErrorKind::NilReturnedToNonnull)
178 bugreporter::trackNullOrUndefValue(N, ValueExpr, *R);
179 }
180 BR.emitReport(std::move(R));
181 }
Gabor Horvath29307352015-09-14 18:31:34 +0000182
183 /// If an SVal wraps a region that should be tracked, it will return a pointer
184 /// to the wrapped region. Otherwise it will return a nullptr.
185 const SymbolicRegion *getTrackRegion(SVal Val,
186 bool CheckSuperRegion = false) const;
Devin Coughlina1d9d752016-03-05 01:32:43 +0000187
188 /// Returns true if the call is diagnosable in the currrent analyzer
189 /// configuration.
190 bool isDiagnosableCall(const CallEvent &Call) const {
191 if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
192 return false;
193
194 return true;
195 }
Gabor Horvath28690922015-08-26 23:17:43 +0000196};
197
198class NullabilityState {
199public:
200 NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
201 : Nullab(Nullab), Source(Source) {}
202
203 const Stmt *getNullabilitySource() const { return Source; }
204
205 Nullability getValue() const { return Nullab; }
206
207 void Profile(llvm::FoldingSetNodeID &ID) const {
208 ID.AddInteger(static_cast<char>(Nullab));
209 ID.AddPointer(Source);
210 }
211
212 void print(raw_ostream &Out) const {
213 Out << getNullabilityString(Nullab) << "\n";
214 }
215
216private:
217 Nullability Nullab;
218 // Source is the expression which determined the nullability. For example in a
219 // message like [nullable nonnull_returning] has nullable nullability, because
220 // the receiver is nullable. Here the receiver will be the source of the
221 // nullability. This is useful information when the diagnostics are generated.
222 const Stmt *Source;
223};
224
225bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
226 return Lhs.getValue() == Rhs.getValue() &&
227 Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
228}
229
230} // end anonymous namespace
231
232REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
233 NullabilityState)
234
Devin Coughlin77942db2016-03-28 20:30:25 +0000235// We say "the nullability type invariant is violated" when a location with a
236// non-null type contains NULL or a function with a non-null return type returns
237// NULL. Violations of the nullability type invariant can be detected either
238// directly (for example, when NULL is passed as an argument to a nonnull
239// parameter) or indirectly (for example, when, inside a function, the
240// programmer defensively checks whether a nonnull parameter contains NULL and
241// finds that it does).
242//
243// As a matter of policy, the nullability checker typically warns on direct
244// violations of the nullability invariant (although it uses various
245// heuristics to suppress warnings in some cases) but will not warn if the
246// invariant has already been violated along the path (either directly or
247// indirectly). As a practical matter, this prevents the analyzer from
248// (1) warning on defensive code paths where a nullability precondition is
249// determined to have been violated, (2) warning additional times after an
250// initial direct violation has been discovered, and (3) warning after a direct
251// violation that has been implicitly or explicitly suppressed (for
252// example, with a cast of NULL to _Nonnull). In essence, once an invariant
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000253// violation is detected on a path, this checker will be essentially turned off
Devin Coughlin77942db2016-03-28 20:30:25 +0000254// for the rest of the analysis
255//
256// The analyzer takes this approach (rather than generating a sink node) to
257// ensure coverage of defensive paths, which may be important for backwards
258// compatibility in codebases that were developed without nullability in mind.
259REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
Gabor Horvathb47128a2015-09-03 23:16:21 +0000260
Gabor Horvath28690922015-08-26 23:17:43 +0000261enum class NullConstraint { IsNull, IsNotNull, Unknown };
262
263static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
264 ProgramStateRef State) {
265 ConditionTruthVal Nullness = State->isNull(Val);
266 if (Nullness.isConstrainedFalse())
267 return NullConstraint::IsNotNull;
268 if (Nullness.isConstrainedTrue())
269 return NullConstraint::IsNull;
270 return NullConstraint::Unknown;
271}
272
Gabor Horvath29307352015-09-14 18:31:34 +0000273const SymbolicRegion *
274NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
275 if (!NeedTracking)
276 return nullptr;
277
Gabor Horvath28690922015-08-26 23:17:43 +0000278 auto RegionSVal = Val.getAs<loc::MemRegionVal>();
279 if (!RegionSVal)
280 return nullptr;
281
282 const MemRegion *Region = RegionSVal->getRegion();
283
284 if (CheckSuperRegion) {
285 if (auto FieldReg = Region->getAs<FieldRegion>())
286 return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
Gabor Horvath3943adb2015-09-11 16:29:05 +0000287 if (auto ElementReg = Region->getAs<ElementRegion>())
Gabor Horvath28690922015-08-26 23:17:43 +0000288 return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
289 }
290
291 return dyn_cast<SymbolicRegion>(Region);
292}
293
David Blaikie0a0c2752017-01-05 17:26:53 +0000294std::shared_ptr<PathDiagnosticPiece>
295NullabilityChecker::NullabilityBugVisitor::VisitNode(const ExplodedNode *N,
296 const ExplodedNode *PrevN,
297 BugReporterContext &BRC,
298 BugReport &BR) {
Gabor Horvath3943adb2015-09-11 16:29:05 +0000299 ProgramStateRef State = N->getState();
300 ProgramStateRef StatePrev = PrevN->getState();
Gabor Horvath28690922015-08-26 23:17:43 +0000301
Gabor Horvath3943adb2015-09-11 16:29:05 +0000302 const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
Gabor Horvath28690922015-08-26 23:17:43 +0000303 const NullabilityState *TrackedNullabPrev =
Gabor Horvath3943adb2015-09-11 16:29:05 +0000304 StatePrev->get<NullabilityMap>(Region);
Gabor Horvath28690922015-08-26 23:17:43 +0000305 if (!TrackedNullab)
306 return nullptr;
307
308 if (TrackedNullabPrev &&
309 TrackedNullabPrev->getValue() == TrackedNullab->getValue())
310 return nullptr;
311
312 // Retrieve the associated statement.
313 const Stmt *S = TrackedNullab->getNullabilitySource();
Artem Dergachevfbe891ee2017-06-05 12:40:03 +0000314 if (!S || S->getLocStart().isInvalid()) {
Gabor Horvath6ee4f902016-08-18 07:54:50 +0000315 S = PathDiagnosticLocation::getStmt(N);
Gabor Horvath28690922015-08-26 23:17:43 +0000316 }
317
318 if (!S)
319 return nullptr;
320
321 std::string InfoText =
322 (llvm::Twine("Nullability '") +
Devin Coughlinc894ac82016-12-07 17:36:27 +0000323 getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
Gabor Horvath28690922015-08-26 23:17:43 +0000324 .str();
325
326 // Generate the extra diagnostic.
327 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
328 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +0000329 return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true,
330 nullptr);
Gabor Horvath28690922015-08-26 23:17:43 +0000331}
332
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000333/// Returns true when the value stored at the given location is null
334/// and the passed in type is nonnnull.
335static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
336 SVal LV, QualType T) {
337 if (getNullabilityAnnotation(T) != Nullability::Nonnull)
338 return false;
339
340 auto RegionVal = LV.getAs<loc::MemRegionVal>();
341 if (!RegionVal)
342 return false;
343
344 auto StoredVal =
345 State->getSVal(RegionVal->getRegion()).getAs<DefinedOrUnknownSVal>();
346 if (!StoredVal)
347 return false;
348
349 if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
350 return true;
351
352 return false;
353}
354
Gabor Horvathb47128a2015-09-03 23:16:21 +0000355static bool
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000356checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
Gabor Horvathb47128a2015-09-03 23:16:21 +0000357 ProgramStateRef State,
358 const LocationContext *LocCtxt) {
359 for (const auto *ParamDecl : Params) {
360 if (ParamDecl->isParameterPack())
361 break;
362
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000363 SVal LV = State->getLValue(ParamDecl, LocCtxt);
364 if (checkValueAtLValForInvariantViolation(State, LV,
365 ParamDecl->getType())) {
366 return true;
367 }
368 }
369 return false;
370}
Gabor Horvathb47128a2015-09-03 23:16:21 +0000371
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000372static bool
373checkSelfIvarsForInvariantViolation(ProgramStateRef State,
374 const LocationContext *LocCtxt) {
375 auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
376 if (!MD || !MD->isInstanceMethod())
377 return false;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000378
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000379 const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
380 if (!SelfDecl)
381 return false;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000382
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000383 SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
384
385 const ObjCObjectPointerType *SelfType =
386 dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
387 if (!SelfType)
388 return false;
389
390 const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
391 if (!ID)
392 return false;
393
394 for (const auto *IvarDecl : ID->ivars()) {
395 SVal LV = State->getLValue(IvarDecl, SelfVal);
396 if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
Gabor Horvathb47128a2015-09-03 23:16:21 +0000397 return true;
398 }
399 }
400 return false;
401}
402
Devin Coughlin77942db2016-03-28 20:30:25 +0000403static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
404 CheckerContext &C) {
405 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000406 return true;
407
408 const LocationContext *LocCtxt = C.getLocationContext();
409 const Decl *D = LocCtxt->getDecl();
410 if (!D)
411 return false;
412
Devin Coughlin851da712016-01-15 21:35:40 +0000413 ArrayRef<ParmVarDecl*> Params;
414 if (const auto *BD = dyn_cast<BlockDecl>(D))
415 Params = BD->parameters();
416 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
417 Params = FD->parameters();
418 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
419 Params = MD->parameters();
420 else
Gabor Horvathb47128a2015-09-03 23:16:21 +0000421 return false;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000422
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000423 if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
424 checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
Devin Coughlin851da712016-01-15 21:35:40 +0000425 if (!N->isSink())
Devin Coughlin77942db2016-03-28 20:30:25 +0000426 C.addTransition(State->set<InvariantViolated>(true), N);
Devin Coughlin851da712016-01-15 21:35:40 +0000427 return true;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000428 }
429 return false;
430}
431
Devin Coughlin77942db2016-03-28 20:30:25 +0000432void NullabilityChecker::reportBugIfInvariantHolds(StringRef Msg,
Gabor Horvathb47128a2015-09-03 23:16:21 +0000433 ErrorKind Error, ExplodedNode *N, const MemRegion *Region,
434 CheckerContext &C, const Stmt *ValueExpr, bool SuppressPath) const {
435 ProgramStateRef OriginalState = N->getState();
436
Devin Coughlin77942db2016-03-28 20:30:25 +0000437 if (checkInvariantViolation(OriginalState, N, C))
Gabor Horvathb47128a2015-09-03 23:16:21 +0000438 return;
439 if (SuppressPath) {
Devin Coughlin77942db2016-03-28 20:30:25 +0000440 OriginalState = OriginalState->set<InvariantViolated>(true);
Gabor Horvathb47128a2015-09-03 23:16:21 +0000441 N = C.addTransition(OriginalState, N);
442 }
443
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000444 reportBug(Msg, Error, N, Region, C.getBugReporter(), ValueExpr);
Gabor Horvathb47128a2015-09-03 23:16:21 +0000445}
446
Gabor Horvath28690922015-08-26 23:17:43 +0000447/// Cleaning up the program state.
448void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
449 CheckerContext &C) const {
Gabor Horvathbe87d5b2015-09-14 20:31:46 +0000450 if (!SR.hasDeadSymbols())
451 return;
452
Gabor Horvath28690922015-08-26 23:17:43 +0000453 ProgramStateRef State = C.getState();
454 NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
455 for (NullabilityMapTy::iterator I = Nullabilities.begin(),
456 E = Nullabilities.end();
457 I != E; ++I) {
Gabor Horvathbe87d5b2015-09-14 20:31:46 +0000458 const auto *Region = I->first->getAs<SymbolicRegion>();
459 assert(Region && "Non-symbolic region is tracked.");
460 if (SR.isDead(Region->getSymbol())) {
Gabor Horvath28690922015-08-26 23:17:43 +0000461 State = State->remove<NullabilityMap>(I->first);
462 }
463 }
Gabor Horvathb47128a2015-09-03 23:16:21 +0000464 // When one of the nonnull arguments are constrained to be null, nullability
465 // preconditions are violated. It is not enough to check this only when we
466 // actually report an error, because at that time interesting symbols might be
467 // reaped.
Devin Coughlin77942db2016-03-28 20:30:25 +0000468 if (checkInvariantViolation(State, C.getPredecessor(), C))
Gabor Horvathb47128a2015-09-03 23:16:21 +0000469 return;
470 C.addTransition(State);
Gabor Horvath28690922015-08-26 23:17:43 +0000471}
472
473/// This callback triggers when a pointer is dereferenced and the analyzer does
474/// not know anything about the value of that pointer. When that pointer is
475/// nullable, this code emits a warning.
476void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
Devin Coughlin77942db2016-03-28 20:30:25 +0000477 if (Event.SinkNode->getState()->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000478 return;
479
Gabor Horvath28690922015-08-26 23:17:43 +0000480 const MemRegion *Region =
481 getTrackRegion(Event.Location, /*CheckSuperregion=*/true);
482 if (!Region)
483 return;
484
485 ProgramStateRef State = Event.SinkNode->getState();
486 const NullabilityState *TrackedNullability =
487 State->get<NullabilityMap>(Region);
488
489 if (!TrackedNullability)
490 return;
491
492 if (Filter.CheckNullableDereferenced &&
493 TrackedNullability->getValue() == Nullability::Nullable) {
494 BugReporter &BR = *Event.BR;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000495 // Do not suppress errors on defensive code paths, because dereferencing
496 // a nullable pointer is always an error.
Gabor Horvath8d3ad6b2015-08-27 18:49:07 +0000497 if (Event.IsDirectDereference)
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000498 reportBug("Nullable pointer is dereferenced",
499 ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR);
500 else {
501 reportBug("Nullable pointer is passed to a callee that requires a "
502 "non-null", ErrorKind::NullablePassedToNonnull,
503 Event.SinkNode, Region, BR);
504 }
Gabor Horvath28690922015-08-26 23:17:43 +0000505 }
506}
507
Devin Coughlin5a3843e2016-01-18 18:53:33 +0000508/// Find the outermost subexpression of E that is not an implicit cast.
509/// This looks through the implicit casts to _Nonnull that ARC adds to
510/// return expressions of ObjC types when the return type of the function or
511/// method is non-null but the express is not.
512static const Expr *lookThroughImplicitCasts(const Expr *E) {
513 assert(E);
514
515 while (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
516 E = ICE->getSubExpr();
517 }
518
519 return E;
520}
521
Gabor Horvath28690922015-08-26 23:17:43 +0000522/// This method check when nullable pointer or null value is returned from a
523/// function that has nonnull return type.
Gabor Horvath28690922015-08-26 23:17:43 +0000524void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
525 CheckerContext &C) const {
526 auto RetExpr = S->getRetValue();
527 if (!RetExpr)
528 return;
529
530 if (!RetExpr->getType()->isAnyPointerType())
531 return;
532
533 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000534 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000535 return;
536
George Karpenkovd703ec92018-01-17 20:27:29 +0000537 auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
Gabor Horvath28690922015-08-26 23:17:43 +0000538 if (!RetSVal)
539 return;
540
Devin Coughlinde217672016-01-28 22:23:34 +0000541 bool InSuppressedMethodFamily = false;
Devin Coughlin4a330202016-01-22 01:01:11 +0000542
Devin Coughlin851da712016-01-15 21:35:40 +0000543 QualType RequiredRetType;
Gabor Horvath28690922015-08-26 23:17:43 +0000544 AnalysisDeclContext *DeclCtxt =
545 C.getLocationContext()->getAnalysisDeclContext();
Devin Coughlin851da712016-01-15 21:35:40 +0000546 const Decl *D = DeclCtxt->getDecl();
Devin Coughlin4a330202016-01-22 01:01:11 +0000547 if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Devin Coughlinde217672016-01-28 22:23:34 +0000548 // HACK: This is a big hammer to avoid warning when there are defensive
549 // nil checks in -init and -copy methods. We should add more sophisticated
550 // logic here to suppress on common defensive idioms but still
551 // warn when there is a likely problem.
552 ObjCMethodFamily Family = MD->getMethodFamily();
553 if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
554 InSuppressedMethodFamily = true;
555
Devin Coughlin851da712016-01-15 21:35:40 +0000556 RequiredRetType = MD->getReturnType();
Devin Coughlin4a330202016-01-22 01:01:11 +0000557 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Devin Coughlin851da712016-01-15 21:35:40 +0000558 RequiredRetType = FD->getReturnType();
Devin Coughlin4a330202016-01-22 01:01:11 +0000559 } else {
Gabor Horvath28690922015-08-26 23:17:43 +0000560 return;
Devin Coughlin4a330202016-01-22 01:01:11 +0000561 }
Gabor Horvath28690922015-08-26 23:17:43 +0000562
563 NullConstraint Nullness = getNullConstraint(*RetSVal, State);
564
Devin Coughlin851da712016-01-15 21:35:40 +0000565 Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
Gabor Horvath28690922015-08-26 23:17:43 +0000566
Devin Coughlin755baa42015-12-29 17:40:49 +0000567 // If the returned value is null but the type of the expression
568 // generating it is nonnull then we will suppress the diagnostic.
569 // This enables explicit suppression when returning a nil literal in a
570 // function with a _Nonnull return type:
571 // return (NSString * _Nonnull)0;
572 Nullability RetExprTypeLevelNullability =
Devin Coughlin5a3843e2016-01-18 18:53:33 +0000573 getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
Devin Coughlin755baa42015-12-29 17:40:49 +0000574
Devin Coughlin77942db2016-03-28 20:30:25 +0000575 bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
576 Nullness == NullConstraint::IsNull);
Gabor Horvath28690922015-08-26 23:17:43 +0000577 if (Filter.CheckNullReturnedFromNonnull &&
Devin Coughlin77942db2016-03-28 20:30:25 +0000578 NullReturnedFromNonNull &&
Devin Coughlin755baa42015-12-29 17:40:49 +0000579 RetExprTypeLevelNullability != Nullability::Nonnull &&
Devin Coughlin49bd58f2016-04-12 19:29:52 +0000580 !InSuppressedMethodFamily &&
581 C.getLocationContext()->inTopFrame()) {
Gabor Horvath28690922015-08-26 23:17:43 +0000582 static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
Devin Coughline39bd402015-09-16 22:03:05 +0000583 ExplodedNode *N = C.generateErrorNode(State, &Tag);
584 if (!N)
585 return;
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000586
587 SmallString<256> SBuf;
588 llvm::raw_svector_ostream OS(SBuf);
Anna Zaks6d4e76b2016-12-15 22:55:15 +0000589 OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
590 OS << " returned from a " << C.getDeclDescription(D) <<
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000591 " that is expected to return a non-null value";
Devin Coughlin77942db2016-03-28 20:30:25 +0000592 reportBugIfInvariantHolds(OS.str(),
593 ErrorKind::NilReturnedToNonnull, N, nullptr, C,
594 RetExpr);
595 return;
596 }
597
598 // If null was returned from a non-null function, mark the nullability
599 // invariant as violated even if the diagnostic was suppressed.
600 if (NullReturnedFromNonNull) {
601 State = State->set<InvariantViolated>(true);
602 C.addTransition(State);
Gabor Horvath28690922015-08-26 23:17:43 +0000603 return;
604 }
605
606 const MemRegion *Region = getTrackRegion(*RetSVal);
607 if (!Region)
608 return;
609
610 const NullabilityState *TrackedNullability =
611 State->get<NullabilityMap>(Region);
612 if (TrackedNullability) {
613 Nullability TrackedNullabValue = TrackedNullability->getValue();
614 if (Filter.CheckNullableReturnedFromNonnull &&
615 Nullness != NullConstraint::IsNotNull &&
616 TrackedNullabValue == Nullability::Nullable &&
Devin Coughlin755baa42015-12-29 17:40:49 +0000617 RequiredNullability == Nullability::Nonnull) {
Gabor Horvath28690922015-08-26 23:17:43 +0000618 static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
619 ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000620
621 SmallString<256> SBuf;
622 llvm::raw_svector_ostream OS(SBuf);
623 OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
624 " that is expected to return a non-null value";
625
Devin Coughlin77942db2016-03-28 20:30:25 +0000626 reportBugIfInvariantHolds(OS.str(),
627 ErrorKind::NullableReturnedToNonnull, N,
628 Region, C);
Gabor Horvath28690922015-08-26 23:17:43 +0000629 }
630 return;
631 }
Devin Coughlin755baa42015-12-29 17:40:49 +0000632 if (RequiredNullability == Nullability::Nullable) {
Gabor Horvath28690922015-08-26 23:17:43 +0000633 State = State->set<NullabilityMap>(Region,
Devin Coughlin755baa42015-12-29 17:40:49 +0000634 NullabilityState(RequiredNullability,
635 S));
Gabor Horvath28690922015-08-26 23:17:43 +0000636 C.addTransition(State);
637 }
638}
639
640/// This callback warns when a nullable pointer or a null value is passed to a
641/// function that expects its argument to be nonnull.
642void NullabilityChecker::checkPreCall(const CallEvent &Call,
643 CheckerContext &C) const {
644 if (!Call.getDecl())
645 return;
646
647 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000648 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000649 return;
650
Gabor Horvath28690922015-08-26 23:17:43 +0000651 ProgramStateRef OrigState = State;
652
653 unsigned Idx = 0;
654 for (const ParmVarDecl *Param : Call.parameters()) {
655 if (Param->isParameterPack())
656 break;
657
Devin Coughline4224cc2016-11-14 22:46:02 +0000658 if (Idx >= Call.getNumArgs())
659 break;
660
661 const Expr *ArgExpr = Call.getArgExpr(Idx);
Gabor Horvath28690922015-08-26 23:17:43 +0000662 auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
663 if (!ArgSVal)
664 continue;
665
666 if (!Param->getType()->isAnyPointerType() &&
667 !Param->getType()->isReferenceType())
668 continue;
669
670 NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
671
Devin Coughlin755baa42015-12-29 17:40:49 +0000672 Nullability RequiredNullability =
673 getNullabilityAnnotation(Param->getType());
674 Nullability ArgExprTypeLevelNullability =
Gabor Horvath28690922015-08-26 23:17:43 +0000675 getNullabilityAnnotation(ArgExpr->getType());
676
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000677 unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
678
Gabor Horvath28690922015-08-26 23:17:43 +0000679 if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull &&
Devin Coughlin755baa42015-12-29 17:40:49 +0000680 ArgExprTypeLevelNullability != Nullability::Nonnull &&
Devin Coughlina1d9d752016-03-05 01:32:43 +0000681 RequiredNullability == Nullability::Nonnull &&
682 isDiagnosableCall(Call)) {
Devin Coughline39bd402015-09-16 22:03:05 +0000683 ExplodedNode *N = C.generateErrorNode(State);
684 if (!N)
685 return;
Anna Zaks6d4e76b2016-12-15 22:55:15 +0000686
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000687 SmallString<256> SBuf;
688 llvm::raw_svector_ostream OS(SBuf);
Anna Zaks6d4e76b2016-12-15 22:55:15 +0000689 OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
690 OS << " passed to a callee that requires a non-null " << ParamIdx
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000691 << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
Devin Coughlin77942db2016-03-28 20:30:25 +0000692 reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull, N,
693 nullptr, C,
694 ArgExpr, /*SuppressPath=*/false);
Gabor Horvath28690922015-08-26 23:17:43 +0000695 return;
696 }
697
698 const MemRegion *Region = getTrackRegion(*ArgSVal);
699 if (!Region)
700 continue;
701
702 const NullabilityState *TrackedNullability =
703 State->get<NullabilityMap>(Region);
704
705 if (TrackedNullability) {
706 if (Nullness == NullConstraint::IsNotNull ||
707 TrackedNullability->getValue() != Nullability::Nullable)
708 continue;
709
710 if (Filter.CheckNullablePassedToNonnull &&
Devin Coughlina1d9d752016-03-05 01:32:43 +0000711 RequiredNullability == Nullability::Nonnull &&
712 isDiagnosableCall(Call)) {
Gabor Horvathb47128a2015-09-03 23:16:21 +0000713 ExplodedNode *N = C.addTransition(State);
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000714 SmallString<256> SBuf;
715 llvm::raw_svector_ostream OS(SBuf);
716 OS << "Nullable pointer is passed to a callee that requires a non-null "
717 << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
Devin Coughlin77942db2016-03-28 20:30:25 +0000718 reportBugIfInvariantHolds(OS.str(),
719 ErrorKind::NullablePassedToNonnull, N,
720 Region, C, ArgExpr, /*SuppressPath=*/true);
Gabor Horvath28690922015-08-26 23:17:43 +0000721 return;
722 }
723 if (Filter.CheckNullableDereferenced &&
724 Param->getType()->isReferenceType()) {
Gabor Horvathb47128a2015-09-03 23:16:21 +0000725 ExplodedNode *N = C.addTransition(State);
Devin Coughlin77942db2016-03-28 20:30:25 +0000726 reportBugIfInvariantHolds("Nullable pointer is dereferenced",
727 ErrorKind::NullableDereferenced, N, Region,
728 C, ArgExpr, /*SuppressPath=*/true);
Gabor Horvath28690922015-08-26 23:17:43 +0000729 return;
730 }
731 continue;
732 }
733 // No tracked nullability yet.
Devin Coughlin755baa42015-12-29 17:40:49 +0000734 if (ArgExprTypeLevelNullability != Nullability::Nullable)
Gabor Horvath28690922015-08-26 23:17:43 +0000735 continue;
736 State = State->set<NullabilityMap>(
Devin Coughlin755baa42015-12-29 17:40:49 +0000737 Region, NullabilityState(ArgExprTypeLevelNullability, ArgExpr));
Gabor Horvath28690922015-08-26 23:17:43 +0000738 }
739 if (State != OrigState)
740 C.addTransition(State);
741}
742
743/// Suppress the nullability warnings for some functions.
744void NullabilityChecker::checkPostCall(const CallEvent &Call,
745 CheckerContext &C) const {
746 auto Decl = Call.getDecl();
747 if (!Decl)
748 return;
749 // ObjC Messages handles in a different callback.
750 if (Call.getKind() == CE_ObjCMessage)
751 return;
752 const FunctionType *FuncType = Decl->getFunctionType();
753 if (!FuncType)
754 return;
755 QualType ReturnType = FuncType->getReturnType();
756 if (!ReturnType->isAnyPointerType())
757 return;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000758 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000759 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000760 return;
761
Gabor Horvath28690922015-08-26 23:17:43 +0000762 const MemRegion *Region = getTrackRegion(Call.getReturnValue());
763 if (!Region)
764 return;
Gabor Horvath28690922015-08-26 23:17:43 +0000765
766 // CG headers are misannotated. Do not warn for symbols that are the results
767 // of CG calls.
768 const SourceManager &SM = C.getSourceManager();
769 StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getLocStart()));
770 if (llvm::sys::path::filename(FilePath).startswith("CG")) {
771 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
772 C.addTransition(State);
773 return;
774 }
775
776 const NullabilityState *TrackedNullability =
777 State->get<NullabilityMap>(Region);
778
779 if (!TrackedNullability &&
780 getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
781 State = State->set<NullabilityMap>(Region, Nullability::Nullable);
782 C.addTransition(State);
783 }
784}
785
786static Nullability getReceiverNullability(const ObjCMethodCall &M,
787 ProgramStateRef State) {
Gabor Horvath28690922015-08-26 23:17:43 +0000788 if (M.isReceiverSelfOrSuper()) {
789 // For super and super class receivers we assume that the receiver is
790 // nonnull.
Gabor Horvath3943adb2015-09-11 16:29:05 +0000791 return Nullability::Nonnull;
Gabor Horvath28690922015-08-26 23:17:43 +0000792 }
Gabor Horvath3943adb2015-09-11 16:29:05 +0000793 // Otherwise look up nullability in the state.
794 SVal Receiver = M.getReceiverSVal();
795 if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
796 // If the receiver is constrained to be nonnull, assume that it is nonnull
797 // regardless of its type.
798 NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
799 if (Nullness == NullConstraint::IsNotNull)
800 return Nullability::Nonnull;
801 }
802 auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
803 if (ValueRegionSVal) {
804 const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
805 assert(SelfRegion);
806
807 const NullabilityState *TrackedSelfNullability =
808 State->get<NullabilityMap>(SelfRegion);
809 if (TrackedSelfNullability)
810 return TrackedSelfNullability->getValue();
811 }
812 return Nullability::Unspecified;
Gabor Horvath28690922015-08-26 23:17:43 +0000813}
814
815/// Calculate the nullability of the result of a message expr based on the
816/// nullability of the receiver, the nullability of the return value, and the
817/// constraints.
818void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
819 CheckerContext &C) const {
820 auto Decl = M.getDecl();
821 if (!Decl)
822 return;
823 QualType RetType = Decl->getReturnType();
824 if (!RetType->isAnyPointerType())
825 return;
826
Gabor Horvathb47128a2015-09-03 23:16:21 +0000827 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000828 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000829 return;
830
Gabor Horvath28690922015-08-26 23:17:43 +0000831 const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
832 if (!ReturnRegion)
833 return;
834
Gabor Horvath28690922015-08-26 23:17:43 +0000835 auto Interface = Decl->getClassInterface();
836 auto Name = Interface ? Interface->getName() : "";
837 // In order to reduce the noise in the diagnostics generated by this checker,
838 // some framework and programming style based heuristics are used. These
839 // heuristics are for Cocoa APIs which have NS prefix.
840 if (Name.startswith("NS")) {
841 // Developers rely on dynamic invariants such as an item should be available
842 // in a collection, or a collection is not empty often. Those invariants can
843 // not be inferred by any static analysis tool. To not to bother the users
844 // with too many false positives, every item retrieval function should be
845 // ignored for collections. The instance methods of dictionaries in Cocoa
846 // are either item retrieval related or not interesting nullability wise.
847 // Using this fact, to keep the code easier to read just ignore the return
848 // value of every instance method of dictionaries.
George Karpenkov2301c5a2018-03-23 00:16:03 +0000849 if (M.isInstanceMessage() && Name.contains("Dictionary")) {
Gabor Horvath28690922015-08-26 23:17:43 +0000850 State =
851 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
852 C.addTransition(State);
853 return;
854 }
855 // For similar reasons ignore some methods of Cocoa arrays.
856 StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
George Karpenkov2301c5a2018-03-23 00:16:03 +0000857 if (Name.contains("Array") &&
Gabor Horvath28690922015-08-26 23:17:43 +0000858 (FirstSelectorSlot == "firstObject" ||
859 FirstSelectorSlot == "lastObject")) {
860 State =
861 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
862 C.addTransition(State);
863 return;
864 }
865
866 // Encoding related methods of string should not fail when lossless
867 // encodings are used. Using lossless encodings is so frequent that ignoring
868 // this class of methods reduced the emitted diagnostics by about 30% on
869 // some projects (and all of that was false positives).
George Karpenkov2301c5a2018-03-23 00:16:03 +0000870 if (Name.contains("String")) {
Gabor Horvath28690922015-08-26 23:17:43 +0000871 for (auto Param : M.parameters()) {
872 if (Param->getName() == "encoding") {
873 State = State->set<NullabilityMap>(ReturnRegion,
874 Nullability::Contradicted);
875 C.addTransition(State);
876 return;
877 }
878 }
879 }
880 }
881
882 const ObjCMessageExpr *Message = M.getOriginExpr();
883 Nullability SelfNullability = getReceiverNullability(M, State);
884
885 const NullabilityState *NullabilityOfReturn =
886 State->get<NullabilityMap>(ReturnRegion);
887
888 if (NullabilityOfReturn) {
889 // When we have a nullability tracked for the return value, the nullability
890 // of the expression will be the most nullable of the receiver and the
891 // return value.
892 Nullability RetValTracked = NullabilityOfReturn->getValue();
893 Nullability ComputedNullab =
894 getMostNullable(RetValTracked, SelfNullability);
895 if (ComputedNullab != RetValTracked &&
896 ComputedNullab != Nullability::Unspecified) {
897 const Stmt *NullabilitySource =
898 ComputedNullab == RetValTracked
899 ? NullabilityOfReturn->getNullabilitySource()
900 : Message->getInstanceReceiver();
901 State = State->set<NullabilityMap>(
902 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
903 C.addTransition(State);
904 }
905 return;
906 }
907
908 // No tracked information. Use static type information for return value.
909 Nullability RetNullability = getNullabilityAnnotation(RetType);
910
911 // Properties might be computed. For this reason the static analyzer creates a
912 // new symbol each time an unknown property is read. To avoid false pozitives
913 // do not treat unknown properties as nullable, even when they explicitly
914 // marked nullable.
915 if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
916 RetNullability = Nullability::Nonnull;
917
918 Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
919 if (ComputedNullab == Nullability::Nullable) {
920 const Stmt *NullabilitySource = ComputedNullab == RetNullability
921 ? Message
922 : Message->getInstanceReceiver();
923 State = State->set<NullabilityMap>(
924 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
925 C.addTransition(State);
926 }
927}
928
929/// Explicit casts are trusted. If there is a disagreement in the nullability
930/// annotations in the destination and the source or '0' is casted to nonnull
931/// track the value as having contraditory nullability. This will allow users to
932/// suppress warnings.
933void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
934 CheckerContext &C) const {
935 QualType OriginType = CE->getSubExpr()->getType();
936 QualType DestType = CE->getType();
937 if (!OriginType->isAnyPointerType())
938 return;
939 if (!DestType->isAnyPointerType())
940 return;
941
Gabor Horvathb47128a2015-09-03 23:16:21 +0000942 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000943 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000944 return;
945
Gabor Horvath28690922015-08-26 23:17:43 +0000946 Nullability DestNullability = getNullabilityAnnotation(DestType);
947
948 // No explicit nullability in the destination type, so this cast does not
949 // change the nullability.
950 if (DestNullability == Nullability::Unspecified)
951 return;
952
George Karpenkovd703ec92018-01-17 20:27:29 +0000953 auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
Gabor Horvath28690922015-08-26 23:17:43 +0000954 const MemRegion *Region = getTrackRegion(*RegionSVal);
955 if (!Region)
956 return;
957
958 // When 0 is converted to nonnull mark it as contradicted.
959 if (DestNullability == Nullability::Nonnull) {
960 NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
961 if (Nullness == NullConstraint::IsNull) {
962 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
963 C.addTransition(State);
964 return;
965 }
966 }
967
968 const NullabilityState *TrackedNullability =
969 State->get<NullabilityMap>(Region);
970
971 if (!TrackedNullability) {
972 if (DestNullability != Nullability::Nullable)
973 return;
974 State = State->set<NullabilityMap>(Region,
975 NullabilityState(DestNullability, CE));
976 C.addTransition(State);
977 return;
978 }
979
980 if (TrackedNullability->getValue() != DestNullability &&
981 TrackedNullability->getValue() != Nullability::Contradicted) {
982 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
983 C.addTransition(State);
984 }
985}
986
Devin Coughlinc1986632015-11-24 19:15:11 +0000987/// For a given statement performing a bind, attempt to syntactically
988/// match the expression resulting in the bound value.
989static const Expr * matchValueExprForBind(const Stmt *S) {
990 // For `x = e` the value expression is the right-hand side.
991 if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
992 if (BinOp->getOpcode() == BO_Assign)
993 return BinOp->getRHS();
994 }
995
996 // For `int x = e` the value expression is the initializer.
997 if (auto *DS = dyn_cast<DeclStmt>(S)) {
998 if (DS->isSingleDecl()) {
999 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1000 if (!VD)
1001 return nullptr;
1002
1003 if (const Expr *Init = VD->getInit())
1004 return Init;
1005 }
1006 }
1007
1008 return nullptr;
1009}
1010
Devin Coughlin3ab8b2e72015-12-29 23:44:19 +00001011/// Returns true if \param S is a DeclStmt for a local variable that
1012/// ObjC automated reference counting initialized with zero.
1013static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
1014 // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
1015 // prevents false positives when a _Nonnull local variable cannot be
1016 // initialized with an initialization expression:
1017 // NSString * _Nonnull s; // no-warning
1018 // @autoreleasepool {
1019 // s = ...
1020 // }
1021 //
1022 // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
1023 // uninitialized in Sema's UninitializedValues analysis to warn when a use of
1024 // the zero-initialized definition will unexpectedly yield nil.
1025
1026 // Locals are only zero-initialized when automated reference counting
1027 // is turned on.
1028 if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
1029 return false;
1030
1031 auto *DS = dyn_cast<DeclStmt>(S);
1032 if (!DS || !DS->isSingleDecl())
1033 return false;
1034
1035 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1036 if (!VD)
1037 return false;
1038
1039 // Sema only zero-initializes locals with ObjCLifetimes.
1040 if(!VD->getType().getQualifiers().hasObjCLifetime())
1041 return false;
1042
1043 const Expr *Init = VD->getInit();
1044 assert(Init && "ObjC local under ARC without initializer");
1045
1046 // Return false if the local is explicitly initialized (e.g., with '= nil').
1047 if (!isa<ImplicitValueInitExpr>(Init))
1048 return false;
1049
1050 return true;
1051}
1052
Gabor Horvath28690922015-08-26 23:17:43 +00001053/// Propagate the nullability information through binds and warn when nullable
1054/// pointer or null symbol is assigned to a pointer with a nonnull type.
1055void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
1056 CheckerContext &C) const {
1057 const TypedValueRegion *TVR =
1058 dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
1059 if (!TVR)
1060 return;
1061
1062 QualType LocType = TVR->getValueType();
1063 if (!LocType->isAnyPointerType())
1064 return;
1065
Gabor Horvathb47128a2015-09-03 23:16:21 +00001066 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +00001067 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +00001068 return;
1069
Gabor Horvath28690922015-08-26 23:17:43 +00001070 auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
1071 if (!ValDefOrUnknown)
1072 return;
1073
Gabor Horvath28690922015-08-26 23:17:43 +00001074 NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
1075
1076 Nullability ValNullability = Nullability::Unspecified;
1077 if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
1078 ValNullability = getNullabilityAnnotation(Sym->getType());
1079
1080 Nullability LocNullability = getNullabilityAnnotation(LocType);
Devin Coughlin4ac12422016-04-13 17:59:24 +00001081
1082 // If the type of the RHS expression is nonnull, don't warn. This
1083 // enables explicit suppression with a cast to nonnull.
1084 Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
1085 const Expr *ValueExpr = matchValueExprForBind(S);
1086 if (ValueExpr) {
1087 ValueExprTypeLevelNullability =
1088 getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
1089 }
1090
1091 bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
1092 RhsNullness == NullConstraint::IsNull);
Gabor Horvath28690922015-08-26 23:17:43 +00001093 if (Filter.CheckNullPassedToNonnull &&
Devin Coughlin4ac12422016-04-13 17:59:24 +00001094 NullAssignedToNonNull &&
Gabor Horvath28690922015-08-26 23:17:43 +00001095 ValNullability != Nullability::Nonnull &&
Devin Coughlin4ac12422016-04-13 17:59:24 +00001096 ValueExprTypeLevelNullability != Nullability::Nonnull &&
Devin Coughlin3ab8b2e72015-12-29 23:44:19 +00001097 !isARCNilInitializedLocal(C, S)) {
Gabor Horvath28690922015-08-26 23:17:43 +00001098 static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
Devin Coughline39bd402015-09-16 22:03:05 +00001099 ExplodedNode *N = C.generateErrorNode(State, &Tag);
1100 if (!N)
1101 return;
Devin Coughlinc1986632015-11-24 19:15:11 +00001102
Devin Coughlin4ac12422016-04-13 17:59:24 +00001103
1104 const Stmt *ValueStmt = S;
1105 if (ValueExpr)
1106 ValueStmt = ValueExpr;
Devin Coughlinc1986632015-11-24 19:15:11 +00001107
Anna Zaks6d4e76b2016-12-15 22:55:15 +00001108 SmallString<256> SBuf;
1109 llvm::raw_svector_ostream OS(SBuf);
1110 OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
1111 OS << " assigned to a pointer which is expected to have non-null value";
1112 reportBugIfInvariantHolds(OS.str(),
Devin Coughlin77942db2016-03-28 20:30:25 +00001113 ErrorKind::NilAssignedToNonnull, N, nullptr, C,
Devin Coughlin4ac12422016-04-13 17:59:24 +00001114 ValueStmt);
Gabor Horvath28690922015-08-26 23:17:43 +00001115 return;
1116 }
Devin Coughlin4ac12422016-04-13 17:59:24 +00001117
1118 // If null was returned from a non-null function, mark the nullability
1119 // invariant as violated even if the diagnostic was suppressed.
1120 if (NullAssignedToNonNull) {
1121 State = State->set<InvariantViolated>(true);
1122 C.addTransition(State);
1123 return;
1124 }
1125
Gabor Horvath28690922015-08-26 23:17:43 +00001126 // Intentionally missing case: '0' is bound to a reference. It is handled by
1127 // the DereferenceChecker.
1128
1129 const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
1130 if (!ValueRegion)
1131 return;
1132
1133 const NullabilityState *TrackedNullability =
1134 State->get<NullabilityMap>(ValueRegion);
1135
1136 if (TrackedNullability) {
1137 if (RhsNullness == NullConstraint::IsNotNull ||
1138 TrackedNullability->getValue() != Nullability::Nullable)
1139 return;
1140 if (Filter.CheckNullablePassedToNonnull &&
1141 LocNullability == Nullability::Nonnull) {
1142 static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
1143 ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
Devin Coughlin77942db2016-03-28 20:30:25 +00001144 reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
1145 "which is expected to have non-null value",
1146 ErrorKind::NullableAssignedToNonnull, N,
1147 ValueRegion, C);
Gabor Horvath28690922015-08-26 23:17:43 +00001148 }
1149 return;
1150 }
1151
1152 const auto *BinOp = dyn_cast<BinaryOperator>(S);
1153
1154 if (ValNullability == Nullability::Nullable) {
1155 // Trust the static information of the value more than the static
1156 // information on the location.
1157 const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
1158 State = State->set<NullabilityMap>(
1159 ValueRegion, NullabilityState(ValNullability, NullabilitySource));
1160 C.addTransition(State);
1161 return;
1162 }
1163
1164 if (LocNullability == Nullability::Nullable) {
1165 const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
1166 State = State->set<NullabilityMap>(
1167 ValueRegion, NullabilityState(LocNullability, NullabilitySource));
1168 C.addTransition(State);
1169 }
1170}
1171
1172void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
1173 const char *NL, const char *Sep) const {
1174
1175 NullabilityMapTy B = State->get<NullabilityMap>();
1176
1177 if (B.isEmpty())
1178 return;
1179
1180 Out << Sep << NL;
1181
1182 for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1183 Out << I->first << " : ";
1184 I->second.print(Out);
1185 Out << NL;
1186 }
1187}
1188
Gabor Horvath29307352015-09-14 18:31:34 +00001189#define REGISTER_CHECKER(name, trackingRequired) \
Gabor Horvath28690922015-08-26 23:17:43 +00001190 void ento::register##name##Checker(CheckerManager &mgr) { \
1191 NullabilityChecker *checker = mgr.registerChecker<NullabilityChecker>(); \
1192 checker->Filter.Check##name = true; \
1193 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
Gabor Horvath29307352015-09-14 18:31:34 +00001194 checker->NeedTracking = checker->NeedTracking || trackingRequired; \
Devin Coughlina1d9d752016-03-05 01:32:43 +00001195 checker->NoDiagnoseCallsToSystemHeaders = \
1196 checker->NoDiagnoseCallsToSystemHeaders || \
1197 mgr.getAnalyzerOptions().getBooleanOption( \
1198 "NoDiagnoseCallsToSystemHeaders", false, checker, true); \
Gabor Horvath28690922015-08-26 23:17:43 +00001199 }
1200
Gabor Horvath29307352015-09-14 18:31:34 +00001201// The checks are likely to be turned on by default and it is possible to do
1202// them without tracking any nullability related information. As an optimization
1203// no nullability information will be tracked when only these two checks are
1204// enables.
1205REGISTER_CHECKER(NullPassedToNonnull, false)
1206REGISTER_CHECKER(NullReturnedFromNonnull, false)
1207
1208REGISTER_CHECKER(NullableDereferenced, true)
1209REGISTER_CHECKER(NullablePassedToNonnull, true)
1210REGISTER_CHECKER(NullableReturnedFromNonnull, true)