BugReporter.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165
  1. // BugReporter.cpp - Generate PathDiagnostics for 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 BugReporter, a utility class for generating
  11. // PathDiagnostics.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/Analysis/CFG.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/Basic/SourceManager.h"
  24. #include "clang/Analysis/ProgramPoint.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SmallString.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/OwningPtr.h"
  31. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  32. #include <queue>
  33. using namespace clang;
  34. using namespace ento;
  35. BugReporterVisitor::~BugReporterVisitor() {}
  36. void BugReporterContext::anchor() {}
  37. //===----------------------------------------------------------------------===//
  38. // Helper routines for walking the ExplodedGraph and fetching statements.
  39. //===----------------------------------------------------------------------===//
  40. static inline const Stmt *GetStmt(const ProgramPoint &P) {
  41. if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P))
  42. return SP->getStmt();
  43. else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
  44. return BE->getSrc()->getTerminator();
  45. else if (const CallEnter *CE = dyn_cast<CallEnter>(&P))
  46. return CE->getCallExpr();
  47. else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&P))
  48. return CEE->getCalleeContext()->getCallSite();
  49. return 0;
  50. }
  51. static inline const ExplodedNode*
  52. GetPredecessorNode(const ExplodedNode *N) {
  53. return N->pred_empty() ? NULL : *(N->pred_begin());
  54. }
  55. static inline const ExplodedNode*
  56. GetSuccessorNode(const ExplodedNode *N) {
  57. return N->succ_empty() ? NULL : *(N->succ_begin());
  58. }
  59. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  60. for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
  61. if (const Stmt *S = GetStmt(N->getLocation()))
  62. return S;
  63. return 0;
  64. }
  65. static const Stmt *GetNextStmt(const ExplodedNode *N) {
  66. for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
  67. if (const Stmt *S = GetStmt(N->getLocation())) {
  68. // Check if the statement is '?' or '&&'/'||'. These are "merges",
  69. // not actual statement points.
  70. switch (S->getStmtClass()) {
  71. case Stmt::ChooseExprClass:
  72. case Stmt::BinaryConditionalOperatorClass: continue;
  73. case Stmt::ConditionalOperatorClass: continue;
  74. case Stmt::BinaryOperatorClass: {
  75. BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
  76. if (Op == BO_LAnd || Op == BO_LOr)
  77. continue;
  78. break;
  79. }
  80. default:
  81. break;
  82. }
  83. return S;
  84. }
  85. return 0;
  86. }
  87. static inline const Stmt*
  88. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  89. if (const Stmt *S = GetStmt(N->getLocation()))
  90. return S;
  91. return GetPreviousStmt(N);
  92. }
  93. static inline const Stmt*
  94. GetCurrentOrNextStmt(const ExplodedNode *N) {
  95. if (const Stmt *S = GetStmt(N->getLocation()))
  96. return S;
  97. return GetNextStmt(N);
  98. }
  99. //===----------------------------------------------------------------------===//
  100. // Diagnostic cleanup.
  101. //===----------------------------------------------------------------------===//
  102. /// Recursively scan through a path and prune out calls and macros pieces
  103. /// that aren't needed. Return true if afterwards the path contains
  104. /// "interesting stuff" which means it should be pruned from the parent path.
  105. static bool RemoveUneededCalls(PathPieces &pieces) {
  106. bool containsSomethingInteresting = false;
  107. const unsigned N = pieces.size();
  108. for (unsigned i = 0 ; i < N ; ++i) {
  109. // Remove the front piece from the path. If it is still something we
  110. // want to keep once we are done, we will push it back on the end.
  111. IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
  112. pieces.pop_front();
  113. switch (piece->getKind()) {
  114. case PathDiagnosticPiece::Call: {
  115. PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
  116. // Recursively clean out the subclass. Keep this call around if
  117. // it contains any informative diagnostics.
  118. if (!RemoveUneededCalls(call->path))
  119. continue;
  120. containsSomethingInteresting = true;
  121. break;
  122. }
  123. case PathDiagnosticPiece::Macro: {
  124. PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
  125. if (!RemoveUneededCalls(macro->subPieces))
  126. continue;
  127. containsSomethingInteresting = true;
  128. break;
  129. }
  130. case PathDiagnosticPiece::Event: {
  131. PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
  132. // We never throw away an event, but we do throw it away wholesale
  133. // as part of a path if we throw the entire path away.
  134. if (event->isPrunable())
  135. continue;
  136. containsSomethingInteresting = true;
  137. break;
  138. }
  139. case PathDiagnosticPiece::ControlFlow:
  140. break;
  141. }
  142. pieces.push_back(piece);
  143. }
  144. return containsSomethingInteresting;
  145. }
  146. //===----------------------------------------------------------------------===//
  147. // PathDiagnosticBuilder and its associated routines and helper objects.
  148. //===----------------------------------------------------------------------===//
  149. typedef llvm::DenseMap<const ExplodedNode*,
  150. const ExplodedNode*> NodeBackMap;
  151. namespace {
  152. class NodeMapClosure : public BugReport::NodeResolver {
  153. NodeBackMap& M;
  154. public:
  155. NodeMapClosure(NodeBackMap *m) : M(*m) {}
  156. ~NodeMapClosure() {}
  157. const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
  158. NodeBackMap::iterator I = M.find(N);
  159. return I == M.end() ? 0 : I->second;
  160. }
  161. };
  162. class PathDiagnosticBuilder : public BugReporterContext {
  163. BugReport *R;
  164. PathDiagnosticConsumer *PDC;
  165. OwningPtr<ParentMap> PM;
  166. NodeMapClosure NMC;
  167. public:
  168. const LocationContext *LC;
  169. PathDiagnosticBuilder(GRBugReporter &br,
  170. BugReport *r, NodeBackMap *Backmap,
  171. PathDiagnosticConsumer *pdc)
  172. : BugReporterContext(br),
  173. R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
  174. {}
  175. PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
  176. PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
  177. const ExplodedNode *N);
  178. BugReport *getBugReport() { return R; }
  179. Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
  180. ParentMap& getParentMap() { return LC->getParentMap(); }
  181. const Stmt *getParent(const Stmt *S) {
  182. return getParentMap().getParent(S);
  183. }
  184. virtual NodeMapClosure& getNodeResolver() { return NMC; }
  185. PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
  186. PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
  187. return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
  188. }
  189. bool supportsLogicalOpControlFlow() const {
  190. return PDC ? PDC->supportsLogicalOpControlFlow() : true;
  191. }
  192. };
  193. } // end anonymous namespace
  194. PathDiagnosticLocation
  195. PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
  196. if (const Stmt *S = GetNextStmt(N))
  197. return PathDiagnosticLocation(S, getSourceManager(), LC);
  198. return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
  199. getSourceManager());
  200. }
  201. PathDiagnosticLocation
  202. PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
  203. const ExplodedNode *N) {
  204. // Slow, but probably doesn't matter.
  205. if (os.str().empty())
  206. os << ' ';
  207. const PathDiagnosticLocation &Loc = ExecutionContinues(N);
  208. if (Loc.asStmt())
  209. os << "Execution continues on line "
  210. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  211. << '.';
  212. else {
  213. os << "Execution jumps to the end of the ";
  214. const Decl *D = N->getLocationContext()->getDecl();
  215. if (isa<ObjCMethodDecl>(D))
  216. os << "method";
  217. else if (isa<FunctionDecl>(D))
  218. os << "function";
  219. else {
  220. assert(isa<BlockDecl>(D));
  221. os << "anonymous block";
  222. }
  223. os << '.';
  224. }
  225. return Loc;
  226. }
  227. static bool IsNested(const Stmt *S, ParentMap &PM) {
  228. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  229. return true;
  230. const Stmt *Parent = PM.getParentIgnoreParens(S);
  231. if (Parent)
  232. switch (Parent->getStmtClass()) {
  233. case Stmt::ForStmtClass:
  234. case Stmt::DoStmtClass:
  235. case Stmt::WhileStmtClass:
  236. return true;
  237. default:
  238. break;
  239. }
  240. return false;
  241. }
  242. PathDiagnosticLocation
  243. PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
  244. assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
  245. ParentMap &P = getParentMap();
  246. SourceManager &SMgr = getSourceManager();
  247. while (IsNested(S, P)) {
  248. const Stmt *Parent = P.getParentIgnoreParens(S);
  249. if (!Parent)
  250. break;
  251. switch (Parent->getStmtClass()) {
  252. case Stmt::BinaryOperatorClass: {
  253. const BinaryOperator *B = cast<BinaryOperator>(Parent);
  254. if (B->isLogicalOp())
  255. return PathDiagnosticLocation(S, SMgr, LC);
  256. break;
  257. }
  258. case Stmt::CompoundStmtClass:
  259. case Stmt::StmtExprClass:
  260. return PathDiagnosticLocation(S, SMgr, LC);
  261. case Stmt::ChooseExprClass:
  262. // Similar to '?' if we are referring to condition, just have the edge
  263. // point to the entire choose expression.
  264. if (cast<ChooseExpr>(Parent)->getCond() == S)
  265. return PathDiagnosticLocation(Parent, SMgr, LC);
  266. else
  267. return PathDiagnosticLocation(S, SMgr, LC);
  268. case Stmt::BinaryConditionalOperatorClass:
  269. case Stmt::ConditionalOperatorClass:
  270. // For '?', if we are referring to condition, just have the edge point
  271. // to the entire '?' expression.
  272. if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  273. return PathDiagnosticLocation(Parent, SMgr, LC);
  274. else
  275. return PathDiagnosticLocation(S, SMgr, LC);
  276. case Stmt::DoStmtClass:
  277. return PathDiagnosticLocation(S, SMgr, LC);
  278. case Stmt::ForStmtClass:
  279. if (cast<ForStmt>(Parent)->getBody() == S)
  280. return PathDiagnosticLocation(S, SMgr, LC);
  281. break;
  282. case Stmt::IfStmtClass:
  283. if (cast<IfStmt>(Parent)->getCond() != S)
  284. return PathDiagnosticLocation(S, SMgr, LC);
  285. break;
  286. case Stmt::ObjCForCollectionStmtClass:
  287. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  288. return PathDiagnosticLocation(S, SMgr, LC);
  289. break;
  290. case Stmt::WhileStmtClass:
  291. if (cast<WhileStmt>(Parent)->getCond() != S)
  292. return PathDiagnosticLocation(S, SMgr, LC);
  293. break;
  294. default:
  295. break;
  296. }
  297. S = Parent;
  298. }
  299. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  300. // Special case: DeclStmts can appear in for statement declarations, in which
  301. // case the ForStmt is the context.
  302. if (isa<DeclStmt>(S)) {
  303. if (const Stmt *Parent = P.getParent(S)) {
  304. switch (Parent->getStmtClass()) {
  305. case Stmt::ForStmtClass:
  306. case Stmt::ObjCForCollectionStmtClass:
  307. return PathDiagnosticLocation(Parent, SMgr, LC);
  308. default:
  309. break;
  310. }
  311. }
  312. }
  313. else if (isa<BinaryOperator>(S)) {
  314. // Special case: the binary operator represents the initialization
  315. // code in a for statement (this can happen when the variable being
  316. // initialized is an old variable.
  317. if (const ForStmt *FS =
  318. dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
  319. if (FS->getInit() == S)
  320. return PathDiagnosticLocation(FS, SMgr, LC);
  321. }
  322. }
  323. return PathDiagnosticLocation(S, SMgr, LC);
  324. }
  325. //===----------------------------------------------------------------------===//
  326. // "Minimal" path diagnostic generation algorithm.
  327. //===----------------------------------------------------------------------===//
  328. typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
  329. typedef SmallVector<StackDiagPair, 6> StackDiagVector;
  330. static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
  331. StackDiagVector &CallStack) {
  332. // If the piece contains a special message, add it to all the call
  333. // pieces on the active stack.
  334. if (PathDiagnosticEventPiece *ep =
  335. dyn_cast<PathDiagnosticEventPiece>(P)) {
  336. if (ep->hasCallStackHint())
  337. for (StackDiagVector::iterator I = CallStack.begin(),
  338. E = CallStack.end(); I != E; ++I) {
  339. PathDiagnosticCallPiece *CP = I->first;
  340. const ExplodedNode *N = I->second;
  341. std::string stackMsg = ep->getCallStackMessage(N);
  342. // The last message on the path to final bug is the most important
  343. // one. Since we traverse the path backwards, do not add the message
  344. // if one has been previously added.
  345. if (!CP->hasCallStackMessage())
  346. CP->setCallStackMessage(stackMsg);
  347. }
  348. }
  349. }
  350. static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
  351. static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
  352. PathDiagnosticBuilder &PDB,
  353. const ExplodedNode *N,
  354. ArrayRef<BugReporterVisitor *> visitors) {
  355. SourceManager& SMgr = PDB.getSourceManager();
  356. const LocationContext *LC = PDB.LC;
  357. const ExplodedNode *NextNode = N->pred_empty()
  358. ? NULL : *(N->pred_begin());
  359. StackDiagVector CallStack;
  360. while (NextNode) {
  361. N = NextNode;
  362. PDB.LC = N->getLocationContext();
  363. NextNode = GetPredecessorNode(N);
  364. ProgramPoint P = N->getLocation();
  365. if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) {
  366. PathDiagnosticCallPiece *C =
  367. PathDiagnosticCallPiece::construct(N, *CE, SMgr);
  368. PD.getActivePath().push_front(C);
  369. PD.pushActivePath(&C->path);
  370. CallStack.push_back(StackDiagPair(C, N));
  371. continue;
  372. }
  373. if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) {
  374. PD.popActivePath();
  375. // The current active path should never be empty. Either we
  376. // just added a bunch of stuff to the top-level path, or
  377. // we have a previous CallExitEnd. If the front of the active
  378. // path is not a PathDiagnosticCallPiece, it means that the
  379. // path terminated within a function call. We must then take the
  380. // current contents of the active path and place it within
  381. // a new PathDiagnosticCallPiece.
  382. assert(!PD.getActivePath().empty());
  383. PathDiagnosticCallPiece *C =
  384. dyn_cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
  385. if (!C) {
  386. const Decl *Caller = CE->getLocationContext()->getDecl();
  387. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  388. }
  389. C->setCallee(*CE, SMgr);
  390. if (!CallStack.empty()) {
  391. assert(CallStack.back().first == C);
  392. CallStack.pop_back();
  393. }
  394. continue;
  395. }
  396. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  397. const CFGBlock *Src = BE->getSrc();
  398. const CFGBlock *Dst = BE->getDst();
  399. const Stmt *T = Src->getTerminator();
  400. if (!T)
  401. continue;
  402. PathDiagnosticLocation Start =
  403. PathDiagnosticLocation::createBegin(T, SMgr,
  404. N->getLocationContext());
  405. switch (T->getStmtClass()) {
  406. default:
  407. break;
  408. case Stmt::GotoStmtClass:
  409. case Stmt::IndirectGotoStmtClass: {
  410. const Stmt *S = GetNextStmt(N);
  411. if (!S)
  412. continue;
  413. std::string sbuf;
  414. llvm::raw_string_ostream os(sbuf);
  415. const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
  416. os << "Control jumps to line "
  417. << End.asLocation().getExpansionLineNumber();
  418. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  419. os.str()));
  420. break;
  421. }
  422. case Stmt::SwitchStmtClass: {
  423. // Figure out what case arm we took.
  424. std::string sbuf;
  425. llvm::raw_string_ostream os(sbuf);
  426. if (const Stmt *S = Dst->getLabel()) {
  427. PathDiagnosticLocation End(S, SMgr, LC);
  428. switch (S->getStmtClass()) {
  429. default:
  430. os << "No cases match in the switch statement. "
  431. "Control jumps to line "
  432. << End.asLocation().getExpansionLineNumber();
  433. break;
  434. case Stmt::DefaultStmtClass:
  435. os << "Control jumps to the 'default' case at line "
  436. << End.asLocation().getExpansionLineNumber();
  437. break;
  438. case Stmt::CaseStmtClass: {
  439. os << "Control jumps to 'case ";
  440. const CaseStmt *Case = cast<CaseStmt>(S);
  441. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  442. // Determine if it is an enum.
  443. bool GetRawInt = true;
  444. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
  445. // FIXME: Maybe this should be an assertion. Are there cases
  446. // were it is not an EnumConstantDecl?
  447. const EnumConstantDecl *D =
  448. dyn_cast<EnumConstantDecl>(DR->getDecl());
  449. if (D) {
  450. GetRawInt = false;
  451. os << *D;
  452. }
  453. }
  454. if (GetRawInt)
  455. os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
  456. os << ":' at line "
  457. << End.asLocation().getExpansionLineNumber();
  458. break;
  459. }
  460. }
  461. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  462. os.str()));
  463. }
  464. else {
  465. os << "'Default' branch taken. ";
  466. const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
  467. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  468. os.str()));
  469. }
  470. break;
  471. }
  472. case Stmt::BreakStmtClass:
  473. case Stmt::ContinueStmtClass: {
  474. std::string sbuf;
  475. llvm::raw_string_ostream os(sbuf);
  476. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  477. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  478. os.str()));
  479. break;
  480. }
  481. // Determine control-flow for ternary '?'.
  482. case Stmt::BinaryConditionalOperatorClass:
  483. case Stmt::ConditionalOperatorClass: {
  484. std::string sbuf;
  485. llvm::raw_string_ostream os(sbuf);
  486. os << "'?' condition is ";
  487. if (*(Src->succ_begin()+1) == Dst)
  488. os << "false";
  489. else
  490. os << "true";
  491. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  492. if (const Stmt *S = End.asStmt())
  493. End = PDB.getEnclosingStmtLocation(S);
  494. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  495. os.str()));
  496. break;
  497. }
  498. // Determine control-flow for short-circuited '&&' and '||'.
  499. case Stmt::BinaryOperatorClass: {
  500. if (!PDB.supportsLogicalOpControlFlow())
  501. break;
  502. const BinaryOperator *B = cast<BinaryOperator>(T);
  503. std::string sbuf;
  504. llvm::raw_string_ostream os(sbuf);
  505. os << "Left side of '";
  506. if (B->getOpcode() == BO_LAnd) {
  507. os << "&&" << "' is ";
  508. if (*(Src->succ_begin()+1) == Dst) {
  509. os << "false";
  510. PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
  511. PathDiagnosticLocation Start =
  512. PathDiagnosticLocation::createOperatorLoc(B, SMgr);
  513. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  514. os.str()));
  515. }
  516. else {
  517. os << "true";
  518. PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
  519. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  520. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  521. os.str()));
  522. }
  523. }
  524. else {
  525. assert(B->getOpcode() == BO_LOr);
  526. os << "||" << "' is ";
  527. if (*(Src->succ_begin()+1) == Dst) {
  528. os << "false";
  529. PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
  530. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  531. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  532. os.str()));
  533. }
  534. else {
  535. os << "true";
  536. PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
  537. PathDiagnosticLocation Start =
  538. PathDiagnosticLocation::createOperatorLoc(B, SMgr);
  539. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  540. os.str()));
  541. }
  542. }
  543. break;
  544. }
  545. case Stmt::DoStmtClass: {
  546. if (*(Src->succ_begin()) == Dst) {
  547. std::string sbuf;
  548. llvm::raw_string_ostream os(sbuf);
  549. os << "Loop condition is true. ";
  550. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  551. if (const Stmt *S = End.asStmt())
  552. End = PDB.getEnclosingStmtLocation(S);
  553. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  554. os.str()));
  555. }
  556. else {
  557. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  558. if (const Stmt *S = End.asStmt())
  559. End = PDB.getEnclosingStmtLocation(S);
  560. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  561. "Loop condition is false. Exiting loop"));
  562. }
  563. break;
  564. }
  565. case Stmt::WhileStmtClass:
  566. case Stmt::ForStmtClass: {
  567. if (*(Src->succ_begin()+1) == Dst) {
  568. std::string sbuf;
  569. llvm::raw_string_ostream os(sbuf);
  570. os << "Loop condition is false. ";
  571. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  572. if (const Stmt *S = End.asStmt())
  573. End = PDB.getEnclosingStmtLocation(S);
  574. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  575. os.str()));
  576. }
  577. else {
  578. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  579. if (const Stmt *S = End.asStmt())
  580. End = PDB.getEnclosingStmtLocation(S);
  581. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  582. "Loop condition is true. Entering loop body"));
  583. }
  584. break;
  585. }
  586. case Stmt::IfStmtClass: {
  587. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  588. if (const Stmt *S = End.asStmt())
  589. End = PDB.getEnclosingStmtLocation(S);
  590. if (*(Src->succ_begin()+1) == Dst)
  591. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  592. "Taking false branch"));
  593. else
  594. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(Start, End,
  595. "Taking true branch"));
  596. break;
  597. }
  598. }
  599. }
  600. if (NextNode) {
  601. // Add diagnostic pieces from custom visitors.
  602. BugReport *R = PDB.getBugReport();
  603. for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
  604. E = visitors.end();
  605. I != E; ++I) {
  606. if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
  607. PD.getActivePath().push_front(p);
  608. updateStackPiecesWithMessage(p, CallStack);
  609. }
  610. }
  611. }
  612. }
  613. // After constructing the full PathDiagnostic, do a pass over it to compact
  614. // PathDiagnosticPieces that occur within a macro.
  615. CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
  616. }
  617. //===----------------------------------------------------------------------===//
  618. // "Extensive" PathDiagnostic generation.
  619. //===----------------------------------------------------------------------===//
  620. static bool IsControlFlowExpr(const Stmt *S) {
  621. const Expr *E = dyn_cast<Expr>(S);
  622. if (!E)
  623. return false;
  624. E = E->IgnoreParenCasts();
  625. if (isa<AbstractConditionalOperator>(E))
  626. return true;
  627. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
  628. if (B->isLogicalOp())
  629. return true;
  630. return false;
  631. }
  632. namespace {
  633. class ContextLocation : public PathDiagnosticLocation {
  634. bool IsDead;
  635. public:
  636. ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
  637. : PathDiagnosticLocation(L), IsDead(isdead) {}
  638. void markDead() { IsDead = true; }
  639. bool isDead() const { return IsDead; }
  640. };
  641. class EdgeBuilder {
  642. std::vector<ContextLocation> CLocs;
  643. typedef std::vector<ContextLocation>::iterator iterator;
  644. PathDiagnostic &PD;
  645. PathDiagnosticBuilder &PDB;
  646. PathDiagnosticLocation PrevLoc;
  647. bool IsConsumedExpr(const PathDiagnosticLocation &L);
  648. bool containsLocation(const PathDiagnosticLocation &Container,
  649. const PathDiagnosticLocation &Containee);
  650. PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
  651. PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
  652. bool firstCharOnly = false) {
  653. if (const Stmt *S = L.asStmt()) {
  654. const Stmt *Original = S;
  655. while (1) {
  656. // Adjust the location for some expressions that are best referenced
  657. // by one of their subexpressions.
  658. switch (S->getStmtClass()) {
  659. default:
  660. break;
  661. case Stmt::ParenExprClass:
  662. case Stmt::GenericSelectionExprClass:
  663. S = cast<Expr>(S)->IgnoreParens();
  664. firstCharOnly = true;
  665. continue;
  666. case Stmt::BinaryConditionalOperatorClass:
  667. case Stmt::ConditionalOperatorClass:
  668. S = cast<AbstractConditionalOperator>(S)->getCond();
  669. firstCharOnly = true;
  670. continue;
  671. case Stmt::ChooseExprClass:
  672. S = cast<ChooseExpr>(S)->getCond();
  673. firstCharOnly = true;
  674. continue;
  675. case Stmt::BinaryOperatorClass:
  676. S = cast<BinaryOperator>(S)->getLHS();
  677. firstCharOnly = true;
  678. continue;
  679. }
  680. break;
  681. }
  682. if (S != Original)
  683. L = PathDiagnosticLocation(S, L.getManager(), PDB.LC);
  684. }
  685. if (firstCharOnly)
  686. L = PathDiagnosticLocation::createSingleLocation(L);
  687. return L;
  688. }
  689. void popLocation() {
  690. if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
  691. // For contexts, we only one the first character as the range.
  692. rawAddEdge(cleanUpLocation(CLocs.back(), true));
  693. }
  694. CLocs.pop_back();
  695. }
  696. public:
  697. EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
  698. : PD(pd), PDB(pdb) {
  699. // If the PathDiagnostic already has pieces, add the enclosing statement
  700. // of the first piece as a context as well.
  701. if (!PD.path.empty()) {
  702. PrevLoc = (*PD.path.begin())->getLocation();
  703. if (const Stmt *S = PrevLoc.asStmt())
  704. addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  705. }
  706. }
  707. ~EdgeBuilder() {
  708. while (!CLocs.empty()) popLocation();
  709. // Finally, add an initial edge from the start location of the first
  710. // statement (if it doesn't already exist).
  711. PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
  712. PDB.LC,
  713. PDB.getSourceManager());
  714. if (L.isValid())
  715. rawAddEdge(L);
  716. }
  717. void flushLocations() {
  718. while (!CLocs.empty())
  719. popLocation();
  720. PrevLoc = PathDiagnosticLocation();
  721. }
  722. void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
  723. void rawAddEdge(PathDiagnosticLocation NewLoc);
  724. void addContext(const Stmt *S);
  725. void addExtendedContext(const Stmt *S);
  726. };
  727. } // end anonymous namespace
  728. PathDiagnosticLocation
  729. EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
  730. if (const Stmt *S = L.asStmt()) {
  731. if (IsControlFlowExpr(S))
  732. return L;
  733. return PDB.getEnclosingStmtLocation(S);
  734. }
  735. return L;
  736. }
  737. bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
  738. const PathDiagnosticLocation &Containee) {
  739. if (Container == Containee)
  740. return true;
  741. if (Container.asDecl())
  742. return true;
  743. if (const Stmt *S = Containee.asStmt())
  744. if (const Stmt *ContainerS = Container.asStmt()) {
  745. while (S) {
  746. if (S == ContainerS)
  747. return true;
  748. S = PDB.getParent(S);
  749. }
  750. return false;
  751. }
  752. // Less accurate: compare using source ranges.
  753. SourceRange ContainerR = Container.asRange();
  754. SourceRange ContaineeR = Containee.asRange();
  755. SourceManager &SM = PDB.getSourceManager();
  756. SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
  757. SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
  758. SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
  759. SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
  760. unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
  761. unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
  762. unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
  763. unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
  764. assert(ContainerBegLine <= ContainerEndLine);
  765. assert(ContaineeBegLine <= ContaineeEndLine);
  766. return (ContainerBegLine <= ContaineeBegLine &&
  767. ContainerEndLine >= ContaineeEndLine &&
  768. (ContainerBegLine != ContaineeBegLine ||
  769. SM.getExpansionColumnNumber(ContainerRBeg) <=
  770. SM.getExpansionColumnNumber(ContaineeRBeg)) &&
  771. (ContainerEndLine != ContaineeEndLine ||
  772. SM.getExpansionColumnNumber(ContainerREnd) >=
  773. SM.getExpansionColumnNumber(ContaineeREnd)));
  774. }
  775. void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
  776. if (!PrevLoc.isValid()) {
  777. PrevLoc = NewLoc;
  778. return;
  779. }
  780. const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
  781. const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
  782. if (NewLocClean.asLocation() == PrevLocClean.asLocation())
  783. return;
  784. // FIXME: Ignore intra-macro edges for now.
  785. if (NewLocClean.asLocation().getExpansionLoc() ==
  786. PrevLocClean.asLocation().getExpansionLoc())
  787. return;
  788. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
  789. PrevLoc = NewLoc;
  790. }
  791. void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
  792. if (!alwaysAdd && NewLoc.asLocation().isMacroID())
  793. return;
  794. const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
  795. while (!CLocs.empty()) {
  796. ContextLocation &TopContextLoc = CLocs.back();
  797. // Is the top location context the same as the one for the new location?
  798. if (TopContextLoc == CLoc) {
  799. if (alwaysAdd) {
  800. if (IsConsumedExpr(TopContextLoc) &&
  801. !IsControlFlowExpr(TopContextLoc.asStmt()))
  802. TopContextLoc.markDead();
  803. rawAddEdge(NewLoc);
  804. }
  805. return;
  806. }
  807. if (containsLocation(TopContextLoc, CLoc)) {
  808. if (alwaysAdd) {
  809. rawAddEdge(NewLoc);
  810. if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
  811. CLocs.push_back(ContextLocation(CLoc, true));
  812. return;
  813. }
  814. }
  815. CLocs.push_back(CLoc);
  816. return;
  817. }
  818. // Context does not contain the location. Flush it.
  819. popLocation();
  820. }
  821. // If we reach here, there is no enclosing context. Just add the edge.
  822. rawAddEdge(NewLoc);
  823. }
  824. bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
  825. if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
  826. return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
  827. return false;
  828. }
  829. void EdgeBuilder::addExtendedContext(const Stmt *S) {
  830. if (!S)
  831. return;
  832. const Stmt *Parent = PDB.getParent(S);
  833. while (Parent) {
  834. if (isa<CompoundStmt>(Parent))
  835. Parent = PDB.getParent(Parent);
  836. else
  837. break;
  838. }
  839. if (Parent) {
  840. switch (Parent->getStmtClass()) {
  841. case Stmt::DoStmtClass:
  842. case Stmt::ObjCAtSynchronizedStmtClass:
  843. addContext(Parent);
  844. default:
  845. break;
  846. }
  847. }
  848. addContext(S);
  849. }
  850. void EdgeBuilder::addContext(const Stmt *S) {
  851. if (!S)
  852. return;
  853. PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
  854. while (!CLocs.empty()) {
  855. const PathDiagnosticLocation &TopContextLoc = CLocs.back();
  856. // Is the top location context the same as the one for the new location?
  857. if (TopContextLoc == L)
  858. return;
  859. if (containsLocation(TopContextLoc, L)) {
  860. CLocs.push_back(L);
  861. return;
  862. }
  863. // Context does not contain the location. Flush it.
  864. popLocation();
  865. }
  866. CLocs.push_back(L);
  867. }
  868. // Cone-of-influence: support the reverse propagation of "interesting" symbols
  869. // and values by tracing interesting calculations backwards through evaluated
  870. // expressions along a path. This is probably overly complicated, but the idea
  871. // is that if an expression computed an "interesting" value, the child
  872. // expressions are are also likely to be "interesting" as well (which then
  873. // propagates to the values they in turn compute). This reverse propagation
  874. // is needed to track interesting correlations across function call boundaries,
  875. // where formal arguments bind to actual arguments, etc. This is also needed
  876. // because the constraint solver sometimes simplifies certain symbolic values
  877. // into constants when appropriate, and this complicates reasoning about
  878. // interesting values.
  879. typedef llvm::DenseSet<const Expr *> InterestingExprs;
  880. static void reversePropagateIntererstingSymbols(BugReport &R,
  881. InterestingExprs &IE,
  882. const ProgramState *State,
  883. const Expr *Ex,
  884. const LocationContext *LCtx) {
  885. SVal V = State->getSVal(Ex, LCtx);
  886. if (!(R.isInteresting(V) || IE.count(Ex)))
  887. return;
  888. switch (Ex->getStmtClass()) {
  889. default:
  890. if (!isa<CastExpr>(Ex))
  891. break;
  892. // Fall through.
  893. case Stmt::BinaryOperatorClass:
  894. case Stmt::UnaryOperatorClass: {
  895. for (Stmt::const_child_iterator CI = Ex->child_begin(),
  896. CE = Ex->child_end();
  897. CI != CE; ++CI) {
  898. if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
  899. IE.insert(child);
  900. SVal ChildV = State->getSVal(child, LCtx);
  901. R.markInteresting(ChildV);
  902. }
  903. break;
  904. }
  905. }
  906. }
  907. R.markInteresting(V);
  908. }
  909. static void reversePropagateInterestingSymbols(BugReport &R,
  910. InterestingExprs &IE,
  911. const ProgramState *State,
  912. const LocationContext *CalleeCtx,
  913. const LocationContext *CallerCtx)
  914. {
  915. // FIXME: Handle non-CallExpr-based CallEvents.
  916. const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
  917. const Stmt *CallSite = Callee->getCallSite();
  918. if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
  919. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
  920. FunctionDecl::param_const_iterator PI = FD->param_begin(),
  921. PE = FD->param_end();
  922. CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
  923. for (; AI != AE && PI != PE; ++AI, ++PI) {
  924. if (const Expr *ArgE = *AI) {
  925. if (const ParmVarDecl *PD = *PI) {
  926. Loc LV = State->getLValue(PD, CalleeCtx);
  927. if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
  928. IE.insert(ArgE);
  929. }
  930. }
  931. }
  932. }
  933. }
  934. }
  935. static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
  936. PathDiagnosticBuilder &PDB,
  937. const ExplodedNode *N,
  938. ArrayRef<BugReporterVisitor *> visitors) {
  939. EdgeBuilder EB(PD, PDB);
  940. const SourceManager& SM = PDB.getSourceManager();
  941. StackDiagVector CallStack;
  942. InterestingExprs IE;
  943. const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
  944. while (NextNode) {
  945. N = NextNode;
  946. NextNode = GetPredecessorNode(N);
  947. ProgramPoint P = N->getLocation();
  948. do {
  949. if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
  950. if (const Expr *Ex = PS->getStmtAs<Expr>())
  951. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  952. N->getState().getPtr(), Ex,
  953. N->getLocationContext());
  954. }
  955. if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) {
  956. const StackFrameContext *LCtx =
  957. CE->getLocationContext()->getCurrentStackFrame();
  958. // FIXME: This needs to handle implicit calls.
  959. if (const Stmt *S = CE->getCalleeContext()->getCallSite()) {
  960. if (const Expr *Ex = dyn_cast<Expr>(S))
  961. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  962. N->getState().getPtr(), Ex,
  963. N->getLocationContext());
  964. PathDiagnosticLocation Loc(S,
  965. PDB.getSourceManager(),
  966. LCtx);
  967. EB.addEdge(Loc, true);
  968. EB.flushLocations();
  969. PathDiagnosticCallPiece *C =
  970. PathDiagnosticCallPiece::construct(N, *CE, SM);
  971. PD.getActivePath().push_front(C);
  972. PD.pushActivePath(&C->path);
  973. CallStack.push_back(StackDiagPair(C, N));
  974. }
  975. break;
  976. }
  977. // Pop the call hierarchy if we are done walking the contents
  978. // of a function call.
  979. if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) {
  980. // Add an edge to the start of the function.
  981. const Decl *D = CE->getCalleeContext()->getDecl();
  982. PathDiagnosticLocation pos =
  983. PathDiagnosticLocation::createBegin(D, SM);
  984. EB.addEdge(pos);
  985. // Flush all locations, and pop the active path.
  986. EB.flushLocations();
  987. PD.popActivePath();
  988. assert(!PD.getActivePath().empty());
  989. PDB.LC = N->getLocationContext();
  990. // The current active path should never be empty. Either we
  991. // just added a bunch of stuff to the top-level path, or
  992. // we have a previous CallExitEnd. If the front of the active
  993. // path is not a PathDiagnosticCallPiece, it means that the
  994. // path terminated within a function call. We must then take the
  995. // current contents of the active path and place it within
  996. // a new PathDiagnosticCallPiece.
  997. PathDiagnosticCallPiece *C =
  998. dyn_cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
  999. if (!C) {
  1000. const Decl * Caller = CE->getLocationContext()->getDecl();
  1001. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  1002. }
  1003. // FIXME: We still need a location for implicit calls.
  1004. if (CE->getCallExpr()) {
  1005. C->setCallee(*CE, SM);
  1006. EB.addContext(CE->getCallExpr());
  1007. }
  1008. if (!CallStack.empty()) {
  1009. assert(CallStack.back().first == C);
  1010. CallStack.pop_back();
  1011. }
  1012. break;
  1013. }
  1014. // Note that is important that we update the LocationContext
  1015. // after looking at CallExits. CallExit basically adds an
  1016. // edge in the *caller*, so we don't want to update the LocationContext
  1017. // too soon.
  1018. PDB.LC = N->getLocationContext();
  1019. // Block edges.
  1020. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  1021. // Does this represent entering a call? If so, look at propagating
  1022. // interesting symbols across call boundaries.
  1023. if (NextNode) {
  1024. const LocationContext *CallerCtx = NextNode->getLocationContext();
  1025. const LocationContext *CalleeCtx = PDB.LC;
  1026. if (CallerCtx != CalleeCtx) {
  1027. reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
  1028. N->getState().getPtr(),
  1029. CalleeCtx, CallerCtx);
  1030. }
  1031. }
  1032. const CFGBlock &Blk = *BE->getSrc();
  1033. const Stmt *Term = Blk.getTerminator();
  1034. // Are we jumping to the head of a loop? Add a special diagnostic.
  1035. if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
  1036. PathDiagnosticLocation L(Loop, SM, PDB.LC);
  1037. const CompoundStmt *CS = NULL;
  1038. if (!Term) {
  1039. if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
  1040. CS = dyn_cast<CompoundStmt>(FS->getBody());
  1041. else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
  1042. CS = dyn_cast<CompoundStmt>(WS->getBody());
  1043. }
  1044. PathDiagnosticEventPiece *p =
  1045. new PathDiagnosticEventPiece(L,
  1046. "Looping back to the head of the loop");
  1047. p->setPrunable(true);
  1048. EB.addEdge(p->getLocation(), true);
  1049. PD.getActivePath().push_front(p);
  1050. if (CS) {
  1051. PathDiagnosticLocation BL =
  1052. PathDiagnosticLocation::createEndBrace(CS, SM);
  1053. EB.addEdge(BL);
  1054. }
  1055. }
  1056. if (Term)
  1057. EB.addContext(Term);
  1058. break;
  1059. }
  1060. if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
  1061. if (const CFGStmt *S = BE->getFirstElement().getAs<CFGStmt>()) {
  1062. const Stmt *stmt = S->getStmt();
  1063. if (IsControlFlowExpr(stmt)) {
  1064. // Add the proper context for '&&', '||', and '?'.
  1065. EB.addContext(stmt);
  1066. }
  1067. else
  1068. EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
  1069. }
  1070. break;
  1071. }
  1072. } while (0);
  1073. if (!NextNode)
  1074. continue;
  1075. // Add pieces from custom visitors.
  1076. BugReport *R = PDB.getBugReport();
  1077. for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
  1078. E = visitors.end();
  1079. I != E; ++I) {
  1080. if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
  1081. const PathDiagnosticLocation &Loc = p->getLocation();
  1082. EB.addEdge(Loc, true);
  1083. PD.getActivePath().push_front(p);
  1084. updateStackPiecesWithMessage(p, CallStack);
  1085. if (const Stmt *S = Loc.asStmt())
  1086. EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  1087. }
  1088. }
  1089. }
  1090. }
  1091. //===----------------------------------------------------------------------===//
  1092. // Methods for BugType and subclasses.
  1093. //===----------------------------------------------------------------------===//
  1094. BugType::~BugType() { }
  1095. void BugType::FlushReports(BugReporter &BR) {}
  1096. void BuiltinBug::anchor() {}
  1097. //===----------------------------------------------------------------------===//
  1098. // Methods for BugReport and subclasses.
  1099. //===----------------------------------------------------------------------===//
  1100. void BugReport::NodeResolver::anchor() {}
  1101. void BugReport::addVisitor(BugReporterVisitor* visitor) {
  1102. if (!visitor)
  1103. return;
  1104. llvm::FoldingSetNodeID ID;
  1105. visitor->Profile(ID);
  1106. void *InsertPos;
  1107. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
  1108. delete visitor;
  1109. return;
  1110. }
  1111. CallbacksSet.InsertNode(visitor, InsertPos);
  1112. Callbacks.push_back(visitor);
  1113. ++ConfigurationChangeToken;
  1114. }
  1115. BugReport::~BugReport() {
  1116. for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
  1117. delete *I;
  1118. }
  1119. }
  1120. const Decl *BugReport::getDeclWithIssue() const {
  1121. if (DeclWithIssue)
  1122. return DeclWithIssue;
  1123. const ExplodedNode *N = getErrorNode();
  1124. if (!N)
  1125. return 0;
  1126. const LocationContext *LC = N->getLocationContext();
  1127. return LC->getCurrentStackFrame()->getDecl();
  1128. }
  1129. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  1130. hash.AddPointer(&BT);
  1131. hash.AddString(Description);
  1132. if (UniqueingLocation.isValid()) {
  1133. UniqueingLocation.Profile(hash);
  1134. } else if (Location.isValid()) {
  1135. Location.Profile(hash);
  1136. } else {
  1137. assert(ErrorNode);
  1138. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  1139. }
  1140. for (SmallVectorImpl<SourceRange>::const_iterator I =
  1141. Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  1142. const SourceRange range = *I;
  1143. if (!range.isValid())
  1144. continue;
  1145. hash.AddInteger(range.getBegin().getRawEncoding());
  1146. hash.AddInteger(range.getEnd().getRawEncoding());
  1147. }
  1148. }
  1149. void BugReport::markInteresting(SymbolRef sym) {
  1150. if (!sym)
  1151. return;
  1152. // If the symbol wasn't already in our set, note a configuration change.
  1153. if (interestingSymbols.insert(sym).second)
  1154. ++ConfigurationChangeToken;
  1155. if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
  1156. interestingRegions.insert(meta->getRegion());
  1157. }
  1158. void BugReport::markInteresting(const MemRegion *R) {
  1159. if (!R)
  1160. return;
  1161. // If the base region wasn't already in our set, note a configuration change.
  1162. R = R->getBaseRegion();
  1163. if (interestingRegions.insert(R).second)
  1164. ++ConfigurationChangeToken;
  1165. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  1166. interestingSymbols.insert(SR->getSymbol());
  1167. }
  1168. void BugReport::markInteresting(SVal V) {
  1169. markInteresting(V.getAsRegion());
  1170. markInteresting(V.getAsSymbol());
  1171. }
  1172. bool BugReport::isInteresting(SVal V) const {
  1173. return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
  1174. }
  1175. bool BugReport::isInteresting(SymbolRef sym) const {
  1176. if (!sym)
  1177. return false;
  1178. // We don't currently consider metadata symbols to be interesting
  1179. // even if we know their region is interesting. Is that correct behavior?
  1180. return interestingSymbols.count(sym);
  1181. }
  1182. bool BugReport::isInteresting(const MemRegion *R) const {
  1183. if (!R)
  1184. return false;
  1185. R = R->getBaseRegion();
  1186. bool b = interestingRegions.count(R);
  1187. if (b)
  1188. return true;
  1189. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  1190. return interestingSymbols.count(SR->getSymbol());
  1191. return false;
  1192. }
  1193. const Stmt *BugReport::getStmt() const {
  1194. if (!ErrorNode)
  1195. return 0;
  1196. ProgramPoint ProgP = ErrorNode->getLocation();
  1197. const Stmt *S = NULL;
  1198. if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) {
  1199. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1200. if (BE->getBlock() == &Exit)
  1201. S = GetPreviousStmt(ErrorNode);
  1202. }
  1203. if (!S)
  1204. S = GetStmt(ProgP);
  1205. return S;
  1206. }
  1207. std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
  1208. BugReport::getRanges() {
  1209. // If no custom ranges, add the range of the statement corresponding to
  1210. // the error node.
  1211. if (Ranges.empty()) {
  1212. if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
  1213. addRange(E->getSourceRange());
  1214. else
  1215. return std::make_pair(ranges_iterator(), ranges_iterator());
  1216. }
  1217. // User-specified absence of range info.
  1218. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  1219. return std::make_pair(ranges_iterator(), ranges_iterator());
  1220. return std::make_pair(Ranges.begin(), Ranges.end());
  1221. }
  1222. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  1223. if (ErrorNode) {
  1224. assert(!Location.isValid() &&
  1225. "Either Location or ErrorNode should be specified but not both.");
  1226. if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
  1227. const LocationContext *LC = ErrorNode->getLocationContext();
  1228. // For member expressions, return the location of the '.' or '->'.
  1229. if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
  1230. return PathDiagnosticLocation::createMemberLoc(ME, SM);
  1231. // For binary operators, return the location of the operator.
  1232. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
  1233. return PathDiagnosticLocation::createOperatorLoc(B, SM);
  1234. return PathDiagnosticLocation::createBegin(S, SM, LC);
  1235. }
  1236. } else {
  1237. assert(Location.isValid());
  1238. return Location;
  1239. }
  1240. return PathDiagnosticLocation();
  1241. }
  1242. //===----------------------------------------------------------------------===//
  1243. // Methods for BugReporter and subclasses.
  1244. //===----------------------------------------------------------------------===//
  1245. BugReportEquivClass::~BugReportEquivClass() { }
  1246. GRBugReporter::~GRBugReporter() { }
  1247. BugReporterData::~BugReporterData() {}
  1248. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  1249. ProgramStateManager&
  1250. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  1251. BugReporter::~BugReporter() {
  1252. FlushReports();
  1253. // Free the bug reports we are tracking.
  1254. typedef std::vector<BugReportEquivClass *> ContTy;
  1255. for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
  1256. I != E; ++I) {
  1257. delete *I;
  1258. }
  1259. }
  1260. void BugReporter::FlushReports() {
  1261. if (BugTypes.isEmpty())
  1262. return;
  1263. // First flush the warnings for each BugType. This may end up creating new
  1264. // warnings and new BugTypes.
  1265. // FIXME: Only NSErrorChecker needs BugType's FlushReports.
  1266. // Turn NSErrorChecker into a proper checker and remove this.
  1267. SmallVector<const BugType*, 16> bugTypes;
  1268. for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
  1269. bugTypes.push_back(*I);
  1270. for (SmallVector<const BugType*, 16>::iterator
  1271. I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
  1272. const_cast<BugType*>(*I)->FlushReports(*this);
  1273. typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
  1274. for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
  1275. BugReportEquivClass& EQ = *EI;
  1276. FlushReport(EQ);
  1277. }
  1278. // BugReporter owns and deletes only BugTypes created implicitly through
  1279. // EmitBasicReport.
  1280. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1281. // create will be destroyed by the BugReporter.
  1282. for (llvm::StringMap<BugType*>::iterator
  1283. I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
  1284. delete I->second;
  1285. // Remove all references to the BugType objects.
  1286. BugTypes = F.getEmptySet();
  1287. }
  1288. //===----------------------------------------------------------------------===//
  1289. // PathDiagnostics generation.
  1290. //===----------------------------------------------------------------------===//
  1291. static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
  1292. std::pair<ExplodedNode*, unsigned> >
  1293. MakeReportGraph(const ExplodedGraph* G,
  1294. SmallVectorImpl<const ExplodedNode*> &nodes) {
  1295. // Create the trimmed graph. It will contain the shortest paths from the
  1296. // error nodes to the root. In the new graph we should only have one
  1297. // error node unless there are two or more error nodes with the same minimum
  1298. // path length.
  1299. ExplodedGraph* GTrim;
  1300. InterExplodedGraphMap* NMap;
  1301. llvm::DenseMap<const void*, const void*> InverseMap;
  1302. llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
  1303. &InverseMap);
  1304. // Create owning pointers for GTrim and NMap just to ensure that they are
  1305. // released when this function exists.
  1306. OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
  1307. OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
  1308. // Find the (first) error node in the trimmed graph. We just need to consult
  1309. // the node map (NMap) which maps from nodes in the original graph to nodes
  1310. // in the new graph.
  1311. std::queue<const ExplodedNode*> WS;
  1312. typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
  1313. IndexMapTy IndexMap;
  1314. for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
  1315. const ExplodedNode *originalNode = nodes[nodeIndex];
  1316. if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
  1317. WS.push(N);
  1318. IndexMap[originalNode] = nodeIndex;
  1319. }
  1320. }
  1321. assert(!WS.empty() && "No error node found in the trimmed graph.");
  1322. // Create a new (third!) graph with a single path. This is the graph
  1323. // that will be returned to the caller.
  1324. ExplodedGraph *GNew = new ExplodedGraph();
  1325. // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
  1326. // to the root node, and then construct a new graph that contains only
  1327. // a single path.
  1328. llvm::DenseMap<const void*,unsigned> Visited;
  1329. unsigned cnt = 0;
  1330. const ExplodedNode *Root = 0;
  1331. while (!WS.empty()) {
  1332. const ExplodedNode *Node = WS.front();
  1333. WS.pop();
  1334. if (Visited.find(Node) != Visited.end())
  1335. continue;
  1336. Visited[Node] = cnt++;
  1337. if (Node->pred_empty()) {
  1338. Root = Node;
  1339. break;
  1340. }
  1341. for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
  1342. E=Node->pred_end(); I!=E; ++I)
  1343. WS.push(*I);
  1344. }
  1345. assert(Root);
  1346. // Now walk from the root down the BFS path, always taking the successor
  1347. // with the lowest number.
  1348. ExplodedNode *Last = 0, *First = 0;
  1349. NodeBackMap *BM = new NodeBackMap();
  1350. unsigned NodeIndex = 0;
  1351. for ( const ExplodedNode *N = Root ;;) {
  1352. // Lookup the number associated with the current node.
  1353. llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
  1354. assert(I != Visited.end());
  1355. // Create the equivalent node in the new graph with the same state
  1356. // and location.
  1357. ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
  1358. // Store the mapping to the original node.
  1359. llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
  1360. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  1361. (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
  1362. // Link up the new node with the previous node.
  1363. if (Last)
  1364. NewN->addPredecessor(Last, *GNew);
  1365. Last = NewN;
  1366. // Are we at the final node?
  1367. IndexMapTy::iterator IMI =
  1368. IndexMap.find((const ExplodedNode*)(IMitr->second));
  1369. if (IMI != IndexMap.end()) {
  1370. First = NewN;
  1371. NodeIndex = IMI->second;
  1372. break;
  1373. }
  1374. // Find the next successor node. We choose the node that is marked
  1375. // with the lowest DFS number.
  1376. ExplodedNode::const_succ_iterator SI = N->succ_begin();
  1377. ExplodedNode::const_succ_iterator SE = N->succ_end();
  1378. N = 0;
  1379. for (unsigned MinVal = 0; SI != SE; ++SI) {
  1380. I = Visited.find(*SI);
  1381. if (I == Visited.end())
  1382. continue;
  1383. if (!N || I->second < MinVal) {
  1384. N = *SI;
  1385. MinVal = I->second;
  1386. }
  1387. }
  1388. assert(N);
  1389. }
  1390. assert(First);
  1391. return std::make_pair(std::make_pair(GNew, BM),
  1392. std::make_pair(First, NodeIndex));
  1393. }
  1394. /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
  1395. /// and collapses PathDiagosticPieces that are expanded by macros.
  1396. static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
  1397. typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
  1398. SourceLocation> > MacroStackTy;
  1399. typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
  1400. PiecesTy;
  1401. MacroStackTy MacroStack;
  1402. PiecesTy Pieces;
  1403. for (PathPieces::const_iterator I = path.begin(), E = path.end();
  1404. I!=E; ++I) {
  1405. PathDiagnosticPiece *piece = I->getPtr();
  1406. // Recursively compact calls.
  1407. if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
  1408. CompactPathDiagnostic(call->path, SM);
  1409. }
  1410. // Get the location of the PathDiagnosticPiece.
  1411. const FullSourceLoc Loc = piece->getLocation().asLocation();
  1412. // Determine the instantiation location, which is the location we group
  1413. // related PathDiagnosticPieces.
  1414. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  1415. SM.getExpansionLoc(Loc) :
  1416. SourceLocation();
  1417. if (Loc.isFileID()) {
  1418. MacroStack.clear();
  1419. Pieces.push_back(piece);
  1420. continue;
  1421. }
  1422. assert(Loc.isMacroID());
  1423. // Is the PathDiagnosticPiece within the same macro group?
  1424. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  1425. MacroStack.back().first->subPieces.push_back(piece);
  1426. continue;
  1427. }
  1428. // We aren't in the same group. Are we descending into a new macro
  1429. // or are part of an old one?
  1430. IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
  1431. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  1432. SM.getExpansionLoc(Loc) :
  1433. SourceLocation();
  1434. // Walk the entire macro stack.
  1435. while (!MacroStack.empty()) {
  1436. if (InstantiationLoc == MacroStack.back().second) {
  1437. MacroGroup = MacroStack.back().first;
  1438. break;
  1439. }
  1440. if (ParentInstantiationLoc == MacroStack.back().second) {
  1441. MacroGroup = MacroStack.back().first;
  1442. break;
  1443. }
  1444. MacroStack.pop_back();
  1445. }
  1446. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  1447. // Create a new macro group and add it to the stack.
  1448. PathDiagnosticMacroPiece *NewGroup =
  1449. new PathDiagnosticMacroPiece(
  1450. PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
  1451. if (MacroGroup)
  1452. MacroGroup->subPieces.push_back(NewGroup);
  1453. else {
  1454. assert(InstantiationLoc.isFileID());
  1455. Pieces.push_back(NewGroup);
  1456. }
  1457. MacroGroup = NewGroup;
  1458. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  1459. }
  1460. // Finally, add the PathDiagnosticPiece to the group.
  1461. MacroGroup->subPieces.push_back(piece);
  1462. }
  1463. // Now take the pieces and construct a new PathDiagnostic.
  1464. path.clear();
  1465. for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
  1466. path.push_back(*I);
  1467. }
  1468. void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
  1469. SmallVectorImpl<BugReport *> &bugReports) {
  1470. assert(!bugReports.empty());
  1471. SmallVector<const ExplodedNode *, 10> errorNodes;
  1472. for (SmallVectorImpl<BugReport*>::iterator I = bugReports.begin(),
  1473. E = bugReports.end(); I != E; ++I) {
  1474. errorNodes.push_back((*I)->getErrorNode());
  1475. }
  1476. // Construct a new graph that contains only a single path from the error
  1477. // node to a root.
  1478. const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
  1479. std::pair<ExplodedNode*, unsigned> >&
  1480. GPair = MakeReportGraph(&getGraph(), errorNodes);
  1481. // Find the BugReport with the original location.
  1482. assert(GPair.second.second < bugReports.size());
  1483. BugReport *R = bugReports[GPair.second.second];
  1484. assert(R && "No original report found for sliced graph.");
  1485. OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
  1486. OwningPtr<NodeBackMap> BackMap(GPair.first.second);
  1487. const ExplodedNode *N = GPair.second.first;
  1488. // Start building the path diagnostic...
  1489. PathDiagnosticBuilder PDB(*this, R, BackMap.get(),
  1490. getPathDiagnosticConsumer());
  1491. // Register additional node visitors.
  1492. R->addVisitor(new NilReceiverBRVisitor());
  1493. R->addVisitor(new ConditionBRVisitor());
  1494. BugReport::VisitorList visitors;
  1495. unsigned originalReportConfigToken, finalReportConfigToken;
  1496. // While generating diagnostics, it's possible the visitors will decide
  1497. // new symbols and regions are interesting, or add other visitors based on
  1498. // the information they find. If they do, we need to regenerate the path
  1499. // based on our new report configuration.
  1500. do {
  1501. // Get a clean copy of all the visitors.
  1502. for (BugReport::visitor_iterator I = R->visitor_begin(),
  1503. E = R->visitor_end(); I != E; ++I)
  1504. visitors.push_back((*I)->clone());
  1505. // Clear out the active path from any previous work.
  1506. PD.getActivePath().clear();
  1507. originalReportConfigToken = R->getConfigurationChangeToken();
  1508. // Generate the very last diagnostic piece - the piece is visible before
  1509. // the trace is expanded.
  1510. PathDiagnosticPiece *LastPiece = 0;
  1511. for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
  1512. I != E; ++I) {
  1513. if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
  1514. assert (!LastPiece &&
  1515. "There can only be one final piece in a diagnostic.");
  1516. LastPiece = Piece;
  1517. }
  1518. }
  1519. if (!LastPiece)
  1520. LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
  1521. if (LastPiece)
  1522. PD.getActivePath().push_back(LastPiece);
  1523. else
  1524. return;
  1525. switch (PDB.getGenerationScheme()) {
  1526. case PathDiagnosticConsumer::Extensive:
  1527. GenerateExtensivePathDiagnostic(PD, PDB, N, visitors);
  1528. break;
  1529. case PathDiagnosticConsumer::Minimal:
  1530. GenerateMinimalPathDiagnostic(PD, PDB, N, visitors);
  1531. break;
  1532. }
  1533. // Clean up the visitors we used.
  1534. llvm::DeleteContainerPointers(visitors);
  1535. // Did anything change while generating this path?
  1536. finalReportConfigToken = R->getConfigurationChangeToken();
  1537. } while(finalReportConfigToken != originalReportConfigToken);
  1538. // Finally, prune the diagnostic path of uninteresting stuff.
  1539. if (R->shouldPrunePath()) {
  1540. bool hasSomethingInteresting = RemoveUneededCalls(PD.getMutablePieces());
  1541. assert(hasSomethingInteresting);
  1542. (void) hasSomethingInteresting;
  1543. }
  1544. }
  1545. void BugReporter::Register(BugType *BT) {
  1546. BugTypes = F.add(BugTypes, BT);
  1547. }
  1548. void BugReporter::EmitReport(BugReport* R) {
  1549. // Compute the bug report's hash to determine its equivalence class.
  1550. llvm::FoldingSetNodeID ID;
  1551. R->Profile(ID);
  1552. // Lookup the equivance class. If there isn't one, create it.
  1553. BugType& BT = R->getBugType();
  1554. Register(&BT);
  1555. void *InsertPos;
  1556. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  1557. if (!EQ) {
  1558. EQ = new BugReportEquivClass(R);
  1559. EQClasses.InsertNode(EQ, InsertPos);
  1560. EQClassesVector.push_back(EQ);
  1561. }
  1562. else
  1563. EQ->AddReport(R);
  1564. }
  1565. //===----------------------------------------------------------------------===//
  1566. // Emitting reports in equivalence classes.
  1567. //===----------------------------------------------------------------------===//
  1568. namespace {
  1569. struct FRIEC_WLItem {
  1570. const ExplodedNode *N;
  1571. ExplodedNode::const_succ_iterator I, E;
  1572. FRIEC_WLItem(const ExplodedNode *n)
  1573. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  1574. };
  1575. }
  1576. static BugReport *
  1577. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  1578. SmallVectorImpl<BugReport*> &bugReports) {
  1579. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  1580. assert(I != E);
  1581. BugType& BT = I->getBugType();
  1582. // If we don't need to suppress any of the nodes because they are
  1583. // post-dominated by a sink, simply add all the nodes in the equivalence class
  1584. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  1585. if (!BT.isSuppressOnSink()) {
  1586. BugReport *R = I;
  1587. for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
  1588. const ExplodedNode *N = I->getErrorNode();
  1589. if (N) {
  1590. R = I;
  1591. bugReports.push_back(R);
  1592. }
  1593. }
  1594. return R;
  1595. }
  1596. // For bug reports that should be suppressed when all paths are post-dominated
  1597. // by a sink node, iterate through the reports in the equivalence class
  1598. // until we find one that isn't post-dominated (if one exists). We use a
  1599. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  1600. // this as a recursive function, but we don't want to risk blowing out the
  1601. // stack for very long paths.
  1602. BugReport *exampleReport = 0;
  1603. for (; I != E; ++I) {
  1604. const ExplodedNode *errorNode = I->getErrorNode();
  1605. if (!errorNode)
  1606. continue;
  1607. if (errorNode->isSink()) {
  1608. llvm_unreachable(
  1609. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  1610. }
  1611. // No successors? By definition this nodes isn't post-dominated by a sink.
  1612. if (errorNode->succ_empty()) {
  1613. bugReports.push_back(I);
  1614. if (!exampleReport)
  1615. exampleReport = I;
  1616. continue;
  1617. }
  1618. // At this point we know that 'N' is not a sink and it has at least one
  1619. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  1620. typedef FRIEC_WLItem WLItem;
  1621. typedef SmallVector<WLItem, 10> DFSWorkList;
  1622. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  1623. DFSWorkList WL;
  1624. WL.push_back(errorNode);
  1625. Visited[errorNode] = 1;
  1626. while (!WL.empty()) {
  1627. WLItem &WI = WL.back();
  1628. assert(!WI.N->succ_empty());
  1629. for (; WI.I != WI.E; ++WI.I) {
  1630. const ExplodedNode *Succ = *WI.I;
  1631. // End-of-path node?
  1632. if (Succ->succ_empty()) {
  1633. // If we found an end-of-path node that is not a sink.
  1634. if (!Succ->isSink()) {
  1635. bugReports.push_back(I);
  1636. if (!exampleReport)
  1637. exampleReport = I;
  1638. WL.clear();
  1639. break;
  1640. }
  1641. // Found a sink? Continue on to the next successor.
  1642. continue;
  1643. }
  1644. // Mark the successor as visited. If it hasn't been explored,
  1645. // enqueue it to the DFS worklist.
  1646. unsigned &mark = Visited[Succ];
  1647. if (!mark) {
  1648. mark = 1;
  1649. WL.push_back(Succ);
  1650. break;
  1651. }
  1652. }
  1653. // The worklist may have been cleared at this point. First
  1654. // check if it is empty before checking the last item.
  1655. if (!WL.empty() && &WL.back() == &WI)
  1656. WL.pop_back();
  1657. }
  1658. }
  1659. // ExampleReport will be NULL if all the nodes in the equivalence class
  1660. // were post-dominated by sinks.
  1661. return exampleReport;
  1662. }
  1663. //===----------------------------------------------------------------------===//
  1664. // DiagnosticCache. This is a hack to cache analyzer diagnostics. It
  1665. // uses global state, which eventually should go elsewhere.
  1666. //===----------------------------------------------------------------------===//
  1667. namespace {
  1668. class DiagCacheItem : public llvm::FoldingSetNode {
  1669. llvm::FoldingSetNodeID ID;
  1670. public:
  1671. DiagCacheItem(BugReport *R, PathDiagnostic *PD) {
  1672. R->Profile(ID);
  1673. PD->Profile(ID);
  1674. }
  1675. void Profile(llvm::FoldingSetNodeID &id) {
  1676. id = ID;
  1677. }
  1678. llvm::FoldingSetNodeID &getID() { return ID; }
  1679. };
  1680. }
  1681. static bool IsCachedDiagnostic(BugReport *R, PathDiagnostic *PD) {
  1682. // FIXME: Eventually this diagnostic cache should reside in something
  1683. // like AnalysisManager instead of being a static variable. This is
  1684. // really unsafe in the long term.
  1685. typedef llvm::FoldingSet<DiagCacheItem> DiagnosticCache;
  1686. static DiagnosticCache DC;
  1687. void *InsertPos;
  1688. DiagCacheItem *Item = new DiagCacheItem(R, PD);
  1689. if (DC.FindNodeOrInsertPos(Item->getID(), InsertPos)) {
  1690. delete Item;
  1691. return true;
  1692. }
  1693. DC.InsertNode(Item, InsertPos);
  1694. return false;
  1695. }
  1696. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  1697. SmallVector<BugReport*, 10> bugReports;
  1698. BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
  1699. if (!exampleReport)
  1700. return;
  1701. PathDiagnosticConsumer* PD = getPathDiagnosticConsumer();
  1702. // FIXME: Make sure we use the 'R' for the path that was actually used.
  1703. // Probably doesn't make a difference in practice.
  1704. BugType& BT = exampleReport->getBugType();
  1705. OwningPtr<PathDiagnostic>
  1706. D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
  1707. exampleReport->getBugType().getName(),
  1708. !PD || PD->useVerboseDescription()
  1709. ? exampleReport->getDescription()
  1710. : exampleReport->getShortDescription(),
  1711. BT.getCategory()));
  1712. if (!bugReports.empty())
  1713. GeneratePathDiagnostic(*D.get(), bugReports);
  1714. // Get the meta data.
  1715. const BugReport::ExtraTextList &Meta =
  1716. exampleReport->getExtraText();
  1717. for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
  1718. e = Meta.end(); i != e; ++i) {
  1719. D->addMeta(*i);
  1720. }
  1721. // Emit a summary diagnostic to the regular Diagnostics engine.
  1722. BugReport::ranges_iterator Beg, End;
  1723. llvm::tie(Beg, End) = exampleReport->getRanges();
  1724. DiagnosticsEngine &Diag = getDiagnostic();
  1725. if (!IsCachedDiagnostic(exampleReport, D.get())) {
  1726. // Search the description for '%', as that will be interpretted as a
  1727. // format character by FormatDiagnostics.
  1728. StringRef desc = exampleReport->getShortDescription();
  1729. SmallString<512> TmpStr;
  1730. llvm::raw_svector_ostream Out(TmpStr);
  1731. for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) {
  1732. if (*I == '%')
  1733. Out << "%%";
  1734. else
  1735. Out << *I;
  1736. }
  1737. Out.flush();
  1738. unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, TmpStr);
  1739. DiagnosticBuilder diagBuilder = Diag.Report(
  1740. exampleReport->getLocation(getSourceManager()).asLocation(), ErrorDiag);
  1741. for (BugReport::ranges_iterator I = Beg; I != End; ++I)
  1742. diagBuilder << *I;
  1743. }
  1744. // Emit a full diagnostic for the path if we have a PathDiagnosticConsumer.
  1745. if (!PD)
  1746. return;
  1747. if (D->path.empty()) {
  1748. PathDiagnosticPiece *piece = new PathDiagnosticEventPiece(
  1749. exampleReport->getLocation(getSourceManager()),
  1750. exampleReport->getDescription());
  1751. for ( ; Beg != End; ++Beg)
  1752. piece->addRange(*Beg);
  1753. D->getActivePath().push_back(piece);
  1754. }
  1755. PD->HandlePathDiagnostic(D.take());
  1756. }
  1757. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  1758. StringRef name,
  1759. StringRef category,
  1760. StringRef str, PathDiagnosticLocation Loc,
  1761. SourceRange* RBeg, unsigned NumRanges) {
  1762. // 'BT' is owned by BugReporter.
  1763. BugType *BT = getBugTypeForName(name, category);
  1764. BugReport *R = new BugReport(*BT, str, Loc);
  1765. R->setDeclWithIssue(DeclWithIssue);
  1766. for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
  1767. EmitReport(R);
  1768. }
  1769. BugType *BugReporter::getBugTypeForName(StringRef name,
  1770. StringRef category) {
  1771. SmallString<136> fullDesc;
  1772. llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
  1773. llvm::StringMapEntry<BugType *> &
  1774. entry = StrBugTypes.GetOrCreateValue(fullDesc);
  1775. BugType *BT = entry.getValue();
  1776. if (!BT) {
  1777. BT = new BugType(name, category);
  1778. entry.setValue(BT);
  1779. }
  1780. return BT;
  1781. }