BugReporterVisitors.cpp 56 KB

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