BugReporterVisitors.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. // BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- 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 file defines a set of BugReporter "visitors" which can be used to
  11. // enhance the diagnostics reported for a bug.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/ExprObjC.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace clang;
  27. using namespace ento;
  28. using llvm::FoldingSetNodeID;
  29. //===----------------------------------------------------------------------===//
  30. // Utility functions.
  31. //===----------------------------------------------------------------------===//
  32. bool bugreporter::isDeclRefExprToReference(const Expr *E) {
  33. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  34. return DRE->getDecl()->getType()->isReferenceType();
  35. }
  36. return false;
  37. }
  38. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  39. // Pattern match for a few useful cases:
  40. // a[0], p->f, *p
  41. const Expr *E = dyn_cast<Expr>(S);
  42. if (!E)
  43. return nullptr;
  44. E = E->IgnoreParenCasts();
  45. while (true) {
  46. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
  47. assert(B->isAssignmentOp());
  48. E = B->getLHS()->IgnoreParenCasts();
  49. continue;
  50. }
  51. else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  52. if (U->getOpcode() == UO_Deref)
  53. return U->getSubExpr()->IgnoreParenCasts();
  54. }
  55. else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  56. if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
  57. return ME->getBase()->IgnoreParenCasts();
  58. } else {
  59. // If we have a member expr with a dot, the base must have been
  60. // dereferenced.
  61. return getDerefExpr(ME->getBase());
  62. }
  63. }
  64. else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  65. return IvarRef->getBase()->IgnoreParenCasts();
  66. }
  67. else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  68. return AE->getBase();
  69. }
  70. else if (isDeclRefExprToReference(E)) {
  71. return E;
  72. }
  73. break;
  74. }
  75. return nullptr;
  76. }
  77. const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
  78. const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
  79. if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
  80. return BE->getRHS();
  81. return nullptr;
  82. }
  83. const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
  84. const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
  85. if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
  86. return RS->getRetValue();
  87. return nullptr;
  88. }
  89. //===----------------------------------------------------------------------===//
  90. // Definitions for bug reporter visitors.
  91. //===----------------------------------------------------------------------===//
  92. std::unique_ptr<PathDiagnosticPiece>
  93. BugReporterVisitor::getEndPath(BugReporterContext &BRC,
  94. const ExplodedNode *EndPathNode, BugReport &BR) {
  95. return nullptr;
  96. }
  97. std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
  98. BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
  99. PathDiagnosticLocation L =
  100. PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
  101. const auto &Ranges = BR.getRanges();
  102. // Only add the statement itself as a range if we didn't specify any
  103. // special ranges for this report.
  104. auto P = llvm::make_unique<PathDiagnosticEventPiece>(
  105. L, BR.getDescription(), Ranges.begin() == Ranges.end());
  106. for (const SourceRange &Range : Ranges)
  107. P->addRange(Range);
  108. return std::move(P);
  109. }
  110. namespace {
  111. /// Emits an extra note at the return statement of an interesting stack frame.
  112. ///
  113. /// The returned value is marked as an interesting value, and if it's null,
  114. /// adds a visitor to track where it became null.
  115. ///
  116. /// This visitor is intended to be used when another visitor discovers that an
  117. /// interesting value comes from an inlined function call.
  118. class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
  119. const StackFrameContext *StackFrame;
  120. enum {
  121. Initial,
  122. MaybeUnsuppress,
  123. Satisfied
  124. } Mode;
  125. bool EnableNullFPSuppression;
  126. public:
  127. ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
  128. : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
  129. static void *getTag() {
  130. static int Tag = 0;
  131. return static_cast<void *>(&Tag);
  132. }
  133. void Profile(llvm::FoldingSetNodeID &ID) const override {
  134. ID.AddPointer(ReturnVisitor::getTag());
  135. ID.AddPointer(StackFrame);
  136. ID.AddBoolean(EnableNullFPSuppression);
  137. }
  138. /// Adds a ReturnVisitor if the given statement represents a call that was
  139. /// inlined.
  140. ///
  141. /// This will search back through the ExplodedGraph, starting from the given
  142. /// node, looking for when the given statement was processed. If it turns out
  143. /// the statement is a call that was inlined, we add the visitor to the
  144. /// bug report, so it can print a note later.
  145. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  146. BugReport &BR,
  147. bool InEnableNullFPSuppression) {
  148. if (!CallEvent::isCallStmt(S))
  149. return;
  150. // First, find when we processed the statement.
  151. do {
  152. if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
  153. if (CEE->getCalleeContext()->getCallSite() == S)
  154. break;
  155. if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
  156. if (SP->getStmt() == S)
  157. break;
  158. Node = Node->getFirstPred();
  159. } while (Node);
  160. // Next, step over any post-statement checks.
  161. while (Node && Node->getLocation().getAs<PostStmt>())
  162. Node = Node->getFirstPred();
  163. if (!Node)
  164. return;
  165. // Finally, see if we inlined the call.
  166. Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
  167. if (!CEE)
  168. return;
  169. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  170. if (CalleeContext->getCallSite() != S)
  171. return;
  172. // Check the return value.
  173. ProgramStateRef State = Node->getState();
  174. SVal RetVal = State->getSVal(S, Node->getLocationContext());
  175. // Handle cases where a reference is returned and then immediately used.
  176. if (cast<Expr>(S)->isGLValue())
  177. if (Optional<Loc> LValue = RetVal.getAs<Loc>())
  178. RetVal = State->getSVal(*LValue);
  179. // See if the return value is NULL. If so, suppress the report.
  180. SubEngine *Eng = State->getStateManager().getOwningEngine();
  181. assert(Eng && "Cannot file a bug report without an owning engine");
  182. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  183. bool EnableNullFPSuppression = false;
  184. if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
  185. if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
  186. EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
  187. BR.markInteresting(CalleeContext);
  188. BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
  189. EnableNullFPSuppression));
  190. }
  191. /// Returns true if any counter-suppression heuristics are enabled for
  192. /// ReturnVisitor.
  193. static bool hasCounterSuppression(AnalyzerOptions &Options) {
  194. return Options.shouldAvoidSuppressingNullArgumentPaths();
  195. }
  196. PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
  197. const ExplodedNode *PrevN,
  198. BugReporterContext &BRC,
  199. BugReport &BR) {
  200. // Only print a message at the interesting return statement.
  201. if (N->getLocationContext() != StackFrame)
  202. return nullptr;
  203. Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
  204. if (!SP)
  205. return nullptr;
  206. const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  207. if (!Ret)
  208. return nullptr;
  209. // Okay, we're at the right return statement, but do we have the return
  210. // value available?
  211. ProgramStateRef State = N->getState();
  212. SVal V = State->getSVal(Ret, StackFrame);
  213. if (V.isUnknownOrUndef())
  214. return nullptr;
  215. // Don't print any more notes after this one.
  216. Mode = Satisfied;
  217. const Expr *RetE = Ret->getRetValue();
  218. assert(RetE && "Tracking a return value for a void function");
  219. // Handle cases where a reference is returned and then immediately used.
  220. Optional<Loc> LValue;
  221. if (RetE->isGLValue()) {
  222. if ((LValue = V.getAs<Loc>())) {
  223. SVal RValue = State->getRawSVal(*LValue, RetE->getType());
  224. if (RValue.getAs<DefinedSVal>())
  225. V = RValue;
  226. }
  227. }
  228. // Ignore aggregate rvalues.
  229. if (V.getAs<nonloc::LazyCompoundVal>() ||
  230. V.getAs<nonloc::CompoundVal>())
  231. return nullptr;
  232. RetE = RetE->IgnoreParenCasts();
  233. // If we can't prove the return value is 0, just mark it interesting, and
  234. // make sure to track it into any further inner functions.
  235. if (!State->isNull(V).isConstrainedTrue()) {
  236. BR.markInteresting(V);
  237. ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
  238. EnableNullFPSuppression);
  239. return nullptr;
  240. }
  241. // If we're returning 0, we should track where that 0 came from.
  242. bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
  243. EnableNullFPSuppression);
  244. // Build an appropriate message based on the return value.
  245. SmallString<64> Msg;
  246. llvm::raw_svector_ostream Out(Msg);
  247. if (V.getAs<Loc>()) {
  248. // If we have counter-suppression enabled, make sure we keep visiting
  249. // future nodes. We want to emit a path note as well, in case
  250. // the report is resurrected as valid later on.
  251. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  252. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  253. if (EnableNullFPSuppression && hasCounterSuppression(Options))
  254. Mode = MaybeUnsuppress;
  255. if (RetE->getType()->isObjCObjectPointerType())
  256. Out << "Returning nil";
  257. else
  258. Out << "Returning null pointer";
  259. } else {
  260. Out << "Returning zero";
  261. }
  262. if (LValue) {
  263. if (const MemRegion *MR = LValue->getAsRegion()) {
  264. if (MR->canPrintPretty()) {
  265. Out << " (reference to ";
  266. MR->printPretty(Out);
  267. Out << ")";
  268. }
  269. }
  270. } else {
  271. // FIXME: We should have a more generalized location printing mechanism.
  272. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
  273. if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  274. Out << " (loaded from '" << *DD << "')";
  275. }
  276. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
  277. return new PathDiagnosticEventPiece(L, Out.str());
  278. }
  279. PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
  280. const ExplodedNode *PrevN,
  281. BugReporterContext &BRC,
  282. BugReport &BR) {
  283. #ifndef NDEBUG
  284. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  285. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  286. assert(hasCounterSuppression(Options));
  287. #endif
  288. // Are we at the entry node for this call?
  289. Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
  290. if (!CE)
  291. return nullptr;
  292. if (CE->getCalleeContext() != StackFrame)
  293. return nullptr;
  294. Mode = Satisfied;
  295. // Don't automatically suppress a report if one of the arguments is
  296. // known to be a null pointer. Instead, start tracking /that/ null
  297. // value back to its origin.
  298. ProgramStateManager &StateMgr = BRC.getStateManager();
  299. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  300. ProgramStateRef State = N->getState();
  301. CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
  302. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  303. Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
  304. if (!ArgV)
  305. continue;
  306. const Expr *ArgE = Call->getArgExpr(I);
  307. if (!ArgE)
  308. continue;
  309. // Is it possible for this argument to be non-null?
  310. if (!State->isNull(*ArgV).isConstrainedTrue())
  311. continue;
  312. if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  313. EnableNullFPSuppression))
  314. BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
  315. // If we /can't/ track the null pointer, we should err on the side of
  316. // false negatives, and continue towards marking this report invalid.
  317. // (We will still look at the other arguments, though.)
  318. }
  319. return nullptr;
  320. }
  321. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  322. const ExplodedNode *PrevN,
  323. BugReporterContext &BRC,
  324. BugReport &BR) override {
  325. switch (Mode) {
  326. case Initial:
  327. return visitNodeInitial(N, PrevN, BRC, BR);
  328. case MaybeUnsuppress:
  329. return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
  330. case Satisfied:
  331. return nullptr;
  332. }
  333. llvm_unreachable("Invalid visit mode!");
  334. }
  335. std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
  336. const ExplodedNode *N,
  337. BugReport &BR) override {
  338. if (EnableNullFPSuppression)
  339. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  340. return nullptr;
  341. }
  342. };
  343. } // end anonymous namespace
  344. void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
  345. static int tag = 0;
  346. ID.AddPointer(&tag);
  347. ID.AddPointer(R);
  348. ID.Add(V);
  349. ID.AddBoolean(EnableNullFPSuppression);
  350. }
  351. /// Returns true if \p N represents the DeclStmt declaring and initializing
  352. /// \p VR.
  353. static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
  354. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  355. if (!P)
  356. return false;
  357. const DeclStmt *DS = P->getStmtAs<DeclStmt>();
  358. if (!DS)
  359. return false;
  360. if (DS->getSingleDecl() != VR->getDecl())
  361. return false;
  362. const MemSpaceRegion *VarSpace = VR->getMemorySpace();
  363. const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
  364. if (!FrameSpace) {
  365. // If we ever directly evaluate global DeclStmts, this assertion will be
  366. // invalid, but this still seems preferable to silently accepting an
  367. // initialization that may be for a path-sensitive variable.
  368. assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
  369. return true;
  370. }
  371. assert(VR->getDecl()->hasLocalStorage());
  372. const LocationContext *LCtx = N->getLocationContext();
  373. return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
  374. }
  375. PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  376. const ExplodedNode *Pred,
  377. BugReporterContext &BRC,
  378. BugReport &BR) {
  379. if (Satisfied)
  380. return nullptr;
  381. const ExplodedNode *StoreSite = nullptr;
  382. const Expr *InitE = nullptr;
  383. bool IsParam = false;
  384. // First see if we reached the declaration of the region.
  385. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  386. if (isInitializationOfVar(Pred, VR)) {
  387. StoreSite = Pred;
  388. InitE = VR->getDecl()->getInit();
  389. }
  390. }
  391. // If this is a post initializer expression, initializing the region, we
  392. // should track the initializer expression.
  393. if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
  394. const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
  395. if (FieldReg && FieldReg == R) {
  396. StoreSite = Pred;
  397. InitE = PIP->getInitializer()->getInit();
  398. }
  399. }
  400. // Otherwise, see if this is the store site:
  401. // (1) Succ has this binding and Pred does not, i.e. this is
  402. // where the binding first occurred.
  403. // (2) Succ has this binding and is a PostStore node for this region, i.e.
  404. // the same binding was re-assigned here.
  405. if (!StoreSite) {
  406. if (Succ->getState()->getSVal(R) != V)
  407. return nullptr;
  408. if (Pred->getState()->getSVal(R) == V) {
  409. Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
  410. if (!PS || PS->getLocationValue() != R)
  411. return nullptr;
  412. }
  413. StoreSite = Succ;
  414. // If this is an assignment expression, we can track the value
  415. // being assigned.
  416. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  417. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  418. if (BO->isAssignmentOp())
  419. InitE = BO->getRHS();
  420. // If this is a call entry, the variable should be a parameter.
  421. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  422. // 'this' should never be NULL, but this visitor isn't just for NULL and
  423. // UndefinedVal.)
  424. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  425. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  426. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  427. ProgramStateManager &StateMgr = BRC.getStateManager();
  428. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  429. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  430. Succ->getState());
  431. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  432. IsParam = true;
  433. }
  434. }
  435. // If this is a CXXTempObjectRegion, the Expr responsible for its creation
  436. // is wrapped inside of it.
  437. if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
  438. InitE = TmpR->getExpr();
  439. }
  440. if (!StoreSite)
  441. return nullptr;
  442. Satisfied = true;
  443. // If we have an expression that provided the value, try to track where it
  444. // came from.
  445. if (InitE) {
  446. if (V.isUndef() ||
  447. V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  448. if (!IsParam)
  449. InitE = InitE->IgnoreParenCasts();
  450. bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
  451. EnableNullFPSuppression);
  452. } else {
  453. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  454. BR, EnableNullFPSuppression);
  455. }
  456. }
  457. // Okay, we've found the binding. Emit an appropriate message.
  458. SmallString<256> sbuf;
  459. llvm::raw_svector_ostream os(sbuf);
  460. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  461. const Stmt *S = PS->getStmt();
  462. const char *action = nullptr;
  463. const DeclStmt *DS = dyn_cast<DeclStmt>(S);
  464. const VarRegion *VR = dyn_cast<VarRegion>(R);
  465. if (DS) {
  466. action = R->canPrintPretty() ? "initialized to " :
  467. "Initializing to ";
  468. } else if (isa<BlockExpr>(S)) {
  469. action = R->canPrintPretty() ? "captured by block as " :
  470. "Captured by block as ";
  471. if (VR) {
  472. // See if we can get the BlockVarRegion.
  473. ProgramStateRef State = StoreSite->getState();
  474. SVal V = State->getSVal(S, PS->getLocationContext());
  475. if (const BlockDataRegion *BDR =
  476. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  477. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  478. if (Optional<KnownSVal> KV =
  479. State->getSVal(OriginalR).getAs<KnownSVal>())
  480. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  481. *KV, OriginalR, EnableNullFPSuppression));
  482. }
  483. }
  484. }
  485. }
  486. if (action) {
  487. if (R->canPrintPretty()) {
  488. R->printPretty(os);
  489. os << " ";
  490. }
  491. if (V.getAs<loc::ConcreteInt>()) {
  492. bool b = false;
  493. if (R->isBoundable()) {
  494. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  495. if (TR->getValueType()->isObjCObjectPointerType()) {
  496. os << action << "nil";
  497. b = true;
  498. }
  499. }
  500. }
  501. if (!b)
  502. os << action << "a null pointer value";
  503. } else if (Optional<nonloc::ConcreteInt> CVal =
  504. V.getAs<nonloc::ConcreteInt>()) {
  505. os << action << CVal->getValue();
  506. }
  507. else if (DS) {
  508. if (V.isUndef()) {
  509. if (isa<VarRegion>(R)) {
  510. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  511. if (VD->getInit()) {
  512. os << (R->canPrintPretty() ? "initialized" : "Initializing")
  513. << " to a garbage value";
  514. } else {
  515. os << (R->canPrintPretty() ? "declared" : "Declaring")
  516. << " without an initial value";
  517. }
  518. }
  519. }
  520. else {
  521. os << (R->canPrintPretty() ? "initialized" : "Initialized")
  522. << " here";
  523. }
  524. }
  525. }
  526. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  527. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  528. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  529. os << "Passing ";
  530. if (V.getAs<loc::ConcreteInt>()) {
  531. if (Param->getType()->isObjCObjectPointerType())
  532. os << "nil object reference";
  533. else
  534. os << "null pointer value";
  535. } else if (V.isUndef()) {
  536. os << "uninitialized value";
  537. } else if (Optional<nonloc::ConcreteInt> CI =
  538. V.getAs<nonloc::ConcreteInt>()) {
  539. os << "the value " << CI->getValue();
  540. } else {
  541. os << "value";
  542. }
  543. // Printed parameter indexes are 1-based, not 0-based.
  544. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  545. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
  546. if (R->canPrintPretty()) {
  547. os << " ";
  548. R->printPretty(os);
  549. }
  550. }
  551. }
  552. if (os.str().empty()) {
  553. if (V.getAs<loc::ConcreteInt>()) {
  554. bool b = false;
  555. if (R->isBoundable()) {
  556. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  557. if (TR->getValueType()->isObjCObjectPointerType()) {
  558. os << "nil object reference stored";
  559. b = true;
  560. }
  561. }
  562. }
  563. if (!b) {
  564. if (R->canPrintPretty())
  565. os << "Null pointer value stored";
  566. else
  567. os << "Storing null pointer value";
  568. }
  569. } else if (V.isUndef()) {
  570. if (R->canPrintPretty())
  571. os << "Uninitialized value stored";
  572. else
  573. os << "Storing uninitialized value";
  574. } else if (Optional<nonloc::ConcreteInt> CV =
  575. V.getAs<nonloc::ConcreteInt>()) {
  576. if (R->canPrintPretty())
  577. os << "The value " << CV->getValue() << " is assigned";
  578. else
  579. os << "Assigning " << CV->getValue();
  580. } else {
  581. if (R->canPrintPretty())
  582. os << "Value assigned";
  583. else
  584. os << "Assigning value";
  585. }
  586. if (R->canPrintPretty()) {
  587. os << " to ";
  588. R->printPretty(os);
  589. }
  590. }
  591. // Construct a new PathDiagnosticPiece.
  592. ProgramPoint P = StoreSite->getLocation();
  593. PathDiagnosticLocation L;
  594. if (P.getAs<CallEnter>() && InitE)
  595. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  596. P.getLocationContext());
  597. if (!L.isValid() || !L.asLocation().isValid())
  598. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  599. if (!L.isValid() || !L.asLocation().isValid())
  600. return nullptr;
  601. return new PathDiagnosticEventPiece(L, os.str());
  602. }
  603. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  604. static int tag = 0;
  605. ID.AddPointer(&tag);
  606. ID.AddBoolean(Assumption);
  607. ID.Add(Constraint);
  608. }
  609. /// Return the tag associated with this visitor. This tag will be used
  610. /// to make all PathDiagnosticPieces created by this visitor.
  611. const char *TrackConstraintBRVisitor::getTag() {
  612. return "TrackConstraintBRVisitor";
  613. }
  614. bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
  615. if (IsZeroCheck)
  616. return N->getState()->isNull(Constraint).isUnderconstrained();
  617. return (bool)N->getState()->assume(Constraint, !Assumption);
  618. }
  619. PathDiagnosticPiece *
  620. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  621. const ExplodedNode *PrevN,
  622. BugReporterContext &BRC,
  623. BugReport &BR) {
  624. if (IsSatisfied)
  625. return nullptr;
  626. // Start tracking after we see the first state in which the value is
  627. // constrained.
  628. if (!IsTrackingTurnedOn)
  629. if (!isUnderconstrained(N))
  630. IsTrackingTurnedOn = true;
  631. if (!IsTrackingTurnedOn)
  632. return nullptr;
  633. // Check if in the previous state it was feasible for this constraint
  634. // to *not* be true.
  635. if (isUnderconstrained(PrevN)) {
  636. IsSatisfied = true;
  637. // As a sanity check, make sure that the negation of the constraint
  638. // was infeasible in the current state. If it is feasible, we somehow
  639. // missed the transition point.
  640. assert(!isUnderconstrained(N));
  641. // We found the transition point for the constraint. We now need to
  642. // pretty-print the constraint. (work-in-progress)
  643. SmallString<64> sbuf;
  644. llvm::raw_svector_ostream os(sbuf);
  645. if (Constraint.getAs<Loc>()) {
  646. os << "Assuming pointer value is ";
  647. os << (Assumption ? "non-null" : "null");
  648. }
  649. if (os.str().empty())
  650. return nullptr;
  651. // Construct a new PathDiagnosticPiece.
  652. ProgramPoint P = N->getLocation();
  653. PathDiagnosticLocation L =
  654. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  655. if (!L.isValid())
  656. return nullptr;
  657. PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
  658. X->setTag(getTag());
  659. return X;
  660. }
  661. return nullptr;
  662. }
  663. SuppressInlineDefensiveChecksVisitor::
  664. SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
  665. : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
  666. // Check if the visitor is disabled.
  667. SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
  668. assert(Eng && "Cannot file a bug report without an owning engine");
  669. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  670. if (!Options.shouldSuppressInlinedDefensiveChecks())
  671. IsSatisfied = true;
  672. assert(N->getState()->isNull(V).isConstrainedTrue() &&
  673. "The visitor only tracks the cases where V is constrained to 0");
  674. }
  675. void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
  676. static int id = 0;
  677. ID.AddPointer(&id);
  678. ID.Add(V);
  679. }
  680. const char *SuppressInlineDefensiveChecksVisitor::getTag() {
  681. return "IDCVisitor";
  682. }
  683. PathDiagnosticPiece *
  684. SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
  685. const ExplodedNode *Pred,
  686. BugReporterContext &BRC,
  687. BugReport &BR) {
  688. if (IsSatisfied)
  689. return nullptr;
  690. // Start tracking after we see the first state in which the value is null.
  691. if (!IsTrackingTurnedOn)
  692. if (Succ->getState()->isNull(V).isConstrainedTrue())
  693. IsTrackingTurnedOn = true;
  694. if (!IsTrackingTurnedOn)
  695. return nullptr;
  696. // Check if in the previous state it was feasible for this value
  697. // to *not* be null.
  698. if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
  699. IsSatisfied = true;
  700. assert(Succ->getState()->isNull(V).isConstrainedTrue());
  701. // Check if this is inlined defensive checks.
  702. const LocationContext *CurLC =Succ->getLocationContext();
  703. const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
  704. if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
  705. BR.markInvalid("Suppress IDC", CurLC);
  706. }
  707. return nullptr;
  708. }
  709. static const MemRegion *getLocationRegionIfReference(const Expr *E,
  710. const ExplodedNode *N) {
  711. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  712. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  713. if (!VD->getType()->isReferenceType())
  714. return nullptr;
  715. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  716. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  717. return MRMgr.getVarRegion(VD, N->getLocationContext());
  718. }
  719. }
  720. // FIXME: This does not handle other kinds of null references,
  721. // for example, references from FieldRegions:
  722. // struct Wrapper { int &ref; };
  723. // Wrapper w = { *(int *)0 };
  724. // w.ref = 1;
  725. return nullptr;
  726. }
  727. static const Expr *peelOffOuterExpr(const Expr *Ex,
  728. const ExplodedNode *N) {
  729. Ex = Ex->IgnoreParenCasts();
  730. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
  731. return peelOffOuterExpr(EWC->getSubExpr(), N);
  732. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
  733. return peelOffOuterExpr(OVE->getSourceExpr(), N);
  734. // Peel off the ternary operator.
  735. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
  736. // Find a node where the branching occurred and find out which branch
  737. // we took (true/false) by looking at the ExplodedGraph.
  738. const ExplodedNode *NI = N;
  739. do {
  740. ProgramPoint ProgPoint = NI->getLocation();
  741. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  742. const CFGBlock *srcBlk = BE->getSrc();
  743. if (const Stmt *term = srcBlk->getTerminator()) {
  744. if (term == CO) {
  745. bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
  746. if (TookTrueBranch)
  747. return peelOffOuterExpr(CO->getTrueExpr(), N);
  748. else
  749. return peelOffOuterExpr(CO->getFalseExpr(), N);
  750. }
  751. }
  752. }
  753. NI = NI->getFirstPred();
  754. } while (NI);
  755. }
  756. return Ex;
  757. }
  758. bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
  759. const Stmt *S,
  760. BugReport &report, bool IsArg,
  761. bool EnableNullFPSuppression) {
  762. if (!S || !N)
  763. return false;
  764. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  765. Ex = Ex->IgnoreParenCasts();
  766. const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
  767. if (Ex != PeeledEx)
  768. S = PeeledEx;
  769. }
  770. const Expr *Inner = nullptr;
  771. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  772. Ex = Ex->IgnoreParenCasts();
  773. if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
  774. Inner = Ex;
  775. }
  776. if (IsArg && !Inner) {
  777. assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
  778. } else {
  779. // Walk through nodes until we get one that matches the statement exactly.
  780. // Alternately, if we hit a known lvalue for the statement, we know we've
  781. // gone too far (though we can likely track the lvalue better anyway).
  782. do {
  783. const ProgramPoint &pp = N->getLocation();
  784. if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
  785. if (ps->getStmt() == S || ps->getStmt() == Inner)
  786. break;
  787. } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
  788. if (CEE->getCalleeContext()->getCallSite() == S ||
  789. CEE->getCalleeContext()->getCallSite() == Inner)
  790. break;
  791. }
  792. N = N->getFirstPred();
  793. } while (N);
  794. if (!N)
  795. return false;
  796. }
  797. ProgramStateRef state = N->getState();
  798. // The message send could be nil due to the receiver being nil.
  799. // At this point in the path, the receiver should be live since we are at the
  800. // message send expr. If it is nil, start tracking it.
  801. if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
  802. trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
  803. // See if the expression we're interested refers to a variable.
  804. // If so, we can track both its contents and constraints on its value.
  805. if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
  806. const MemRegion *R = nullptr;
  807. // Find the ExplodedNode where the lvalue (the value of 'Ex')
  808. // was computed. We need this for getting the location value.
  809. const ExplodedNode *LVNode = N;
  810. while (LVNode) {
  811. if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
  812. if (P->getStmt() == Inner)
  813. break;
  814. }
  815. LVNode = LVNode->getFirstPred();
  816. }
  817. assert(LVNode && "Unable to find the lvalue node.");
  818. ProgramStateRef LVState = LVNode->getState();
  819. SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
  820. if (LVState->isNull(LVal).isConstrainedTrue()) {
  821. // In case of C++ references, we want to differentiate between a null
  822. // reference and reference to null pointer.
  823. // If the LVal is null, check if we are dealing with null reference.
  824. // For those, we want to track the location of the reference.
  825. if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
  826. R = RR;
  827. } else {
  828. R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
  829. // If this is a C++ reference to a null pointer, we are tracking the
  830. // pointer. In additon, we should find the store at which the reference
  831. // got initialized.
  832. if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
  833. if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
  834. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  835. *KV, RR, EnableNullFPSuppression));
  836. }
  837. }
  838. if (R) {
  839. // Mark both the variable region and its contents as interesting.
  840. SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
  841. report.markInteresting(R);
  842. report.markInteresting(V);
  843. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
  844. // If the contents are symbolic, find out when they became null.
  845. if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
  846. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  847. V.castAs<DefinedSVal>(), false));
  848. // Add visitor, which will suppress inline defensive checks.
  849. if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
  850. if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
  851. EnableNullFPSuppression) {
  852. report.addVisitor(
  853. llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
  854. LVNode));
  855. }
  856. }
  857. if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
  858. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  859. *KV, R, EnableNullFPSuppression));
  860. return true;
  861. }
  862. }
  863. // If the expression is not an "lvalue expression", we can still
  864. // track the constraints on its contents.
  865. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  866. // If the value came from an inlined function call, we should at least make
  867. // sure that function isn't pruned in our output.
  868. if (const Expr *E = dyn_cast<Expr>(S))
  869. S = E->IgnoreParenCasts();
  870. ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
  871. // Uncomment this to find cases where we aren't properly getting the
  872. // base value that was dereferenced.
  873. // assert(!V.isUnknownOrUndef());
  874. // Is it a symbolic value?
  875. if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
  876. // At this point we are dealing with the region's LValue.
  877. // However, if the rvalue is a symbolic region, we should track it as well.
  878. // Try to use the correct type when looking up the value.
  879. SVal RVal;
  880. if (const Expr *E = dyn_cast<Expr>(S))
  881. RVal = state->getRawSVal(L.getValue(), E->getType());
  882. else
  883. RVal = state->getSVal(L->getRegion());
  884. const MemRegion *RegionRVal = RVal.getAsRegion();
  885. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  886. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  887. report.markInteresting(RegionRVal);
  888. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  889. loc::MemRegionVal(RegionRVal), false));
  890. }
  891. }
  892. return true;
  893. }
  894. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  895. const ExplodedNode *N) {
  896. const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
  897. if (!ME)
  898. return nullptr;
  899. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  900. ProgramStateRef state = N->getState();
  901. SVal V = state->getSVal(Receiver, N->getLocationContext());
  902. if (state->isNull(V).isConstrainedTrue())
  903. return Receiver;
  904. }
  905. return nullptr;
  906. }
  907. PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  908. const ExplodedNode *PrevN,
  909. BugReporterContext &BRC,
  910. BugReport &BR) {
  911. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  912. if (!P)
  913. return nullptr;
  914. const Stmt *S = P->getStmt();
  915. const Expr *Receiver = getNilReceiver(S, N);
  916. if (!Receiver)
  917. return nullptr;
  918. llvm::SmallString<256> Buf;
  919. llvm::raw_svector_ostream OS(Buf);
  920. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
  921. OS << "'";
  922. ME->getSelector().print(OS);
  923. OS << "' not called";
  924. }
  925. else {
  926. OS << "No method is called";
  927. }
  928. OS << " because the receiver is nil";
  929. // The receiver was nil, and hence the method was skipped.
  930. // Register a BugReporterVisitor to issue a message telling us how
  931. // the receiver was null.
  932. bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
  933. /*EnableNullFPSuppression*/ false);
  934. // Issue a message saying that the method was skipped.
  935. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  936. N->getLocationContext());
  937. return new PathDiagnosticEventPiece(L, OS.str());
  938. }
  939. // Registers every VarDecl inside a Stmt with a last store visitor.
  940. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  941. const Stmt *S,
  942. bool EnableNullFPSuppression) {
  943. const ExplodedNode *N = BR.getErrorNode();
  944. std::deque<const Stmt *> WorkList;
  945. WorkList.push_back(S);
  946. while (!WorkList.empty()) {
  947. const Stmt *Head = WorkList.front();
  948. WorkList.pop_front();
  949. ProgramStateRef state = N->getState();
  950. ProgramStateManager &StateMgr = state->getStateManager();
  951. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
  952. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  953. const VarRegion *R =
  954. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  955. // What did we load?
  956. SVal V = state->getSVal(S, N->getLocationContext());
  957. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  958. // Register a new visitor with the BugReport.
  959. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  960. V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
  961. }
  962. }
  963. }
  964. for (const Stmt *SubStmt : Head->children())
  965. WorkList.push_back(SubStmt);
  966. }
  967. }
  968. //===----------------------------------------------------------------------===//
  969. // Visitor that tries to report interesting diagnostics from conditions.
  970. //===----------------------------------------------------------------------===//
  971. /// Return the tag associated with this visitor. This tag will be used
  972. /// to make all PathDiagnosticPieces created by this visitor.
  973. const char *ConditionBRVisitor::getTag() {
  974. return "ConditionBRVisitor";
  975. }
  976. PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
  977. const ExplodedNode *Prev,
  978. BugReporterContext &BRC,
  979. BugReport &BR) {
  980. PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
  981. if (piece) {
  982. piece->setTag(getTag());
  983. if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
  984. ev->setPrunable(true, /* override */ false);
  985. }
  986. return piece;
  987. }
  988. PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  989. const ExplodedNode *Prev,
  990. BugReporterContext &BRC,
  991. BugReport &BR) {
  992. ProgramPoint progPoint = N->getLocation();
  993. ProgramStateRef CurrentState = N->getState();
  994. ProgramStateRef PrevState = Prev->getState();
  995. // Compare the GDMs of the state, because that is where constraints
  996. // are managed. Note that ensure that we only look at nodes that
  997. // were generated by the analyzer engine proper, not checkers.
  998. if (CurrentState->getGDM().getRoot() ==
  999. PrevState->getGDM().getRoot())
  1000. return nullptr;
  1001. // If an assumption was made on a branch, it should be caught
  1002. // here by looking at the state transition.
  1003. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  1004. const CFGBlock *srcBlk = BE->getSrc();
  1005. if (const Stmt *term = srcBlk->getTerminator())
  1006. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  1007. return nullptr;
  1008. }
  1009. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  1010. // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
  1011. // violation.
  1012. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  1013. cast<GRBugReporter>(BRC.getBugReporter()).
  1014. getEngine().geteagerlyAssumeBinOpBifurcationTags();
  1015. const ProgramPointTag *tag = PS->getTag();
  1016. if (tag == tags.first)
  1017. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  1018. BRC, BR, N);
  1019. if (tag == tags.second)
  1020. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  1021. BRC, BR, N);
  1022. return nullptr;
  1023. }
  1024. return nullptr;
  1025. }
  1026. PathDiagnosticPiece *
  1027. ConditionBRVisitor::VisitTerminator(const Stmt *Term,
  1028. const ExplodedNode *N,
  1029. const CFGBlock *srcBlk,
  1030. const CFGBlock *dstBlk,
  1031. BugReport &R,
  1032. BugReporterContext &BRC) {
  1033. const Expr *Cond = nullptr;
  1034. switch (Term->getStmtClass()) {
  1035. default:
  1036. return nullptr;
  1037. case Stmt::IfStmtClass:
  1038. Cond = cast<IfStmt>(Term)->getCond();
  1039. break;
  1040. case Stmt::ConditionalOperatorClass:
  1041. Cond = cast<ConditionalOperator>(Term)->getCond();
  1042. break;
  1043. }
  1044. assert(Cond);
  1045. assert(srcBlk->succ_size() == 2);
  1046. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1047. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  1048. }
  1049. PathDiagnosticPiece *
  1050. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1051. bool tookTrue,
  1052. BugReporterContext &BRC,
  1053. BugReport &R,
  1054. const ExplodedNode *N) {
  1055. const Expr *Ex = Cond;
  1056. while (true) {
  1057. Ex = Ex->IgnoreParenCasts();
  1058. switch (Ex->getStmtClass()) {
  1059. default:
  1060. return nullptr;
  1061. case Stmt::BinaryOperatorClass:
  1062. return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
  1063. R, N);
  1064. case Stmt::DeclRefExprClass:
  1065. return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
  1066. R, N);
  1067. case Stmt::UnaryOperatorClass: {
  1068. const UnaryOperator *UO = cast<UnaryOperator>(Ex);
  1069. if (UO->getOpcode() == UO_LNot) {
  1070. tookTrue = !tookTrue;
  1071. Ex = UO->getSubExpr();
  1072. continue;
  1073. }
  1074. return nullptr;
  1075. }
  1076. }
  1077. }
  1078. }
  1079. bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
  1080. BugReporterContext &BRC,
  1081. BugReport &report,
  1082. const ExplodedNode *N,
  1083. Optional<bool> &prunable) {
  1084. const Expr *OriginalExpr = Ex;
  1085. Ex = Ex->IgnoreParenCasts();
  1086. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1087. const bool quotes = isa<VarDecl>(DR->getDecl());
  1088. if (quotes) {
  1089. Out << '\'';
  1090. const LocationContext *LCtx = N->getLocationContext();
  1091. const ProgramState *state = N->getState().get();
  1092. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1093. LCtx).getAsRegion()) {
  1094. if (report.isInteresting(R))
  1095. prunable = false;
  1096. else {
  1097. const ProgramState *state = N->getState().get();
  1098. SVal V = state->getSVal(R);
  1099. if (report.isInteresting(V))
  1100. prunable = false;
  1101. }
  1102. }
  1103. }
  1104. Out << DR->getDecl()->getDeclName().getAsString();
  1105. if (quotes)
  1106. Out << '\'';
  1107. return quotes;
  1108. }
  1109. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
  1110. QualType OriginalTy = OriginalExpr->getType();
  1111. if (OriginalTy->isPointerType()) {
  1112. if (IL->getValue() == 0) {
  1113. Out << "null";
  1114. return false;
  1115. }
  1116. }
  1117. else if (OriginalTy->isObjCObjectPointerType()) {
  1118. if (IL->getValue() == 0) {
  1119. Out << "nil";
  1120. return false;
  1121. }
  1122. }
  1123. Out << IL->getValue();
  1124. return false;
  1125. }
  1126. return false;
  1127. }
  1128. PathDiagnosticPiece *
  1129. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1130. const BinaryOperator *BExpr,
  1131. const bool tookTrue,
  1132. BugReporterContext &BRC,
  1133. BugReport &R,
  1134. const ExplodedNode *N) {
  1135. bool shouldInvert = false;
  1136. Optional<bool> shouldPrune;
  1137. SmallString<128> LhsString, RhsString;
  1138. {
  1139. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  1140. const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
  1141. shouldPrune);
  1142. const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
  1143. shouldPrune);
  1144. shouldInvert = !isVarLHS && isVarRHS;
  1145. }
  1146. BinaryOperator::Opcode Op = BExpr->getOpcode();
  1147. if (BinaryOperator::isAssignmentOp(Op)) {
  1148. // For assignment operators, all that we care about is that the LHS
  1149. // evaluates to "true" or "false".
  1150. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  1151. BRC, R, N);
  1152. }
  1153. // For non-assignment operations, we require that we can understand
  1154. // both the LHS and RHS.
  1155. if (LhsString.empty() || RhsString.empty() ||
  1156. !BinaryOperator::isComparisonOp(Op))
  1157. return nullptr;
  1158. // Should we invert the strings if the LHS is not a variable name?
  1159. SmallString<256> buf;
  1160. llvm::raw_svector_ostream Out(buf);
  1161. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  1162. // Do we need to invert the opcode?
  1163. if (shouldInvert)
  1164. switch (Op) {
  1165. default: break;
  1166. case BO_LT: Op = BO_GT; break;
  1167. case BO_GT: Op = BO_LT; break;
  1168. case BO_LE: Op = BO_GE; break;
  1169. case BO_GE: Op = BO_LE; break;
  1170. }
  1171. if (!tookTrue)
  1172. switch (Op) {
  1173. case BO_EQ: Op = BO_NE; break;
  1174. case BO_NE: Op = BO_EQ; break;
  1175. case BO_LT: Op = BO_GE; break;
  1176. case BO_GT: Op = BO_LE; break;
  1177. case BO_LE: Op = BO_GT; break;
  1178. case BO_GE: Op = BO_LT; break;
  1179. default:
  1180. return nullptr;
  1181. }
  1182. switch (Op) {
  1183. case BO_EQ:
  1184. Out << "equal to ";
  1185. break;
  1186. case BO_NE:
  1187. Out << "not equal to ";
  1188. break;
  1189. default:
  1190. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  1191. break;
  1192. }
  1193. Out << (shouldInvert ? LhsString : RhsString);
  1194. const LocationContext *LCtx = N->getLocationContext();
  1195. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1196. PathDiagnosticEventPiece *event =
  1197. new PathDiagnosticEventPiece(Loc, Out.str());
  1198. if (shouldPrune.hasValue())
  1199. event->setPrunable(shouldPrune.getValue());
  1200. return event;
  1201. }
  1202. PathDiagnosticPiece *
  1203. ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
  1204. const Expr *CondVarExpr,
  1205. const bool tookTrue,
  1206. BugReporterContext &BRC,
  1207. BugReport &report,
  1208. const ExplodedNode *N) {
  1209. // FIXME: If there's already a constraint tracker for this variable,
  1210. // we shouldn't emit anything here (c.f. the double note in
  1211. // test/Analysis/inlining/path-notes.c)
  1212. SmallString<256> buf;
  1213. llvm::raw_svector_ostream Out(buf);
  1214. Out << "Assuming " << LhsString << " is ";
  1215. QualType Ty = CondVarExpr->getType();
  1216. if (Ty->isPointerType())
  1217. Out << (tookTrue ? "not null" : "null");
  1218. else if (Ty->isObjCObjectPointerType())
  1219. Out << (tookTrue ? "not nil" : "nil");
  1220. else if (Ty->isBooleanType())
  1221. Out << (tookTrue ? "true" : "false");
  1222. else if (Ty->isIntegralOrEnumerationType())
  1223. Out << (tookTrue ? "non-zero" : "zero");
  1224. else
  1225. return nullptr;
  1226. const LocationContext *LCtx = N->getLocationContext();
  1227. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  1228. PathDiagnosticEventPiece *event =
  1229. new PathDiagnosticEventPiece(Loc, Out.str());
  1230. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  1231. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1232. const ProgramState *state = N->getState().get();
  1233. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1234. if (report.isInteresting(R))
  1235. event->setPrunable(false);
  1236. }
  1237. }
  1238. }
  1239. return event;
  1240. }
  1241. PathDiagnosticPiece *
  1242. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1243. const DeclRefExpr *DR,
  1244. const bool tookTrue,
  1245. BugReporterContext &BRC,
  1246. BugReport &report,
  1247. const ExplodedNode *N) {
  1248. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  1249. if (!VD)
  1250. return nullptr;
  1251. SmallString<256> Buf;
  1252. llvm::raw_svector_ostream Out(Buf);
  1253. Out << "Assuming '" << VD->getDeclName() << "' is ";
  1254. QualType VDTy = VD->getType();
  1255. if (VDTy->isPointerType())
  1256. Out << (tookTrue ? "non-null" : "null");
  1257. else if (VDTy->isObjCObjectPointerType())
  1258. Out << (tookTrue ? "non-nil" : "nil");
  1259. else if (VDTy->isScalarType())
  1260. Out << (tookTrue ? "not equal to 0" : "0");
  1261. else
  1262. return nullptr;
  1263. const LocationContext *LCtx = N->getLocationContext();
  1264. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1265. PathDiagnosticEventPiece *event =
  1266. new PathDiagnosticEventPiece(Loc, Out.str());
  1267. const ProgramState *state = N->getState().get();
  1268. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1269. if (report.isInteresting(R))
  1270. event->setPrunable(false);
  1271. else {
  1272. SVal V = state->getSVal(R);
  1273. if (report.isInteresting(V))
  1274. event->setPrunable(false);
  1275. }
  1276. }
  1277. return event;
  1278. }
  1279. // FIXME: Copied from ExprEngineCallAndReturn.cpp.
  1280. static bool isInStdNamespace(const Decl *D) {
  1281. const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
  1282. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
  1283. if (!ND)
  1284. return false;
  1285. while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
  1286. ND = Parent;
  1287. return ND->isStdNamespace();
  1288. }
  1289. std::unique_ptr<PathDiagnosticPiece>
  1290. LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
  1291. const ExplodedNode *N,
  1292. BugReport &BR) {
  1293. // Here we suppress false positives coming from system headers. This list is
  1294. // based on known issues.
  1295. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  1296. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  1297. const Decl *D = N->getLocationContext()->getDecl();
  1298. if (isInStdNamespace(D)) {
  1299. // Skip reports within the 'std' namespace. Although these can sometimes be
  1300. // the user's fault, we currently don't report them very well, and
  1301. // Note that this will not help for any other data structure libraries, like
  1302. // TR1, Boost, or llvm/ADT.
  1303. if (Options.shouldSuppressFromCXXStandardLibrary()) {
  1304. BR.markInvalid(getTag(), nullptr);
  1305. return nullptr;
  1306. } else {
  1307. // If the complete 'std' suppression is not enabled, suppress reports
  1308. // from the 'std' namespace that are known to produce false positives.
  1309. // The analyzer issues a false use-after-free when std::list::pop_front
  1310. // or std::list::pop_back are called multiple times because we cannot
  1311. // reason about the internal invariants of the datastructure.
  1312. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  1313. const CXXRecordDecl *CD = MD->getParent();
  1314. if (CD->getName() == "list") {
  1315. BR.markInvalid(getTag(), nullptr);
  1316. return nullptr;
  1317. }
  1318. }
  1319. // The analyzer issues a false positive on
  1320. // std::basic_string<uint8_t> v; v.push_back(1);
  1321. // and
  1322. // std::u16string s; s += u'a';
  1323. // because we cannot reason about the internal invariants of the
  1324. // datastructure.
  1325. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  1326. LCtx = LCtx->getParent()) {
  1327. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  1328. if (!MD)
  1329. continue;
  1330. const CXXRecordDecl *CD = MD->getParent();
  1331. if (CD->getName() == "basic_string") {
  1332. BR.markInvalid(getTag(), nullptr);
  1333. return nullptr;
  1334. }
  1335. }
  1336. }
  1337. }
  1338. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1339. // reason about data structure shapes.
  1340. SourceManager &SM = BRC.getSourceManager();
  1341. FullSourceLoc Loc = BR.getLocation(SM).asLocation();
  1342. while (Loc.isMacroID()) {
  1343. Loc = Loc.getSpellingLoc();
  1344. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  1345. BR.markInvalid(getTag(), nullptr);
  1346. return nullptr;
  1347. }
  1348. }
  1349. return nullptr;
  1350. }
  1351. PathDiagnosticPiece *
  1352. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1353. const ExplodedNode *PrevN,
  1354. BugReporterContext &BRC,
  1355. BugReport &BR) {
  1356. ProgramStateRef State = N->getState();
  1357. ProgramPoint ProgLoc = N->getLocation();
  1358. // We are only interested in visiting CallEnter nodes.
  1359. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1360. if (!CEnter)
  1361. return nullptr;
  1362. // Check if one of the arguments is the region the visitor is tracking.
  1363. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1364. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1365. unsigned Idx = 0;
  1366. ArrayRef<ParmVarDecl*> parms = Call->parameters();
  1367. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  1368. I != E; ++I, ++Idx) {
  1369. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1370. // Are we tracking the argument or its subregion?
  1371. if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
  1372. continue;
  1373. // Check the function parameter type.
  1374. const ParmVarDecl *ParamDecl = *I;
  1375. assert(ParamDecl && "Formal parameter has no decl?");
  1376. QualType T = ParamDecl->getType();
  1377. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1378. // Function can only change the value passed in by address.
  1379. continue;
  1380. }
  1381. // If it is a const pointer value, the function does not intend to
  1382. // change the value.
  1383. if (T->getPointeeType().isConstQualified())
  1384. continue;
  1385. // Mark the call site (LocationContext) as interesting if the value of the
  1386. // argument is undefined or '0'/'NULL'.
  1387. SVal BoundVal = State->getSVal(R);
  1388. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1389. BR.markInteresting(CEnter->getCalleeContext());
  1390. return nullptr;
  1391. }
  1392. }
  1393. return nullptr;
  1394. }