NullabilityChecker.cpp 45 KB

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