NullabilityChecker.cpp 52 KB

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