blob: d642356cb40a050c2e76649efa23bd3638fb4462 [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"
33#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
35
Anna Zaksad9e7ea2016-01-29 18:43:15 +000036#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/Path.h"
38
Gabor Horvath28690922015-08-26 23:17:43 +000039using namespace clang;
40using namespace ento;
41
42namespace {
43// Do not reorder! The getMostNullable method relies on the order.
44// Optimization: Most pointers expected to be unspecified. When a symbol has an
45// unspecified or nonnull type non of the rules would indicate any problem for
46// that symbol. For this reason only nullable and contradicted nullability are
47// stored for a symbol. When a symbol is already contradicted, it can not be
48// casted back to nullable.
49enum class Nullability : char {
50 Contradicted, // Tracked nullability is contradicted by an explicit cast. Do
51 // not report any nullability related issue for this symbol.
52 // This nullability is propagated agressively to avoid false
53 // positive results. See the comment on getMostNullable method.
54 Nullable,
55 Unspecified,
56 Nonnull
57};
58
59/// Returns the most nullable nullability. This is used for message expressions
60/// like [reciever method], where the nullability of this expression is either
61/// the nullability of the receiver or the nullability of the return type of the
62/// method, depending on which is more nullable. Contradicted is considered to
63/// be the most nullable, to avoid false positive results.
Gabor Horvath3943adb2015-09-11 16:29:05 +000064Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
Gabor Horvath28690922015-08-26 23:17:43 +000065 return static_cast<Nullability>(
66 std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
67}
68
Gabor Horvath3943adb2015-09-11 16:29:05 +000069const char *getNullabilityString(Nullability Nullab) {
Gabor Horvath28690922015-08-26 23:17:43 +000070 switch (Nullab) {
71 case Nullability::Contradicted:
72 return "contradicted";
73 case Nullability::Nullable:
74 return "nullable";
75 case Nullability::Unspecified:
76 return "unspecified";
77 case Nullability::Nonnull:
78 return "nonnull";
79 }
Gabor Horvath3943adb2015-09-11 16:29:05 +000080 llvm_unreachable("Unexpected enumeration.");
Gabor Horvath28690922015-08-26 23:17:43 +000081 return "";
82}
83
84// These enums are used as an index to ErrorMessages array.
85enum class ErrorKind : int {
86 NilAssignedToNonnull,
87 NilPassedToNonnull,
88 NilReturnedToNonnull,
89 NullableAssignedToNonnull,
90 NullableReturnedToNonnull,
91 NullableDereferenced,
92 NullablePassedToNonnull
93};
94
Gabor Horvath28690922015-08-26 23:17:43 +000095class NullabilityChecker
96 : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
97 check::PostCall, check::PostStmt<ExplicitCastExpr>,
98 check::PostObjCMessage, check::DeadSymbols,
99 check::Event<ImplicitNullDerefEvent>> {
100 mutable std::unique_ptr<BugType> BT;
101
102public:
Devin Coughlina1d9d752016-03-05 01:32:43 +0000103 // If true, the checker will not diagnose nullabilility issues for calls
104 // to system headers. This option is motivated by the observation that large
105 // projects may have many nullability warnings. These projects may
106 // find warnings about nullability annotations that they have explicitly
107 // added themselves higher priority to fix than warnings on calls to system
108 // libraries.
109 DefaultBool NoDiagnoseCallsToSystemHeaders;
110
Gabor Horvath28690922015-08-26 23:17:43 +0000111 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
112 void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
113 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
114 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
115 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
116 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
117 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
118 void checkEvent(ImplicitNullDerefEvent Event) const;
119
120 void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
121 const char *Sep) const override;
122
123 struct NullabilityChecksFilter {
124 DefaultBool CheckNullPassedToNonnull;
125 DefaultBool CheckNullReturnedFromNonnull;
126 DefaultBool CheckNullableDereferenced;
127 DefaultBool CheckNullablePassedToNonnull;
128 DefaultBool CheckNullableReturnedFromNonnull;
129
130 CheckName CheckNameNullPassedToNonnull;
131 CheckName CheckNameNullReturnedFromNonnull;
132 CheckName CheckNameNullableDereferenced;
133 CheckName CheckNameNullablePassedToNonnull;
134 CheckName CheckNameNullableReturnedFromNonnull;
135 };
136
137 NullabilityChecksFilter Filter;
Gabor Horvath29307352015-09-14 18:31:34 +0000138 // When set to false no nullability information will be tracked in
139 // NullabilityMap. It is possible to catch errors like passing a null pointer
140 // to a callee that expects nonnull argument without the information that is
141 // stroed in the NullabilityMap. This is an optimization.
142 DefaultBool NeedTracking;
Gabor Horvath28690922015-08-26 23:17:43 +0000143
144private:
145 class NullabilityBugVisitor
146 : public BugReporterVisitorImpl<NullabilityBugVisitor> {
147 public:
148 NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
149
150 void Profile(llvm::FoldingSetNodeID &ID) const override {
151 static int X = 0;
152 ID.AddPointer(&X);
153 ID.AddPointer(Region);
154 }
155
156 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
157 const ExplodedNode *PrevN,
158 BugReporterContext &BRC,
159 BugReport &BR) override;
160
161 private:
162 // The tracked region.
163 const MemRegion *Region;
164 };
165
Gabor Horvathb47128a2015-09-03 23:16:21 +0000166 /// When any of the nonnull arguments of the analyzed function is null, do not
167 /// report anything and turn off the check.
168 ///
169 /// When \p SuppressPath is set to true, no more bugs will be reported on this
170 /// path by this checker.
Devin Coughlin77942db2016-03-28 20:30:25 +0000171 void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error,
172 ExplodedNode *N, const MemRegion *Region,
173 CheckerContext &C,
174 const Stmt *ValueExpr = nullptr,
175 bool SuppressPath = false) const;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000176
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000177 void reportBug(StringRef Msg, ErrorKind Error, ExplodedNode *N,
178 const MemRegion *Region, BugReporter &BR,
179 const Stmt *ValueExpr = nullptr) const {
Gabor Horvath28690922015-08-26 23:17:43 +0000180 if (!BT)
181 BT.reset(new BugType(this, "Nullability", "Memory error"));
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000182
183 auto R = llvm::make_unique<BugReport>(*BT, Msg, N);
Gabor Horvath28690922015-08-26 23:17:43 +0000184 if (Region) {
185 R->markInteresting(Region);
186 R->addVisitor(llvm::make_unique<NullabilityBugVisitor>(Region));
187 }
188 if (ValueExpr) {
189 R->addRange(ValueExpr->getSourceRange());
190 if (Error == ErrorKind::NilAssignedToNonnull ||
191 Error == ErrorKind::NilPassedToNonnull ||
192 Error == ErrorKind::NilReturnedToNonnull)
193 bugreporter::trackNullOrUndefValue(N, ValueExpr, *R);
194 }
195 BR.emitReport(std::move(R));
196 }
Gabor Horvath29307352015-09-14 18:31:34 +0000197
198 /// If an SVal wraps a region that should be tracked, it will return a pointer
199 /// to the wrapped region. Otherwise it will return a nullptr.
200 const SymbolicRegion *getTrackRegion(SVal Val,
201 bool CheckSuperRegion = false) const;
Devin Coughlina1d9d752016-03-05 01:32:43 +0000202
203 /// Returns true if the call is diagnosable in the currrent analyzer
204 /// configuration.
205 bool isDiagnosableCall(const CallEvent &Call) const {
206 if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
207 return false;
208
209 return true;
210 }
Gabor Horvath28690922015-08-26 23:17:43 +0000211};
212
213class NullabilityState {
214public:
215 NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
216 : Nullab(Nullab), Source(Source) {}
217
218 const Stmt *getNullabilitySource() const { return Source; }
219
220 Nullability getValue() const { return Nullab; }
221
222 void Profile(llvm::FoldingSetNodeID &ID) const {
223 ID.AddInteger(static_cast<char>(Nullab));
224 ID.AddPointer(Source);
225 }
226
227 void print(raw_ostream &Out) const {
228 Out << getNullabilityString(Nullab) << "\n";
229 }
230
231private:
232 Nullability Nullab;
233 // Source is the expression which determined the nullability. For example in a
234 // message like [nullable nonnull_returning] has nullable nullability, because
235 // the receiver is nullable. Here the receiver will be the source of the
236 // nullability. This is useful information when the diagnostics are generated.
237 const Stmt *Source;
238};
239
240bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
241 return Lhs.getValue() == Rhs.getValue() &&
242 Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
243}
244
245} // end anonymous namespace
246
247REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
248 NullabilityState)
249
Devin Coughlin77942db2016-03-28 20:30:25 +0000250// We say "the nullability type invariant is violated" when a location with a
251// non-null type contains NULL or a function with a non-null return type returns
252// NULL. Violations of the nullability type invariant can be detected either
253// directly (for example, when NULL is passed as an argument to a nonnull
254// parameter) or indirectly (for example, when, inside a function, the
255// programmer defensively checks whether a nonnull parameter contains NULL and
256// finds that it does).
257//
258// As a matter of policy, the nullability checker typically warns on direct
259// violations of the nullability invariant (although it uses various
260// heuristics to suppress warnings in some cases) but will not warn if the
261// invariant has already been violated along the path (either directly or
262// indirectly). As a practical matter, this prevents the analyzer from
263// (1) warning on defensive code paths where a nullability precondition is
264// determined to have been violated, (2) warning additional times after an
265// initial direct violation has been discovered, and (3) warning after a direct
266// violation that has been implicitly or explicitly suppressed (for
267// example, with a cast of NULL to _Nonnull). In essence, once an invariant
268// violation is detected on a path, this checker will be esentially turned off
269// for the rest of the analysis
270//
271// The analyzer takes this approach (rather than generating a sink node) to
272// ensure coverage of defensive paths, which may be important for backwards
273// compatibility in codebases that were developed without nullability in mind.
274REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
Gabor Horvathb47128a2015-09-03 23:16:21 +0000275
Gabor Horvath28690922015-08-26 23:17:43 +0000276enum class NullConstraint { IsNull, IsNotNull, Unknown };
277
278static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
279 ProgramStateRef State) {
280 ConditionTruthVal Nullness = State->isNull(Val);
281 if (Nullness.isConstrainedFalse())
282 return NullConstraint::IsNotNull;
283 if (Nullness.isConstrainedTrue())
284 return NullConstraint::IsNull;
285 return NullConstraint::Unknown;
286}
287
Gabor Horvath29307352015-09-14 18:31:34 +0000288const SymbolicRegion *
289NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
290 if (!NeedTracking)
291 return nullptr;
292
Gabor Horvath28690922015-08-26 23:17:43 +0000293 auto RegionSVal = Val.getAs<loc::MemRegionVal>();
294 if (!RegionSVal)
295 return nullptr;
296
297 const MemRegion *Region = RegionSVal->getRegion();
298
299 if (CheckSuperRegion) {
300 if (auto FieldReg = Region->getAs<FieldRegion>())
301 return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
Gabor Horvath3943adb2015-09-11 16:29:05 +0000302 if (auto ElementReg = Region->getAs<ElementRegion>())
Gabor Horvath28690922015-08-26 23:17:43 +0000303 return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
304 }
305
306 return dyn_cast<SymbolicRegion>(Region);
307}
308
309PathDiagnosticPiece *NullabilityChecker::NullabilityBugVisitor::VisitNode(
310 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
311 BugReport &BR) {
Gabor Horvath3943adb2015-09-11 16:29:05 +0000312 ProgramStateRef State = N->getState();
313 ProgramStateRef StatePrev = PrevN->getState();
Gabor Horvath28690922015-08-26 23:17:43 +0000314
Gabor Horvath3943adb2015-09-11 16:29:05 +0000315 const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
Gabor Horvath28690922015-08-26 23:17:43 +0000316 const NullabilityState *TrackedNullabPrev =
Gabor Horvath3943adb2015-09-11 16:29:05 +0000317 StatePrev->get<NullabilityMap>(Region);
Gabor Horvath28690922015-08-26 23:17:43 +0000318 if (!TrackedNullab)
319 return nullptr;
320
321 if (TrackedNullabPrev &&
322 TrackedNullabPrev->getValue() == TrackedNullab->getValue())
323 return nullptr;
324
325 // Retrieve the associated statement.
326 const Stmt *S = TrackedNullab->getNullabilitySource();
327 if (!S) {
Gabor Horvath6ee4f902016-08-18 07:54:50 +0000328 S = PathDiagnosticLocation::getStmt(N);
Gabor Horvath28690922015-08-26 23:17:43 +0000329 }
330
331 if (!S)
332 return nullptr;
333
334 std::string InfoText =
335 (llvm::Twine("Nullability '") +
336 getNullabilityString(TrackedNullab->getValue()) + "' is infered")
337 .str();
338
339 // Generate the extra diagnostic.
340 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
341 N->getLocationContext());
342 return new PathDiagnosticEventPiece(Pos, InfoText, true, nullptr);
343}
344
345static Nullability getNullabilityAnnotation(QualType Type) {
346 const auto *AttrType = Type->getAs<AttributedType>();
347 if (!AttrType)
348 return Nullability::Unspecified;
349 if (AttrType->getAttrKind() == AttributedType::attr_nullable)
350 return Nullability::Nullable;
351 else if (AttrType->getAttrKind() == AttributedType::attr_nonnull)
352 return Nullability::Nonnull;
353 return Nullability::Unspecified;
354}
355
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000356/// Returns true when the value stored at the given location is null
357/// and the passed in type is nonnnull.
358static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
359 SVal LV, QualType T) {
360 if (getNullabilityAnnotation(T) != Nullability::Nonnull)
361 return false;
362
363 auto RegionVal = LV.getAs<loc::MemRegionVal>();
364 if (!RegionVal)
365 return false;
366
367 auto StoredVal =
368 State->getSVal(RegionVal->getRegion()).getAs<DefinedOrUnknownSVal>();
369 if (!StoredVal)
370 return false;
371
372 if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
373 return true;
374
375 return false;
376}
377
Gabor Horvathb47128a2015-09-03 23:16:21 +0000378static bool
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000379checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
Gabor Horvathb47128a2015-09-03 23:16:21 +0000380 ProgramStateRef State,
381 const LocationContext *LocCtxt) {
382 for (const auto *ParamDecl : Params) {
383 if (ParamDecl->isParameterPack())
384 break;
385
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000386 SVal LV = State->getLValue(ParamDecl, LocCtxt);
387 if (checkValueAtLValForInvariantViolation(State, LV,
388 ParamDecl->getType())) {
389 return true;
390 }
391 }
392 return false;
393}
Gabor Horvathb47128a2015-09-03 23:16:21 +0000394
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000395static bool
396checkSelfIvarsForInvariantViolation(ProgramStateRef State,
397 const LocationContext *LocCtxt) {
398 auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
399 if (!MD || !MD->isInstanceMethod())
400 return false;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000401
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000402 const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
403 if (!SelfDecl)
404 return false;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000405
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000406 SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
407
408 const ObjCObjectPointerType *SelfType =
409 dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
410 if (!SelfType)
411 return false;
412
413 const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
414 if (!ID)
415 return false;
416
417 for (const auto *IvarDecl : ID->ivars()) {
418 SVal LV = State->getLValue(IvarDecl, SelfVal);
419 if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
Gabor Horvathb47128a2015-09-03 23:16:21 +0000420 return true;
421 }
422 }
423 return false;
424}
425
Devin Coughlin77942db2016-03-28 20:30:25 +0000426static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
427 CheckerContext &C) {
428 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000429 return true;
430
431 const LocationContext *LocCtxt = C.getLocationContext();
432 const Decl *D = LocCtxt->getDecl();
433 if (!D)
434 return false;
435
Devin Coughlin851da712016-01-15 21:35:40 +0000436 ArrayRef<ParmVarDecl*> Params;
437 if (const auto *BD = dyn_cast<BlockDecl>(D))
438 Params = BD->parameters();
439 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
440 Params = FD->parameters();
441 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
442 Params = MD->parameters();
443 else
Gabor Horvathb47128a2015-09-03 23:16:21 +0000444 return false;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000445
Devin Coughlinb2d2a012016-04-13 00:41:54 +0000446 if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
447 checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
Devin Coughlin851da712016-01-15 21:35:40 +0000448 if (!N->isSink())
Devin Coughlin77942db2016-03-28 20:30:25 +0000449 C.addTransition(State->set<InvariantViolated>(true), N);
Devin Coughlin851da712016-01-15 21:35:40 +0000450 return true;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000451 }
452 return false;
453}
454
Devin Coughlin77942db2016-03-28 20:30:25 +0000455void NullabilityChecker::reportBugIfInvariantHolds(StringRef Msg,
Gabor Horvathb47128a2015-09-03 23:16:21 +0000456 ErrorKind Error, ExplodedNode *N, const MemRegion *Region,
457 CheckerContext &C, const Stmt *ValueExpr, bool SuppressPath) const {
458 ProgramStateRef OriginalState = N->getState();
459
Devin Coughlin77942db2016-03-28 20:30:25 +0000460 if (checkInvariantViolation(OriginalState, N, C))
Gabor Horvathb47128a2015-09-03 23:16:21 +0000461 return;
462 if (SuppressPath) {
Devin Coughlin77942db2016-03-28 20:30:25 +0000463 OriginalState = OriginalState->set<InvariantViolated>(true);
Gabor Horvathb47128a2015-09-03 23:16:21 +0000464 N = C.addTransition(OriginalState, N);
465 }
466
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000467 reportBug(Msg, Error, N, Region, C.getBugReporter(), ValueExpr);
Gabor Horvathb47128a2015-09-03 23:16:21 +0000468}
469
Gabor Horvath28690922015-08-26 23:17:43 +0000470/// Cleaning up the program state.
471void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
472 CheckerContext &C) const {
Gabor Horvathbe87d5b2015-09-14 20:31:46 +0000473 if (!SR.hasDeadSymbols())
474 return;
475
Gabor Horvath28690922015-08-26 23:17:43 +0000476 ProgramStateRef State = C.getState();
477 NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
478 for (NullabilityMapTy::iterator I = Nullabilities.begin(),
479 E = Nullabilities.end();
480 I != E; ++I) {
Gabor Horvathbe87d5b2015-09-14 20:31:46 +0000481 const auto *Region = I->first->getAs<SymbolicRegion>();
482 assert(Region && "Non-symbolic region is tracked.");
483 if (SR.isDead(Region->getSymbol())) {
Gabor Horvath28690922015-08-26 23:17:43 +0000484 State = State->remove<NullabilityMap>(I->first);
485 }
486 }
Gabor Horvathb47128a2015-09-03 23:16:21 +0000487 // When one of the nonnull arguments are constrained to be null, nullability
488 // preconditions are violated. It is not enough to check this only when we
489 // actually report an error, because at that time interesting symbols might be
490 // reaped.
Devin Coughlin77942db2016-03-28 20:30:25 +0000491 if (checkInvariantViolation(State, C.getPredecessor(), C))
Gabor Horvathb47128a2015-09-03 23:16:21 +0000492 return;
493 C.addTransition(State);
Gabor Horvath28690922015-08-26 23:17:43 +0000494}
495
496/// This callback triggers when a pointer is dereferenced and the analyzer does
497/// not know anything about the value of that pointer. When that pointer is
498/// nullable, this code emits a warning.
499void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
Devin Coughlin77942db2016-03-28 20:30:25 +0000500 if (Event.SinkNode->getState()->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000501 return;
502
Gabor Horvath28690922015-08-26 23:17:43 +0000503 const MemRegion *Region =
504 getTrackRegion(Event.Location, /*CheckSuperregion=*/true);
505 if (!Region)
506 return;
507
508 ProgramStateRef State = Event.SinkNode->getState();
509 const NullabilityState *TrackedNullability =
510 State->get<NullabilityMap>(Region);
511
512 if (!TrackedNullability)
513 return;
514
515 if (Filter.CheckNullableDereferenced &&
516 TrackedNullability->getValue() == Nullability::Nullable) {
517 BugReporter &BR = *Event.BR;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000518 // Do not suppress errors on defensive code paths, because dereferencing
519 // a nullable pointer is always an error.
Gabor Horvath8d3ad6b2015-08-27 18:49:07 +0000520 if (Event.IsDirectDereference)
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000521 reportBug("Nullable pointer is dereferenced",
522 ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR);
523 else {
524 reportBug("Nullable pointer is passed to a callee that requires a "
525 "non-null", ErrorKind::NullablePassedToNonnull,
526 Event.SinkNode, Region, BR);
527 }
Gabor Horvath28690922015-08-26 23:17:43 +0000528 }
529}
530
Devin Coughlin5a3843e2016-01-18 18:53:33 +0000531/// Find the outermost subexpression of E that is not an implicit cast.
532/// This looks through the implicit casts to _Nonnull that ARC adds to
533/// return expressions of ObjC types when the return type of the function or
534/// method is non-null but the express is not.
535static const Expr *lookThroughImplicitCasts(const Expr *E) {
536 assert(E);
537
538 while (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
539 E = ICE->getSubExpr();
540 }
541
542 return E;
543}
544
Gabor Horvath28690922015-08-26 23:17:43 +0000545/// This method check when nullable pointer or null value is returned from a
546/// function that has nonnull return type.
Gabor Horvath28690922015-08-26 23:17:43 +0000547void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
548 CheckerContext &C) const {
549 auto RetExpr = S->getRetValue();
550 if (!RetExpr)
551 return;
552
553 if (!RetExpr->getType()->isAnyPointerType())
554 return;
555
556 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000557 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000558 return;
559
Gabor Horvath28690922015-08-26 23:17:43 +0000560 auto RetSVal =
561 State->getSVal(S, C.getLocationContext()).getAs<DefinedOrUnknownSVal>();
562 if (!RetSVal)
563 return;
564
Devin Coughlinde217672016-01-28 22:23:34 +0000565 bool InSuppressedMethodFamily = false;
Devin Coughlin4a330202016-01-22 01:01:11 +0000566
Devin Coughlin851da712016-01-15 21:35:40 +0000567 QualType RequiredRetType;
Gabor Horvath28690922015-08-26 23:17:43 +0000568 AnalysisDeclContext *DeclCtxt =
569 C.getLocationContext()->getAnalysisDeclContext();
Devin Coughlin851da712016-01-15 21:35:40 +0000570 const Decl *D = DeclCtxt->getDecl();
Devin Coughlin4a330202016-01-22 01:01:11 +0000571 if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Devin Coughlinde217672016-01-28 22:23:34 +0000572 // HACK: This is a big hammer to avoid warning when there are defensive
573 // nil checks in -init and -copy methods. We should add more sophisticated
574 // logic here to suppress on common defensive idioms but still
575 // warn when there is a likely problem.
576 ObjCMethodFamily Family = MD->getMethodFamily();
577 if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
578 InSuppressedMethodFamily = true;
579
Devin Coughlin851da712016-01-15 21:35:40 +0000580 RequiredRetType = MD->getReturnType();
Devin Coughlin4a330202016-01-22 01:01:11 +0000581 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Devin Coughlin851da712016-01-15 21:35:40 +0000582 RequiredRetType = FD->getReturnType();
Devin Coughlin4a330202016-01-22 01:01:11 +0000583 } else {
Gabor Horvath28690922015-08-26 23:17:43 +0000584 return;
Devin Coughlin4a330202016-01-22 01:01:11 +0000585 }
Gabor Horvath28690922015-08-26 23:17:43 +0000586
587 NullConstraint Nullness = getNullConstraint(*RetSVal, State);
588
Devin Coughlin851da712016-01-15 21:35:40 +0000589 Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
Gabor Horvath28690922015-08-26 23:17:43 +0000590
Devin Coughlin755baa42015-12-29 17:40:49 +0000591 // If the returned value is null but the type of the expression
592 // generating it is nonnull then we will suppress the diagnostic.
593 // This enables explicit suppression when returning a nil literal in a
594 // function with a _Nonnull return type:
595 // return (NSString * _Nonnull)0;
596 Nullability RetExprTypeLevelNullability =
Devin Coughlin5a3843e2016-01-18 18:53:33 +0000597 getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
Devin Coughlin755baa42015-12-29 17:40:49 +0000598
Devin Coughlin77942db2016-03-28 20:30:25 +0000599 bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
600 Nullness == NullConstraint::IsNull);
Gabor Horvath28690922015-08-26 23:17:43 +0000601 if (Filter.CheckNullReturnedFromNonnull &&
Devin Coughlin77942db2016-03-28 20:30:25 +0000602 NullReturnedFromNonNull &&
Devin Coughlin755baa42015-12-29 17:40:49 +0000603 RetExprTypeLevelNullability != Nullability::Nonnull &&
Devin Coughlin49bd58f2016-04-12 19:29:52 +0000604 !InSuppressedMethodFamily &&
605 C.getLocationContext()->inTopFrame()) {
Gabor Horvath28690922015-08-26 23:17:43 +0000606 static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
Devin Coughline39bd402015-09-16 22:03:05 +0000607 ExplodedNode *N = C.generateErrorNode(State, &Tag);
608 if (!N)
609 return;
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000610
611 SmallString<256> SBuf;
612 llvm::raw_svector_ostream OS(SBuf);
613 OS << "Null is returned from a " << C.getDeclDescription(D) <<
614 " that is expected to return a non-null value";
615
Devin Coughlin77942db2016-03-28 20:30:25 +0000616 reportBugIfInvariantHolds(OS.str(),
617 ErrorKind::NilReturnedToNonnull, N, nullptr, C,
618 RetExpr);
619 return;
620 }
621
622 // If null was returned from a non-null function, mark the nullability
623 // invariant as violated even if the diagnostic was suppressed.
624 if (NullReturnedFromNonNull) {
625 State = State->set<InvariantViolated>(true);
626 C.addTransition(State);
Gabor Horvath28690922015-08-26 23:17:43 +0000627 return;
628 }
629
630 const MemRegion *Region = getTrackRegion(*RetSVal);
631 if (!Region)
632 return;
633
634 const NullabilityState *TrackedNullability =
635 State->get<NullabilityMap>(Region);
636 if (TrackedNullability) {
637 Nullability TrackedNullabValue = TrackedNullability->getValue();
638 if (Filter.CheckNullableReturnedFromNonnull &&
639 Nullness != NullConstraint::IsNotNull &&
640 TrackedNullabValue == Nullability::Nullable &&
Devin Coughlin755baa42015-12-29 17:40:49 +0000641 RequiredNullability == Nullability::Nonnull) {
Gabor Horvath28690922015-08-26 23:17:43 +0000642 static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
643 ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000644
645 SmallString<256> SBuf;
646 llvm::raw_svector_ostream OS(SBuf);
647 OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
648 " that is expected to return a non-null value";
649
Devin Coughlin77942db2016-03-28 20:30:25 +0000650 reportBugIfInvariantHolds(OS.str(),
651 ErrorKind::NullableReturnedToNonnull, N,
652 Region, C);
Gabor Horvath28690922015-08-26 23:17:43 +0000653 }
654 return;
655 }
Devin Coughlin755baa42015-12-29 17:40:49 +0000656 if (RequiredNullability == Nullability::Nullable) {
Gabor Horvath28690922015-08-26 23:17:43 +0000657 State = State->set<NullabilityMap>(Region,
Devin Coughlin755baa42015-12-29 17:40:49 +0000658 NullabilityState(RequiredNullability,
659 S));
Gabor Horvath28690922015-08-26 23:17:43 +0000660 C.addTransition(State);
661 }
662}
663
664/// This callback warns when a nullable pointer or a null value is passed to a
665/// function that expects its argument to be nonnull.
666void NullabilityChecker::checkPreCall(const CallEvent &Call,
667 CheckerContext &C) const {
668 if (!Call.getDecl())
669 return;
670
671 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000672 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000673 return;
674
Gabor Horvath28690922015-08-26 23:17:43 +0000675 ProgramStateRef OrigState = State;
676
677 unsigned Idx = 0;
678 for (const ParmVarDecl *Param : Call.parameters()) {
679 if (Param->isParameterPack())
680 break;
681
682 const Expr *ArgExpr = nullptr;
683 if (Idx < Call.getNumArgs())
684 ArgExpr = Call.getArgExpr(Idx);
685 auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
686 if (!ArgSVal)
687 continue;
688
689 if (!Param->getType()->isAnyPointerType() &&
690 !Param->getType()->isReferenceType())
691 continue;
692
693 NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
694
Devin Coughlin755baa42015-12-29 17:40:49 +0000695 Nullability RequiredNullability =
696 getNullabilityAnnotation(Param->getType());
697 Nullability ArgExprTypeLevelNullability =
Gabor Horvath28690922015-08-26 23:17:43 +0000698 getNullabilityAnnotation(ArgExpr->getType());
699
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000700 unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
701
Gabor Horvath28690922015-08-26 23:17:43 +0000702 if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull &&
Devin Coughlin755baa42015-12-29 17:40:49 +0000703 ArgExprTypeLevelNullability != Nullability::Nonnull &&
Devin Coughlina1d9d752016-03-05 01:32:43 +0000704 RequiredNullability == Nullability::Nonnull &&
705 isDiagnosableCall(Call)) {
Devin Coughline39bd402015-09-16 22:03:05 +0000706 ExplodedNode *N = C.generateErrorNode(State);
707 if (!N)
708 return;
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000709 SmallString<256> SBuf;
710 llvm::raw_svector_ostream OS(SBuf);
711 OS << "Null passed to a callee that requires a non-null " << ParamIdx
712 << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
Devin Coughlin77942db2016-03-28 20:30:25 +0000713 reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull, N,
714 nullptr, C,
715 ArgExpr, /*SuppressPath=*/false);
Gabor Horvath28690922015-08-26 23:17:43 +0000716 return;
717 }
718
719 const MemRegion *Region = getTrackRegion(*ArgSVal);
720 if (!Region)
721 continue;
722
723 const NullabilityState *TrackedNullability =
724 State->get<NullabilityMap>(Region);
725
726 if (TrackedNullability) {
727 if (Nullness == NullConstraint::IsNotNull ||
728 TrackedNullability->getValue() != Nullability::Nullable)
729 continue;
730
731 if (Filter.CheckNullablePassedToNonnull &&
Devin Coughlina1d9d752016-03-05 01:32:43 +0000732 RequiredNullability == Nullability::Nonnull &&
733 isDiagnosableCall(Call)) {
Gabor Horvathb47128a2015-09-03 23:16:21 +0000734 ExplodedNode *N = C.addTransition(State);
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000735 SmallString<256> SBuf;
736 llvm::raw_svector_ostream OS(SBuf);
737 OS << "Nullable pointer is passed to a callee that requires a non-null "
738 << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
Devin Coughlin77942db2016-03-28 20:30:25 +0000739 reportBugIfInvariantHolds(OS.str(),
740 ErrorKind::NullablePassedToNonnull, N,
741 Region, C, ArgExpr, /*SuppressPath=*/true);
Gabor Horvath28690922015-08-26 23:17:43 +0000742 return;
743 }
744 if (Filter.CheckNullableDereferenced &&
745 Param->getType()->isReferenceType()) {
Gabor Horvathb47128a2015-09-03 23:16:21 +0000746 ExplodedNode *N = C.addTransition(State);
Devin Coughlin77942db2016-03-28 20:30:25 +0000747 reportBugIfInvariantHolds("Nullable pointer is dereferenced",
748 ErrorKind::NullableDereferenced, N, Region,
749 C, ArgExpr, /*SuppressPath=*/true);
Gabor Horvath28690922015-08-26 23:17:43 +0000750 return;
751 }
752 continue;
753 }
754 // No tracked nullability yet.
Devin Coughlin755baa42015-12-29 17:40:49 +0000755 if (ArgExprTypeLevelNullability != Nullability::Nullable)
Gabor Horvath28690922015-08-26 23:17:43 +0000756 continue;
757 State = State->set<NullabilityMap>(
Devin Coughlin755baa42015-12-29 17:40:49 +0000758 Region, NullabilityState(ArgExprTypeLevelNullability, ArgExpr));
Gabor Horvath28690922015-08-26 23:17:43 +0000759 }
760 if (State != OrigState)
761 C.addTransition(State);
762}
763
764/// Suppress the nullability warnings for some functions.
765void NullabilityChecker::checkPostCall(const CallEvent &Call,
766 CheckerContext &C) const {
767 auto Decl = Call.getDecl();
768 if (!Decl)
769 return;
770 // ObjC Messages handles in a different callback.
771 if (Call.getKind() == CE_ObjCMessage)
772 return;
773 const FunctionType *FuncType = Decl->getFunctionType();
774 if (!FuncType)
775 return;
776 QualType ReturnType = FuncType->getReturnType();
777 if (!ReturnType->isAnyPointerType())
778 return;
Gabor Horvathb47128a2015-09-03 23:16:21 +0000779 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000780 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000781 return;
782
Gabor Horvath28690922015-08-26 23:17:43 +0000783 const MemRegion *Region = getTrackRegion(Call.getReturnValue());
784 if (!Region)
785 return;
Gabor Horvath28690922015-08-26 23:17:43 +0000786
787 // CG headers are misannotated. Do not warn for symbols that are the results
788 // of CG calls.
789 const SourceManager &SM = C.getSourceManager();
790 StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getLocStart()));
791 if (llvm::sys::path::filename(FilePath).startswith("CG")) {
792 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
793 C.addTransition(State);
794 return;
795 }
796
797 const NullabilityState *TrackedNullability =
798 State->get<NullabilityMap>(Region);
799
800 if (!TrackedNullability &&
801 getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
802 State = State->set<NullabilityMap>(Region, Nullability::Nullable);
803 C.addTransition(State);
804 }
805}
806
807static Nullability getReceiverNullability(const ObjCMethodCall &M,
808 ProgramStateRef State) {
Gabor Horvath28690922015-08-26 23:17:43 +0000809 if (M.isReceiverSelfOrSuper()) {
810 // For super and super class receivers we assume that the receiver is
811 // nonnull.
Gabor Horvath3943adb2015-09-11 16:29:05 +0000812 return Nullability::Nonnull;
Gabor Horvath28690922015-08-26 23:17:43 +0000813 }
Gabor Horvath3943adb2015-09-11 16:29:05 +0000814 // Otherwise look up nullability in the state.
815 SVal Receiver = M.getReceiverSVal();
816 if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
817 // If the receiver is constrained to be nonnull, assume that it is nonnull
818 // regardless of its type.
819 NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
820 if (Nullness == NullConstraint::IsNotNull)
821 return Nullability::Nonnull;
822 }
823 auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
824 if (ValueRegionSVal) {
825 const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
826 assert(SelfRegion);
827
828 const NullabilityState *TrackedSelfNullability =
829 State->get<NullabilityMap>(SelfRegion);
830 if (TrackedSelfNullability)
831 return TrackedSelfNullability->getValue();
832 }
833 return Nullability::Unspecified;
Gabor Horvath28690922015-08-26 23:17:43 +0000834}
835
836/// Calculate the nullability of the result of a message expr based on the
837/// nullability of the receiver, the nullability of the return value, and the
838/// constraints.
839void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
840 CheckerContext &C) const {
841 auto Decl = M.getDecl();
842 if (!Decl)
843 return;
844 QualType RetType = Decl->getReturnType();
845 if (!RetType->isAnyPointerType())
846 return;
847
Gabor Horvathb47128a2015-09-03 23:16:21 +0000848 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000849 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000850 return;
851
Gabor Horvath28690922015-08-26 23:17:43 +0000852 const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
853 if (!ReturnRegion)
854 return;
855
Gabor Horvath28690922015-08-26 23:17:43 +0000856 auto Interface = Decl->getClassInterface();
857 auto Name = Interface ? Interface->getName() : "";
858 // In order to reduce the noise in the diagnostics generated by this checker,
859 // some framework and programming style based heuristics are used. These
860 // heuristics are for Cocoa APIs which have NS prefix.
861 if (Name.startswith("NS")) {
862 // Developers rely on dynamic invariants such as an item should be available
863 // in a collection, or a collection is not empty often. Those invariants can
864 // not be inferred by any static analysis tool. To not to bother the users
865 // with too many false positives, every item retrieval function should be
866 // ignored for collections. The instance methods of dictionaries in Cocoa
867 // are either item retrieval related or not interesting nullability wise.
868 // Using this fact, to keep the code easier to read just ignore the return
869 // value of every instance method of dictionaries.
870 if (M.isInstanceMessage() && Name.find("Dictionary") != StringRef::npos) {
871 State =
872 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
873 C.addTransition(State);
874 return;
875 }
876 // For similar reasons ignore some methods of Cocoa arrays.
877 StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
878 if (Name.find("Array") != StringRef::npos &&
879 (FirstSelectorSlot == "firstObject" ||
880 FirstSelectorSlot == "lastObject")) {
881 State =
882 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
883 C.addTransition(State);
884 return;
885 }
886
887 // Encoding related methods of string should not fail when lossless
888 // encodings are used. Using lossless encodings is so frequent that ignoring
889 // this class of methods reduced the emitted diagnostics by about 30% on
890 // some projects (and all of that was false positives).
891 if (Name.find("String") != StringRef::npos) {
892 for (auto Param : M.parameters()) {
893 if (Param->getName() == "encoding") {
894 State = State->set<NullabilityMap>(ReturnRegion,
895 Nullability::Contradicted);
896 C.addTransition(State);
897 return;
898 }
899 }
900 }
901 }
902
903 const ObjCMessageExpr *Message = M.getOriginExpr();
904 Nullability SelfNullability = getReceiverNullability(M, State);
905
906 const NullabilityState *NullabilityOfReturn =
907 State->get<NullabilityMap>(ReturnRegion);
908
909 if (NullabilityOfReturn) {
910 // When we have a nullability tracked for the return value, the nullability
911 // of the expression will be the most nullable of the receiver and the
912 // return value.
913 Nullability RetValTracked = NullabilityOfReturn->getValue();
914 Nullability ComputedNullab =
915 getMostNullable(RetValTracked, SelfNullability);
916 if (ComputedNullab != RetValTracked &&
917 ComputedNullab != Nullability::Unspecified) {
918 const Stmt *NullabilitySource =
919 ComputedNullab == RetValTracked
920 ? NullabilityOfReturn->getNullabilitySource()
921 : Message->getInstanceReceiver();
922 State = State->set<NullabilityMap>(
923 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
924 C.addTransition(State);
925 }
926 return;
927 }
928
929 // No tracked information. Use static type information for return value.
930 Nullability RetNullability = getNullabilityAnnotation(RetType);
931
932 // Properties might be computed. For this reason the static analyzer creates a
933 // new symbol each time an unknown property is read. To avoid false pozitives
934 // do not treat unknown properties as nullable, even when they explicitly
935 // marked nullable.
936 if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
937 RetNullability = Nullability::Nonnull;
938
939 Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
940 if (ComputedNullab == Nullability::Nullable) {
941 const Stmt *NullabilitySource = ComputedNullab == RetNullability
942 ? Message
943 : Message->getInstanceReceiver();
944 State = State->set<NullabilityMap>(
945 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
946 C.addTransition(State);
947 }
948}
949
950/// Explicit casts are trusted. If there is a disagreement in the nullability
951/// annotations in the destination and the source or '0' is casted to nonnull
952/// track the value as having contraditory nullability. This will allow users to
953/// suppress warnings.
954void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
955 CheckerContext &C) const {
956 QualType OriginType = CE->getSubExpr()->getType();
957 QualType DestType = CE->getType();
958 if (!OriginType->isAnyPointerType())
959 return;
960 if (!DestType->isAnyPointerType())
961 return;
962
Gabor Horvathb47128a2015-09-03 23:16:21 +0000963 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +0000964 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +0000965 return;
966
Gabor Horvath28690922015-08-26 23:17:43 +0000967 Nullability DestNullability = getNullabilityAnnotation(DestType);
968
969 // No explicit nullability in the destination type, so this cast does not
970 // change the nullability.
971 if (DestNullability == Nullability::Unspecified)
972 return;
973
Gabor Horvath28690922015-08-26 23:17:43 +0000974 auto RegionSVal =
975 State->getSVal(CE, C.getLocationContext()).getAs<DefinedOrUnknownSVal>();
976 const MemRegion *Region = getTrackRegion(*RegionSVal);
977 if (!Region)
978 return;
979
980 // When 0 is converted to nonnull mark it as contradicted.
981 if (DestNullability == Nullability::Nonnull) {
982 NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
983 if (Nullness == NullConstraint::IsNull) {
984 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
985 C.addTransition(State);
986 return;
987 }
988 }
989
990 const NullabilityState *TrackedNullability =
991 State->get<NullabilityMap>(Region);
992
993 if (!TrackedNullability) {
994 if (DestNullability != Nullability::Nullable)
995 return;
996 State = State->set<NullabilityMap>(Region,
997 NullabilityState(DestNullability, CE));
998 C.addTransition(State);
999 return;
1000 }
1001
1002 if (TrackedNullability->getValue() != DestNullability &&
1003 TrackedNullability->getValue() != Nullability::Contradicted) {
1004 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1005 C.addTransition(State);
1006 }
1007}
1008
Devin Coughlinc1986632015-11-24 19:15:11 +00001009/// For a given statement performing a bind, attempt to syntactically
1010/// match the expression resulting in the bound value.
1011static const Expr * matchValueExprForBind(const Stmt *S) {
1012 // For `x = e` the value expression is the right-hand side.
1013 if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
1014 if (BinOp->getOpcode() == BO_Assign)
1015 return BinOp->getRHS();
1016 }
1017
1018 // For `int x = e` the value expression is the initializer.
1019 if (auto *DS = dyn_cast<DeclStmt>(S)) {
1020 if (DS->isSingleDecl()) {
1021 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1022 if (!VD)
1023 return nullptr;
1024
1025 if (const Expr *Init = VD->getInit())
1026 return Init;
1027 }
1028 }
1029
1030 return nullptr;
1031}
1032
Devin Coughlin3ab8b2e72015-12-29 23:44:19 +00001033/// Returns true if \param S is a DeclStmt for a local variable that
1034/// ObjC automated reference counting initialized with zero.
1035static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
1036 // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
1037 // prevents false positives when a _Nonnull local variable cannot be
1038 // initialized with an initialization expression:
1039 // NSString * _Nonnull s; // no-warning
1040 // @autoreleasepool {
1041 // s = ...
1042 // }
1043 //
1044 // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
1045 // uninitialized in Sema's UninitializedValues analysis to warn when a use of
1046 // the zero-initialized definition will unexpectedly yield nil.
1047
1048 // Locals are only zero-initialized when automated reference counting
1049 // is turned on.
1050 if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
1051 return false;
1052
1053 auto *DS = dyn_cast<DeclStmt>(S);
1054 if (!DS || !DS->isSingleDecl())
1055 return false;
1056
1057 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1058 if (!VD)
1059 return false;
1060
1061 // Sema only zero-initializes locals with ObjCLifetimes.
1062 if(!VD->getType().getQualifiers().hasObjCLifetime())
1063 return false;
1064
1065 const Expr *Init = VD->getInit();
1066 assert(Init && "ObjC local under ARC without initializer");
1067
1068 // Return false if the local is explicitly initialized (e.g., with '= nil').
1069 if (!isa<ImplicitValueInitExpr>(Init))
1070 return false;
1071
1072 return true;
1073}
1074
Gabor Horvath28690922015-08-26 23:17:43 +00001075/// Propagate the nullability information through binds and warn when nullable
1076/// pointer or null symbol is assigned to a pointer with a nonnull type.
1077void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
1078 CheckerContext &C) const {
1079 const TypedValueRegion *TVR =
1080 dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
1081 if (!TVR)
1082 return;
1083
1084 QualType LocType = TVR->getValueType();
1085 if (!LocType->isAnyPointerType())
1086 return;
1087
Gabor Horvathb47128a2015-09-03 23:16:21 +00001088 ProgramStateRef State = C.getState();
Devin Coughlin77942db2016-03-28 20:30:25 +00001089 if (State->get<InvariantViolated>())
Gabor Horvathb47128a2015-09-03 23:16:21 +00001090 return;
1091
Gabor Horvath28690922015-08-26 23:17:43 +00001092 auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
1093 if (!ValDefOrUnknown)
1094 return;
1095
Gabor Horvath28690922015-08-26 23:17:43 +00001096 NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
1097
1098 Nullability ValNullability = Nullability::Unspecified;
1099 if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
1100 ValNullability = getNullabilityAnnotation(Sym->getType());
1101
1102 Nullability LocNullability = getNullabilityAnnotation(LocType);
Devin Coughlin4ac12422016-04-13 17:59:24 +00001103
1104 // If the type of the RHS expression is nonnull, don't warn. This
1105 // enables explicit suppression with a cast to nonnull.
1106 Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
1107 const Expr *ValueExpr = matchValueExprForBind(S);
1108 if (ValueExpr) {
1109 ValueExprTypeLevelNullability =
1110 getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
1111 }
1112
1113 bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
1114 RhsNullness == NullConstraint::IsNull);
Gabor Horvath28690922015-08-26 23:17:43 +00001115 if (Filter.CheckNullPassedToNonnull &&
Devin Coughlin4ac12422016-04-13 17:59:24 +00001116 NullAssignedToNonNull &&
Gabor Horvath28690922015-08-26 23:17:43 +00001117 ValNullability != Nullability::Nonnull &&
Devin Coughlin4ac12422016-04-13 17:59:24 +00001118 ValueExprTypeLevelNullability != Nullability::Nonnull &&
Devin Coughlin3ab8b2e72015-12-29 23:44:19 +00001119 !isARCNilInitializedLocal(C, S)) {
Gabor Horvath28690922015-08-26 23:17:43 +00001120 static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
Devin Coughline39bd402015-09-16 22:03:05 +00001121 ExplodedNode *N = C.generateErrorNode(State, &Tag);
1122 if (!N)
1123 return;
Devin Coughlinc1986632015-11-24 19:15:11 +00001124
Devin Coughlin4ac12422016-04-13 17:59:24 +00001125
1126 const Stmt *ValueStmt = S;
1127 if (ValueExpr)
1128 ValueStmt = ValueExpr;
Devin Coughlinc1986632015-11-24 19:15:11 +00001129
Devin Coughlin77942db2016-03-28 20:30:25 +00001130 reportBugIfInvariantHolds("Null is assigned to a pointer which is "
1131 "expected to have non-null value",
1132 ErrorKind::NilAssignedToNonnull, N, nullptr, C,
Devin Coughlin4ac12422016-04-13 17:59:24 +00001133 ValueStmt);
Gabor Horvath28690922015-08-26 23:17:43 +00001134 return;
1135 }
Devin Coughlin4ac12422016-04-13 17:59:24 +00001136
1137 // If null was returned from a non-null function, mark the nullability
1138 // invariant as violated even if the diagnostic was suppressed.
1139 if (NullAssignedToNonNull) {
1140 State = State->set<InvariantViolated>(true);
1141 C.addTransition(State);
1142 return;
1143 }
1144
Gabor Horvath28690922015-08-26 23:17:43 +00001145 // Intentionally missing case: '0' is bound to a reference. It is handled by
1146 // the DereferenceChecker.
1147
1148 const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
1149 if (!ValueRegion)
1150 return;
1151
1152 const NullabilityState *TrackedNullability =
1153 State->get<NullabilityMap>(ValueRegion);
1154
1155 if (TrackedNullability) {
1156 if (RhsNullness == NullConstraint::IsNotNull ||
1157 TrackedNullability->getValue() != Nullability::Nullable)
1158 return;
1159 if (Filter.CheckNullablePassedToNonnull &&
1160 LocNullability == Nullability::Nonnull) {
1161 static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
1162 ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
Devin Coughlin77942db2016-03-28 20:30:25 +00001163 reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
1164 "which is expected to have non-null value",
1165 ErrorKind::NullableAssignedToNonnull, N,
1166 ValueRegion, C);
Gabor Horvath28690922015-08-26 23:17:43 +00001167 }
1168 return;
1169 }
1170
1171 const auto *BinOp = dyn_cast<BinaryOperator>(S);
1172
1173 if (ValNullability == Nullability::Nullable) {
1174 // Trust the static information of the value more than the static
1175 // information on the location.
1176 const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
1177 State = State->set<NullabilityMap>(
1178 ValueRegion, NullabilityState(ValNullability, NullabilitySource));
1179 C.addTransition(State);
1180 return;
1181 }
1182
1183 if (LocNullability == Nullability::Nullable) {
1184 const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
1185 State = State->set<NullabilityMap>(
1186 ValueRegion, NullabilityState(LocNullability, NullabilitySource));
1187 C.addTransition(State);
1188 }
1189}
1190
1191void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
1192 const char *NL, const char *Sep) const {
1193
1194 NullabilityMapTy B = State->get<NullabilityMap>();
1195
1196 if (B.isEmpty())
1197 return;
1198
1199 Out << Sep << NL;
1200
1201 for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1202 Out << I->first << " : ";
1203 I->second.print(Out);
1204 Out << NL;
1205 }
1206}
1207
Gabor Horvath29307352015-09-14 18:31:34 +00001208#define REGISTER_CHECKER(name, trackingRequired) \
Gabor Horvath28690922015-08-26 23:17:43 +00001209 void ento::register##name##Checker(CheckerManager &mgr) { \
1210 NullabilityChecker *checker = mgr.registerChecker<NullabilityChecker>(); \
1211 checker->Filter.Check##name = true; \
1212 checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \
Gabor Horvath29307352015-09-14 18:31:34 +00001213 checker->NeedTracking = checker->NeedTracking || trackingRequired; \
Devin Coughlina1d9d752016-03-05 01:32:43 +00001214 checker->NoDiagnoseCallsToSystemHeaders = \
1215 checker->NoDiagnoseCallsToSystemHeaders || \
1216 mgr.getAnalyzerOptions().getBooleanOption( \
1217 "NoDiagnoseCallsToSystemHeaders", false, checker, true); \
Gabor Horvath28690922015-08-26 23:17:43 +00001218 }
1219
Gabor Horvath29307352015-09-14 18:31:34 +00001220// The checks are likely to be turned on by default and it is possible to do
1221// them without tracking any nullability related information. As an optimization
1222// no nullability information will be tracked when only these two checks are
1223// enables.
1224REGISTER_CHECKER(NullPassedToNonnull, false)
1225REGISTER_CHECKER(NullReturnedFromNonnull, false)
1226
1227REGISTER_CHECKER(NullableDereferenced, true)
1228REGISTER_CHECKER(NullablePassedToNonnull, true)
1229REGISTER_CHECKER(NullableReturnedFromNonnull, true)