BugReporterVisitors.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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 (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  568. // FIXME: Right now we only track VarDecls because it's non-trivial to
  569. // get a MemRegion for any other DeclRefExprs. <rdar://problem/12114812>
  570. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  571. ProgramStateManager &StateMgr = state->getStateManager();
  572. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  573. const VarRegion *R = MRMgr.getVarRegion(VD, N->getLocationContext());
  574. // Mark both the variable region and its contents as interesting.
  575. SVal V = state->getRawSVal(loc::MemRegionVal(R));
  576. // If the value matches the default for the variable region, that
  577. // might mean that it's been cleared out of the state. Fall back to
  578. // the full argument expression (with casts and such intact).
  579. if (IsArg) {
  580. bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
  581. if (!UseArgValue) {
  582. const SymbolRegionValue *SRV =
  583. dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
  584. if (SRV)
  585. UseArgValue = (SRV->getRegion() == R);
  586. }
  587. if (UseArgValue)
  588. V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  589. }
  590. report.markInteresting(R);
  591. report.markInteresting(V);
  592. report.addVisitor(new UndefOrNullArgVisitor(R));
  593. // If the contents are symbolic, find out when they became null.
  594. if (V.getAsLocSymbol()) {
  595. BugReporterVisitor *ConstraintTracker =
  596. new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
  597. report.addVisitor(ConstraintTracker);
  598. }
  599. if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
  600. report.addVisitor(new FindLastStoreBRVisitor(*KV, R));
  601. return true;
  602. }
  603. }
  604. }
  605. // If the expression does NOT refer to a variable, we can still track
  606. // constraints on its contents.
  607. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  608. // Uncomment this to find cases where we aren't properly getting the
  609. // base value that was dereferenced.
  610. // assert(!V.isUnknownOrUndef());
  611. // Is it a symbolic value?
  612. if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
  613. // At this point we are dealing with the region's LValue.
  614. // However, if the rvalue is a symbolic region, we should track it as well.
  615. SVal RVal = state->getSVal(L->getRegion());
  616. const MemRegion *RegionRVal = RVal.getAsRegion();
  617. report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
  618. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  619. report.markInteresting(RegionRVal);
  620. report.addVisitor(new TrackConstraintBRVisitor(
  621. loc::MemRegionVal(RegionRVal), false));
  622. }
  623. } else {
  624. // Otherwise, if the value came from an inlined function call,
  625. // we should at least make sure that function isn't pruned in our output.
  626. if (const Expr *E = dyn_cast<Expr>(S))
  627. S = E->IgnoreParenCasts();
  628. ReturnVisitor::addVisitorIfNecessary(N, S, report);
  629. }
  630. return true;
  631. }
  632. BugReporterVisitor *
  633. FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
  634. const MemRegion *R) {
  635. assert(R && "The memory region is null.");
  636. ProgramStateRef state = N->getState();
  637. if (Optional<KnownSVal> KV = state->getSVal(R).getAs<KnownSVal>())
  638. return new FindLastStoreBRVisitor(*KV, R);
  639. return 0;
  640. }
  641. PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  642. const ExplodedNode *PrevN,
  643. BugReporterContext &BRC,
  644. BugReport &BR) {
  645. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  646. if (!P)
  647. return 0;
  648. const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
  649. if (!ME)
  650. return 0;
  651. const Expr *Receiver = ME->getInstanceReceiver();
  652. if (!Receiver)
  653. return 0;
  654. ProgramStateRef state = N->getState();
  655. const SVal &V = state->getSVal(Receiver, N->getLocationContext());
  656. Optional<DefinedOrUnknownSVal> DV = V.getAs<DefinedOrUnknownSVal>();
  657. if (!DV)
  658. return 0;
  659. state = state->assume(*DV, true);
  660. if (state)
  661. return 0;
  662. // The receiver was nil, and hence the method was skipped.
  663. // Register a BugReporterVisitor to issue a message telling us how
  664. // the receiver was null.
  665. bugreporter::trackNullOrUndefValue(N, Receiver, BR);
  666. // Issue a message saying that the method was skipped.
  667. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  668. N->getLocationContext());
  669. return new PathDiagnosticEventPiece(L, "No method is called "
  670. "because the receiver is nil");
  671. }
  672. // Registers every VarDecl inside a Stmt with a last store visitor.
  673. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  674. const Stmt *S) {
  675. const ExplodedNode *N = BR.getErrorNode();
  676. std::deque<const Stmt *> WorkList;
  677. WorkList.push_back(S);
  678. while (!WorkList.empty()) {
  679. const Stmt *Head = WorkList.front();
  680. WorkList.pop_front();
  681. ProgramStateRef state = N->getState();
  682. ProgramStateManager &StateMgr = state->getStateManager();
  683. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
  684. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  685. const VarRegion *R =
  686. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  687. // What did we load?
  688. SVal V = state->getSVal(S, N->getLocationContext());
  689. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  690. // Register a new visitor with the BugReport.
  691. BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R));
  692. }
  693. }
  694. }
  695. for (Stmt::const_child_iterator I = Head->child_begin();
  696. I != Head->child_end(); ++I)
  697. WorkList.push_back(*I);
  698. }
  699. }
  700. //===----------------------------------------------------------------------===//
  701. // Visitor that tries to report interesting diagnostics from conditions.
  702. //===----------------------------------------------------------------------===//
  703. /// Return the tag associated with this visitor. This tag will be used
  704. /// to make all PathDiagnosticPieces created by this visitor.
  705. const char *ConditionBRVisitor::getTag() {
  706. return "ConditionBRVisitor";
  707. }
  708. PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
  709. const ExplodedNode *Prev,
  710. BugReporterContext &BRC,
  711. BugReport &BR) {
  712. PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
  713. if (piece) {
  714. piece->setTag(getTag());
  715. if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
  716. ev->setPrunable(true, /* override */ false);
  717. }
  718. return piece;
  719. }
  720. PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  721. const ExplodedNode *Prev,
  722. BugReporterContext &BRC,
  723. BugReport &BR) {
  724. ProgramPoint progPoint = N->getLocation();
  725. ProgramStateRef CurrentState = N->getState();
  726. ProgramStateRef PrevState = Prev->getState();
  727. // Compare the GDMs of the state, because that is where constraints
  728. // are managed. Note that ensure that we only look at nodes that
  729. // were generated by the analyzer engine proper, not checkers.
  730. if (CurrentState->getGDM().getRoot() ==
  731. PrevState->getGDM().getRoot())
  732. return 0;
  733. // If an assumption was made on a branch, it should be caught
  734. // here by looking at the state transition.
  735. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  736. const CFGBlock *srcBlk = BE->getSrc();
  737. if (const Stmt *term = srcBlk->getTerminator())
  738. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  739. return 0;
  740. }
  741. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  742. // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
  743. // violation.
  744. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  745. cast<GRBugReporter>(BRC.getBugReporter()).
  746. getEngine().geteagerlyAssumeBinOpBifurcationTags();
  747. const ProgramPointTag *tag = PS->getTag();
  748. if (tag == tags.first)
  749. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  750. BRC, BR, N);
  751. if (tag == tags.second)
  752. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  753. BRC, BR, N);
  754. return 0;
  755. }
  756. return 0;
  757. }
  758. PathDiagnosticPiece *
  759. ConditionBRVisitor::VisitTerminator(const Stmt *Term,
  760. const ExplodedNode *N,
  761. const CFGBlock *srcBlk,
  762. const CFGBlock *dstBlk,
  763. BugReport &R,
  764. BugReporterContext &BRC) {
  765. const Expr *Cond = 0;
  766. switch (Term->getStmtClass()) {
  767. default:
  768. return 0;
  769. case Stmt::IfStmtClass:
  770. Cond = cast<IfStmt>(Term)->getCond();
  771. break;
  772. case Stmt::ConditionalOperatorClass:
  773. Cond = cast<ConditionalOperator>(Term)->getCond();
  774. break;
  775. }
  776. assert(Cond);
  777. assert(srcBlk->succ_size() == 2);
  778. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  779. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  780. }
  781. PathDiagnosticPiece *
  782. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  783. bool tookTrue,
  784. BugReporterContext &BRC,
  785. BugReport &R,
  786. const ExplodedNode *N) {
  787. const Expr *Ex = Cond;
  788. while (true) {
  789. Ex = Ex->IgnoreParenCasts();
  790. switch (Ex->getStmtClass()) {
  791. default:
  792. return 0;
  793. case Stmt::BinaryOperatorClass:
  794. return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
  795. R, N);
  796. case Stmt::DeclRefExprClass:
  797. return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
  798. R, N);
  799. case Stmt::UnaryOperatorClass: {
  800. const UnaryOperator *UO = cast<UnaryOperator>(Ex);
  801. if (UO->getOpcode() == UO_LNot) {
  802. tookTrue = !tookTrue;
  803. Ex = UO->getSubExpr();
  804. continue;
  805. }
  806. return 0;
  807. }
  808. }
  809. }
  810. }
  811. bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
  812. BugReporterContext &BRC,
  813. BugReport &report,
  814. const ExplodedNode *N,
  815. Optional<bool> &prunable) {
  816. const Expr *OriginalExpr = Ex;
  817. Ex = Ex->IgnoreParenCasts();
  818. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
  819. const bool quotes = isa<VarDecl>(DR->getDecl());
  820. if (quotes) {
  821. Out << '\'';
  822. const LocationContext *LCtx = N->getLocationContext();
  823. const ProgramState *state = N->getState().getPtr();
  824. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  825. LCtx).getAsRegion()) {
  826. if (report.isInteresting(R))
  827. prunable = false;
  828. else {
  829. const ProgramState *state = N->getState().getPtr();
  830. SVal V = state->getSVal(R);
  831. if (report.isInteresting(V))
  832. prunable = false;
  833. }
  834. }
  835. }
  836. Out << DR->getDecl()->getDeclName().getAsString();
  837. if (quotes)
  838. Out << '\'';
  839. return quotes;
  840. }
  841. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
  842. QualType OriginalTy = OriginalExpr->getType();
  843. if (OriginalTy->isPointerType()) {
  844. if (IL->getValue() == 0) {
  845. Out << "null";
  846. return false;
  847. }
  848. }
  849. else if (OriginalTy->isObjCObjectPointerType()) {
  850. if (IL->getValue() == 0) {
  851. Out << "nil";
  852. return false;
  853. }
  854. }
  855. Out << IL->getValue();
  856. return false;
  857. }
  858. return false;
  859. }
  860. PathDiagnosticPiece *
  861. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  862. const BinaryOperator *BExpr,
  863. const bool tookTrue,
  864. BugReporterContext &BRC,
  865. BugReport &R,
  866. const ExplodedNode *N) {
  867. bool shouldInvert = false;
  868. Optional<bool> shouldPrune;
  869. SmallString<128> LhsString, RhsString;
  870. {
  871. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  872. const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
  873. shouldPrune);
  874. const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
  875. shouldPrune);
  876. shouldInvert = !isVarLHS && isVarRHS;
  877. }
  878. BinaryOperator::Opcode Op = BExpr->getOpcode();
  879. if (BinaryOperator::isAssignmentOp(Op)) {
  880. // For assignment operators, all that we care about is that the LHS
  881. // evaluates to "true" or "false".
  882. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  883. BRC, R, N);
  884. }
  885. // For non-assignment operations, we require that we can understand
  886. // both the LHS and RHS.
  887. if (LhsString.empty() || RhsString.empty())
  888. return 0;
  889. // Should we invert the strings if the LHS is not a variable name?
  890. SmallString<256> buf;
  891. llvm::raw_svector_ostream Out(buf);
  892. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  893. // Do we need to invert the opcode?
  894. if (shouldInvert)
  895. switch (Op) {
  896. default: break;
  897. case BO_LT: Op = BO_GT; break;
  898. case BO_GT: Op = BO_LT; break;
  899. case BO_LE: Op = BO_GE; break;
  900. case BO_GE: Op = BO_LE; break;
  901. }
  902. if (!tookTrue)
  903. switch (Op) {
  904. case BO_EQ: Op = BO_NE; break;
  905. case BO_NE: Op = BO_EQ; break;
  906. case BO_LT: Op = BO_GE; break;
  907. case BO_GT: Op = BO_LE; break;
  908. case BO_LE: Op = BO_GT; break;
  909. case BO_GE: Op = BO_LT; break;
  910. default:
  911. return 0;
  912. }
  913. switch (Op) {
  914. case BO_EQ:
  915. Out << "equal to ";
  916. break;
  917. case BO_NE:
  918. Out << "not equal to ";
  919. break;
  920. default:
  921. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  922. break;
  923. }
  924. Out << (shouldInvert ? LhsString : RhsString);
  925. const LocationContext *LCtx = N->getLocationContext();
  926. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  927. PathDiagnosticEventPiece *event =
  928. new PathDiagnosticEventPiece(Loc, Out.str());
  929. if (shouldPrune.hasValue())
  930. event->setPrunable(shouldPrune.getValue());
  931. return event;
  932. }
  933. PathDiagnosticPiece *
  934. ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
  935. const Expr *CondVarExpr,
  936. const bool tookTrue,
  937. BugReporterContext &BRC,
  938. BugReport &report,
  939. const ExplodedNode *N) {
  940. // FIXME: If there's already a constraint tracker for this variable,
  941. // we shouldn't emit anything here (c.f. the double note in
  942. // test/Analysis/inlining/path-notes.c)
  943. SmallString<256> buf;
  944. llvm::raw_svector_ostream Out(buf);
  945. Out << "Assuming " << LhsString << " is ";
  946. QualType Ty = CondVarExpr->getType();
  947. if (Ty->isPointerType())
  948. Out << (tookTrue ? "not null" : "null");
  949. else if (Ty->isObjCObjectPointerType())
  950. Out << (tookTrue ? "not nil" : "nil");
  951. else if (Ty->isBooleanType())
  952. Out << (tookTrue ? "true" : "false");
  953. else if (Ty->isIntegerType())
  954. Out << (tookTrue ? "non-zero" : "zero");
  955. else
  956. return 0;
  957. const LocationContext *LCtx = N->getLocationContext();
  958. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  959. PathDiagnosticEventPiece *event =
  960. new PathDiagnosticEventPiece(Loc, Out.str());
  961. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  962. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  963. const ProgramState *state = N->getState().getPtr();
  964. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  965. if (report.isInteresting(R))
  966. event->setPrunable(false);
  967. }
  968. }
  969. }
  970. return event;
  971. }
  972. PathDiagnosticPiece *
  973. ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
  974. const DeclRefExpr *DR,
  975. const bool tookTrue,
  976. BugReporterContext &BRC,
  977. BugReport &report,
  978. const ExplodedNode *N) {
  979. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  980. if (!VD)
  981. return 0;
  982. SmallString<256> Buf;
  983. llvm::raw_svector_ostream Out(Buf);
  984. Out << "Assuming '";
  985. VD->getDeclName().printName(Out);
  986. Out << "' is ";
  987. QualType VDTy = VD->getType();
  988. if (VDTy->isPointerType())
  989. Out << (tookTrue ? "non-null" : "null");
  990. else if (VDTy->isObjCObjectPointerType())
  991. Out << (tookTrue ? "non-nil" : "nil");
  992. else if (VDTy->isScalarType())
  993. Out << (tookTrue ? "not equal to 0" : "0");
  994. else
  995. return 0;
  996. const LocationContext *LCtx = N->getLocationContext();
  997. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  998. PathDiagnosticEventPiece *event =
  999. new PathDiagnosticEventPiece(Loc, Out.str());
  1000. const ProgramState *state = N->getState().getPtr();
  1001. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1002. if (report.isInteresting(R))
  1003. event->setPrunable(false);
  1004. else {
  1005. SVal V = state->getSVal(R);
  1006. if (report.isInteresting(V))
  1007. event->setPrunable(false);
  1008. }
  1009. }
  1010. return event;
  1011. }
  1012. PathDiagnosticPiece *
  1013. LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
  1014. const ExplodedNode *N,
  1015. BugReport &BR) {
  1016. const Stmt *S = BR.getStmt();
  1017. if (!S)
  1018. return 0;
  1019. // Here we suppress false positives coming from system macros. This list is
  1020. // based on known issues.
  1021. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1022. // reason about data structure shapes.
  1023. SourceManager &SM = BRC.getSourceManager();
  1024. SourceLocation Loc = S->getLocStart();
  1025. while (Loc.isMacroID()) {
  1026. if (SM.isInSystemMacro(Loc) &&
  1027. (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
  1028. BR.markInvalid(getTag(), 0);
  1029. return 0;
  1030. }
  1031. Loc = SM.getSpellingLoc(Loc);
  1032. }
  1033. return 0;
  1034. }
  1035. PathDiagnosticPiece *
  1036. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1037. const ExplodedNode *PrevN,
  1038. BugReporterContext &BRC,
  1039. BugReport &BR) {
  1040. ProgramStateRef State = N->getState();
  1041. ProgramPoint ProgLoc = N->getLocation();
  1042. // We are only interested in visiting CallEnter nodes.
  1043. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1044. if (!CEnter)
  1045. return 0;
  1046. // Check if one of the arguments is the region the visitor is tracking.
  1047. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1048. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1049. unsigned Idx = 0;
  1050. for (CallEvent::param_iterator I = Call->param_begin(),
  1051. E = Call->param_end(); I != E; ++I, ++Idx) {
  1052. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1053. // Are we tracking the argument or its subregion?
  1054. if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
  1055. continue;
  1056. // Check the function parameter type.
  1057. const ParmVarDecl *ParamDecl = *I;
  1058. assert(ParamDecl && "Formal parameter has no decl?");
  1059. QualType T = ParamDecl->getType();
  1060. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1061. // Function can only change the value passed in by address.
  1062. continue;
  1063. }
  1064. // If it is a const pointer value, the function does not intend to
  1065. // change the value.
  1066. if (T->getPointeeType().isConstQualified())
  1067. continue;
  1068. // Mark the call site (LocationContext) as interesting if the value of the
  1069. // argument is undefined or '0'/'NULL'.
  1070. SVal BoundVal = State->getSVal(R);
  1071. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1072. BR.markInteresting(CEnter->getCalleeContext());
  1073. return 0;
  1074. }
  1075. }
  1076. return 0;
  1077. }