NullabilityChecker.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. //===-- NullabilityChecker.cpp - Nullability checker ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This checker tries to find nullability violations. There are several kinds of
  10. // possible violations:
  11. // * Null pointer is passed to a pointer which has a _Nonnull type.
  12. // * Null pointer is returned from a function which has a _Nonnull return type.
  13. // * Nullable pointer is passed to a pointer which has a _Nonnull type.
  14. // * Nullable pointer is returned from a function which has a _Nonnull return
  15. // type.
  16. // * Nullable pointer is dereferenced.
  17. //
  18. // This checker propagates the nullability information of the pointers and looks
  19. // for the patterns that are described above. Explicit casts are trusted and are
  20. // considered a way to suppress false positives for this checker. The other way
  21. // to suppress warnings would be to add asserts or guarding if statements to the
  22. // code. In addition to the nullability propagation this checker also uses some
  23. // heuristics to suppress potential false positives.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  27. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  28. #include "clang/StaticAnalyzer/Core/Checker.h"
  29. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  30. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
  31. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  32. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  33. #include "llvm/ADT/StringExtras.h"
  34. #include "llvm/Support/Path.h"
  35. using namespace clang;
  36. using namespace ento;
  37. namespace {
  38. /// Returns the most nullable nullability. This is used for message expressions
  39. /// like [receiver method], where the nullability of this expression is either
  40. /// the nullability of the receiver or the nullability of the return type of the
  41. /// method, depending on which is more nullable. Contradicted is considered to
  42. /// be the most nullable, to avoid false positive results.
  43. Nullability getMostNullable(Nullability Lhs, Nullability Rhs) {
  44. return static_cast<Nullability>(
  45. std::min(static_cast<char>(Lhs), static_cast<char>(Rhs)));
  46. }
  47. const char *getNullabilityString(Nullability Nullab) {
  48. switch (Nullab) {
  49. case Nullability::Contradicted:
  50. return "contradicted";
  51. case Nullability::Nullable:
  52. return "nullable";
  53. case Nullability::Unspecified:
  54. return "unspecified";
  55. case Nullability::Nonnull:
  56. return "nonnull";
  57. }
  58. llvm_unreachable("Unexpected enumeration.");
  59. return "";
  60. }
  61. // These enums are used as an index to ErrorMessages array.
  62. enum class ErrorKind : int {
  63. NilAssignedToNonnull,
  64. NilPassedToNonnull,
  65. NilReturnedToNonnull,
  66. NullableAssignedToNonnull,
  67. NullableReturnedToNonnull,
  68. NullableDereferenced,
  69. NullablePassedToNonnull
  70. };
  71. class NullabilityChecker
  72. : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
  73. check::PostCall, check::PostStmt<ExplicitCastExpr>,
  74. check::PostObjCMessage, check::DeadSymbols,
  75. check::Location, check::Event<ImplicitNullDerefEvent>> {
  76. public:
  77. // If true, the checker will not diagnose nullabilility issues for calls
  78. // to system headers. This option is motivated by the observation that large
  79. // projects may have many nullability warnings. These projects may
  80. // find warnings about nullability annotations that they have explicitly
  81. // added themselves higher priority to fix than warnings on calls to system
  82. // libraries.
  83. DefaultBool NoDiagnoseCallsToSystemHeaders;
  84. void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
  85. void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const;
  86. void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  87. void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
  88. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  89. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  90. void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
  91. void checkEvent(ImplicitNullDerefEvent Event) const;
  92. void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
  93. CheckerContext &C) const;
  94. void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
  95. const char *Sep) const override;
  96. enum CheckKind {
  97. CK_NullPassedToNonnull,
  98. CK_NullReturnedFromNonnull,
  99. CK_NullableDereferenced,
  100. CK_NullablePassedToNonnull,
  101. CK_NullableReturnedFromNonnull,
  102. CK_NumCheckKinds
  103. };
  104. DefaultBool ChecksEnabled[CK_NumCheckKinds];
  105. CheckerNameRef CheckNames[CK_NumCheckKinds];
  106. mutable std::unique_ptr<BugType> BTs[CK_NumCheckKinds];
  107. const std::unique_ptr<BugType> &getBugType(CheckKind Kind) const {
  108. if (!BTs[Kind])
  109. BTs[Kind].reset(new BugType(CheckNames[Kind], "Nullability",
  110. categories::MemoryError));
  111. return BTs[Kind];
  112. }
  113. // When set to false no nullability information will be tracked in
  114. // NullabilityMap. It is possible to catch errors like passing a null pointer
  115. // to a callee that expects nonnull argument without the information that is
  116. // stroed in the NullabilityMap. This is an optimization.
  117. DefaultBool NeedTracking;
  118. private:
  119. class NullabilityBugVisitor : public BugReporterVisitor {
  120. public:
  121. NullabilityBugVisitor(const MemRegion *M) : Region(M) {}
  122. void Profile(llvm::FoldingSetNodeID &ID) const override {
  123. static int X = 0;
  124. ID.AddPointer(&X);
  125. ID.AddPointer(Region);
  126. }
  127. PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
  128. BugReporterContext &BRC,
  129. PathSensitiveBugReport &BR) override;
  130. private:
  131. // The tracked region.
  132. const MemRegion *Region;
  133. };
  134. /// When any of the nonnull arguments of the analyzed function is null, do not
  135. /// report anything and turn off the check.
  136. ///
  137. /// When \p SuppressPath is set to true, no more bugs will be reported on this
  138. /// path by this checker.
  139. void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
  140. ExplodedNode *N, const MemRegion *Region,
  141. CheckerContext &C,
  142. const Stmt *ValueExpr = nullptr,
  143. bool SuppressPath = false) const;
  144. void reportBug(StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
  145. const MemRegion *Region, BugReporter &BR,
  146. const Stmt *ValueExpr = nullptr) const {
  147. const std::unique_ptr<BugType> &BT = getBugType(CK);
  148. auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
  149. if (Region) {
  150. R->markInteresting(Region);
  151. R->addVisitor<NullabilityBugVisitor>(Region);
  152. }
  153. if (ValueExpr) {
  154. R->addRange(ValueExpr->getSourceRange());
  155. if (Error == ErrorKind::NilAssignedToNonnull ||
  156. Error == ErrorKind::NilPassedToNonnull ||
  157. Error == ErrorKind::NilReturnedToNonnull)
  158. if (const auto *Ex = dyn_cast<Expr>(ValueExpr))
  159. bugreporter::trackExpressionValue(N, Ex, *R);
  160. }
  161. BR.emitReport(std::move(R));
  162. }
  163. /// If an SVal wraps a region that should be tracked, it will return a pointer
  164. /// to the wrapped region. Otherwise it will return a nullptr.
  165. const SymbolicRegion *getTrackRegion(SVal Val,
  166. bool CheckSuperRegion = false) const;
  167. /// Returns true if the call is diagnosable in the current analyzer
  168. /// configuration.
  169. bool isDiagnosableCall(const CallEvent &Call) const {
  170. if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader())
  171. return false;
  172. return true;
  173. }
  174. };
  175. class NullabilityState {
  176. public:
  177. NullabilityState(Nullability Nullab, const Stmt *Source = nullptr)
  178. : Nullab(Nullab), Source(Source) {}
  179. const Stmt *getNullabilitySource() const { return Source; }
  180. Nullability getValue() const { return Nullab; }
  181. void Profile(llvm::FoldingSetNodeID &ID) const {
  182. ID.AddInteger(static_cast<char>(Nullab));
  183. ID.AddPointer(Source);
  184. }
  185. void print(raw_ostream &Out) const {
  186. Out << getNullabilityString(Nullab) << "\n";
  187. }
  188. private:
  189. Nullability Nullab;
  190. // Source is the expression which determined the nullability. For example in a
  191. // message like [nullable nonnull_returning] has nullable nullability, because
  192. // the receiver is nullable. Here the receiver will be the source of the
  193. // nullability. This is useful information when the diagnostics are generated.
  194. const Stmt *Source;
  195. };
  196. bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
  197. return Lhs.getValue() == Rhs.getValue() &&
  198. Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
  199. }
  200. } // end anonymous namespace
  201. REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *,
  202. NullabilityState)
  203. // We say "the nullability type invariant is violated" when a location with a
  204. // non-null type contains NULL or a function with a non-null return type returns
  205. // NULL. Violations of the nullability type invariant can be detected either
  206. // directly (for example, when NULL is passed as an argument to a nonnull
  207. // parameter) or indirectly (for example, when, inside a function, the
  208. // programmer defensively checks whether a nonnull parameter contains NULL and
  209. // finds that it does).
  210. //
  211. // As a matter of policy, the nullability checker typically warns on direct
  212. // violations of the nullability invariant (although it uses various
  213. // heuristics to suppress warnings in some cases) but will not warn if the
  214. // invariant has already been violated along the path (either directly or
  215. // indirectly). As a practical matter, this prevents the analyzer from
  216. // (1) warning on defensive code paths where a nullability precondition is
  217. // determined to have been violated, (2) warning additional times after an
  218. // initial direct violation has been discovered, and (3) warning after a direct
  219. // violation that has been implicitly or explicitly suppressed (for
  220. // example, with a cast of NULL to _Nonnull). In essence, once an invariant
  221. // violation is detected on a path, this checker will be essentially turned off
  222. // for the rest of the analysis
  223. //
  224. // The analyzer takes this approach (rather than generating a sink node) to
  225. // ensure coverage of defensive paths, which may be important for backwards
  226. // compatibility in codebases that were developed without nullability in mind.
  227. REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool)
  228. enum class NullConstraint { IsNull, IsNotNull, Unknown };
  229. static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val,
  230. ProgramStateRef State) {
  231. ConditionTruthVal Nullness = State->isNull(Val);
  232. if (Nullness.isConstrainedFalse())
  233. return NullConstraint::IsNotNull;
  234. if (Nullness.isConstrainedTrue())
  235. return NullConstraint::IsNull;
  236. return NullConstraint::Unknown;
  237. }
  238. const SymbolicRegion *
  239. NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const {
  240. if (!NeedTracking)
  241. return nullptr;
  242. auto RegionSVal = Val.getAs<loc::MemRegionVal>();
  243. if (!RegionSVal)
  244. return nullptr;
  245. const MemRegion *Region = RegionSVal->getRegion();
  246. if (CheckSuperRegion) {
  247. if (auto FieldReg = Region->getAs<FieldRegion>())
  248. return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
  249. if (auto ElementReg = Region->getAs<ElementRegion>())
  250. return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
  251. }
  252. return dyn_cast<SymbolicRegion>(Region);
  253. }
  254. PathDiagnosticPieceRef NullabilityChecker::NullabilityBugVisitor::VisitNode(
  255. const ExplodedNode *N, BugReporterContext &BRC,
  256. PathSensitiveBugReport &BR) {
  257. ProgramStateRef State = N->getState();
  258. ProgramStateRef StatePrev = N->getFirstPred()->getState();
  259. const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
  260. const NullabilityState *TrackedNullabPrev =
  261. StatePrev->get<NullabilityMap>(Region);
  262. if (!TrackedNullab)
  263. return nullptr;
  264. if (TrackedNullabPrev &&
  265. TrackedNullabPrev->getValue() == TrackedNullab->getValue())
  266. return nullptr;
  267. // Retrieve the associated statement.
  268. const Stmt *S = TrackedNullab->getNullabilitySource();
  269. if (!S || S->getBeginLoc().isInvalid()) {
  270. S = N->getStmtForDiagnostics();
  271. }
  272. if (!S)
  273. return nullptr;
  274. std::string InfoText =
  275. (llvm::Twine("Nullability '") +
  276. getNullabilityString(TrackedNullab->getValue()) + "' is inferred")
  277. .str();
  278. // Generate the extra diagnostic.
  279. PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
  280. N->getLocationContext());
  281. return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
  282. }
  283. /// Returns true when the value stored at the given location has been
  284. /// constrained to null after being passed through an object of nonnnull type.
  285. static bool checkValueAtLValForInvariantViolation(ProgramStateRef State,
  286. SVal LV, QualType T) {
  287. if (getNullabilityAnnotation(T) != Nullability::Nonnull)
  288. return false;
  289. auto RegionVal = LV.getAs<loc::MemRegionVal>();
  290. if (!RegionVal)
  291. return false;
  292. // If the value was constrained to null *after* it was passed through that
  293. // location, it could not have been a concrete pointer *when* it was passed.
  294. // In that case we would have handled the situation when the value was
  295. // bound to that location, by emitting (or not emitting) a report.
  296. // Therefore we are only interested in symbolic regions that can be either
  297. // null or non-null depending on the value of their respective symbol.
  298. auto StoredVal = State->getSVal(*RegionVal).getAs<loc::MemRegionVal>();
  299. if (!StoredVal || !isa<SymbolicRegion>(StoredVal->getRegion()))
  300. return false;
  301. if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull)
  302. return true;
  303. return false;
  304. }
  305. static bool
  306. checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params,
  307. ProgramStateRef State,
  308. const LocationContext *LocCtxt) {
  309. for (const auto *ParamDecl : Params) {
  310. if (ParamDecl->isParameterPack())
  311. break;
  312. SVal LV = State->getLValue(ParamDecl, LocCtxt);
  313. if (checkValueAtLValForInvariantViolation(State, LV,
  314. ParamDecl->getType())) {
  315. return true;
  316. }
  317. }
  318. return false;
  319. }
  320. static bool
  321. checkSelfIvarsForInvariantViolation(ProgramStateRef State,
  322. const LocationContext *LocCtxt) {
  323. auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl());
  324. if (!MD || !MD->isInstanceMethod())
  325. return false;
  326. const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl();
  327. if (!SelfDecl)
  328. return false;
  329. SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt));
  330. const ObjCObjectPointerType *SelfType =
  331. dyn_cast<ObjCObjectPointerType>(SelfDecl->getType());
  332. if (!SelfType)
  333. return false;
  334. const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl();
  335. if (!ID)
  336. return false;
  337. for (const auto *IvarDecl : ID->ivars()) {
  338. SVal LV = State->getLValue(IvarDecl, SelfVal);
  339. if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) {
  340. return true;
  341. }
  342. }
  343. return false;
  344. }
  345. static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N,
  346. CheckerContext &C) {
  347. if (State->get<InvariantViolated>())
  348. return true;
  349. const LocationContext *LocCtxt = C.getLocationContext();
  350. const Decl *D = LocCtxt->getDecl();
  351. if (!D)
  352. return false;
  353. ArrayRef<ParmVarDecl*> Params;
  354. if (const auto *BD = dyn_cast<BlockDecl>(D))
  355. Params = BD->parameters();
  356. else if (const auto *FD = dyn_cast<FunctionDecl>(D))
  357. Params = FD->parameters();
  358. else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  359. Params = MD->parameters();
  360. else
  361. return false;
  362. if (checkParamsForPreconditionViolation(Params, State, LocCtxt) ||
  363. checkSelfIvarsForInvariantViolation(State, LocCtxt)) {
  364. if (!N->isSink())
  365. C.addTransition(State->set<InvariantViolated>(true), N);
  366. return true;
  367. }
  368. return false;
  369. }
  370. void NullabilityChecker::reportBugIfInvariantHolds(
  371. StringRef Msg, ErrorKind Error, CheckKind CK, ExplodedNode *N,
  372. const MemRegion *Region, CheckerContext &C, const Stmt *ValueExpr,
  373. bool SuppressPath) const {
  374. ProgramStateRef OriginalState = N->getState();
  375. if (checkInvariantViolation(OriginalState, N, C))
  376. return;
  377. if (SuppressPath) {
  378. OriginalState = OriginalState->set<InvariantViolated>(true);
  379. N = C.addTransition(OriginalState, N);
  380. }
  381. reportBug(Msg, Error, CK, N, Region, C.getBugReporter(), ValueExpr);
  382. }
  383. /// Cleaning up the program state.
  384. void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
  385. CheckerContext &C) const {
  386. ProgramStateRef State = C.getState();
  387. NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
  388. for (NullabilityMapTy::iterator I = Nullabilities.begin(),
  389. E = Nullabilities.end();
  390. I != E; ++I) {
  391. const auto *Region = I->first->getAs<SymbolicRegion>();
  392. assert(Region && "Non-symbolic region is tracked.");
  393. if (SR.isDead(Region->getSymbol())) {
  394. State = State->remove<NullabilityMap>(I->first);
  395. }
  396. }
  397. // When one of the nonnull arguments are constrained to be null, nullability
  398. // preconditions are violated. It is not enough to check this only when we
  399. // actually report an error, because at that time interesting symbols might be
  400. // reaped.
  401. if (checkInvariantViolation(State, C.getPredecessor(), C))
  402. return;
  403. C.addTransition(State);
  404. }
  405. /// This callback triggers when a pointer is dereferenced and the analyzer does
  406. /// not know anything about the value of that pointer. When that pointer is
  407. /// nullable, this code emits a warning.
  408. void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const {
  409. if (Event.SinkNode->getState()->get<InvariantViolated>())
  410. return;
  411. const MemRegion *Region =
  412. getTrackRegion(Event.Location, /*CheckSuperRegion=*/true);
  413. if (!Region)
  414. return;
  415. ProgramStateRef State = Event.SinkNode->getState();
  416. const NullabilityState *TrackedNullability =
  417. State->get<NullabilityMap>(Region);
  418. if (!TrackedNullability)
  419. return;
  420. if (ChecksEnabled[CK_NullableDereferenced] &&
  421. TrackedNullability->getValue() == Nullability::Nullable) {
  422. BugReporter &BR = *Event.BR;
  423. // Do not suppress errors on defensive code paths, because dereferencing
  424. // a nullable pointer is always an error.
  425. if (Event.IsDirectDereference)
  426. reportBug("Nullable pointer is dereferenced",
  427. ErrorKind::NullableDereferenced, CK_NullableDereferenced,
  428. Event.SinkNode, Region, BR);
  429. else {
  430. reportBug("Nullable pointer is passed to a callee that requires a "
  431. "non-null",
  432. ErrorKind::NullablePassedToNonnull, CK_NullableDereferenced,
  433. Event.SinkNode, Region, BR);
  434. }
  435. }
  436. }
  437. // Whenever we see a load from a typed memory region that's been annotated as
  438. // 'nonnull', we want to trust the user on that and assume that it is is indeed
  439. // non-null.
  440. //
  441. // We do so even if the value is known to have been assigned to null.
  442. // The user should be warned on assigning the null value to a non-null pointer
  443. // as opposed to warning on the later dereference of this pointer.
  444. //
  445. // \code
  446. // int * _Nonnull var = 0; // we want to warn the user here...
  447. // // . . .
  448. // *var = 42; // ...and not here
  449. // \endcode
  450. void NullabilityChecker::checkLocation(SVal Location, bool IsLoad,
  451. const Stmt *S,
  452. CheckerContext &Context) const {
  453. // We should care only about loads.
  454. // The main idea is to add a constraint whenever we're loading a value from
  455. // an annotated pointer type.
  456. if (!IsLoad)
  457. return;
  458. // Annotations that we want to consider make sense only for types.
  459. const auto *Region =
  460. dyn_cast_or_null<TypedValueRegion>(Location.getAsRegion());
  461. if (!Region)
  462. return;
  463. ProgramStateRef State = Context.getState();
  464. auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
  465. if (!StoredVal)
  466. return;
  467. Nullability NullabilityOfTheLoadedValue =
  468. getNullabilityAnnotation(Region->getValueType());
  469. if (NullabilityOfTheLoadedValue == Nullability::Nonnull) {
  470. // It doesn't matter what we think about this particular pointer, it should
  471. // be considered non-null as annotated by the developer.
  472. if (ProgramStateRef NewState = State->assume(*StoredVal, true)) {
  473. Context.addTransition(NewState);
  474. }
  475. }
  476. }
  477. /// Find the outermost subexpression of E that is not an implicit cast.
  478. /// This looks through the implicit casts to _Nonnull that ARC adds to
  479. /// return expressions of ObjC types when the return type of the function or
  480. /// method is non-null but the express is not.
  481. static const Expr *lookThroughImplicitCasts(const Expr *E) {
  482. return E->IgnoreImpCasts();
  483. }
  484. /// This method check when nullable pointer or null value is returned from a
  485. /// function that has nonnull return type.
  486. void NullabilityChecker::checkPreStmt(const ReturnStmt *S,
  487. CheckerContext &C) const {
  488. auto RetExpr = S->getRetValue();
  489. if (!RetExpr)
  490. return;
  491. if (!RetExpr->getType()->isAnyPointerType())
  492. return;
  493. ProgramStateRef State = C.getState();
  494. if (State->get<InvariantViolated>())
  495. return;
  496. auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>();
  497. if (!RetSVal)
  498. return;
  499. bool InSuppressedMethodFamily = false;
  500. QualType RequiredRetType;
  501. AnalysisDeclContext *DeclCtxt =
  502. C.getLocationContext()->getAnalysisDeclContext();
  503. const Decl *D = DeclCtxt->getDecl();
  504. if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  505. // HACK: This is a big hammer to avoid warning when there are defensive
  506. // nil checks in -init and -copy methods. We should add more sophisticated
  507. // logic here to suppress on common defensive idioms but still
  508. // warn when there is a likely problem.
  509. ObjCMethodFamily Family = MD->getMethodFamily();
  510. if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family)
  511. InSuppressedMethodFamily = true;
  512. RequiredRetType = MD->getReturnType();
  513. } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  514. RequiredRetType = FD->getReturnType();
  515. } else {
  516. return;
  517. }
  518. NullConstraint Nullness = getNullConstraint(*RetSVal, State);
  519. Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType);
  520. // If the returned value is null but the type of the expression
  521. // generating it is nonnull then we will suppress the diagnostic.
  522. // This enables explicit suppression when returning a nil literal in a
  523. // function with a _Nonnull return type:
  524. // return (NSString * _Nonnull)0;
  525. Nullability RetExprTypeLevelNullability =
  526. getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType());
  527. bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull &&
  528. Nullness == NullConstraint::IsNull);
  529. if (ChecksEnabled[CK_NullReturnedFromNonnull] && NullReturnedFromNonNull &&
  530. RetExprTypeLevelNullability != Nullability::Nonnull &&
  531. !InSuppressedMethodFamily && C.getLocationContext()->inTopFrame()) {
  532. static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull");
  533. ExplodedNode *N = C.generateErrorNode(State, &Tag);
  534. if (!N)
  535. return;
  536. SmallString<256> SBuf;
  537. llvm::raw_svector_ostream OS(SBuf);
  538. OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null");
  539. OS << " returned from a " << C.getDeclDescription(D) <<
  540. " that is expected to return a non-null value";
  541. reportBugIfInvariantHolds(OS.str(), ErrorKind::NilReturnedToNonnull,
  542. CK_NullReturnedFromNonnull, N, nullptr, C,
  543. RetExpr);
  544. return;
  545. }
  546. // If null was returned from a non-null function, mark the nullability
  547. // invariant as violated even if the diagnostic was suppressed.
  548. if (NullReturnedFromNonNull) {
  549. State = State->set<InvariantViolated>(true);
  550. C.addTransition(State);
  551. return;
  552. }
  553. const MemRegion *Region = getTrackRegion(*RetSVal);
  554. if (!Region)
  555. return;
  556. const NullabilityState *TrackedNullability =
  557. State->get<NullabilityMap>(Region);
  558. if (TrackedNullability) {
  559. Nullability TrackedNullabValue = TrackedNullability->getValue();
  560. if (ChecksEnabled[CK_NullableReturnedFromNonnull] &&
  561. Nullness != NullConstraint::IsNotNull &&
  562. TrackedNullabValue == Nullability::Nullable &&
  563. RequiredNullability == Nullability::Nonnull) {
  564. static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull");
  565. ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
  566. SmallString<256> SBuf;
  567. llvm::raw_svector_ostream OS(SBuf);
  568. OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) <<
  569. " that is expected to return a non-null value";
  570. reportBugIfInvariantHolds(OS.str(), ErrorKind::NullableReturnedToNonnull,
  571. CK_NullableReturnedFromNonnull, N, Region, C);
  572. }
  573. return;
  574. }
  575. if (RequiredNullability == Nullability::Nullable) {
  576. State = State->set<NullabilityMap>(Region,
  577. NullabilityState(RequiredNullability,
  578. S));
  579. C.addTransition(State);
  580. }
  581. }
  582. /// This callback warns when a nullable pointer or a null value is passed to a
  583. /// function that expects its argument to be nonnull.
  584. void NullabilityChecker::checkPreCall(const CallEvent &Call,
  585. CheckerContext &C) const {
  586. if (!Call.getDecl())
  587. return;
  588. ProgramStateRef State = C.getState();
  589. if (State->get<InvariantViolated>())
  590. return;
  591. ProgramStateRef OrigState = State;
  592. unsigned Idx = 0;
  593. for (const ParmVarDecl *Param : Call.parameters()) {
  594. if (Param->isParameterPack())
  595. break;
  596. if (Idx >= Call.getNumArgs())
  597. break;
  598. const Expr *ArgExpr = Call.getArgExpr(Idx);
  599. auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
  600. if (!ArgSVal)
  601. continue;
  602. if (!Param->getType()->isAnyPointerType() &&
  603. !Param->getType()->isReferenceType())
  604. continue;
  605. NullConstraint Nullness = getNullConstraint(*ArgSVal, State);
  606. Nullability RequiredNullability =
  607. getNullabilityAnnotation(Param->getType());
  608. Nullability ArgExprTypeLevelNullability =
  609. getNullabilityAnnotation(ArgExpr->getType());
  610. unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
  611. if (ChecksEnabled[CK_NullPassedToNonnull] &&
  612. Nullness == NullConstraint::IsNull &&
  613. ArgExprTypeLevelNullability != Nullability::Nonnull &&
  614. RequiredNullability == Nullability::Nonnull &&
  615. isDiagnosableCall(Call)) {
  616. ExplodedNode *N = C.generateErrorNode(State);
  617. if (!N)
  618. return;
  619. SmallString<256> SBuf;
  620. llvm::raw_svector_ostream OS(SBuf);
  621. OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null");
  622. OS << " passed to a callee that requires a non-null " << ParamIdx
  623. << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
  624. reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull,
  625. CK_NullPassedToNonnull, N, nullptr, C, ArgExpr,
  626. /*SuppressPath=*/false);
  627. return;
  628. }
  629. const MemRegion *Region = getTrackRegion(*ArgSVal);
  630. if (!Region)
  631. continue;
  632. const NullabilityState *TrackedNullability =
  633. State->get<NullabilityMap>(Region);
  634. if (TrackedNullability) {
  635. if (Nullness == NullConstraint::IsNotNull ||
  636. TrackedNullability->getValue() != Nullability::Nullable)
  637. continue;
  638. if (ChecksEnabled[CK_NullablePassedToNonnull] &&
  639. RequiredNullability == Nullability::Nonnull &&
  640. isDiagnosableCall(Call)) {
  641. ExplodedNode *N = C.addTransition(State);
  642. SmallString<256> SBuf;
  643. llvm::raw_svector_ostream OS(SBuf);
  644. OS << "Nullable pointer is passed to a callee that requires a non-null "
  645. << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter";
  646. reportBugIfInvariantHolds(OS.str(), ErrorKind::NullablePassedToNonnull,
  647. CK_NullablePassedToNonnull, N, Region, C,
  648. ArgExpr, /*SuppressPath=*/true);
  649. return;
  650. }
  651. if (ChecksEnabled[CK_NullableDereferenced] &&
  652. Param->getType()->isReferenceType()) {
  653. ExplodedNode *N = C.addTransition(State);
  654. reportBugIfInvariantHolds("Nullable pointer is dereferenced",
  655. ErrorKind::NullableDereferenced,
  656. CK_NullableDereferenced, N, Region, C,
  657. ArgExpr, /*SuppressPath=*/true);
  658. return;
  659. }
  660. continue;
  661. }
  662. }
  663. if (State != OrigState)
  664. C.addTransition(State);
  665. }
  666. /// Suppress the nullability warnings for some functions.
  667. void NullabilityChecker::checkPostCall(const CallEvent &Call,
  668. CheckerContext &C) const {
  669. auto Decl = Call.getDecl();
  670. if (!Decl)
  671. return;
  672. // ObjC Messages handles in a different callback.
  673. if (Call.getKind() == CE_ObjCMessage)
  674. return;
  675. const FunctionType *FuncType = Decl->getFunctionType();
  676. if (!FuncType)
  677. return;
  678. QualType ReturnType = FuncType->getReturnType();
  679. if (!ReturnType->isAnyPointerType())
  680. return;
  681. ProgramStateRef State = C.getState();
  682. if (State->get<InvariantViolated>())
  683. return;
  684. const MemRegion *Region = getTrackRegion(Call.getReturnValue());
  685. if (!Region)
  686. return;
  687. // CG headers are misannotated. Do not warn for symbols that are the results
  688. // of CG calls.
  689. const SourceManager &SM = C.getSourceManager();
  690. StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getBeginLoc()));
  691. if (llvm::sys::path::filename(FilePath).startswith("CG")) {
  692. State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
  693. C.addTransition(State);
  694. return;
  695. }
  696. const NullabilityState *TrackedNullability =
  697. State->get<NullabilityMap>(Region);
  698. if (!TrackedNullability &&
  699. getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
  700. State = State->set<NullabilityMap>(Region, Nullability::Nullable);
  701. C.addTransition(State);
  702. }
  703. }
  704. static Nullability getReceiverNullability(const ObjCMethodCall &M,
  705. ProgramStateRef State) {
  706. if (M.isReceiverSelfOrSuper()) {
  707. // For super and super class receivers we assume that the receiver is
  708. // nonnull.
  709. return Nullability::Nonnull;
  710. }
  711. // Otherwise look up nullability in the state.
  712. SVal Receiver = M.getReceiverSVal();
  713. if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) {
  714. // If the receiver is constrained to be nonnull, assume that it is nonnull
  715. // regardless of its type.
  716. NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State);
  717. if (Nullness == NullConstraint::IsNotNull)
  718. return Nullability::Nonnull;
  719. }
  720. auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>();
  721. if (ValueRegionSVal) {
  722. const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
  723. assert(SelfRegion);
  724. const NullabilityState *TrackedSelfNullability =
  725. State->get<NullabilityMap>(SelfRegion);
  726. if (TrackedSelfNullability)
  727. return TrackedSelfNullability->getValue();
  728. }
  729. return Nullability::Unspecified;
  730. }
  731. /// Calculate the nullability of the result of a message expr based on the
  732. /// nullability of the receiver, the nullability of the return value, and the
  733. /// constraints.
  734. void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M,
  735. CheckerContext &C) const {
  736. auto Decl = M.getDecl();
  737. if (!Decl)
  738. return;
  739. QualType RetType = Decl->getReturnType();
  740. if (!RetType->isAnyPointerType())
  741. return;
  742. ProgramStateRef State = C.getState();
  743. if (State->get<InvariantViolated>())
  744. return;
  745. const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue());
  746. if (!ReturnRegion)
  747. return;
  748. auto Interface = Decl->getClassInterface();
  749. auto Name = Interface ? Interface->getName() : "";
  750. // In order to reduce the noise in the diagnostics generated by this checker,
  751. // some framework and programming style based heuristics are used. These
  752. // heuristics are for Cocoa APIs which have NS prefix.
  753. if (Name.startswith("NS")) {
  754. // Developers rely on dynamic invariants such as an item should be available
  755. // in a collection, or a collection is not empty often. Those invariants can
  756. // not be inferred by any static analysis tool. To not to bother the users
  757. // with too many false positives, every item retrieval function should be
  758. // ignored for collections. The instance methods of dictionaries in Cocoa
  759. // are either item retrieval related or not interesting nullability wise.
  760. // Using this fact, to keep the code easier to read just ignore the return
  761. // value of every instance method of dictionaries.
  762. if (M.isInstanceMessage() && Name.contains("Dictionary")) {
  763. State =
  764. State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
  765. C.addTransition(State);
  766. return;
  767. }
  768. // For similar reasons ignore some methods of Cocoa arrays.
  769. StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0);
  770. if (Name.contains("Array") &&
  771. (FirstSelectorSlot == "firstObject" ||
  772. FirstSelectorSlot == "lastObject")) {
  773. State =
  774. State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
  775. C.addTransition(State);
  776. return;
  777. }
  778. // Encoding related methods of string should not fail when lossless
  779. // encodings are used. Using lossless encodings is so frequent that ignoring
  780. // this class of methods reduced the emitted diagnostics by about 30% on
  781. // some projects (and all of that was false positives).
  782. if (Name.contains("String")) {
  783. for (auto Param : M.parameters()) {
  784. if (Param->getName() == "encoding") {
  785. State = State->set<NullabilityMap>(ReturnRegion,
  786. Nullability::Contradicted);
  787. C.addTransition(State);
  788. return;
  789. }
  790. }
  791. }
  792. }
  793. const ObjCMessageExpr *Message = M.getOriginExpr();
  794. Nullability SelfNullability = getReceiverNullability(M, State);
  795. const NullabilityState *NullabilityOfReturn =
  796. State->get<NullabilityMap>(ReturnRegion);
  797. if (NullabilityOfReturn) {
  798. // When we have a nullability tracked for the return value, the nullability
  799. // of the expression will be the most nullable of the receiver and the
  800. // return value.
  801. Nullability RetValTracked = NullabilityOfReturn->getValue();
  802. Nullability ComputedNullab =
  803. getMostNullable(RetValTracked, SelfNullability);
  804. if (ComputedNullab != RetValTracked &&
  805. ComputedNullab != Nullability::Unspecified) {
  806. const Stmt *NullabilitySource =
  807. ComputedNullab == RetValTracked
  808. ? NullabilityOfReturn->getNullabilitySource()
  809. : Message->getInstanceReceiver();
  810. State = State->set<NullabilityMap>(
  811. ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
  812. C.addTransition(State);
  813. }
  814. return;
  815. }
  816. // No tracked information. Use static type information for return value.
  817. Nullability RetNullability = getNullabilityAnnotation(RetType);
  818. // Properties might be computed. For this reason the static analyzer creates a
  819. // new symbol each time an unknown property is read. To avoid false pozitives
  820. // do not treat unknown properties as nullable, even when they explicitly
  821. // marked nullable.
  822. if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined)
  823. RetNullability = Nullability::Nonnull;
  824. Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
  825. if (ComputedNullab == Nullability::Nullable) {
  826. const Stmt *NullabilitySource = ComputedNullab == RetNullability
  827. ? Message
  828. : Message->getInstanceReceiver();
  829. State = State->set<NullabilityMap>(
  830. ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
  831. C.addTransition(State);
  832. }
  833. }
  834. /// Explicit casts are trusted. If there is a disagreement in the nullability
  835. /// annotations in the destination and the source or '0' is casted to nonnull
  836. /// track the value as having contraditory nullability. This will allow users to
  837. /// suppress warnings.
  838. void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE,
  839. CheckerContext &C) const {
  840. QualType OriginType = CE->getSubExpr()->getType();
  841. QualType DestType = CE->getType();
  842. if (!OriginType->isAnyPointerType())
  843. return;
  844. if (!DestType->isAnyPointerType())
  845. return;
  846. ProgramStateRef State = C.getState();
  847. if (State->get<InvariantViolated>())
  848. return;
  849. Nullability DestNullability = getNullabilityAnnotation(DestType);
  850. // No explicit nullability in the destination type, so this cast does not
  851. // change the nullability.
  852. if (DestNullability == Nullability::Unspecified)
  853. return;
  854. auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
  855. const MemRegion *Region = getTrackRegion(*RegionSVal);
  856. if (!Region)
  857. return;
  858. // When 0 is converted to nonnull mark it as contradicted.
  859. if (DestNullability == Nullability::Nonnull) {
  860. NullConstraint Nullness = getNullConstraint(*RegionSVal, State);
  861. if (Nullness == NullConstraint::IsNull) {
  862. State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
  863. C.addTransition(State);
  864. return;
  865. }
  866. }
  867. const NullabilityState *TrackedNullability =
  868. State->get<NullabilityMap>(Region);
  869. if (!TrackedNullability) {
  870. if (DestNullability != Nullability::Nullable)
  871. return;
  872. State = State->set<NullabilityMap>(Region,
  873. NullabilityState(DestNullability, CE));
  874. C.addTransition(State);
  875. return;
  876. }
  877. if (TrackedNullability->getValue() != DestNullability &&
  878. TrackedNullability->getValue() != Nullability::Contradicted) {
  879. State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
  880. C.addTransition(State);
  881. }
  882. }
  883. /// For a given statement performing a bind, attempt to syntactically
  884. /// match the expression resulting in the bound value.
  885. static const Expr * matchValueExprForBind(const Stmt *S) {
  886. // For `x = e` the value expression is the right-hand side.
  887. if (auto *BinOp = dyn_cast<BinaryOperator>(S)) {
  888. if (BinOp->getOpcode() == BO_Assign)
  889. return BinOp->getRHS();
  890. }
  891. // For `int x = e` the value expression is the initializer.
  892. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  893. if (DS->isSingleDecl()) {
  894. auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  895. if (!VD)
  896. return nullptr;
  897. if (const Expr *Init = VD->getInit())
  898. return Init;
  899. }
  900. }
  901. return nullptr;
  902. }
  903. /// Returns true if \param S is a DeclStmt for a local variable that
  904. /// ObjC automated reference counting initialized with zero.
  905. static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
  906. // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
  907. // prevents false positives when a _Nonnull local variable cannot be
  908. // initialized with an initialization expression:
  909. // NSString * _Nonnull s; // no-warning
  910. // @autoreleasepool {
  911. // s = ...
  912. // }
  913. //
  914. // FIXME: We should treat implicitly zero-initialized _Nonnull locals as
  915. // uninitialized in Sema's UninitializedValues analysis to warn when a use of
  916. // the zero-initialized definition will unexpectedly yield nil.
  917. // Locals are only zero-initialized when automated reference counting
  918. // is turned on.
  919. if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
  920. return false;
  921. auto *DS = dyn_cast<DeclStmt>(S);
  922. if (!DS || !DS->isSingleDecl())
  923. return false;
  924. auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  925. if (!VD)
  926. return false;
  927. // Sema only zero-initializes locals with ObjCLifetimes.
  928. if(!VD->getType().getQualifiers().hasObjCLifetime())
  929. return false;
  930. const Expr *Init = VD->getInit();
  931. assert(Init && "ObjC local under ARC without initializer");
  932. // Return false if the local is explicitly initialized (e.g., with '= nil').
  933. if (!isa<ImplicitValueInitExpr>(Init))
  934. return false;
  935. return true;
  936. }
  937. /// Propagate the nullability information through binds and warn when nullable
  938. /// pointer or null symbol is assigned to a pointer with a nonnull type.
  939. void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S,
  940. CheckerContext &C) const {
  941. const TypedValueRegion *TVR =
  942. dyn_cast_or_null<TypedValueRegion>(L.getAsRegion());
  943. if (!TVR)
  944. return;
  945. QualType LocType = TVR->getValueType();
  946. if (!LocType->isAnyPointerType())
  947. return;
  948. ProgramStateRef State = C.getState();
  949. if (State->get<InvariantViolated>())
  950. return;
  951. auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>();
  952. if (!ValDefOrUnknown)
  953. return;
  954. NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State);
  955. Nullability ValNullability = Nullability::Unspecified;
  956. if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
  957. ValNullability = getNullabilityAnnotation(Sym->getType());
  958. Nullability LocNullability = getNullabilityAnnotation(LocType);
  959. // If the type of the RHS expression is nonnull, don't warn. This
  960. // enables explicit suppression with a cast to nonnull.
  961. Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
  962. const Expr *ValueExpr = matchValueExprForBind(S);
  963. if (ValueExpr) {
  964. ValueExprTypeLevelNullability =
  965. getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType());
  966. }
  967. bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
  968. RhsNullness == NullConstraint::IsNull);
  969. if (ChecksEnabled[CK_NullPassedToNonnull] && NullAssignedToNonNull &&
  970. ValNullability != Nullability::Nonnull &&
  971. ValueExprTypeLevelNullability != Nullability::Nonnull &&
  972. !isARCNilInitializedLocal(C, S)) {
  973. static CheckerProgramPointTag Tag(this, "NullPassedToNonnull");
  974. ExplodedNode *N = C.generateErrorNode(State, &Tag);
  975. if (!N)
  976. return;
  977. const Stmt *ValueStmt = S;
  978. if (ValueExpr)
  979. ValueStmt = ValueExpr;
  980. SmallString<256> SBuf;
  981. llvm::raw_svector_ostream OS(SBuf);
  982. OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null");
  983. OS << " assigned to a pointer which is expected to have non-null value";
  984. reportBugIfInvariantHolds(OS.str(), ErrorKind::NilAssignedToNonnull,
  985. CK_NullPassedToNonnull, N, nullptr, C, ValueStmt);
  986. return;
  987. }
  988. // If null was returned from a non-null function, mark the nullability
  989. // invariant as violated even if the diagnostic was suppressed.
  990. if (NullAssignedToNonNull) {
  991. State = State->set<InvariantViolated>(true);
  992. C.addTransition(State);
  993. return;
  994. }
  995. // Intentionally missing case: '0' is bound to a reference. It is handled by
  996. // the DereferenceChecker.
  997. const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
  998. if (!ValueRegion)
  999. return;
  1000. const NullabilityState *TrackedNullability =
  1001. State->get<NullabilityMap>(ValueRegion);
  1002. if (TrackedNullability) {
  1003. if (RhsNullness == NullConstraint::IsNotNull ||
  1004. TrackedNullability->getValue() != Nullability::Nullable)
  1005. return;
  1006. if (ChecksEnabled[CK_NullablePassedToNonnull] &&
  1007. LocNullability == Nullability::Nonnull) {
  1008. static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull");
  1009. ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag);
  1010. reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer "
  1011. "which is expected to have non-null value",
  1012. ErrorKind::NullableAssignedToNonnull,
  1013. CK_NullablePassedToNonnull, N, ValueRegion, C);
  1014. }
  1015. return;
  1016. }
  1017. const auto *BinOp = dyn_cast<BinaryOperator>(S);
  1018. if (ValNullability == Nullability::Nullable) {
  1019. // Trust the static information of the value more than the static
  1020. // information on the location.
  1021. const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
  1022. State = State->set<NullabilityMap>(
  1023. ValueRegion, NullabilityState(ValNullability, NullabilitySource));
  1024. C.addTransition(State);
  1025. return;
  1026. }
  1027. if (LocNullability == Nullability::Nullable) {
  1028. const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
  1029. State = State->set<NullabilityMap>(
  1030. ValueRegion, NullabilityState(LocNullability, NullabilitySource));
  1031. C.addTransition(State);
  1032. }
  1033. }
  1034. void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State,
  1035. const char *NL, const char *Sep) const {
  1036. NullabilityMapTy B = State->get<NullabilityMap>();
  1037. if (State->get<InvariantViolated>())
  1038. Out << Sep << NL
  1039. << "Nullability invariant was violated, warnings suppressed." << NL;
  1040. if (B.isEmpty())
  1041. return;
  1042. if (!State->get<InvariantViolated>())
  1043. Out << Sep << NL;
  1044. for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
  1045. Out << I->first << " : ";
  1046. I->second.print(Out);
  1047. Out << NL;
  1048. }
  1049. }
  1050. void ento::registerNullabilityBase(CheckerManager &mgr) {
  1051. mgr.registerChecker<NullabilityChecker>();
  1052. }
  1053. bool ento::shouldRegisterNullabilityBase(const CheckerManager &mgr) {
  1054. return true;
  1055. }
  1056. #define REGISTER_CHECKER(name, trackingRequired) \
  1057. void ento::register##name##Checker(CheckerManager &mgr) { \
  1058. NullabilityChecker *checker = mgr.getChecker<NullabilityChecker>(); \
  1059. checker->ChecksEnabled[NullabilityChecker::CK_##name] = true; \
  1060. checker->CheckNames[NullabilityChecker::CK_##name] = \
  1061. mgr.getCurrentCheckerName(); \
  1062. checker->NeedTracking = checker->NeedTracking || trackingRequired; \
  1063. checker->NoDiagnoseCallsToSystemHeaders = \
  1064. checker->NoDiagnoseCallsToSystemHeaders || \
  1065. mgr.getAnalyzerOptions().getCheckerBooleanOption( \
  1066. checker, "NoDiagnoseCallsToSystemHeaders", true); \
  1067. } \
  1068. \
  1069. bool ento::shouldRegister##name##Checker(const CheckerManager &mgr) { \
  1070. return true; \
  1071. }
  1072. // The checks are likely to be turned on by default and it is possible to do
  1073. // them without tracking any nullability related information. As an optimization
  1074. // no nullability information will be tracked when only these two checks are
  1075. // enables.
  1076. REGISTER_CHECKER(NullPassedToNonnull, false)
  1077. REGISTER_CHECKER(NullReturnedFromNonnull, false)
  1078. REGISTER_CHECKER(NullableDereferenced, true)
  1079. REGISTER_CHECKER(NullablePassedToNonnull, true)
  1080. REGISTER_CHECKER(NullableReturnedFromNonnull, true)