BugReporterVisitors.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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. //===----------------------------------------------------------------------===//
  29. // Utility functions.
  30. //===----------------------------------------------------------------------===//
  31. bool bugreporter::isDeclRefExprToReference(const Expr *E) {
  32. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  33. return DRE->getDecl()->getType()->isReferenceType();
  34. }
  35. return false;
  36. }
  37. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  38. // Pattern match for a few useful cases (do something smarter later):
  39. // a[0], p->f, *p
  40. const Expr *E = dyn_cast<Expr>(S);
  41. if (!E)
  42. return 0;
  43. E = E->IgnoreParenCasts();
  44. while (true) {
  45. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
  46. assert(B->isAssignmentOp());
  47. E = B->getLHS()->IgnoreParenCasts();
  48. continue;
  49. }
  50. else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  51. if (U->getOpcode() == UO_Deref)
  52. return U->getSubExpr()->IgnoreParenCasts();
  53. }
  54. else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  55. if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
  56. return ME->getBase()->IgnoreParenCasts();
  57. }
  58. }
  59. else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  60. return IvarRef->getBase()->IgnoreParenCasts();
  61. }
  62. else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  63. return AE->getBase();
  64. }
  65. break;
  66. }
  67. return NULL;
  68. }
  69. const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
  70. const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
  71. if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
  72. return BE->getRHS();
  73. return NULL;
  74. }
  75. const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
  76. const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
  77. if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
  78. return RS->getRetValue();
  79. return NULL;
  80. }
  81. //===----------------------------------------------------------------------===//
  82. // Definitions for bug reporter visitors.
  83. //===----------------------------------------------------------------------===//
  84. PathDiagnosticPiece*
  85. BugReporterVisitor::getEndPath(BugReporterContext &BRC,
  86. const ExplodedNode *EndPathNode,
  87. BugReport &BR) {
  88. return 0;
  89. }
  90. PathDiagnosticPiece*
  91. BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
  92. const ExplodedNode *EndPathNode,
  93. BugReport &BR) {
  94. PathDiagnosticLocation L =
  95. PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
  96. BugReport::ranges_iterator Beg, End;
  97. llvm::tie(Beg, End) = BR.getRanges();
  98. // Only add the statement itself as a range if we didn't specify any
  99. // special ranges for this report.
  100. PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
  101. BR.getDescription(),
  102. Beg == End);
  103. for (; Beg != End; ++Beg)
  104. P->addRange(*Beg);
  105. return P;
  106. }
  107. namespace {
  108. /// Emits an extra note at the return statement of an interesting stack frame.
  109. ///
  110. /// The returned value is marked as an interesting value, and if it's null,
  111. /// adds a visitor to track where it became null.
  112. ///
  113. /// This visitor is intended to be used when another visitor discovers that an
  114. /// interesting value comes from an inlined function call.
  115. class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
  116. const StackFrameContext *StackFrame;
  117. enum {
  118. Initial,
  119. MaybeSuppress,
  120. Satisfied
  121. } Mode;
  122. public:
  123. ReturnVisitor(const StackFrameContext *Frame)
  124. : StackFrame(Frame), Mode(Initial) {}
  125. static void *getTag() {
  126. static int Tag = 0;
  127. return static_cast<void *>(&Tag);
  128. }
  129. virtual void Profile(llvm::FoldingSetNodeID &ID) const {
  130. ID.AddPointer(ReturnVisitor::getTag());
  131. ID.AddPointer(StackFrame);
  132. }
  133. /// Adds a ReturnVisitor if the given statement represents a call that was
  134. /// inlined.
  135. ///
  136. /// This will search back through the ExplodedGraph, starting from the given
  137. /// node, looking for when the given statement was processed. If it turns out
  138. /// the statement is a call that was inlined, we add the visitor to the
  139. /// bug report, so it can print a note later.
  140. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  141. BugReport &BR) {
  142. if (!CallEvent::isCallStmt(S))
  143. return;
  144. // First, find when we processed the statement.
  145. do {
  146. if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
  147. if (CEE->getCalleeContext()->getCallSite() == S)
  148. break;
  149. if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
  150. if (SP->getStmt() == S)
  151. break;
  152. Node = Node->getFirstPred();
  153. } while (Node);
  154. // Next, step over any post-statement checks.
  155. while (Node && Node->getLocation().getAs<PostStmt>())
  156. Node = Node->getFirstPred();
  157. // Finally, see if we inlined the call.
  158. if (Node) {
  159. if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>()) {
  160. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  161. if (CalleeContext->getCallSite() == S) {
  162. BR.markInteresting(CalleeContext);
  163. BR.addVisitor(new ReturnVisitor(CalleeContext));
  164. }
  165. }
  166. }
  167. }
  168. /// Returns true if any counter-suppression heuristics are enabled for
  169. /// ReturnVisitor.
  170. static bool hasCounterSuppression(AnalyzerOptions &Options) {
  171. return Options.shouldAvoidSuppressingNullArgumentPaths();
  172. }
  173. PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
  174. const ExplodedNode *PrevN,
  175. BugReporterContext &BRC,
  176. BugReport &BR) {
  177. // Only print a message at the interesting return statement.
  178. if (N->getLocationContext() != StackFrame)
  179. return 0;
  180. Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
  181. if (!SP)
  182. return 0;
  183. const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  184. if (!Ret)
  185. return 0;
  186. // Okay, we're at the right return statement, but do we have the return
  187. // value available?
  188. ProgramStateRef State = N->getState();
  189. SVal V = State->getSVal(Ret, StackFrame);
  190. if (V.isUnknownOrUndef())
  191. return 0;
  192. // Don't print any more notes after this one.
  193. Mode = Satisfied;
  194. const Expr *RetE = Ret->getRetValue();
  195. assert(RetE && "Tracking a return value for a void function");
  196. RetE = RetE->IgnoreParenCasts();
  197. // If we can't prove the return value is 0, just mark it interesting, and
  198. // make sure to track it into any further inner functions.
  199. if (State->assume(V.castAs<DefinedSVal>(), true)) {
  200. BR.markInteresting(V);
  201. ReturnVisitor::addVisitorIfNecessary(N, RetE, BR);
  202. return 0;
  203. }
  204. // If we're returning 0, we should track where that 0 came from.
  205. bugreporter::trackNullOrUndefValue(N, RetE, BR);
  206. // Build an appropriate message based on the return value.
  207. SmallString<64> Msg;
  208. llvm::raw_svector_ostream Out(Msg);
  209. if (V.getAs<Loc>()) {
  210. // If we are pruning null-return paths as unlikely error paths, mark the
  211. // report invalid. We still want to emit a path note, however, in case
  212. // the report is resurrected as valid later on.
  213. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  214. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  215. if (Options.shouldSuppressNullReturnPaths()) {
  216. if (hasCounterSuppression(Options))
  217. Mode = MaybeSuppress;
  218. else
  219. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  220. }
  221. if (RetE->getType()->isObjCObjectPointerType())
  222. Out << "Returning nil";
  223. else
  224. Out << "Returning null pointer";
  225. } else {
  226. Out << "Returning zero";
  227. }
  228. // FIXME: We should have a more generalized location printing mechanism.
  229. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
  230. if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  231. Out << " (loaded from '" << *DD << "')";
  232. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
  233. return new PathDiagnosticEventPiece(L, Out.str());
  234. }
  235. PathDiagnosticPiece *visitNodeMaybeSuppress(const ExplodedNode *N,
  236. const ExplodedNode *PrevN,
  237. BugReporterContext &BRC,
  238. BugReport &BR) {
  239. // Are we at the entry node for this call?
  240. Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
  241. if (!CE)
  242. return 0;
  243. if (CE->getCalleeContext() != StackFrame)
  244. return 0;
  245. Mode = Satisfied;
  246. ExprEngine &Eng = BRC.getBugReporter().getEngine();
  247. AnalyzerOptions &Options = Eng.getAnalysisManager().options;
  248. if (Options.shouldAvoidSuppressingNullArgumentPaths()) {
  249. // Don't automatically suppress a report if one of the arguments is
  250. // known to be a null pointer. Instead, start tracking /that/ null
  251. // value back to its origin.
  252. ProgramStateManager &StateMgr = BRC.getStateManager();
  253. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  254. ProgramStateRef State = N->getState();
  255. CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
  256. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  257. SVal ArgV = Call->getArgSVal(I);
  258. if (!ArgV.getAs<Loc>())
  259. continue;
  260. const Expr *ArgE = Call->getArgExpr(I);
  261. if (!ArgE)
  262. continue;
  263. // Is it possible for this argument to be non-null?
  264. if (State->assume(ArgV.castAs<Loc>(), true))
  265. continue;
  266. if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true))
  267. return 0;
  268. // If we /can't/ track the null pointer, we should err on the side of
  269. // false negatives, and continue towards marking this report invalid.
  270. // (We will still look at the other arguments, though.)
  271. }
  272. }
  273. // There is no reason not to suppress this report; go ahead and do it.
  274. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  275. return 0;
  276. }
  277. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  278. const ExplodedNode *PrevN,
  279. BugReporterContext &BRC,
  280. BugReport &BR) {
  281. switch (Mode) {
  282. case Initial:
  283. return visitNodeInitial(N, PrevN, BRC, BR);
  284. case MaybeSuppress:
  285. return visitNodeMaybeSuppress(N, PrevN, BRC, BR);
  286. case Satisfied:
  287. return 0;
  288. }
  289. llvm_unreachable("Invalid visit mode!");
  290. }
  291. };
  292. } // end anonymous namespace
  293. void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
  294. static int tag = 0;
  295. ID.AddPointer(&tag);
  296. ID.AddPointer(R);
  297. ID.Add(V);
  298. }
  299. PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  300. const ExplodedNode *Pred,
  301. BugReporterContext &BRC,
  302. BugReport &BR) {
  303. if (Satisfied)
  304. return NULL;
  305. const ExplodedNode *StoreSite = 0;
  306. const Expr *InitE = 0;
  307. bool IsParam = false;
  308. // First see if we reached the declaration of the region.
  309. if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
  310. if (Optional<PostStmt> P = Pred->getLocationAs<PostStmt>()) {
  311. if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
  312. if (DS->getSingleDecl() == VR->getDecl()) {
  313. StoreSite = Pred;
  314. InitE = VR->getDecl()->getInit();
  315. }
  316. }
  317. }
  318. }
  319. // Otherwise, check that Succ has this binding and Pred does not, i.e. this is
  320. // where the binding first occurred.
  321. if (!StoreSite) {
  322. if (Succ->getState()->getSVal(R) != V)
  323. return NULL;
  324. if (Pred->getState()->getSVal(R) == V)
  325. return NULL;
  326. StoreSite = Succ;
  327. // If this is an assignment expression, we can track the value
  328. // being assigned.
  329. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  330. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  331. if (BO->isAssignmentOp())
  332. InitE = BO->getRHS();
  333. // If this is a call entry, the variable should be a parameter.
  334. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  335. // 'this' should never be NULL, but this visitor isn't just for NULL and
  336. // UndefinedVal.)
  337. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  338. const VarRegion *VR = cast<VarRegion>(R);
  339. const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
  340. ProgramStateManager &StateMgr = BRC.getStateManager();
  341. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  342. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  343. Succ->getState());
  344. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  345. IsParam = true;
  346. }
  347. }
  348. if (!StoreSite)
  349. return NULL;
  350. Satisfied = true;
  351. // If we have an expression that provided the value, try to track where it
  352. // came from.
  353. if (InitE) {
  354. if (V.isUndef() || V.getAs<loc::ConcreteInt>()) {
  355. if (!IsParam)
  356. InitE = InitE->IgnoreParenCasts();
  357. bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam);
  358. } else {
  359. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  360. BR);
  361. }
  362. }
  363. if (!R->canPrintPretty())
  364. return 0;
  365. // Okay, we've found the binding. Emit an appropriate message.
  366. SmallString<256> sbuf;
  367. llvm::raw_svector_ostream os(sbuf);
  368. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  369. const Stmt *S = PS->getStmt();
  370. const char *action = 0;
  371. const DeclStmt *DS = dyn_cast<DeclStmt>(S);
  372. const VarRegion *VR = dyn_cast<VarRegion>(R);
  373. if (DS) {
  374. action = "initialized to ";
  375. } else if (isa<BlockExpr>(S)) {
  376. action = "captured by block as ";
  377. if (VR) {
  378. // See if we can get the BlockVarRegion.
  379. ProgramStateRef State = StoreSite->getState();
  380. SVal V = State->getSVal(S, PS->getLocationContext());
  381. if (const BlockDataRegion *BDR =
  382. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  383. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  384. if (Optional<KnownSVal> KV =
  385. State->getSVal(OriginalR).getAs<KnownSVal>())
  386. BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR));
  387. }
  388. }
  389. }
  390. }
  391. if (action) {
  392. if (!R)
  393. return 0;
  394. os << "Variable '" << *VR->getDecl() << "' ";
  395. if (V.getAs<loc::ConcreteInt>()) {
  396. bool b = false;
  397. if (R->isBoundable()) {
  398. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  399. if (TR->getValueType()->isObjCObjectPointerType()) {
  400. os << action << "nil";
  401. b = true;
  402. }
  403. }
  404. }
  405. if (!b)
  406. os << action << "a null pointer value";
  407. } else if (Optional<nonloc::ConcreteInt> CVal =
  408. V.getAs<nonloc::ConcreteInt>()) {
  409. os << action << CVal->getValue();
  410. }
  411. else if (DS) {
  412. if (V.isUndef()) {
  413. if (isa<VarRegion>(R)) {
  414. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  415. if (VD->getInit())
  416. os << "initialized to a garbage value";
  417. else
  418. os << "declared without an initial value";
  419. }
  420. }
  421. else {
  422. os << "initialized here";
  423. }
  424. }
  425. }
  426. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  427. const ParmVarDecl *Param = cast<ParmVarDecl>(cast<VarRegion>(R)->getDecl());
  428. os << "Passing ";
  429. if (V.getAs<loc::ConcreteInt>()) {
  430. if (Param->getType()->isObjCObjectPointerType())
  431. os << "nil object reference";
  432. else
  433. os << "null pointer value";
  434. } else if (V.isUndef()) {
  435. os << "uninitialized value";
  436. } else if (Optional<nonloc::ConcreteInt> CI =
  437. V.getAs<nonloc::ConcreteInt>()) {
  438. os << "the value " << CI->getValue();
  439. } else {
  440. os << "value";
  441. }
  442. // Printed parameter indexes are 1-based, not 0-based.
  443. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  444. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
  445. R->printPretty(os);
  446. os << '\'';
  447. }
  448. if (os.str().empty()) {
  449. if (V.getAs<loc::ConcreteInt>()) {
  450. bool b = false;
  451. if (R->isBoundable()) {
  452. if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
  453. if (TR->getValueType()->isObjCObjectPointerType()) {
  454. os << "nil object reference stored to ";
  455. b = true;
  456. }
  457. }
  458. }
  459. if (!b)
  460. os << "Null pointer value stored to ";
  461. }
  462. else if (V.isUndef()) {
  463. os << "Uninitialized value stored to ";
  464. } else if (Optional<nonloc::ConcreteInt> CV =
  465. V.getAs<nonloc::ConcreteInt>()) {
  466. os << "The value " << CV->getValue() << " is assigned to ";
  467. }
  468. else
  469. os << "Value assigned to ";
  470. os << '\'';
  471. R->printPretty(os);
  472. os << '\'';
  473. }
  474. // Construct a new PathDiagnosticPiece.
  475. ProgramPoint P = StoreSite->getLocation();
  476. PathDiagnosticLocation L;
  477. if (P.getAs<CallEnter>())
  478. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  479. P.getLocationContext());
  480. else
  481. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  482. if (!L.isValid())
  483. return NULL;
  484. return new PathDiagnosticEventPiece(L, os.str());
  485. }
  486. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  487. static int tag = 0;
  488. ID.AddPointer(&tag);
  489. ID.AddBoolean(Assumption);
  490. ID.Add(Constraint);
  491. }
  492. /// Return the tag associated with this visitor. This tag will be used
  493. /// to make all PathDiagnosticPieces created by this visitor.
  494. const char *TrackConstraintBRVisitor::getTag() {
  495. return "TrackConstraintBRVisitor";
  496. }
  497. PathDiagnosticPiece *
  498. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  499. const ExplodedNode *PrevN,
  500. BugReporterContext &BRC,
  501. BugReport &BR) {
  502. if (isSatisfied)
  503. return NULL;
  504. // Check if in the previous state it was feasible for this constraint
  505. // to *not* be true.
  506. if (PrevN->getState()->assume(Constraint, !Assumption)) {
  507. isSatisfied = true;
  508. // As a sanity check, make sure that the negation of the constraint
  509. // was infeasible in the current state. If it is feasible, we somehow
  510. // missed the transition point.
  511. if (N->getState()->assume(Constraint, !Assumption))
  512. return NULL;
  513. // We found the transition point for the constraint. We now need to
  514. // pretty-print the constraint. (work-in-progress)
  515. std::string sbuf;
  516. llvm::raw_string_ostream os(sbuf);
  517. if (Constraint.getAs<Loc>()) {
  518. os << "Assuming pointer value is ";
  519. os << (Assumption ? "non-null" : "null");
  520. }
  521. if (os.str().empty())
  522. return NULL;
  523. // Construct a new PathDiagnosticPiece.
  524. ProgramPoint P = N->getLocation();
  525. PathDiagnosticLocation L =
  526. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  527. if (!L.isValid())
  528. return NULL;
  529. PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
  530. X->setTag(getTag());
  531. return X;
  532. }
  533. return NULL;
  534. }
  535. bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S,
  536. BugReport &report, bool IsArg) {
  537. if (!S || !N)
  538. return false;
  539. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
  540. S = OVE->getSourceExpr();
  541. if (IsArg) {
  542. assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
  543. } else {
  544. // Walk through nodes until we get one that matches the statement exactly.
  545. do {
  546. const ProgramPoint &pp = N->getLocation();
  547. if (Optional<PostStmt> ps = pp.getAs<PostStmt>()) {
  548. if (ps->getStmt() == S)
  549. break;
  550. } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
  551. if (CEE->getCalleeContext()->getCallSite() == S)
  552. break;
  553. }
  554. N = N->getFirstPred();
  555. } while (N);
  556. if (!N)
  557. return false;
  558. }
  559. ProgramStateRef state = N->getState();
  560. // See if the expression we're interested refers to a variable.
  561. // If so, we can track both its contents and constraints on its value.
  562. if (const Expr *Ex = dyn_cast<Expr>(S)) {
  563. // Strip off parens and casts. Note that this will never have issues with
  564. // C++ user-defined implicit conversions, because those have a constructor
  565. // or function call inside.
  566. Ex = Ex->IgnoreParenCasts();
  567. if (Ex->isLValue()) {
  568. const MemRegion *R = 0;
  569. // First check if this is a DeclRefExpr for a C++ reference type.
  570. // For those, we want the location of the reference.
  571. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  572. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  573. if (VD->getType()->isReferenceType()) {
  574. ProgramStateManager &StateMgr = state->getStateManager();
  575. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  576. R = MRMgr.getVarRegion(VD, N->getLocationContext());
  577. }
  578. }
  579. }
  580. // For all other cases, find the location by scouring the ExplodedGraph.
  581. if (!R) {
  582. // Find the ExplodedNode where the lvalue (the value of 'Ex')
  583. // was computed. We need this for getting the location value.
  584. const ExplodedNode *LVNode = N;
  585. const Expr *SearchEx = Ex;
  586. if (const OpaqueValueExpr *OPE = dyn_cast<OpaqueValueExpr>(Ex)) {
  587. SearchEx = OPE->getSourceExpr();
  588. }
  589. while (LVNode) {
  590. if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
  591. if (P->getStmt() == SearchEx)
  592. break;
  593. }
  594. LVNode = LVNode->getFirstPred();
  595. }
  596. assert(LVNode && "Unable to find the lvalue node.");
  597. ProgramStateRef LVState = LVNode->getState();
  598. if (Optional<Loc> L =
  599. LVState->getSVal(Ex, LVNode->getLocationContext()).getAs<Loc>()) {
  600. R = L->getAsRegion();
  601. }
  602. }
  603. if (R) {
  604. // Mark both the variable region and its contents as interesting.
  605. SVal V = state->getRawSVal(loc::MemRegionVal(R));
  606. // If the value matches the default for the variable region, that
  607. // might mean that it's been cleared out of the state. Fall back to
  608. // the full argument expression (with casts and such intact).
  609. if (IsArg) {
  610. bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
  611. if (!UseArgValue) {
  612. const SymbolRegionValue *SRV =
  613. dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
  614. if (SRV)
  615. UseArgValue = (SRV->getRegion() == R);
  616. }
  617. if (UseArgValue)
  618. V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  619. }
  620. report.markInteresting(R);
  621. report.markInteresting(V);
  622. report.addVisitor(new UndefOrNullArgVisitor(R));
  623. if (isa<SymbolicRegion>(R)) {
  624. TrackConstraintBRVisitor *VI =
  625. new TrackConstraintBRVisitor(loc::MemRegionVal(R), false);
  626. report.addVisitor(VI);
  627. }
  628. // If the contents are symbolic, find out when they became null.
  629. if (V.getAsLocSymbol()) {
  630. BugReporterVisitor *ConstraintTracker =
  631. new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
  632. report.addVisitor(ConstraintTracker);
  633. }
  634. if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
  635. report.addVisitor(new FindLastStoreBRVisitor(*KV, R));
  636. return true;
  637. }
  638. }
  639. }
  640. // If the expression is not an "lvalue expression", we can still
  641. // track the constraints on its contents.
  642. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  643. // Uncomment this to find cases where we aren't properly getting the
  644. // base value that was dereferenced.
  645. // assert(!V.isUnknownOrUndef());
  646. // Is it a symbolic value?
  647. if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
  648. // At this point we are dealing with the region's LValue.
  649. // However, if the rvalue is a symbolic region, we should track it as well.
  650. SVal RVal = state->getSVal(L->getRegion());
  651. const MemRegion *RegionRVal = RVal.getAsRegion();
  652. report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
  653. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  654. report.markInteresting(RegionRVal);
  655. report.addVisitor(new TrackConstraintBRVisitor(
  656. loc::MemRegionVal(RegionRVal), false));
  657. }
  658. } else {
  659. // Otherwise, if the value came from an inlined function call,
  660. // we should at least make sure that function isn't pruned in our output.
  661. if (const Expr *E = dyn_cast<Expr>(S))
  662. S = E->IgnoreParenCasts();
  663. ReturnVisitor::addVisitorIfNecessary(N, S, report);
  664. }
  665. return true;
  666. }
  667. BugReporterVisitor *
  668. FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
  669. const MemRegion *R) {
  670. assert(R && "The memory region is null.");
  671. ProgramStateRef state = N->getState();
  672. if (Optional<KnownSVal> KV = state->getSVal(R).getAs<KnownSVal>())
  673. return new FindLastStoreBRVisitor(*KV, R);
  674. return 0;
  675. }
  676. PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  677. const ExplodedNode *PrevN,
  678. BugReporterContext &BRC,
  679. BugReport &BR) {
  680. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  681. if (!P)
  682. return 0;
  683. const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
  684. if (!ME)
  685. return 0;
  686. const Expr *Receiver = ME->getInstanceReceiver();
  687. if (!Receiver)
  688. return 0;
  689. ProgramStateRef state = N->getState();
  690. const SVal &V = state->getSVal(Receiver, N->getLocationContext());
  691. Optional<DefinedOrUnknownSVal> DV = V.getAs<DefinedOrUnknownSVal>();
  692. if (!DV)
  693. return 0;
  694. state = state->assume(*DV, true);
  695. if (state)
  696. return 0;
  697. // The receiver was nil, and hence the method was skipped.
  698. // Register a BugReporterVisitor to issue a message telling us how
  699. // the receiver was null.
  700. bugreporter::trackNullOrUndefValue(N, Receiver, BR);
  701. // Issue a message saying that the method was skipped.
  702. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  703. N->getLocationContext());
  704. return new PathDiagnosticEventPiece(L, "No method is called "
  705. "because the receiver is nil");
  706. }
  707. // Registers every VarDecl inside a Stmt with a last store visitor.
  708. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  709. const Stmt *S) {
  710. const ExplodedNode *N = BR.getErrorNode();
  711. std::deque<const Stmt *> WorkList;
  712. WorkList.push_back(S);
  713. while (!WorkList.empty()) {
  714. const Stmt *Head = WorkList.front();
  715. WorkList.pop_front();
  716. ProgramStateRef state = N->getState();
  717. ProgramStateManager &StateMgr = state->getStateManager();
  718. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
  719. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  720. const VarRegion *R =
  721. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  722. // What did we load?
  723. SVal V = state->getSVal(S, N->getLocationContext());
  724. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  725. // Register a new visitor with the BugReport.
  726. BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R));
  727. }
  728. }
  729. }
  730. for (Stmt::const_child_iterator I = Head->child_begin();
  731. I != Head->child_end(); ++I)
  732. WorkList.push_back(*I);
  733. }
  734. }
  735. //===----------------------------------------------------------------------===//
  736. // Visitor that tries to report interesting diagnostics from conditions.
  737. //===----------------------------------------------------------------------===//
  738. /// Return the tag associated with this visitor. This tag will be used
  739. /// to make all PathDiagnosticPieces created by this visitor.
  740. const char *ConditionBRVisitor::getTag() {
  741. return "ConditionBRVisitor";
  742. }
  743. PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
  744. const ExplodedNode *Prev,
  745. BugReporterContext &BRC,
  746. BugReport &BR) {
  747. PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
  748. if (piece) {
  749. piece->setTag(getTag());
  750. if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
  751. ev->setPrunable(true, /* override */ false);
  752. }
  753. return piece;
  754. }
  755. PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  756. const ExplodedNode *Prev,
  757. BugReporterContext &BRC,
  758. BugReport &BR) {
  759. ProgramPoint progPoint = N->getLocation();
  760. ProgramStateRef CurrentState = N->getState();
  761. ProgramStateRef PrevState = Prev->getState();
  762. // Compare the GDMs of the state, because that is where constraints
  763. // are managed. Note that ensure that we only look at nodes that
  764. // were generated by the analyzer engine proper, not checkers.
  765. if (CurrentState->getGDM().getRoot() ==
  766. PrevState->getGDM().getRoot())
  767. return 0;
  768. // If an assumption was made on a branch, it should be caught
  769. // here by looking at the state transition.
  770. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  771. const CFGBlock *srcBlk = BE->getSrc();
  772. if (const Stmt *term = srcBlk->getTerminator())
  773. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  774. return 0;
  775. }
  776. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  777. // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
  778. // violation.
  779. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  780. cast<GRBugReporter>(BRC.getBugReporter()).
  781. getEngine().geteagerlyAssumeBinOpBifurcationTags();
  782. const ProgramPointTag *tag = PS->getTag();
  783. if (tag == tags.first)
  784. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  785. BRC, BR, N);
  786. if (tag == tags.second)
  787. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  788. BRC, BR, N);
  789. return 0;
  790. }
  791. return 0;
  792. }
  793. PathDiagnosticPiece *
  794. ConditionBRVisitor::VisitTerminator(const Stmt *Term,
  795. const ExplodedNode *N,
  796. const CFGBlock *srcBlk,
  797. const CFGBlock *dstBlk,
  798. BugReport &R,
  799. BugReporterContext &BRC) {
  800. const Expr *Cond = 0;
  801. switch (Term->getStmtClass()) {
  802. default:
  803. return 0;
  804. case Stmt::IfStmtClass:
  805. Cond = cast<IfStmt>(Term)->getCond();
  806. break;
  807. case Stmt::ConditionalOperatorClass:
  808. Cond = cast<ConditionalOperator>(Term)->getCond();
  809. break;
  810. }
  811. assert(Cond);
  812. assert(srcBlk->succ_size() == 2);
  813. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  814. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  815. }
  816. PathDiagnosticPiece *
  817. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  818. bool tookTrue,
  819. BugReporterContext &BRC,
  820. BugReport &R,
  821. const ExplodedNode *N) {
  822. const Expr *Ex = Cond;
  823. while (true) {
  824. Ex = Ex->IgnoreParenCasts();
  825. switch (Ex->getStmtClass()) {
  826. default:
  827. return 0;
  828. case Stmt::BinaryOperatorClass:
  829. return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
  830. R, N);
  831. case Stmt::DeclRefExprClass:
  832. return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
  833. R, N);
  834. case Stmt::UnaryOperatorClass: {
  835. const UnaryOperator *UO = cast<UnaryOperator>(Ex);
  836. if (UO->getOpcode() == UO_LNot) {
  837. tookTrue = !tookTrue;
  838. Ex = UO->getSubExpr();
  839. continue;
  840. }
  841. return 0;
  842. }
  843. }
  844. }
  845. }
  846. bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
  847. BugReporterContext &BRC,
  848. BugReport &report,
  849. const ExplodedNode *N,
  850. Optional<bool> &prunable) {
  851. const Expr *OriginalExpr = Ex;
  852. Ex = Ex->IgnoreParenCasts();
  853. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  854. const bool quotes = isa<VarDecl>(DR->getDecl());
  855. if (quotes) {
  856. Out << '\'';
  857. const LocationContext *LCtx = N->getLocationContext();
  858. const ProgramState *state = N->getState().getPtr();
  859. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  860. LCtx).getAsRegion()) {
  861. if (report.isInteresting(R))
  862. prunable = false;
  863. else {
  864. const ProgramState *state = N->getState().getPtr();
  865. SVal V = state->getSVal(R);
  866. if (report.isInteresting(V))
  867. prunable = false;
  868. }
  869. }
  870. }
  871. Out << DR->getDecl()->getDeclName().getAsString();
  872. if (quotes)
  873. Out << '\'';
  874. return quotes;
  875. }
  876. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
  877. QualType OriginalTy = OriginalExpr->getType();
  878. if (OriginalTy->isPointerType()) {
  879. if (IL->getValue() == 0) {
  880. Out << "null";
  881. return false;
  882. }
  883. }
  884. else if (OriginalTy->isObjCObjectPointerType()) {
  885. if (IL->getValue() == 0) {
  886. Out << "nil";
  887. return false;
  888. }
  889. }
  890. Out << IL->getValue();
  891. return false;
  892. }
  893. return false;
  894. }
  895. PathDiagnosticPiece *
  896. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  897. const BinaryOperator *BExpr,
  898. const bool tookTrue,
  899. BugReporterContext &BRC,
  900. BugReport &R,
  901. const ExplodedNode *N) {
  902. bool shouldInvert = false;
  903. Optional<bool> shouldPrune;
  904. SmallString<128> LhsString, RhsString;
  905. {
  906. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  907. const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
  908. shouldPrune);
  909. const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
  910. shouldPrune);
  911. shouldInvert = !isVarLHS && isVarRHS;
  912. }
  913. BinaryOperator::Opcode Op = BExpr->getOpcode();
  914. if (BinaryOperator::isAssignmentOp(Op)) {
  915. // For assignment operators, all that we care about is that the LHS
  916. // evaluates to "true" or "false".
  917. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  918. BRC, R, N);
  919. }
  920. // For non-assignment operations, we require that we can understand
  921. // both the LHS and RHS.
  922. if (LhsString.empty() || RhsString.empty())
  923. return 0;
  924. // Should we invert the strings if the LHS is not a variable name?
  925. SmallString<256> buf;
  926. llvm::raw_svector_ostream Out(buf);
  927. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  928. // Do we need to invert the opcode?
  929. if (shouldInvert)
  930. switch (Op) {
  931. default: break;
  932. case BO_LT: Op = BO_GT; break;
  933. case BO_GT: Op = BO_LT; break;
  934. case BO_LE: Op = BO_GE; break;
  935. case BO_GE: Op = BO_LE; break;
  936. }
  937. if (!tookTrue)
  938. switch (Op) {
  939. case BO_EQ: Op = BO_NE; break;
  940. case BO_NE: Op = BO_EQ; break;
  941. case BO_LT: Op = BO_GE; break;
  942. case BO_GT: Op = BO_LE; break;
  943. case BO_LE: Op = BO_GT; break;
  944. case BO_GE: Op = BO_LT; break;
  945. default:
  946. return 0;
  947. }
  948. switch (Op) {
  949. case BO_EQ:
  950. Out << "equal to ";
  951. break;
  952. case BO_NE:
  953. Out << "not equal to ";
  954. break;
  955. default:
  956. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  957. break;
  958. }
  959. Out << (shouldInvert ? LhsString : RhsString);
  960. const LocationContext *LCtx = N->getLocationContext();
  961. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  962. PathDiagnosticEventPiece *event =
  963. new PathDiagnosticEventPiece(Loc, Out.str());
  964. if (shouldPrune.hasValue())
  965. event->setPrunable(shouldPrune.getValue());
  966. return event;
  967. }
  968. PathDiagnosticPiece *
  969. ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
  970. const Expr *CondVarExpr,
  971. const bool tookTrue,
  972. BugReporterContext &BRC,
  973. BugReport &report,
  974. const ExplodedNode *N) {
  975. // FIXME: If there's already a constraint tracker for this variable,
  976. // we shouldn't emit anything here (c.f. the double note in
  977. // test/Analysis/inlining/path-notes.c)
  978. SmallString<256> buf;
  979. llvm::raw_svector_ostream Out(buf);
  980. Out << "Assuming " << LhsString << " is ";
  981. QualType Ty = CondVarExpr->getType();
  982. if (Ty->isPointerType())
  983. Out << (tookTrue ? "not null" : "null");
  984. else if (Ty->isObjCObjectPointerType())
  985. Out << (tookTrue ? "not nil" : "nil");
  986. else if (Ty->isBooleanType())
  987. Out << (tookTrue ? "true" : "false");
  988. else if (Ty->isIntegerType())
  989. Out << (tookTrue ? "non-zero" : "zero");
  990. else
  991. return 0;
  992. const LocationContext *LCtx = N->getLocationContext();
  993. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  994. PathDiagnosticEventPiece *event =
  995. new PathDiagnosticEventPiece(Loc, Out.str());
  996. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  997. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  998. const ProgramState *state = N->getState().getPtr();
  999. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1000. if (report.isInteresting(R))
  1001. event->setPrunable(false);
  1002. }
  1003. }
  1004. }
  1005. return event;
  1006. }
  1007. PathDiagnosticPiece *
  1008. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  1009. const DeclRefExpr *DR,
  1010. const bool tookTrue,
  1011. BugReporterContext &BRC,
  1012. BugReport &report,
  1013. const ExplodedNode *N) {
  1014. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  1015. if (!VD)
  1016. return 0;
  1017. SmallString<256> Buf;
  1018. llvm::raw_svector_ostream Out(Buf);
  1019. Out << "Assuming '";
  1020. VD->getDeclName().printName(Out);
  1021. Out << "' is ";
  1022. QualType VDTy = VD->getType();
  1023. if (VDTy->isPointerType())
  1024. Out << (tookTrue ? "non-null" : "null");
  1025. else if (VDTy->isObjCObjectPointerType())
  1026. Out << (tookTrue ? "non-nil" : "nil");
  1027. else if (VDTy->isScalarType())
  1028. Out << (tookTrue ? "not equal to 0" : "0");
  1029. else
  1030. return 0;
  1031. const LocationContext *LCtx = N->getLocationContext();
  1032. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1033. PathDiagnosticEventPiece *event =
  1034. new PathDiagnosticEventPiece(Loc, Out.str());
  1035. const ProgramState *state = N->getState().getPtr();
  1036. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1037. if (report.isInteresting(R))
  1038. event->setPrunable(false);
  1039. else {
  1040. SVal V = state->getSVal(R);
  1041. if (report.isInteresting(V))
  1042. event->setPrunable(false);
  1043. }
  1044. }
  1045. return event;
  1046. }
  1047. PathDiagnosticPiece *
  1048. LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
  1049. const ExplodedNode *N,
  1050. BugReport &BR) {
  1051. const Stmt *S = BR.getStmt();
  1052. if (!S)
  1053. return 0;
  1054. // Here we suppress false positives coming from system macros. This list is
  1055. // based on known issues.
  1056. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1057. // reason about data structure shapes.
  1058. SourceManager &SM = BRC.getSourceManager();
  1059. SourceLocation Loc = S->getLocStart();
  1060. while (Loc.isMacroID()) {
  1061. if (SM.isInSystemMacro(Loc) &&
  1062. (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
  1063. BR.markInvalid(getTag(), 0);
  1064. return 0;
  1065. }
  1066. Loc = SM.getSpellingLoc(Loc);
  1067. }
  1068. return 0;
  1069. }
  1070. PathDiagnosticPiece *
  1071. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1072. const ExplodedNode *PrevN,
  1073. BugReporterContext &BRC,
  1074. BugReport &BR) {
  1075. ProgramStateRef State = N->getState();
  1076. ProgramPoint ProgLoc = N->getLocation();
  1077. // We are only interested in visiting CallEnter nodes.
  1078. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1079. if (!CEnter)
  1080. return 0;
  1081. // Check if one of the arguments is the region the visitor is tracking.
  1082. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1083. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1084. unsigned Idx = 0;
  1085. for (CallEvent::param_iterator I = Call->param_begin(),
  1086. E = Call->param_end(); I != E; ++I, ++Idx) {
  1087. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1088. // Are we tracking the argument or its subregion?
  1089. if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
  1090. continue;
  1091. // Check the function parameter type.
  1092. const ParmVarDecl *ParamDecl = *I;
  1093. assert(ParamDecl && "Formal parameter has no decl?");
  1094. QualType T = ParamDecl->getType();
  1095. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1096. // Function can only change the value passed in by address.
  1097. continue;
  1098. }
  1099. // If it is a const pointer value, the function does not intend to
  1100. // change the value.
  1101. if (T->getPointeeType().isConstQualified())
  1102. continue;
  1103. // Mark the call site (LocationContext) as interesting if the value of the
  1104. // argument is undefined or '0'/'NULL'.
  1105. SVal BoundVal = State->getSVal(R);
  1106. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1107. BR.markInteresting(CEnter->getCalleeContext());
  1108. return 0;
  1109. }
  1110. }
  1111. return 0;
  1112. }