BugReporter.cpp 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153
  1. //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines BugReporter, a utility class for generating
  10. // PathDiagnostics.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclBase.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ParentMap.h"
  20. #include "clang/AST/Stmt.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/Analysis/AnalysisDeclContext.h"
  24. #include "clang/Analysis/CFG.h"
  25. #include "clang/Analysis/CFGStmtMap.h"
  26. #include "clang/Analysis/ProgramPoint.h"
  27. #include "clang/Basic/LLVM.h"
  28. #include "clang/Basic/SourceLocation.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  31. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
  32. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  33. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  34. #include "clang/StaticAnalyzer/Core/Checker.h"
  35. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  36. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  42. #include "llvm/ADT/ArrayRef.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/DenseSet.h"
  45. #include "llvm/ADT/FoldingSet.h"
  46. #include "llvm/ADT/None.h"
  47. #include "llvm/ADT/Optional.h"
  48. #include "llvm/ADT/STLExtras.h"
  49. #include "llvm/ADT/SmallPtrSet.h"
  50. #include "llvm/ADT/SmallString.h"
  51. #include "llvm/ADT/SmallVector.h"
  52. #include "llvm/ADT/Statistic.h"
  53. #include "llvm/ADT/StringRef.h"
  54. #include "llvm/ADT/iterator_range.h"
  55. #include "llvm/Support/Casting.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/MemoryBuffer.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include <algorithm>
  61. #include <cassert>
  62. #include <cstddef>
  63. #include <iterator>
  64. #include <memory>
  65. #include <queue>
  66. #include <string>
  67. #include <tuple>
  68. #include <utility>
  69. #include <vector>
  70. using namespace clang;
  71. using namespace ento;
  72. #define DEBUG_TYPE "BugReporter"
  73. STATISTIC(MaxBugClassSize,
  74. "The maximum number of bug reports in the same equivalence class");
  75. STATISTIC(MaxValidBugClassSize,
  76. "The maximum number of bug reports in the same equivalence class "
  77. "where at least one report is valid (not suppressed)");
  78. BugReporterVisitor::~BugReporterVisitor() = default;
  79. void BugReporterContext::anchor() {}
  80. //===----------------------------------------------------------------------===//
  81. // Helper routines for walking the ExplodedGraph and fetching statements.
  82. //===----------------------------------------------------------------------===//
  83. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  84. for (N = N->getFirstPred(); N; N = N->getFirstPred())
  85. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  86. return S;
  87. return nullptr;
  88. }
  89. static inline const Stmt*
  90. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  91. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  92. return S;
  93. return GetPreviousStmt(N);
  94. }
  95. //===----------------------------------------------------------------------===//
  96. // Diagnostic cleanup.
  97. //===----------------------------------------------------------------------===//
  98. static PathDiagnosticEventPiece *
  99. eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
  100. PathDiagnosticEventPiece *Y) {
  101. // Prefer diagnostics that come from ConditionBRVisitor over
  102. // those that came from TrackConstraintBRVisitor,
  103. // unless the one from ConditionBRVisitor is
  104. // its generic fallback diagnostic.
  105. const void *tagPreferred = ConditionBRVisitor::getTag();
  106. const void *tagLesser = TrackConstraintBRVisitor::getTag();
  107. if (X->getLocation() != Y->getLocation())
  108. return nullptr;
  109. if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
  110. return ConditionBRVisitor::isPieceMessageGeneric(X) ? Y : X;
  111. if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
  112. return ConditionBRVisitor::isPieceMessageGeneric(Y) ? X : Y;
  113. return nullptr;
  114. }
  115. /// An optimization pass over PathPieces that removes redundant diagnostics
  116. /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
  117. /// BugReporterVisitors use different methods to generate diagnostics, with
  118. /// one capable of emitting diagnostics in some cases but not in others. This
  119. /// can lead to redundant diagnostic pieces at the same point in a path.
  120. static void removeRedundantMsgs(PathPieces &path) {
  121. unsigned N = path.size();
  122. if (N < 2)
  123. return;
  124. // NOTE: this loop intentionally is not using an iterator. Instead, we
  125. // are streaming the path and modifying it in place. This is done by
  126. // grabbing the front, processing it, and if we decide to keep it append
  127. // it to the end of the path. The entire path is processed in this way.
  128. for (unsigned i = 0; i < N; ++i) {
  129. auto piece = std::move(path.front());
  130. path.pop_front();
  131. switch (piece->getKind()) {
  132. case PathDiagnosticPiece::Call:
  133. removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
  134. break;
  135. case PathDiagnosticPiece::Macro:
  136. removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
  137. break;
  138. case PathDiagnosticPiece::Event: {
  139. if (i == N-1)
  140. break;
  141. if (auto *nextEvent =
  142. dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
  143. auto *event = cast<PathDiagnosticEventPiece>(piece.get());
  144. // Check to see if we should keep one of the two pieces. If we
  145. // come up with a preference, record which piece to keep, and consume
  146. // another piece from the path.
  147. if (auto *pieceToKeep =
  148. eventsDescribeSameCondition(event, nextEvent)) {
  149. piece = std::move(pieceToKeep == event ? piece : path.front());
  150. path.pop_front();
  151. ++i;
  152. }
  153. }
  154. break;
  155. }
  156. case PathDiagnosticPiece::ControlFlow:
  157. case PathDiagnosticPiece::Note:
  158. case PathDiagnosticPiece::PopUp:
  159. break;
  160. }
  161. path.push_back(std::move(piece));
  162. }
  163. }
  164. /// A map from PathDiagnosticPiece to the LocationContext of the inlined
  165. /// function call it represents.
  166. using LocationContextMap =
  167. llvm::DenseMap<const PathPieces *, const LocationContext *>;
  168. /// Recursively scan through a path and prune out calls and macros pieces
  169. /// that aren't needed. Return true if afterwards the path contains
  170. /// "interesting stuff" which means it shouldn't be pruned from the parent path.
  171. static bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
  172. LocationContextMap &LCM,
  173. bool IsInteresting = false) {
  174. bool containsSomethingInteresting = IsInteresting;
  175. const unsigned N = pieces.size();
  176. for (unsigned i = 0 ; i < N ; ++i) {
  177. // Remove the front piece from the path. If it is still something we
  178. // want to keep once we are done, we will push it back on the end.
  179. auto piece = std::move(pieces.front());
  180. pieces.pop_front();
  181. switch (piece->getKind()) {
  182. case PathDiagnosticPiece::Call: {
  183. auto &call = cast<PathDiagnosticCallPiece>(*piece);
  184. // Check if the location context is interesting.
  185. assert(LCM.count(&call.path));
  186. if (!removeUnneededCalls(call.path, R, LCM,
  187. R->isInteresting(LCM[&call.path])))
  188. continue;
  189. containsSomethingInteresting = true;
  190. break;
  191. }
  192. case PathDiagnosticPiece::Macro: {
  193. auto &macro = cast<PathDiagnosticMacroPiece>(*piece);
  194. if (!removeUnneededCalls(macro.subPieces, R, LCM, IsInteresting))
  195. continue;
  196. containsSomethingInteresting = true;
  197. break;
  198. }
  199. case PathDiagnosticPiece::Event: {
  200. auto &event = cast<PathDiagnosticEventPiece>(*piece);
  201. // We never throw away an event, but we do throw it away wholesale
  202. // as part of a path if we throw the entire path away.
  203. containsSomethingInteresting |= !event.isPrunable();
  204. break;
  205. }
  206. case PathDiagnosticPiece::ControlFlow:
  207. case PathDiagnosticPiece::Note:
  208. case PathDiagnosticPiece::PopUp:
  209. break;
  210. }
  211. pieces.push_back(std::move(piece));
  212. }
  213. return containsSomethingInteresting;
  214. }
  215. /// Same logic as above to remove extra pieces.
  216. static void removePopUpNotes(PathPieces &Path) {
  217. for (unsigned int i = 0; i < Path.size(); ++i) {
  218. auto Piece = std::move(Path.front());
  219. Path.pop_front();
  220. if (!isa<PathDiagnosticPopUpPiece>(*Piece))
  221. Path.push_back(std::move(Piece));
  222. }
  223. }
  224. /// Returns true if the given decl has been implicitly given a body, either by
  225. /// the analyzer or by the compiler proper.
  226. static bool hasImplicitBody(const Decl *D) {
  227. assert(D);
  228. return D->isImplicit() || !D->hasBody();
  229. }
  230. /// Recursively scan through a path and make sure that all call pieces have
  231. /// valid locations.
  232. static void
  233. adjustCallLocations(PathPieces &Pieces,
  234. PathDiagnosticLocation *LastCallLocation = nullptr) {
  235. for (const auto &I : Pieces) {
  236. auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
  237. if (!Call)
  238. continue;
  239. if (LastCallLocation) {
  240. bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
  241. if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
  242. Call->callEnter = *LastCallLocation;
  243. if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
  244. Call->callReturn = *LastCallLocation;
  245. }
  246. // Recursively clean out the subclass. Keep this call around if
  247. // it contains any informative diagnostics.
  248. PathDiagnosticLocation *ThisCallLocation;
  249. if (Call->callEnterWithin.asLocation().isValid() &&
  250. !hasImplicitBody(Call->getCallee()))
  251. ThisCallLocation = &Call->callEnterWithin;
  252. else
  253. ThisCallLocation = &Call->callEnter;
  254. assert(ThisCallLocation && "Outermost call has an invalid location");
  255. adjustCallLocations(Call->path, ThisCallLocation);
  256. }
  257. }
  258. /// Remove edges in and out of C++ default initializer expressions. These are
  259. /// for fields that have in-class initializers, as opposed to being initialized
  260. /// explicitly in a constructor or braced list.
  261. static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
  262. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  263. if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
  264. removeEdgesToDefaultInitializers(C->path);
  265. if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
  266. removeEdgesToDefaultInitializers(M->subPieces);
  267. if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
  268. const Stmt *Start = CF->getStartLocation().asStmt();
  269. const Stmt *End = CF->getEndLocation().asStmt();
  270. if (Start && isa<CXXDefaultInitExpr>(Start)) {
  271. I = Pieces.erase(I);
  272. continue;
  273. } else if (End && isa<CXXDefaultInitExpr>(End)) {
  274. PathPieces::iterator Next = std::next(I);
  275. if (Next != E) {
  276. if (auto *NextCF =
  277. dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
  278. NextCF->setStartLocation(CF->getStartLocation());
  279. }
  280. }
  281. I = Pieces.erase(I);
  282. continue;
  283. }
  284. }
  285. I++;
  286. }
  287. }
  288. /// Remove all pieces with invalid locations as these cannot be serialized.
  289. /// We might have pieces with invalid locations as a result of inlining Body
  290. /// Farm generated functions.
  291. static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
  292. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  293. if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
  294. removePiecesWithInvalidLocations(C->path);
  295. if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
  296. removePiecesWithInvalidLocations(M->subPieces);
  297. if (!(*I)->getLocation().isValid() ||
  298. !(*I)->getLocation().asLocation().isValid()) {
  299. I = Pieces.erase(I);
  300. continue;
  301. }
  302. I++;
  303. }
  304. }
  305. //===----------------------------------------------------------------------===//
  306. // PathDiagnosticBuilder and its associated routines and helper objects.
  307. //===----------------------------------------------------------------------===//
  308. namespace {
  309. class PathDiagnosticBuilder : public BugReporterContext {
  310. BugReport *R;
  311. PathDiagnosticConsumer *PDC;
  312. public:
  313. const LocationContext *LC;
  314. PathDiagnosticBuilder(GRBugReporter &br,
  315. BugReport *r, InterExplodedGraphMap &Backmap,
  316. PathDiagnosticConsumer *pdc)
  317. : BugReporterContext(br, Backmap), R(r), PDC(pdc),
  318. LC(r->getErrorNode()->getLocationContext()) {}
  319. PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
  320. PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
  321. const ExplodedNode *N);
  322. BugReport *getBugReport() { return R; }
  323. Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
  324. ParentMap& getParentMap() { return LC->getParentMap(); }
  325. const Stmt *getParent(const Stmt *S) {
  326. return getParentMap().getParent(S);
  327. }
  328. PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
  329. PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
  330. return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Minimal;
  331. }
  332. bool supportsLogicalOpControlFlow() const {
  333. return PDC ? PDC->supportsLogicalOpControlFlow() : true;
  334. }
  335. };
  336. } // namespace
  337. PathDiagnosticLocation
  338. PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
  339. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
  340. return PathDiagnosticLocation(S, getSourceManager(), LC);
  341. return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
  342. getSourceManager());
  343. }
  344. PathDiagnosticLocation
  345. PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
  346. const ExplodedNode *N) {
  347. // Slow, but probably doesn't matter.
  348. if (os.str().empty())
  349. os << ' ';
  350. const PathDiagnosticLocation &Loc = ExecutionContinues(N);
  351. if (Loc.asStmt())
  352. os << "Execution continues on line "
  353. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  354. << '.';
  355. else {
  356. os << "Execution jumps to the end of the ";
  357. const Decl *D = N->getLocationContext()->getDecl();
  358. if (isa<ObjCMethodDecl>(D))
  359. os << "method";
  360. else if (isa<FunctionDecl>(D))
  361. os << "function";
  362. else {
  363. assert(isa<BlockDecl>(D));
  364. os << "anonymous block";
  365. }
  366. os << '.';
  367. }
  368. return Loc;
  369. }
  370. static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
  371. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  372. return PM.getParentIgnoreParens(S);
  373. const Stmt *Parent = PM.getParentIgnoreParens(S);
  374. if (!Parent)
  375. return nullptr;
  376. switch (Parent->getStmtClass()) {
  377. case Stmt::ForStmtClass:
  378. case Stmt::DoStmtClass:
  379. case Stmt::WhileStmtClass:
  380. case Stmt::ObjCForCollectionStmtClass:
  381. case Stmt::CXXForRangeStmtClass:
  382. return Parent;
  383. default:
  384. break;
  385. }
  386. return nullptr;
  387. }
  388. static PathDiagnosticLocation
  389. getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P,
  390. const LocationContext *LC, bool allowNestedContexts) {
  391. if (!S)
  392. return {};
  393. while (const Stmt *Parent = getEnclosingParent(S, P)) {
  394. switch (Parent->getStmtClass()) {
  395. case Stmt::BinaryOperatorClass: {
  396. const auto *B = cast<BinaryOperator>(Parent);
  397. if (B->isLogicalOp())
  398. return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
  399. break;
  400. }
  401. case Stmt::CompoundStmtClass:
  402. case Stmt::StmtExprClass:
  403. return PathDiagnosticLocation(S, SMgr, LC);
  404. case Stmt::ChooseExprClass:
  405. // Similar to '?' if we are referring to condition, just have the edge
  406. // point to the entire choose expression.
  407. if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
  408. return PathDiagnosticLocation(Parent, SMgr, LC);
  409. else
  410. return PathDiagnosticLocation(S, SMgr, LC);
  411. case Stmt::BinaryConditionalOperatorClass:
  412. case Stmt::ConditionalOperatorClass:
  413. // For '?', if we are referring to condition, just have the edge point
  414. // to the entire '?' expression.
  415. if (allowNestedContexts ||
  416. cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  417. return PathDiagnosticLocation(Parent, SMgr, LC);
  418. else
  419. return PathDiagnosticLocation(S, SMgr, LC);
  420. case Stmt::CXXForRangeStmtClass:
  421. if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
  422. return PathDiagnosticLocation(S, SMgr, LC);
  423. break;
  424. case Stmt::DoStmtClass:
  425. return PathDiagnosticLocation(S, SMgr, LC);
  426. case Stmt::ForStmtClass:
  427. if (cast<ForStmt>(Parent)->getBody() == S)
  428. return PathDiagnosticLocation(S, SMgr, LC);
  429. break;
  430. case Stmt::IfStmtClass:
  431. if (cast<IfStmt>(Parent)->getCond() != S)
  432. return PathDiagnosticLocation(S, SMgr, LC);
  433. break;
  434. case Stmt::ObjCForCollectionStmtClass:
  435. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  436. return PathDiagnosticLocation(S, SMgr, LC);
  437. break;
  438. case Stmt::WhileStmtClass:
  439. if (cast<WhileStmt>(Parent)->getCond() != S)
  440. return PathDiagnosticLocation(S, SMgr, LC);
  441. break;
  442. default:
  443. break;
  444. }
  445. S = Parent;
  446. }
  447. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  448. return PathDiagnosticLocation(S, SMgr, LC);
  449. }
  450. PathDiagnosticLocation
  451. PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
  452. assert(S && "Null Stmt passed to getEnclosingStmtLocation");
  453. return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC,
  454. /*allowNestedContexts=*/false);
  455. }
  456. //===----------------------------------------------------------------------===//
  457. // "Minimal" path diagnostic generation algorithm.
  458. //===----------------------------------------------------------------------===//
  459. using StackDiagPair =
  460. std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
  461. using StackDiagVector = SmallVector<StackDiagPair, 6>;
  462. static void updateStackPiecesWithMessage(PathDiagnosticPiece &P,
  463. StackDiagVector &CallStack) {
  464. // If the piece contains a special message, add it to all the call
  465. // pieces on the active stack.
  466. if (auto *ep = dyn_cast<PathDiagnosticEventPiece>(&P)) {
  467. if (ep->hasCallStackHint())
  468. for (const auto &I : CallStack) {
  469. PathDiagnosticCallPiece *CP = I.first;
  470. const ExplodedNode *N = I.second;
  471. std::string stackMsg = ep->getCallStackMessage(N);
  472. // The last message on the path to final bug is the most important
  473. // one. Since we traverse the path backwards, do not add the message
  474. // if one has been previously added.
  475. if (!CP->hasCallStackMessage())
  476. CP->setCallStackMessage(stackMsg);
  477. }
  478. }
  479. }
  480. static void CompactMacroExpandedPieces(PathPieces &path,
  481. const SourceManager& SM);
  482. std::shared_ptr<PathDiagnosticControlFlowPiece> generateDiagForSwitchOP(
  483. const ExplodedNode *N,
  484. const CFGBlock *Dst,
  485. const SourceManager &SM,
  486. const LocationContext *LC,
  487. PathDiagnosticBuilder &PDB,
  488. PathDiagnosticLocation &Start
  489. ) {
  490. // Figure out what case arm we took.
  491. std::string sbuf;
  492. llvm::raw_string_ostream os(sbuf);
  493. PathDiagnosticLocation End;
  494. if (const Stmt *S = Dst->getLabel()) {
  495. End = PathDiagnosticLocation(S, SM, LC);
  496. switch (S->getStmtClass()) {
  497. default:
  498. os << "No cases match in the switch statement. "
  499. "Control jumps to line "
  500. << End.asLocation().getExpansionLineNumber();
  501. break;
  502. case Stmt::DefaultStmtClass:
  503. os << "Control jumps to the 'default' case at line "
  504. << End.asLocation().getExpansionLineNumber();
  505. break;
  506. case Stmt::CaseStmtClass: {
  507. os << "Control jumps to 'case ";
  508. const auto *Case = cast<CaseStmt>(S);
  509. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  510. // Determine if it is an enum.
  511. bool GetRawInt = true;
  512. if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
  513. // FIXME: Maybe this should be an assertion. Are there cases
  514. // were it is not an EnumConstantDecl?
  515. const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
  516. if (D) {
  517. GetRawInt = false;
  518. os << *D;
  519. }
  520. }
  521. if (GetRawInt)
  522. os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
  523. os << ":' at line " << End.asLocation().getExpansionLineNumber();
  524. break;
  525. }
  526. }
  527. } else {
  528. os << "'Default' branch taken. ";
  529. End = PDB.ExecutionContinues(os, N);
  530. }
  531. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  532. os.str());
  533. }
  534. std::shared_ptr<PathDiagnosticControlFlowPiece> generateDiagForGotoOP(
  535. const Stmt *S,
  536. PathDiagnosticBuilder &PDB,
  537. PathDiagnosticLocation &Start) {
  538. std::string sbuf;
  539. llvm::raw_string_ostream os(sbuf);
  540. const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
  541. os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
  542. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
  543. }
  544. std::shared_ptr<PathDiagnosticControlFlowPiece> generateDiagForBinaryOP(
  545. const ExplodedNode *N,
  546. const Stmt *T,
  547. const CFGBlock *Src,
  548. const CFGBlock *Dst,
  549. const SourceManager &SM,
  550. PathDiagnosticBuilder &PDB,
  551. const LocationContext *LC) {
  552. const auto *B = cast<BinaryOperator>(T);
  553. std::string sbuf;
  554. llvm::raw_string_ostream os(sbuf);
  555. os << "Left side of '";
  556. PathDiagnosticLocation Start, End;
  557. if (B->getOpcode() == BO_LAnd) {
  558. os << "&&"
  559. << "' is ";
  560. if (*(Src->succ_begin() + 1) == Dst) {
  561. os << "false";
  562. End = PathDiagnosticLocation(B->getLHS(), SM, LC);
  563. Start =
  564. PathDiagnosticLocation::createOperatorLoc(B, SM);
  565. } else {
  566. os << "true";
  567. Start = PathDiagnosticLocation(B->getLHS(), SM, LC);
  568. End = PDB.ExecutionContinues(N);
  569. }
  570. } else {
  571. assert(B->getOpcode() == BO_LOr);
  572. os << "||"
  573. << "' is ";
  574. if (*(Src->succ_begin() + 1) == Dst) {
  575. os << "false";
  576. Start = PathDiagnosticLocation(B->getLHS(), SM, LC);
  577. End = PDB.ExecutionContinues(N);
  578. } else {
  579. os << "true";
  580. End = PathDiagnosticLocation(B->getLHS(), SM, LC);
  581. Start =
  582. PathDiagnosticLocation::createOperatorLoc(B, SM);
  583. }
  584. }
  585. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  586. os.str());
  587. }
  588. void generateMinimalDiagForBlockEdge(const ExplodedNode *N, BlockEdge BE,
  589. const SourceManager &SM,
  590. PathDiagnosticBuilder &PDB,
  591. PathDiagnostic &PD) {
  592. const LocationContext *LC = N->getLocationContext();
  593. const CFGBlock *Src = BE.getSrc();
  594. const CFGBlock *Dst = BE.getDst();
  595. const Stmt *T = Src->getTerminatorStmt();
  596. if (!T)
  597. return;
  598. auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
  599. switch (T->getStmtClass()) {
  600. default:
  601. break;
  602. case Stmt::GotoStmtClass:
  603. case Stmt::IndirectGotoStmtClass: {
  604. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
  605. PD.getActivePath().push_front(generateDiagForGotoOP(S, PDB, Start));
  606. break;
  607. }
  608. case Stmt::SwitchStmtClass: {
  609. PD.getActivePath().push_front(
  610. generateDiagForSwitchOP(N, Dst, SM, LC, PDB, Start));
  611. break;
  612. }
  613. case Stmt::BreakStmtClass:
  614. case Stmt::ContinueStmtClass: {
  615. std::string sbuf;
  616. llvm::raw_string_ostream os(sbuf);
  617. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  618. PD.getActivePath().push_front(
  619. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
  620. break;
  621. }
  622. // Determine control-flow for ternary '?'.
  623. case Stmt::BinaryConditionalOperatorClass:
  624. case Stmt::ConditionalOperatorClass: {
  625. std::string sbuf;
  626. llvm::raw_string_ostream os(sbuf);
  627. os << "'?' condition is ";
  628. if (*(Src->succ_begin() + 1) == Dst)
  629. os << "false";
  630. else
  631. os << "true";
  632. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  633. if (const Stmt *S = End.asStmt())
  634. End = PDB.getEnclosingStmtLocation(S);
  635. PD.getActivePath().push_front(
  636. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
  637. break;
  638. }
  639. // Determine control-flow for short-circuited '&&' and '||'.
  640. case Stmt::BinaryOperatorClass: {
  641. if (!PDB.supportsLogicalOpControlFlow())
  642. break;
  643. std::shared_ptr<PathDiagnosticControlFlowPiece> Diag =
  644. generateDiagForBinaryOP(N, T, Src, Dst, SM, PDB, LC);
  645. PD.getActivePath().push_front(Diag);
  646. break;
  647. }
  648. case Stmt::DoStmtClass:
  649. if (*(Src->succ_begin()) == Dst) {
  650. std::string sbuf;
  651. llvm::raw_string_ostream os(sbuf);
  652. os << "Loop condition is true. ";
  653. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  654. if (const Stmt *S = End.asStmt())
  655. End = PDB.getEnclosingStmtLocation(S);
  656. PD.getActivePath().push_front(
  657. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  658. os.str()));
  659. } else {
  660. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  661. if (const Stmt *S = End.asStmt())
  662. End = PDB.getEnclosingStmtLocation(S);
  663. PD.getActivePath().push_front(
  664. std::make_shared<PathDiagnosticControlFlowPiece>(
  665. Start, End, "Loop condition is false. Exiting loop"));
  666. }
  667. break;
  668. case Stmt::WhileStmtClass:
  669. case Stmt::ForStmtClass:
  670. if (*(Src->succ_begin() + 1) == Dst) {
  671. std::string sbuf;
  672. llvm::raw_string_ostream os(sbuf);
  673. os << "Loop condition is false. ";
  674. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  675. if (const Stmt *S = End.asStmt())
  676. End = PDB.getEnclosingStmtLocation(S);
  677. PD.getActivePath().push_front(
  678. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  679. os.str()));
  680. } else {
  681. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  682. if (const Stmt *S = End.asStmt())
  683. End = PDB.getEnclosingStmtLocation(S);
  684. PD.getActivePath().push_front(
  685. std::make_shared<PathDiagnosticControlFlowPiece>(
  686. Start, End, "Loop condition is true. Entering loop body"));
  687. }
  688. break;
  689. case Stmt::IfStmtClass: {
  690. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  691. if (const Stmt *S = End.asStmt())
  692. End = PDB.getEnclosingStmtLocation(S);
  693. if (*(Src->succ_begin() + 1) == Dst)
  694. PD.getActivePath().push_front(
  695. std::make_shared<PathDiagnosticControlFlowPiece>(
  696. Start, End, "Taking false branch"));
  697. else
  698. PD.getActivePath().push_front(
  699. std::make_shared<PathDiagnosticControlFlowPiece>(
  700. Start, End, "Taking true branch"));
  701. break;
  702. }
  703. }
  704. }
  705. // Cone-of-influence: support the reverse propagation of "interesting" symbols
  706. // and values by tracing interesting calculations backwards through evaluated
  707. // expressions along a path. This is probably overly complicated, but the idea
  708. // is that if an expression computed an "interesting" value, the child
  709. // expressions are also likely to be "interesting" as well (which then
  710. // propagates to the values they in turn compute). This reverse propagation
  711. // is needed to track interesting correlations across function call boundaries,
  712. // where formal arguments bind to actual arguments, etc. This is also needed
  713. // because the constraint solver sometimes simplifies certain symbolic values
  714. // into constants when appropriate, and this complicates reasoning about
  715. // interesting values.
  716. using InterestingExprs = llvm::DenseSet<const Expr *>;
  717. static void reversePropagateIntererstingSymbols(BugReport &R,
  718. InterestingExprs &IE,
  719. const ProgramState *State,
  720. const Expr *Ex,
  721. const LocationContext *LCtx) {
  722. SVal V = State->getSVal(Ex, LCtx);
  723. if (!(R.isInteresting(V) || IE.count(Ex)))
  724. return;
  725. switch (Ex->getStmtClass()) {
  726. default:
  727. if (!isa<CastExpr>(Ex))
  728. break;
  729. LLVM_FALLTHROUGH;
  730. case Stmt::BinaryOperatorClass:
  731. case Stmt::UnaryOperatorClass: {
  732. for (const Stmt *SubStmt : Ex->children()) {
  733. if (const auto *child = dyn_cast_or_null<Expr>(SubStmt)) {
  734. IE.insert(child);
  735. SVal ChildV = State->getSVal(child, LCtx);
  736. R.markInteresting(ChildV);
  737. }
  738. }
  739. break;
  740. }
  741. }
  742. R.markInteresting(V);
  743. }
  744. static void reversePropagateInterestingSymbols(BugReport &R,
  745. InterestingExprs &IE,
  746. const ProgramState *State,
  747. const LocationContext *CalleeCtx)
  748. {
  749. // FIXME: Handle non-CallExpr-based CallEvents.
  750. const StackFrameContext *Callee = CalleeCtx->getStackFrame();
  751. const Stmt *CallSite = Callee->getCallSite();
  752. if (const auto *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
  753. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
  754. FunctionDecl::param_const_iterator PI = FD->param_begin(),
  755. PE = FD->param_end();
  756. CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
  757. for (; AI != AE && PI != PE; ++AI, ++PI) {
  758. if (const Expr *ArgE = *AI) {
  759. if (const ParmVarDecl *PD = *PI) {
  760. Loc LV = State->getLValue(PD, CalleeCtx);
  761. if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
  762. IE.insert(ArgE);
  763. }
  764. }
  765. }
  766. }
  767. }
  768. }
  769. //===----------------------------------------------------------------------===//
  770. // Functions for determining if a loop was executed 0 times.
  771. //===----------------------------------------------------------------------===//
  772. static bool isLoop(const Stmt *Term) {
  773. switch (Term->getStmtClass()) {
  774. case Stmt::ForStmtClass:
  775. case Stmt::WhileStmtClass:
  776. case Stmt::ObjCForCollectionStmtClass:
  777. case Stmt::CXXForRangeStmtClass:
  778. return true;
  779. default:
  780. // Note that we intentionally do not include do..while here.
  781. return false;
  782. }
  783. }
  784. static bool isJumpToFalseBranch(const BlockEdge *BE) {
  785. const CFGBlock *Src = BE->getSrc();
  786. assert(Src->succ_size() == 2);
  787. return (*(Src->succ_begin()+1) == BE->getDst());
  788. }
  789. static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
  790. while (SubS) {
  791. if (SubS == S)
  792. return true;
  793. SubS = PM.getParent(SubS);
  794. }
  795. return false;
  796. }
  797. static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
  798. const ExplodedNode *N) {
  799. while (N) {
  800. Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
  801. if (SP) {
  802. const Stmt *S = SP->getStmt();
  803. if (!isContainedByStmt(PM, Term, S))
  804. return S;
  805. }
  806. N = N->getFirstPred();
  807. }
  808. return nullptr;
  809. }
  810. static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
  811. const Stmt *LoopBody = nullptr;
  812. switch (Term->getStmtClass()) {
  813. case Stmt::CXXForRangeStmtClass: {
  814. const auto *FR = cast<CXXForRangeStmt>(Term);
  815. if (isContainedByStmt(PM, FR->getInc(), S))
  816. return true;
  817. if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
  818. return true;
  819. LoopBody = FR->getBody();
  820. break;
  821. }
  822. case Stmt::ForStmtClass: {
  823. const auto *FS = cast<ForStmt>(Term);
  824. if (isContainedByStmt(PM, FS->getInc(), S))
  825. return true;
  826. LoopBody = FS->getBody();
  827. break;
  828. }
  829. case Stmt::ObjCForCollectionStmtClass: {
  830. const auto *FC = cast<ObjCForCollectionStmt>(Term);
  831. LoopBody = FC->getBody();
  832. break;
  833. }
  834. case Stmt::WhileStmtClass:
  835. LoopBody = cast<WhileStmt>(Term)->getBody();
  836. break;
  837. default:
  838. return false;
  839. }
  840. return isContainedByStmt(PM, LoopBody, S);
  841. }
  842. /// Adds a sanitized control-flow diagnostic edge to a path.
  843. static void addEdgeToPath(PathPieces &path,
  844. PathDiagnosticLocation &PrevLoc,
  845. PathDiagnosticLocation NewLoc) {
  846. if (!NewLoc.isValid())
  847. return;
  848. SourceLocation NewLocL = NewLoc.asLocation();
  849. if (NewLocL.isInvalid())
  850. return;
  851. if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
  852. PrevLoc = NewLoc;
  853. return;
  854. }
  855. // Ignore self-edges, which occur when there are multiple nodes at the same
  856. // statement.
  857. if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
  858. return;
  859. path.push_front(
  860. std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
  861. PrevLoc = NewLoc;
  862. }
  863. /// A customized wrapper for CFGBlock::getTerminatorCondition()
  864. /// which returns the element for ObjCForCollectionStmts.
  865. static const Stmt *getTerminatorCondition(const CFGBlock *B) {
  866. const Stmt *S = B->getTerminatorCondition();
  867. if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
  868. return FS->getElement();
  869. return S;
  870. }
  871. static const char StrEnteringLoop[] = "Entering loop body";
  872. static const char StrLoopBodyZero[] = "Loop body executed 0 times";
  873. static const char StrLoopRangeEmpty[] =
  874. "Loop body skipped when range is empty";
  875. static const char StrLoopCollectionEmpty[] =
  876. "Loop body skipped when collection is empty";
  877. static std::unique_ptr<FilesToLineNumsMap>
  878. findExecutedLines(SourceManager &SM, const ExplodedNode *N);
  879. /// Generate diagnostics for the node \p N,
  880. /// and write it into \p PD.
  881. /// \p AddPathEdges Whether diagnostic consumer can generate path arrows
  882. /// showing both row and column.
  883. static void generatePathDiagnosticsForNode(const ExplodedNode *N,
  884. PathDiagnostic &PD,
  885. PathDiagnosticLocation &PrevLoc,
  886. PathDiagnosticBuilder &PDB,
  887. LocationContextMap &LCM,
  888. StackDiagVector &CallStack,
  889. InterestingExprs &IE,
  890. bool AddPathEdges) {
  891. ProgramPoint P = N->getLocation();
  892. const SourceManager& SM = PDB.getSourceManager();
  893. // Have we encountered an entrance to a call? It may be
  894. // the case that we have not encountered a matching
  895. // call exit before this point. This means that the path
  896. // terminated within the call itself.
  897. if (auto CE = P.getAs<CallEnter>()) {
  898. if (AddPathEdges) {
  899. // Add an edge to the start of the function.
  900. const StackFrameContext *CalleeLC = CE->getCalleeContext();
  901. const Decl *D = CalleeLC->getDecl();
  902. // Add the edge only when the callee has body. We jump to the beginning
  903. // of the *declaration*, however we expect it to be followed by the
  904. // body. This isn't the case for autosynthesized property accessors in
  905. // Objective-C. No need for a similar extra check for CallExit points
  906. // because the exit edge comes from a statement (i.e. return),
  907. // not from declaration.
  908. if (D->hasBody())
  909. addEdgeToPath(PD.getActivePath(), PrevLoc,
  910. PathDiagnosticLocation::createBegin(D, SM));
  911. }
  912. // Did we visit an entire call?
  913. bool VisitedEntireCall = PD.isWithinCall();
  914. PD.popActivePath();
  915. PathDiagnosticCallPiece *C;
  916. if (VisitedEntireCall) {
  917. C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front().get());
  918. } else {
  919. const Decl *Caller = CE->getLocationContext()->getDecl();
  920. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  921. if (AddPathEdges) {
  922. // Since we just transferred the path over to the call piece,
  923. // reset the mapping from active to location context.
  924. assert(PD.getActivePath().size() == 1 &&
  925. PD.getActivePath().front().get() == C);
  926. LCM[&PD.getActivePath()] = nullptr;
  927. }
  928. // Record the location context mapping for the path within
  929. // the call.
  930. assert(LCM[&C->path] == nullptr ||
  931. LCM[&C->path] == CE->getCalleeContext());
  932. LCM[&C->path] = CE->getCalleeContext();
  933. // If this is the first item in the active path, record
  934. // the new mapping from active path to location context.
  935. const LocationContext *&NewLC = LCM[&PD.getActivePath()];
  936. if (!NewLC)
  937. NewLC = N->getLocationContext();
  938. PDB.LC = NewLC;
  939. }
  940. C->setCallee(*CE, SM);
  941. // Update the previous location in the active path.
  942. PrevLoc = C->getLocation();
  943. if (!CallStack.empty()) {
  944. assert(CallStack.back().first == C);
  945. CallStack.pop_back();
  946. }
  947. return;
  948. }
  949. if (AddPathEdges) {
  950. // Query the location context here and the previous location
  951. // as processing CallEnter may change the active path.
  952. PDB.LC = N->getLocationContext();
  953. // Record the mapping from the active path to the location
  954. // context.
  955. assert(!LCM[&PD.getActivePath()] || LCM[&PD.getActivePath()] == PDB.LC);
  956. LCM[&PD.getActivePath()] = PDB.LC;
  957. }
  958. // Have we encountered an exit from a function call?
  959. if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
  960. // We are descending into a call (backwards). Construct
  961. // a new call piece to contain the path pieces for that call.
  962. auto C = PathDiagnosticCallPiece::construct(*CE, SM);
  963. // Record the mapping from call piece to LocationContext.
  964. LCM[&C->path] = CE->getCalleeContext();
  965. if (AddPathEdges) {
  966. const Stmt *S = CE->getCalleeContext()->getCallSite();
  967. // Propagate the interesting symbols accordingly.
  968. if (const auto *Ex = dyn_cast_or_null<Expr>(S)) {
  969. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  970. N->getState().get(), Ex,
  971. N->getLocationContext());
  972. }
  973. // Add the edge to the return site.
  974. addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn);
  975. PrevLoc.invalidate();
  976. }
  977. auto *P = C.get();
  978. PD.getActivePath().push_front(std::move(C));
  979. // Make the contents of the call the active path for now.
  980. PD.pushActivePath(&P->path);
  981. CallStack.push_back(StackDiagPair(P, N));
  982. return;
  983. }
  984. if (auto PS = P.getAs<PostStmt>()) {
  985. if (!AddPathEdges)
  986. return;
  987. // For expressions, make sure we propagate the
  988. // interesting symbols correctly.
  989. if (const Expr *Ex = PS->getStmtAs<Expr>())
  990. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  991. N->getState().get(), Ex,
  992. N->getLocationContext());
  993. // Add an edge. If this is an ObjCForCollectionStmt do
  994. // not add an edge here as it appears in the CFG both
  995. // as a terminator and as a terminator condition.
  996. if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
  997. PathDiagnosticLocation L =
  998. PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
  999. addEdgeToPath(PD.getActivePath(), PrevLoc, L);
  1000. }
  1001. } else if (auto BE = P.getAs<BlockEdge>()) {
  1002. if (!AddPathEdges) {
  1003. generateMinimalDiagForBlockEdge(N, *BE, SM, PDB, PD);
  1004. return;
  1005. }
  1006. // Does this represent entering a call? If so, look at propagating
  1007. // interesting symbols across call boundaries.
  1008. if (const ExplodedNode *NextNode = N->getFirstPred()) {
  1009. const LocationContext *CallerCtx = NextNode->getLocationContext();
  1010. const LocationContext *CalleeCtx = PDB.LC;
  1011. if (CallerCtx != CalleeCtx && AddPathEdges) {
  1012. reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
  1013. N->getState().get(), CalleeCtx);
  1014. }
  1015. }
  1016. // Are we jumping to the head of a loop? Add a special diagnostic.
  1017. if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
  1018. PathDiagnosticLocation L(Loop, SM, PDB.LC);
  1019. const Stmt *Body = nullptr;
  1020. if (const auto *FS = dyn_cast<ForStmt>(Loop))
  1021. Body = FS->getBody();
  1022. else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
  1023. Body = WS->getBody();
  1024. else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
  1025. Body = OFS->getBody();
  1026. } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
  1027. Body = FRS->getBody();
  1028. }
  1029. // do-while statements are explicitly excluded here
  1030. auto p = std::make_shared<PathDiagnosticEventPiece>(
  1031. L, "Looping back to the head "
  1032. "of the loop");
  1033. p->setPrunable(true);
  1034. addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation());
  1035. PD.getActivePath().push_front(std::move(p));
  1036. if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  1037. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1038. PathDiagnosticLocation::createEndBrace(CS, SM));
  1039. }
  1040. }
  1041. const CFGBlock *BSrc = BE->getSrc();
  1042. ParentMap &PM = PDB.getParentMap();
  1043. if (const Stmt *Term = BSrc->getTerminatorStmt()) {
  1044. // Are we jumping past the loop body without ever executing the
  1045. // loop (because the condition was false)?
  1046. if (isLoop(Term)) {
  1047. const Stmt *TermCond = getTerminatorCondition(BSrc);
  1048. bool IsInLoopBody =
  1049. isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
  1050. const char *str = nullptr;
  1051. if (isJumpToFalseBranch(&*BE)) {
  1052. if (!IsInLoopBody) {
  1053. if (isa<ObjCForCollectionStmt>(Term)) {
  1054. str = StrLoopCollectionEmpty;
  1055. } else if (isa<CXXForRangeStmt>(Term)) {
  1056. str = StrLoopRangeEmpty;
  1057. } else {
  1058. str = StrLoopBodyZero;
  1059. }
  1060. }
  1061. } else {
  1062. str = StrEnteringLoop;
  1063. }
  1064. if (str) {
  1065. PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC);
  1066. auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
  1067. PE->setPrunable(true);
  1068. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1069. PE->getLocation());
  1070. PD.getActivePath().push_front(std::move(PE));
  1071. }
  1072. } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
  1073. isa<GotoStmt>(Term)) {
  1074. PathDiagnosticLocation L(Term, SM, PDB.LC);
  1075. addEdgeToPath(PD.getActivePath(), PrevLoc, L);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. static std::unique_ptr<PathDiagnostic>
  1081. generateEmptyDiagnosticForReport(BugReport *R, SourceManager &SM) {
  1082. const BugType &BT = R->getBugType();
  1083. return llvm::make_unique<PathDiagnostic>(
  1084. R->getBugType().getCheckName(), R->getDeclWithIssue(),
  1085. R->getBugType().getName(), R->getDescription(),
  1086. R->getShortDescription(/*Fallback=*/false), BT.getCategory(),
  1087. R->getUniqueingLocation(), R->getUniqueingDecl(),
  1088. findExecutedLines(SM, R->getErrorNode()));
  1089. }
  1090. static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
  1091. if (!S)
  1092. return nullptr;
  1093. while (true) {
  1094. S = PM.getParentIgnoreParens(S);
  1095. if (!S)
  1096. break;
  1097. if (isa<FullExpr>(S) ||
  1098. isa<CXXBindTemporaryExpr>(S) ||
  1099. isa<SubstNonTypeTemplateParmExpr>(S))
  1100. continue;
  1101. break;
  1102. }
  1103. return S;
  1104. }
  1105. static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
  1106. switch (S->getStmtClass()) {
  1107. case Stmt::BinaryOperatorClass: {
  1108. const auto *BO = cast<BinaryOperator>(S);
  1109. if (!BO->isLogicalOp())
  1110. return false;
  1111. return BO->getLHS() == Cond || BO->getRHS() == Cond;
  1112. }
  1113. case Stmt::IfStmtClass:
  1114. return cast<IfStmt>(S)->getCond() == Cond;
  1115. case Stmt::ForStmtClass:
  1116. return cast<ForStmt>(S)->getCond() == Cond;
  1117. case Stmt::WhileStmtClass:
  1118. return cast<WhileStmt>(S)->getCond() == Cond;
  1119. case Stmt::DoStmtClass:
  1120. return cast<DoStmt>(S)->getCond() == Cond;
  1121. case Stmt::ChooseExprClass:
  1122. return cast<ChooseExpr>(S)->getCond() == Cond;
  1123. case Stmt::IndirectGotoStmtClass:
  1124. return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
  1125. case Stmt::SwitchStmtClass:
  1126. return cast<SwitchStmt>(S)->getCond() == Cond;
  1127. case Stmt::BinaryConditionalOperatorClass:
  1128. return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
  1129. case Stmt::ConditionalOperatorClass: {
  1130. const auto *CO = cast<ConditionalOperator>(S);
  1131. return CO->getCond() == Cond ||
  1132. CO->getLHS() == Cond ||
  1133. CO->getRHS() == Cond;
  1134. }
  1135. case Stmt::ObjCForCollectionStmtClass:
  1136. return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
  1137. case Stmt::CXXForRangeStmtClass: {
  1138. const auto *FRS = cast<CXXForRangeStmt>(S);
  1139. return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
  1140. }
  1141. default:
  1142. return false;
  1143. }
  1144. }
  1145. static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
  1146. if (const auto *FS = dyn_cast<ForStmt>(FL))
  1147. return FS->getInc() == S || FS->getInit() == S;
  1148. if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
  1149. return FRS->getInc() == S || FRS->getRangeStmt() == S ||
  1150. FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
  1151. return false;
  1152. }
  1153. using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
  1154. /// Adds synthetic edges from top-level statements to their subexpressions.
  1155. ///
  1156. /// This avoids a "swoosh" effect, where an edge from a top-level statement A
  1157. /// points to a sub-expression B.1 that's not at the start of B. In these cases,
  1158. /// we'd like to see an edge from A to B, then another one from B to B.1.
  1159. static void addContextEdges(PathPieces &pieces, SourceManager &SM,
  1160. const ParentMap &PM, const LocationContext *LCtx) {
  1161. PathPieces::iterator Prev = pieces.end();
  1162. for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
  1163. Prev = I, ++I) {
  1164. auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1165. if (!Piece)
  1166. continue;
  1167. PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
  1168. SmallVector<PathDiagnosticLocation, 4> SrcContexts;
  1169. PathDiagnosticLocation NextSrcContext = SrcLoc;
  1170. const Stmt *InnerStmt = nullptr;
  1171. while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
  1172. SrcContexts.push_back(NextSrcContext);
  1173. InnerStmt = NextSrcContext.asStmt();
  1174. NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx,
  1175. /*allowNested=*/true);
  1176. }
  1177. // Repeatedly split the edge as necessary.
  1178. // This is important for nested logical expressions (||, &&, ?:) where we
  1179. // want to show all the levels of context.
  1180. while (true) {
  1181. const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
  1182. // We are looking at an edge. Is the destination within a larger
  1183. // expression?
  1184. PathDiagnosticLocation DstContext =
  1185. getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true);
  1186. if (!DstContext.isValid() || DstContext.asStmt() == Dst)
  1187. break;
  1188. // If the source is in the same context, we're already good.
  1189. if (llvm::find(SrcContexts, DstContext) != SrcContexts.end())
  1190. break;
  1191. // Update the subexpression node to point to the context edge.
  1192. Piece->setStartLocation(DstContext);
  1193. // Try to extend the previous edge if it's at the same level as the source
  1194. // context.
  1195. if (Prev != E) {
  1196. auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
  1197. if (PrevPiece) {
  1198. if (const Stmt *PrevSrc =
  1199. PrevPiece->getStartLocation().getStmtOrNull()) {
  1200. const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
  1201. if (PrevSrcParent ==
  1202. getStmtParent(DstContext.getStmtOrNull(), PM)) {
  1203. PrevPiece->setEndLocation(DstContext);
  1204. break;
  1205. }
  1206. }
  1207. }
  1208. }
  1209. // Otherwise, split the current edge into a context edge and a
  1210. // subexpression edge. Note that the context statement may itself have
  1211. // context.
  1212. auto P =
  1213. std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
  1214. Piece = P.get();
  1215. I = pieces.insert(I, std::move(P));
  1216. }
  1217. }
  1218. }
  1219. /// Move edges from a branch condition to a branch target
  1220. /// when the condition is simple.
  1221. ///
  1222. /// This restructures some of the work of addContextEdges. That function
  1223. /// creates edges this may destroy, but they work together to create a more
  1224. /// aesthetically set of edges around branches. After the call to
  1225. /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
  1226. /// the branch to the branch condition, and (3) an edge from the branch
  1227. /// condition to the branch target. We keep (1), but may wish to remove (2)
  1228. /// and move the source of (3) to the branch if the branch condition is simple.
  1229. static void simplifySimpleBranches(PathPieces &pieces) {
  1230. for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
  1231. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1232. if (!PieceI)
  1233. continue;
  1234. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1235. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1236. if (!s1Start || !s1End)
  1237. continue;
  1238. PathPieces::iterator NextI = I; ++NextI;
  1239. if (NextI == E)
  1240. break;
  1241. PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
  1242. while (true) {
  1243. if (NextI == E)
  1244. break;
  1245. const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
  1246. if (EV) {
  1247. StringRef S = EV->getString();
  1248. if (S == StrEnteringLoop || S == StrLoopBodyZero ||
  1249. S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
  1250. ++NextI;
  1251. continue;
  1252. }
  1253. break;
  1254. }
  1255. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1256. break;
  1257. }
  1258. if (!PieceNextI)
  1259. continue;
  1260. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1261. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1262. if (!s2Start || !s2End || s1End != s2Start)
  1263. continue;
  1264. // We only perform this transformation for specific branch kinds.
  1265. // We don't want to do this for do..while, for example.
  1266. if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
  1267. isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
  1268. isa<CXXForRangeStmt>(s1Start)))
  1269. continue;
  1270. // Is s1End the branch condition?
  1271. if (!isConditionForTerminator(s1Start, s1End))
  1272. continue;
  1273. // Perform the hoisting by eliminating (2) and changing the start
  1274. // location of (3).
  1275. PieceNextI->setStartLocation(PieceI->getStartLocation());
  1276. I = pieces.erase(I);
  1277. }
  1278. }
  1279. /// Returns the number of bytes in the given (character-based) SourceRange.
  1280. ///
  1281. /// If the locations in the range are not on the same line, returns None.
  1282. ///
  1283. /// Note that this does not do a precise user-visible character or column count.
  1284. static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
  1285. SourceRange Range) {
  1286. SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
  1287. SM.getExpansionRange(Range.getEnd()).getEnd());
  1288. FileID FID = SM.getFileID(ExpansionRange.getBegin());
  1289. if (FID != SM.getFileID(ExpansionRange.getEnd()))
  1290. return None;
  1291. bool Invalid;
  1292. const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
  1293. if (Invalid)
  1294. return None;
  1295. unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
  1296. unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
  1297. StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
  1298. // We're searching the raw bytes of the buffer here, which might include
  1299. // escaped newlines and such. That's okay; we're trying to decide whether the
  1300. // SourceRange is covering a large or small amount of space in the user's
  1301. // editor.
  1302. if (Snippet.find_first_of("\r\n") != StringRef::npos)
  1303. return None;
  1304. // This isn't Unicode-aware, but it doesn't need to be.
  1305. return Snippet.size();
  1306. }
  1307. /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
  1308. static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
  1309. const Stmt *S) {
  1310. return getLengthOnSingleLine(SM, S->getSourceRange());
  1311. }
  1312. /// Eliminate two-edge cycles created by addContextEdges().
  1313. ///
  1314. /// Once all the context edges are in place, there are plenty of cases where
  1315. /// there's a single edge from a top-level statement to a subexpression,
  1316. /// followed by a single path note, and then a reverse edge to get back out to
  1317. /// the top level. If the statement is simple enough, the subexpression edges
  1318. /// just add noise and make it harder to understand what's going on.
  1319. ///
  1320. /// This function only removes edges in pairs, because removing only one edge
  1321. /// might leave other edges dangling.
  1322. ///
  1323. /// This will not remove edges in more complicated situations:
  1324. /// - if there is more than one "hop" leading to or from a subexpression.
  1325. /// - if there is an inlined call between the edges instead of a single event.
  1326. /// - if the whole statement is large enough that having subexpression arrows
  1327. /// might be helpful.
  1328. static void removeContextCycles(PathPieces &Path, SourceManager &SM) {
  1329. for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
  1330. // Pattern match the current piece and its successor.
  1331. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1332. if (!PieceI) {
  1333. ++I;
  1334. continue;
  1335. }
  1336. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1337. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1338. PathPieces::iterator NextI = I; ++NextI;
  1339. if (NextI == E)
  1340. break;
  1341. const auto *PieceNextI =
  1342. dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1343. if (!PieceNextI) {
  1344. if (isa<PathDiagnosticEventPiece>(NextI->get())) {
  1345. ++NextI;
  1346. if (NextI == E)
  1347. break;
  1348. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1349. }
  1350. if (!PieceNextI) {
  1351. ++I;
  1352. continue;
  1353. }
  1354. }
  1355. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1356. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1357. if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
  1358. const size_t MAX_SHORT_LINE_LENGTH = 80;
  1359. Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
  1360. if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
  1361. Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
  1362. if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
  1363. Path.erase(I);
  1364. I = Path.erase(NextI);
  1365. continue;
  1366. }
  1367. }
  1368. }
  1369. ++I;
  1370. }
  1371. }
  1372. /// Return true if X is contained by Y.
  1373. static bool lexicalContains(ParentMap &PM, const Stmt *X, const Stmt *Y) {
  1374. while (X) {
  1375. if (X == Y)
  1376. return true;
  1377. X = PM.getParent(X);
  1378. }
  1379. return false;
  1380. }
  1381. // Remove short edges on the same line less than 3 columns in difference.
  1382. static void removePunyEdges(PathPieces &path, SourceManager &SM,
  1383. ParentMap &PM) {
  1384. bool erased = false;
  1385. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
  1386. erased ? I : ++I) {
  1387. erased = false;
  1388. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1389. if (!PieceI)
  1390. continue;
  1391. const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
  1392. const Stmt *end = PieceI->getEndLocation().getStmtOrNull();
  1393. if (!start || !end)
  1394. continue;
  1395. const Stmt *endParent = PM.getParent(end);
  1396. if (!endParent)
  1397. continue;
  1398. if (isConditionForTerminator(end, endParent))
  1399. continue;
  1400. SourceLocation FirstLoc = start->getBeginLoc();
  1401. SourceLocation SecondLoc = end->getBeginLoc();
  1402. if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
  1403. continue;
  1404. if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
  1405. std::swap(SecondLoc, FirstLoc);
  1406. SourceRange EdgeRange(FirstLoc, SecondLoc);
  1407. Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
  1408. // If the statements are on different lines, continue.
  1409. if (!ByteWidth)
  1410. continue;
  1411. const size_t MAX_PUNY_EDGE_LENGTH = 2;
  1412. if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
  1413. // FIXME: There are enough /bytes/ between the endpoints of the edge, but
  1414. // there might not be enough /columns/. A proper user-visible column count
  1415. // is probably too expensive, though.
  1416. I = path.erase(I);
  1417. erased = true;
  1418. continue;
  1419. }
  1420. }
  1421. }
  1422. static void removeIdenticalEvents(PathPieces &path) {
  1423. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
  1424. const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
  1425. if (!PieceI)
  1426. continue;
  1427. PathPieces::iterator NextI = I; ++NextI;
  1428. if (NextI == E)
  1429. return;
  1430. const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
  1431. if (!PieceNextI)
  1432. continue;
  1433. // Erase the second piece if it has the same exact message text.
  1434. if (PieceI->getString() == PieceNextI->getString()) {
  1435. path.erase(NextI);
  1436. }
  1437. }
  1438. }
  1439. static bool optimizeEdges(PathPieces &path, SourceManager &SM,
  1440. OptimizedCallsSet &OCS,
  1441. LocationContextMap &LCM) {
  1442. bool hasChanges = false;
  1443. const LocationContext *LC = LCM[&path];
  1444. assert(LC);
  1445. ParentMap &PM = LC->getParentMap();
  1446. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
  1447. // Optimize subpaths.
  1448. if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
  1449. // Record the fact that a call has been optimized so we only do the
  1450. // effort once.
  1451. if (!OCS.count(CallI)) {
  1452. while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
  1453. OCS.insert(CallI);
  1454. }
  1455. ++I;
  1456. continue;
  1457. }
  1458. // Pattern match the current piece and its successor.
  1459. auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1460. if (!PieceI) {
  1461. ++I;
  1462. continue;
  1463. }
  1464. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1465. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1466. const Stmt *level1 = getStmtParent(s1Start, PM);
  1467. const Stmt *level2 = getStmtParent(s1End, PM);
  1468. PathPieces::iterator NextI = I; ++NextI;
  1469. if (NextI == E)
  1470. break;
  1471. const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1472. if (!PieceNextI) {
  1473. ++I;
  1474. continue;
  1475. }
  1476. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1477. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1478. const Stmt *level3 = getStmtParent(s2Start, PM);
  1479. const Stmt *level4 = getStmtParent(s2End, PM);
  1480. // Rule I.
  1481. //
  1482. // If we have two consecutive control edges whose end/begin locations
  1483. // are at the same level (e.g. statements or top-level expressions within
  1484. // a compound statement, or siblings share a single ancestor expression),
  1485. // then merge them if they have no interesting intermediate event.
  1486. //
  1487. // For example:
  1488. //
  1489. // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
  1490. // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
  1491. //
  1492. // NOTE: this will be limited later in cases where we add barriers
  1493. // to prevent this optimization.
  1494. if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
  1495. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1496. path.erase(NextI);
  1497. hasChanges = true;
  1498. continue;
  1499. }
  1500. // Rule II.
  1501. //
  1502. // Eliminate edges between subexpressions and parent expressions
  1503. // when the subexpression is consumed.
  1504. //
  1505. // NOTE: this will be limited later in cases where we add barriers
  1506. // to prevent this optimization.
  1507. if (s1End && s1End == s2Start && level2) {
  1508. bool removeEdge = false;
  1509. // Remove edges into the increment or initialization of a
  1510. // loop that have no interleaving event. This means that
  1511. // they aren't interesting.
  1512. if (isIncrementOrInitInForLoop(s1End, level2))
  1513. removeEdge = true;
  1514. // Next only consider edges that are not anchored on
  1515. // the condition of a terminator. This are intermediate edges
  1516. // that we might want to trim.
  1517. else if (!isConditionForTerminator(level2, s1End)) {
  1518. // Trim edges on expressions that are consumed by
  1519. // the parent expression.
  1520. if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
  1521. removeEdge = true;
  1522. }
  1523. // Trim edges where a lexical containment doesn't exist.
  1524. // For example:
  1525. //
  1526. // X -> Y -> Z
  1527. //
  1528. // If 'Z' lexically contains Y (it is an ancestor) and
  1529. // 'X' does not lexically contain Y (it is a descendant OR
  1530. // it has no lexical relationship at all) then trim.
  1531. //
  1532. // This can eliminate edges where we dive into a subexpression
  1533. // and then pop back out, etc.
  1534. else if (s1Start && s2End &&
  1535. lexicalContains(PM, s2Start, s2End) &&
  1536. !lexicalContains(PM, s1End, s1Start)) {
  1537. removeEdge = true;
  1538. }
  1539. // Trim edges from a subexpression back to the top level if the
  1540. // subexpression is on a different line.
  1541. //
  1542. // A.1 -> A -> B
  1543. // becomes
  1544. // A.1 -> B
  1545. //
  1546. // These edges just look ugly and don't usually add anything.
  1547. else if (s1Start && s2End &&
  1548. lexicalContains(PM, s1Start, s1End)) {
  1549. SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
  1550. PieceI->getStartLocation().asLocation());
  1551. if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
  1552. removeEdge = true;
  1553. }
  1554. }
  1555. if (removeEdge) {
  1556. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1557. path.erase(NextI);
  1558. hasChanges = true;
  1559. continue;
  1560. }
  1561. }
  1562. // Optimize edges for ObjC fast-enumeration loops.
  1563. //
  1564. // (X -> collection) -> (collection -> element)
  1565. //
  1566. // becomes:
  1567. //
  1568. // (X -> element)
  1569. if (s1End == s2Start) {
  1570. const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
  1571. if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
  1572. s2End == FS->getElement()) {
  1573. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1574. path.erase(NextI);
  1575. hasChanges = true;
  1576. continue;
  1577. }
  1578. }
  1579. // No changes at this index? Move to the next one.
  1580. ++I;
  1581. }
  1582. if (!hasChanges) {
  1583. // Adjust edges into subexpressions to make them more uniform
  1584. // and aesthetically pleasing.
  1585. addContextEdges(path, SM, PM, LC);
  1586. // Remove "cyclical" edges that include one or more context edges.
  1587. removeContextCycles(path, SM);
  1588. // Hoist edges originating from branch conditions to branches
  1589. // for simple branches.
  1590. simplifySimpleBranches(path);
  1591. // Remove any puny edges left over after primary optimization pass.
  1592. removePunyEdges(path, SM, PM);
  1593. // Remove identical events.
  1594. removeIdenticalEvents(path);
  1595. }
  1596. return hasChanges;
  1597. }
  1598. /// Drop the very first edge in a path, which should be a function entry edge.
  1599. ///
  1600. /// If the first edge is not a function entry edge (say, because the first
  1601. /// statement had an invalid source location), this function does nothing.
  1602. // FIXME: We should just generate invalid edges anyway and have the optimizer
  1603. // deal with them.
  1604. static void dropFunctionEntryEdge(PathPieces &Path, LocationContextMap &LCM,
  1605. SourceManager &SM) {
  1606. const auto *FirstEdge =
  1607. dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
  1608. if (!FirstEdge)
  1609. return;
  1610. const Decl *D = LCM[&Path]->getDecl();
  1611. PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM);
  1612. if (FirstEdge->getStartLocation() != EntryLoc)
  1613. return;
  1614. Path.pop_front();
  1615. }
  1616. using VisitorsDiagnosticsTy = llvm::DenseMap<const ExplodedNode *,
  1617. std::vector<std::shared_ptr<PathDiagnosticPiece>>>;
  1618. /// Populate executes lines with lines containing at least one diagnostics.
  1619. static void updateExecutedLinesWithDiagnosticPieces(
  1620. PathDiagnostic &PD) {
  1621. PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
  1622. FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
  1623. for (const auto &P : path) {
  1624. FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
  1625. FileID FID = Loc.getFileID();
  1626. unsigned LineNo = Loc.getLineNumber();
  1627. assert(FID.isValid());
  1628. ExecutedLines[FID].insert(LineNo);
  1629. }
  1630. }
  1631. /// This function is responsible for generating diagnostic pieces that are
  1632. /// *not* provided by bug report visitors.
  1633. /// These diagnostics may differ depending on the consumer's settings,
  1634. /// and are therefore constructed separately for each consumer.
  1635. ///
  1636. /// There are two path diagnostics generation modes: with adding edges (used
  1637. /// for plists) and without (used for HTML and text).
  1638. /// When edges are added (\p ActiveScheme is Extensive),
  1639. /// the path is modified to insert artificially generated
  1640. /// edges.
  1641. /// Otherwise, more detailed diagnostics is emitted for block edges, explaining
  1642. /// the transitions in words.
  1643. static std::unique_ptr<PathDiagnostic> generatePathDiagnosticForConsumer(
  1644. PathDiagnosticConsumer::PathGenerationScheme ActiveScheme,
  1645. PathDiagnosticBuilder &PDB,
  1646. const ExplodedNode *ErrorNode,
  1647. const VisitorsDiagnosticsTy &VisitorsDiagnostics) {
  1648. bool GenerateDiagnostics = (ActiveScheme != PathDiagnosticConsumer::None);
  1649. bool AddPathEdges = (ActiveScheme == PathDiagnosticConsumer::Extensive);
  1650. SourceManager &SM = PDB.getSourceManager();
  1651. BugReport *R = PDB.getBugReport();
  1652. AnalyzerOptions &Opts = PDB.getBugReporter().getAnalyzerOptions();
  1653. StackDiagVector CallStack;
  1654. InterestingExprs IE;
  1655. LocationContextMap LCM;
  1656. std::unique_ptr<PathDiagnostic> PD = generateEmptyDiagnosticForReport(R, SM);
  1657. if (GenerateDiagnostics) {
  1658. auto EndNotes = VisitorsDiagnostics.find(ErrorNode);
  1659. std::shared_ptr<PathDiagnosticPiece> LastPiece;
  1660. if (EndNotes != VisitorsDiagnostics.end()) {
  1661. assert(!EndNotes->second.empty());
  1662. LastPiece = EndNotes->second[0];
  1663. } else {
  1664. LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, ErrorNode, *R);
  1665. }
  1666. PD->setEndOfPath(LastPiece);
  1667. }
  1668. PathDiagnosticLocation PrevLoc = PD->getLocation();
  1669. const ExplodedNode *NextNode = ErrorNode->getFirstPred();
  1670. while (NextNode) {
  1671. if (GenerateDiagnostics)
  1672. generatePathDiagnosticsForNode(
  1673. NextNode, *PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
  1674. auto VisitorNotes = VisitorsDiagnostics.find(NextNode);
  1675. NextNode = NextNode->getFirstPred();
  1676. if (!GenerateDiagnostics || VisitorNotes == VisitorsDiagnostics.end())
  1677. continue;
  1678. // This is a workaround due to inability to put shared PathDiagnosticPiece
  1679. // into a FoldingSet.
  1680. std::set<llvm::FoldingSetNodeID> DeduplicationSet;
  1681. // Add pieces from custom visitors.
  1682. for (const auto &Note : VisitorNotes->second) {
  1683. llvm::FoldingSetNodeID ID;
  1684. Note->Profile(ID);
  1685. auto P = DeduplicationSet.insert(ID);
  1686. if (!P.second)
  1687. continue;
  1688. if (AddPathEdges)
  1689. addEdgeToPath(PD->getActivePath(), PrevLoc, Note->getLocation());
  1690. updateStackPiecesWithMessage(*Note, CallStack);
  1691. PD->getActivePath().push_front(Note);
  1692. }
  1693. }
  1694. if (AddPathEdges) {
  1695. // Add an edge to the start of the function.
  1696. // We'll prune it out later, but it helps make diagnostics more uniform.
  1697. const StackFrameContext *CalleeLC = PDB.LC->getStackFrame();
  1698. const Decl *D = CalleeLC->getDecl();
  1699. addEdgeToPath(PD->getActivePath(), PrevLoc,
  1700. PathDiagnosticLocation::createBegin(D, SM));
  1701. }
  1702. // Finally, prune the diagnostic path of uninteresting stuff.
  1703. if (!PD->path.empty()) {
  1704. if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
  1705. bool stillHasNotes =
  1706. removeUnneededCalls(PD->getMutablePieces(), R, LCM);
  1707. assert(stillHasNotes);
  1708. (void)stillHasNotes;
  1709. }
  1710. // Remove pop-up notes if needed.
  1711. if (!Opts.ShouldAddPopUpNotes)
  1712. removePopUpNotes(PD->getMutablePieces());
  1713. // Redirect all call pieces to have valid locations.
  1714. adjustCallLocations(PD->getMutablePieces());
  1715. removePiecesWithInvalidLocations(PD->getMutablePieces());
  1716. if (AddPathEdges) {
  1717. // Reduce the number of edges from a very conservative set
  1718. // to an aesthetically pleasing subset that conveys the
  1719. // necessary information.
  1720. OptimizedCallsSet OCS;
  1721. while (optimizeEdges(PD->getMutablePieces(), SM, OCS, LCM)) {}
  1722. // Drop the very first function-entry edge. It's not really necessary
  1723. // for top-level functions.
  1724. dropFunctionEntryEdge(PD->getMutablePieces(), LCM, SM);
  1725. }
  1726. // Remove messages that are basically the same, and edges that may not
  1727. // make sense.
  1728. // We have to do this after edge optimization in the Extensive mode.
  1729. removeRedundantMsgs(PD->getMutablePieces());
  1730. removeEdgesToDefaultInitializers(PD->getMutablePieces());
  1731. }
  1732. if (GenerateDiagnostics && Opts.ShouldDisplayMacroExpansions)
  1733. CompactMacroExpandedPieces(PD->getMutablePieces(), SM);
  1734. return PD;
  1735. }
  1736. //===----------------------------------------------------------------------===//
  1737. // Methods for BugType and subclasses.
  1738. //===----------------------------------------------------------------------===//
  1739. void BugType::anchor() {}
  1740. void BuiltinBug::anchor() {}
  1741. //===----------------------------------------------------------------------===//
  1742. // Methods for BugReport and subclasses.
  1743. //===----------------------------------------------------------------------===//
  1744. void BugReport::NodeResolver::anchor() {}
  1745. void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
  1746. if (!visitor)
  1747. return;
  1748. llvm::FoldingSetNodeID ID;
  1749. visitor->Profile(ID);
  1750. void *InsertPos = nullptr;
  1751. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
  1752. return;
  1753. }
  1754. Callbacks.push_back(std::move(visitor));
  1755. }
  1756. void BugReport::clearVisitors() {
  1757. Callbacks.clear();
  1758. }
  1759. BugReport::~BugReport() {
  1760. while (!interestingSymbols.empty()) {
  1761. popInterestingSymbolsAndRegions();
  1762. }
  1763. }
  1764. const Decl *BugReport::getDeclWithIssue() const {
  1765. if (DeclWithIssue)
  1766. return DeclWithIssue;
  1767. const ExplodedNode *N = getErrorNode();
  1768. if (!N)
  1769. return nullptr;
  1770. const LocationContext *LC = N->getLocationContext();
  1771. return LC->getStackFrame()->getDecl();
  1772. }
  1773. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  1774. hash.AddPointer(&BT);
  1775. hash.AddString(Description);
  1776. PathDiagnosticLocation UL = getUniqueingLocation();
  1777. if (UL.isValid()) {
  1778. UL.Profile(hash);
  1779. } else if (Location.isValid()) {
  1780. Location.Profile(hash);
  1781. } else {
  1782. assert(ErrorNode);
  1783. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  1784. }
  1785. for (SourceRange range : Ranges) {
  1786. if (!range.isValid())
  1787. continue;
  1788. hash.AddInteger(range.getBegin().getRawEncoding());
  1789. hash.AddInteger(range.getEnd().getRawEncoding());
  1790. }
  1791. }
  1792. void BugReport::markInteresting(SymbolRef sym) {
  1793. if (!sym)
  1794. return;
  1795. getInterestingSymbols().insert(sym);
  1796. if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
  1797. getInterestingRegions().insert(meta->getRegion());
  1798. }
  1799. void BugReport::markInteresting(const MemRegion *R) {
  1800. if (!R)
  1801. return;
  1802. R = R->getBaseRegion();
  1803. getInterestingRegions().insert(R);
  1804. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1805. getInterestingSymbols().insert(SR->getSymbol());
  1806. }
  1807. void BugReport::markInteresting(SVal V) {
  1808. markInteresting(V.getAsRegion());
  1809. markInteresting(V.getAsSymbol());
  1810. }
  1811. void BugReport::markInteresting(const LocationContext *LC) {
  1812. if (!LC)
  1813. return;
  1814. InterestingLocationContexts.insert(LC);
  1815. }
  1816. bool BugReport::isInteresting(SVal V) {
  1817. return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
  1818. }
  1819. bool BugReport::isInteresting(SymbolRef sym) {
  1820. if (!sym)
  1821. return false;
  1822. // We don't currently consider metadata symbols to be interesting
  1823. // even if we know their region is interesting. Is that correct behavior?
  1824. return getInterestingSymbols().count(sym);
  1825. }
  1826. bool BugReport::isInteresting(const MemRegion *R) {
  1827. if (!R)
  1828. return false;
  1829. R = R->getBaseRegion();
  1830. bool b = getInterestingRegions().count(R);
  1831. if (b)
  1832. return true;
  1833. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1834. return getInterestingSymbols().count(SR->getSymbol());
  1835. return false;
  1836. }
  1837. bool BugReport::isInteresting(const LocationContext *LC) {
  1838. if (!LC)
  1839. return false;
  1840. return InterestingLocationContexts.count(LC);
  1841. }
  1842. void BugReport::lazyInitializeInterestingSets() {
  1843. if (interestingSymbols.empty()) {
  1844. interestingSymbols.push_back(new Symbols());
  1845. interestingRegions.push_back(new Regions());
  1846. }
  1847. }
  1848. BugReport::Symbols &BugReport::getInterestingSymbols() {
  1849. lazyInitializeInterestingSets();
  1850. return *interestingSymbols.back();
  1851. }
  1852. BugReport::Regions &BugReport::getInterestingRegions() {
  1853. lazyInitializeInterestingSets();
  1854. return *interestingRegions.back();
  1855. }
  1856. void BugReport::pushInterestingSymbolsAndRegions() {
  1857. interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
  1858. interestingRegions.push_back(new Regions(getInterestingRegions()));
  1859. }
  1860. void BugReport::popInterestingSymbolsAndRegions() {
  1861. delete interestingSymbols.pop_back_val();
  1862. delete interestingRegions.pop_back_val();
  1863. }
  1864. const Stmt *BugReport::getStmt() const {
  1865. if (!ErrorNode)
  1866. return nullptr;
  1867. ProgramPoint ProgP = ErrorNode->getLocation();
  1868. const Stmt *S = nullptr;
  1869. if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
  1870. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1871. if (BE->getBlock() == &Exit)
  1872. S = GetPreviousStmt(ErrorNode);
  1873. }
  1874. if (!S)
  1875. S = PathDiagnosticLocation::getStmt(ErrorNode);
  1876. return S;
  1877. }
  1878. llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
  1879. // If no custom ranges, add the range of the statement corresponding to
  1880. // the error node.
  1881. if (Ranges.empty()) {
  1882. if (const auto *E = dyn_cast_or_null<Expr>(getStmt()))
  1883. addRange(E->getSourceRange());
  1884. else
  1885. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1886. }
  1887. // User-specified absence of range info.
  1888. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  1889. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1890. return llvm::make_range(Ranges.begin(), Ranges.end());
  1891. }
  1892. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  1893. if (ErrorNode) {
  1894. assert(!Location.isValid() &&
  1895. "Either Location or ErrorNode should be specified but not both.");
  1896. return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
  1897. }
  1898. assert(Location.isValid());
  1899. return Location;
  1900. }
  1901. //===----------------------------------------------------------------------===//
  1902. // Methods for BugReporter and subclasses.
  1903. //===----------------------------------------------------------------------===//
  1904. BugReportEquivClass::~BugReportEquivClass() = default;
  1905. GRBugReporter::~GRBugReporter() = default;
  1906. BugReporterData::~BugReporterData() = default;
  1907. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  1908. ProgramStateManager&
  1909. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  1910. BugReporter::~BugReporter() {
  1911. FlushReports();
  1912. // Free the bug reports we are tracking.
  1913. for (const auto I : EQClassesVector)
  1914. delete I;
  1915. }
  1916. void BugReporter::FlushReports() {
  1917. if (BugTypes.isEmpty())
  1918. return;
  1919. // We need to flush reports in deterministic order to ensure the order
  1920. // of the reports is consistent between runs.
  1921. for (const auto EQ : EQClassesVector)
  1922. FlushReport(*EQ);
  1923. // BugReporter owns and deletes only BugTypes created implicitly through
  1924. // EmitBasicReport.
  1925. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1926. // create will be destroyed by the BugReporter.
  1927. llvm::DeleteContainerSeconds(StrBugTypes);
  1928. // Remove all references to the BugType objects.
  1929. BugTypes = F.getEmptySet();
  1930. }
  1931. //===----------------------------------------------------------------------===//
  1932. // PathDiagnostics generation.
  1933. //===----------------------------------------------------------------------===//
  1934. namespace {
  1935. /// A wrapper around a report graph, which contains only a single path, and its
  1936. /// node maps.
  1937. class ReportGraph {
  1938. public:
  1939. InterExplodedGraphMap BackMap;
  1940. std::unique_ptr<ExplodedGraph> Graph;
  1941. const ExplodedNode *ErrorNode;
  1942. size_t Index;
  1943. };
  1944. /// A wrapper around a trimmed graph and its node maps.
  1945. class TrimmedGraph {
  1946. InterExplodedGraphMap InverseMap;
  1947. using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
  1948. PriorityMapTy PriorityMap;
  1949. using NodeIndexPair = std::pair<const ExplodedNode *, size_t>;
  1950. SmallVector<NodeIndexPair, 32> ReportNodes;
  1951. std::unique_ptr<ExplodedGraph> G;
  1952. /// A helper class for sorting ExplodedNodes by priority.
  1953. template <bool Descending>
  1954. class PriorityCompare {
  1955. const PriorityMapTy &PriorityMap;
  1956. public:
  1957. PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
  1958. bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
  1959. PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
  1960. PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
  1961. PriorityMapTy::const_iterator E = PriorityMap.end();
  1962. if (LI == E)
  1963. return Descending;
  1964. if (RI == E)
  1965. return !Descending;
  1966. return Descending ? LI->second > RI->second
  1967. : LI->second < RI->second;
  1968. }
  1969. bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
  1970. return (*this)(LHS.first, RHS.first);
  1971. }
  1972. };
  1973. public:
  1974. TrimmedGraph(const ExplodedGraph *OriginalGraph,
  1975. ArrayRef<const ExplodedNode *> Nodes);
  1976. bool popNextReportGraph(ReportGraph &GraphWrapper);
  1977. };
  1978. } // namespace
  1979. TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
  1980. ArrayRef<const ExplodedNode *> Nodes) {
  1981. // The trimmed graph is created in the body of the constructor to ensure
  1982. // that the DenseMaps have been initialized already.
  1983. InterExplodedGraphMap ForwardMap;
  1984. G = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
  1985. // Find the (first) error node in the trimmed graph. We just need to consult
  1986. // the node map which maps from nodes in the original graph to nodes
  1987. // in the new graph.
  1988. llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
  1989. for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
  1990. if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
  1991. ReportNodes.push_back(std::make_pair(NewNode, i));
  1992. RemainingNodes.insert(NewNode);
  1993. }
  1994. }
  1995. assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
  1996. // Perform a forward BFS to find all the shortest paths.
  1997. std::queue<const ExplodedNode *> WS;
  1998. assert(G->num_roots() == 1);
  1999. WS.push(*G->roots_begin());
  2000. unsigned Priority = 0;
  2001. while (!WS.empty()) {
  2002. const ExplodedNode *Node = WS.front();
  2003. WS.pop();
  2004. PriorityMapTy::iterator PriorityEntry;
  2005. bool IsNew;
  2006. std::tie(PriorityEntry, IsNew) =
  2007. PriorityMap.insert(std::make_pair(Node, Priority));
  2008. ++Priority;
  2009. if (!IsNew) {
  2010. assert(PriorityEntry->second <= Priority);
  2011. continue;
  2012. }
  2013. if (RemainingNodes.erase(Node))
  2014. if (RemainingNodes.empty())
  2015. break;
  2016. for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
  2017. E = Node->succ_end();
  2018. I != E; ++I)
  2019. WS.push(*I);
  2020. }
  2021. // Sort the error paths from longest to shortest.
  2022. llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
  2023. }
  2024. bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
  2025. if (ReportNodes.empty())
  2026. return false;
  2027. const ExplodedNode *OrigN;
  2028. std::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
  2029. assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
  2030. "error node not accessible from root");
  2031. // Create a new graph with a single path. This is the graph
  2032. // that will be returned to the caller.
  2033. auto GNew = llvm::make_unique<ExplodedGraph>();
  2034. GraphWrapper.BackMap.clear();
  2035. // Now walk from the error node up the BFS path, always taking the
  2036. // predeccessor with the lowest number.
  2037. ExplodedNode *Succ = nullptr;
  2038. while (true) {
  2039. // Create the equivalent node in the new graph with the same state
  2040. // and location.
  2041. ExplodedNode *NewN = GNew->createUncachedNode(OrigN->getLocation(), OrigN->getState(),
  2042. OrigN->isSink());
  2043. // Store the mapping to the original node.
  2044. InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
  2045. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  2046. GraphWrapper.BackMap[NewN] = IMitr->second;
  2047. // Link up the new node with the previous node.
  2048. if (Succ)
  2049. Succ->addPredecessor(NewN, *GNew);
  2050. else
  2051. GraphWrapper.ErrorNode = NewN;
  2052. Succ = NewN;
  2053. // Are we at the final node?
  2054. if (OrigN->pred_empty()) {
  2055. GNew->addRoot(NewN);
  2056. break;
  2057. }
  2058. // Find the next predeccessor node. We choose the node that is marked
  2059. // with the lowest BFS number.
  2060. OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
  2061. PriorityCompare<false>(PriorityMap));
  2062. }
  2063. GraphWrapper.Graph = std::move(GNew);
  2064. return true;
  2065. }
  2066. /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
  2067. /// object and collapses PathDiagosticPieces that are expanded by macros.
  2068. static void CompactMacroExpandedPieces(PathPieces &path,
  2069. const SourceManager& SM) {
  2070. using MacroStackTy =
  2071. std::vector<
  2072. std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
  2073. using PiecesTy = std::vector<std::shared_ptr<PathDiagnosticPiece>>;
  2074. MacroStackTy MacroStack;
  2075. PiecesTy Pieces;
  2076. for (PathPieces::const_iterator I = path.begin(), E = path.end();
  2077. I != E; ++I) {
  2078. const auto &piece = *I;
  2079. // Recursively compact calls.
  2080. if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
  2081. CompactMacroExpandedPieces(call->path, SM);
  2082. }
  2083. // Get the location of the PathDiagnosticPiece.
  2084. const FullSourceLoc Loc = piece->getLocation().asLocation();
  2085. // Determine the instantiation location, which is the location we group
  2086. // related PathDiagnosticPieces.
  2087. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  2088. SM.getExpansionLoc(Loc) :
  2089. SourceLocation();
  2090. if (Loc.isFileID()) {
  2091. MacroStack.clear();
  2092. Pieces.push_back(piece);
  2093. continue;
  2094. }
  2095. assert(Loc.isMacroID());
  2096. // Is the PathDiagnosticPiece within the same macro group?
  2097. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  2098. MacroStack.back().first->subPieces.push_back(piece);
  2099. continue;
  2100. }
  2101. // We aren't in the same group. Are we descending into a new macro
  2102. // or are part of an old one?
  2103. std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
  2104. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  2105. SM.getExpansionLoc(Loc) :
  2106. SourceLocation();
  2107. // Walk the entire macro stack.
  2108. while (!MacroStack.empty()) {
  2109. if (InstantiationLoc == MacroStack.back().second) {
  2110. MacroGroup = MacroStack.back().first;
  2111. break;
  2112. }
  2113. if (ParentInstantiationLoc == MacroStack.back().second) {
  2114. MacroGroup = MacroStack.back().first;
  2115. break;
  2116. }
  2117. MacroStack.pop_back();
  2118. }
  2119. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  2120. // Create a new macro group and add it to the stack.
  2121. auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
  2122. PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
  2123. if (MacroGroup)
  2124. MacroGroup->subPieces.push_back(NewGroup);
  2125. else {
  2126. assert(InstantiationLoc.isFileID());
  2127. Pieces.push_back(NewGroup);
  2128. }
  2129. MacroGroup = NewGroup;
  2130. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  2131. }
  2132. // Finally, add the PathDiagnosticPiece to the group.
  2133. MacroGroup->subPieces.push_back(piece);
  2134. }
  2135. // Now take the pieces and construct a new PathDiagnostic.
  2136. path.clear();
  2137. path.insert(path.end(), Pieces.begin(), Pieces.end());
  2138. }
  2139. /// Generate notes from all visitors.
  2140. /// Notes associated with {@code ErrorNode} are generated using
  2141. /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
  2142. static std::unique_ptr<VisitorsDiagnosticsTy>
  2143. generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
  2144. BugReporterContext &BRC) {
  2145. auto Notes = llvm::make_unique<VisitorsDiagnosticsTy>();
  2146. BugReport::VisitorList visitors;
  2147. // Run visitors on all nodes starting from the node *before* the last one.
  2148. // The last node is reserved for notes generated with {@code getEndPath}.
  2149. const ExplodedNode *NextNode = ErrorNode->getFirstPred();
  2150. while (NextNode) {
  2151. // At each iteration, move all visitors from report to visitor list.
  2152. for (BugReport::visitor_iterator I = R->visitor_begin(),
  2153. E = R->visitor_end();
  2154. I != E; ++I) {
  2155. visitors.push_back(std::move(*I));
  2156. }
  2157. R->clearVisitors();
  2158. const ExplodedNode *Pred = NextNode->getFirstPred();
  2159. if (!Pred) {
  2160. std::shared_ptr<PathDiagnosticPiece> LastPiece;
  2161. for (auto &V : visitors) {
  2162. V->finalizeVisitor(BRC, ErrorNode, *R);
  2163. if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
  2164. assert(!LastPiece &&
  2165. "There can only be one final piece in a diagnostic.");
  2166. LastPiece = std::move(Piece);
  2167. (*Notes)[ErrorNode].push_back(LastPiece);
  2168. }
  2169. }
  2170. break;
  2171. }
  2172. for (auto &V : visitors) {
  2173. auto P = V->VisitNode(NextNode, BRC, *R);
  2174. if (P)
  2175. (*Notes)[NextNode].push_back(std::move(P));
  2176. }
  2177. if (!R->isValid())
  2178. break;
  2179. NextNode = Pred;
  2180. }
  2181. return Notes;
  2182. }
  2183. /// Find a non-invalidated report for a given equivalence class,
  2184. /// and return together with a cache of visitors notes.
  2185. /// If none found, return a nullptr paired with an empty cache.
  2186. static
  2187. std::pair<BugReport*, std::unique_ptr<VisitorsDiagnosticsTy>> findValidReport(
  2188. TrimmedGraph &TrimG,
  2189. ReportGraph &ErrorGraph,
  2190. ArrayRef<BugReport *> &bugReports,
  2191. AnalyzerOptions &Opts,
  2192. GRBugReporter &Reporter) {
  2193. while (TrimG.popNextReportGraph(ErrorGraph)) {
  2194. // Find the BugReport with the original location.
  2195. assert(ErrorGraph.Index < bugReports.size());
  2196. BugReport *R = bugReports[ErrorGraph.Index];
  2197. assert(R && "No original report found for sliced graph.");
  2198. assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
  2199. const ExplodedNode *ErrorNode = ErrorGraph.ErrorNode;
  2200. // Register refutation visitors first, if they mark the bug invalid no
  2201. // further analysis is required
  2202. R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
  2203. // Register additional node visitors.
  2204. R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
  2205. R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
  2206. R->addVisitor(llvm::make_unique<TagVisitor>());
  2207. BugReporterContext BRC(Reporter, ErrorGraph.BackMap);
  2208. // Run all visitors on a given graph, once.
  2209. std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
  2210. generateVisitorsDiagnostics(R, ErrorNode, BRC);
  2211. if (R->isValid()) {
  2212. if (Opts.ShouldCrosscheckWithZ3) {
  2213. // If crosscheck is enabled, remove all visitors, add the refutation
  2214. // visitor and check again
  2215. R->clearVisitors();
  2216. R->addVisitor(llvm::make_unique<FalsePositiveRefutationBRVisitor>());
  2217. // We don't overrite the notes inserted by other visitors because the
  2218. // refutation manager does not add any new note to the path
  2219. generateVisitorsDiagnostics(R, ErrorGraph.ErrorNode, BRC);
  2220. }
  2221. // Check if the bug is still valid
  2222. if (R->isValid())
  2223. return std::make_pair(R, std::move(visitorNotes));
  2224. }
  2225. }
  2226. return std::make_pair(nullptr, llvm::make_unique<VisitorsDiagnosticsTy>());
  2227. }
  2228. std::unique_ptr<DiagnosticForConsumerMapTy>
  2229. GRBugReporter::generatePathDiagnostics(
  2230. ArrayRef<PathDiagnosticConsumer *> consumers,
  2231. ArrayRef<BugReport *> &bugReports) {
  2232. assert(!bugReports.empty());
  2233. auto Out = llvm::make_unique<DiagnosticForConsumerMapTy>();
  2234. bool HasValid = false;
  2235. SmallVector<const ExplodedNode *, 32> errorNodes;
  2236. for (const auto I : bugReports) {
  2237. if (I->isValid()) {
  2238. HasValid = true;
  2239. errorNodes.push_back(I->getErrorNode());
  2240. } else {
  2241. // Keep the errorNodes list in sync with the bugReports list.
  2242. errorNodes.push_back(nullptr);
  2243. }
  2244. }
  2245. // If all the reports have been marked invalid by a previous path generation,
  2246. // we're done.
  2247. if (!HasValid)
  2248. return Out;
  2249. TrimmedGraph TrimG(&getGraph(), errorNodes);
  2250. ReportGraph ErrorGraph;
  2251. auto ReportInfo = findValidReport(TrimG, ErrorGraph, bugReports,
  2252. getAnalyzerOptions(), *this);
  2253. BugReport *R = ReportInfo.first;
  2254. if (R && R->isValid()) {
  2255. const ExplodedNode *ErrorNode = ErrorGraph.ErrorNode;
  2256. for (PathDiagnosticConsumer *PC : consumers) {
  2257. PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, PC);
  2258. std::unique_ptr<PathDiagnostic> PD = generatePathDiagnosticForConsumer(
  2259. PC->getGenerationScheme(), PDB, ErrorNode, *ReportInfo.second);
  2260. (*Out)[PC] = std::move(PD);
  2261. }
  2262. }
  2263. return Out;
  2264. }
  2265. void BugReporter::Register(const BugType *BT) {
  2266. BugTypes = F.add(BugTypes, BT);
  2267. }
  2268. void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
  2269. if (const ExplodedNode *E = R->getErrorNode()) {
  2270. // An error node must either be a sink or have a tag, otherwise
  2271. // it could get reclaimed before the path diagnostic is created.
  2272. assert((E->isSink() || E->getLocation().getTag()) &&
  2273. "Error node must either be a sink or have a tag");
  2274. const AnalysisDeclContext *DeclCtx =
  2275. E->getLocationContext()->getAnalysisDeclContext();
  2276. // The source of autosynthesized body can be handcrafted AST or a model
  2277. // file. The locations from handcrafted ASTs have no valid source locations
  2278. // and have to be discarded. Locations from model files should be preserved
  2279. // for processing and reporting.
  2280. if (DeclCtx->isBodyAutosynthesized() &&
  2281. !DeclCtx->isBodyAutosynthesizedFromModelFile())
  2282. return;
  2283. }
  2284. bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
  2285. assert(ValidSourceLoc);
  2286. // If we mess up in a release build, we'd still prefer to just drop the bug
  2287. // instead of trying to go on.
  2288. if (!ValidSourceLoc)
  2289. return;
  2290. // Compute the bug report's hash to determine its equivalence class.
  2291. llvm::FoldingSetNodeID ID;
  2292. R->Profile(ID);
  2293. // Lookup the equivance class. If there isn't one, create it.
  2294. const BugType& BT = R->getBugType();
  2295. Register(&BT);
  2296. void *InsertPos;
  2297. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  2298. if (!EQ) {
  2299. EQ = new BugReportEquivClass(std::move(R));
  2300. EQClasses.InsertNode(EQ, InsertPos);
  2301. EQClassesVector.push_back(EQ);
  2302. } else
  2303. EQ->AddReport(std::move(R));
  2304. }
  2305. //===----------------------------------------------------------------------===//
  2306. // Emitting reports in equivalence classes.
  2307. //===----------------------------------------------------------------------===//
  2308. namespace {
  2309. struct FRIEC_WLItem {
  2310. const ExplodedNode *N;
  2311. ExplodedNode::const_succ_iterator I, E;
  2312. FRIEC_WLItem(const ExplodedNode *n)
  2313. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  2314. };
  2315. } // namespace
  2316. static const CFGBlock *findBlockForNode(const ExplodedNode *N) {
  2317. ProgramPoint P = N->getLocation();
  2318. if (auto BEP = P.getAs<BlockEntrance>())
  2319. return BEP->getBlock();
  2320. // Find the node's current statement in the CFG.
  2321. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  2322. return N->getLocationContext()->getAnalysisDeclContext()
  2323. ->getCFGStmtMap()->getBlock(S);
  2324. return nullptr;
  2325. }
  2326. // Returns true if by simply looking at the block, we can be sure that it
  2327. // results in a sink during analysis. This is useful to know when the analysis
  2328. // was interrupted, and we try to figure out if it would sink eventually.
  2329. // There may be many more reasons why a sink would appear during analysis
  2330. // (eg. checkers may generate sinks arbitrarily), but here we only consider
  2331. // sinks that would be obvious by looking at the CFG.
  2332. static bool isImmediateSinkBlock(const CFGBlock *Blk) {
  2333. if (Blk->hasNoReturnElement())
  2334. return true;
  2335. // FIXME: Throw-expressions are currently generating sinks during analysis:
  2336. // they're not supported yet, and also often used for actually terminating
  2337. // the program. So we should treat them as sinks in this analysis as well,
  2338. // at least for now, but once we have better support for exceptions,
  2339. // we'd need to carefully handle the case when the throw is being
  2340. // immediately caught.
  2341. if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
  2342. if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
  2343. if (isa<CXXThrowExpr>(StmtElm->getStmt()))
  2344. return true;
  2345. return false;
  2346. }))
  2347. return true;
  2348. return false;
  2349. }
  2350. // Returns true if by looking at the CFG surrounding the node's program
  2351. // point, we can be sure that any analysis starting from this point would
  2352. // eventually end with a sink. We scan the child CFG blocks in a depth-first
  2353. // manner and see if all paths eventually end up in an immediate sink block.
  2354. static bool isInevitablySinking(const ExplodedNode *N) {
  2355. const CFG &Cfg = N->getCFG();
  2356. const CFGBlock *StartBlk = findBlockForNode(N);
  2357. if (!StartBlk)
  2358. return false;
  2359. if (isImmediateSinkBlock(StartBlk))
  2360. return true;
  2361. llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
  2362. llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
  2363. DFSWorkList.push_back(StartBlk);
  2364. while (!DFSWorkList.empty()) {
  2365. const CFGBlock *Blk = DFSWorkList.back();
  2366. DFSWorkList.pop_back();
  2367. Visited.insert(Blk);
  2368. // If at least one path reaches the CFG exit, it means that control is
  2369. // returned to the caller. For now, say that we are not sure what
  2370. // happens next. If necessary, this can be improved to analyze
  2371. // the parent StackFrameContext's call site in a similar manner.
  2372. if (Blk == &Cfg.getExit())
  2373. return false;
  2374. for (const auto &Succ : Blk->succs()) {
  2375. if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
  2376. if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
  2377. // If the block has reachable child blocks that aren't no-return,
  2378. // add them to the worklist.
  2379. DFSWorkList.push_back(SuccBlk);
  2380. }
  2381. }
  2382. }
  2383. }
  2384. // Nothing reached the exit. It can only mean one thing: there's no return.
  2385. return true;
  2386. }
  2387. static BugReport *
  2388. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  2389. SmallVectorImpl<BugReport*> &bugReports) {
  2390. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  2391. assert(I != E);
  2392. const BugType& BT = I->getBugType();
  2393. // If we don't need to suppress any of the nodes because they are
  2394. // post-dominated by a sink, simply add all the nodes in the equivalence class
  2395. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  2396. if (!BT.isSuppressOnSink()) {
  2397. BugReport *R = &*I;
  2398. for (auto &I : EQ) {
  2399. const ExplodedNode *N = I.getErrorNode();
  2400. if (N) {
  2401. R = &I;
  2402. bugReports.push_back(R);
  2403. }
  2404. }
  2405. return R;
  2406. }
  2407. // For bug reports that should be suppressed when all paths are post-dominated
  2408. // by a sink node, iterate through the reports in the equivalence class
  2409. // until we find one that isn't post-dominated (if one exists). We use a
  2410. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  2411. // this as a recursive function, but we don't want to risk blowing out the
  2412. // stack for very long paths.
  2413. BugReport *exampleReport = nullptr;
  2414. for (; I != E; ++I) {
  2415. const ExplodedNode *errorNode = I->getErrorNode();
  2416. if (!errorNode)
  2417. continue;
  2418. if (errorNode->isSink()) {
  2419. llvm_unreachable(
  2420. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  2421. }
  2422. // No successors? By definition this nodes isn't post-dominated by a sink.
  2423. if (errorNode->succ_empty()) {
  2424. bugReports.push_back(&*I);
  2425. if (!exampleReport)
  2426. exampleReport = &*I;
  2427. continue;
  2428. }
  2429. // See if we are in a no-return CFG block. If so, treat this similarly
  2430. // to being post-dominated by a sink. This works better when the analysis
  2431. // is incomplete and we have never reached the no-return function call(s)
  2432. // that we'd inevitably bump into on this path.
  2433. if (isInevitablySinking(errorNode))
  2434. continue;
  2435. // At this point we know that 'N' is not a sink and it has at least one
  2436. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  2437. using WLItem = FRIEC_WLItem;
  2438. using DFSWorkList = SmallVector<WLItem, 10>;
  2439. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  2440. DFSWorkList WL;
  2441. WL.push_back(errorNode);
  2442. Visited[errorNode] = 1;
  2443. while (!WL.empty()) {
  2444. WLItem &WI = WL.back();
  2445. assert(!WI.N->succ_empty());
  2446. for (; WI.I != WI.E; ++WI.I) {
  2447. const ExplodedNode *Succ = *WI.I;
  2448. // End-of-path node?
  2449. if (Succ->succ_empty()) {
  2450. // If we found an end-of-path node that is not a sink.
  2451. if (!Succ->isSink()) {
  2452. bugReports.push_back(&*I);
  2453. if (!exampleReport)
  2454. exampleReport = &*I;
  2455. WL.clear();
  2456. break;
  2457. }
  2458. // Found a sink? Continue on to the next successor.
  2459. continue;
  2460. }
  2461. // Mark the successor as visited. If it hasn't been explored,
  2462. // enqueue it to the DFS worklist.
  2463. unsigned &mark = Visited[Succ];
  2464. if (!mark) {
  2465. mark = 1;
  2466. WL.push_back(Succ);
  2467. break;
  2468. }
  2469. }
  2470. // The worklist may have been cleared at this point. First
  2471. // check if it is empty before checking the last item.
  2472. if (!WL.empty() && &WL.back() == &WI)
  2473. WL.pop_back();
  2474. }
  2475. }
  2476. // ExampleReport will be NULL if all the nodes in the equivalence class
  2477. // were post-dominated by sinks.
  2478. return exampleReport;
  2479. }
  2480. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  2481. SmallVector<BugReport*, 10> bugReports;
  2482. BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
  2483. if (!report)
  2484. return;
  2485. ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
  2486. std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
  2487. generateDiagnosticForConsumerMap(report, Consumers, bugReports);
  2488. for (auto &P : *Diagnostics) {
  2489. PathDiagnosticConsumer *Consumer = P.first;
  2490. std::unique_ptr<PathDiagnostic> &PD = P.second;
  2491. // If the path is empty, generate a single step path with the location
  2492. // of the issue.
  2493. if (PD->path.empty()) {
  2494. PathDiagnosticLocation L = report->getLocation(getSourceManager());
  2495. auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
  2496. L, report->getDescription());
  2497. for (SourceRange Range : report->getRanges())
  2498. piece->addRange(Range);
  2499. PD->setEndOfPath(std::move(piece));
  2500. }
  2501. PathPieces &Pieces = PD->getMutablePieces();
  2502. if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
  2503. // For path diagnostic consumers that don't support extra notes,
  2504. // we may optionally convert those to path notes.
  2505. for (auto I = report->getNotes().rbegin(),
  2506. E = report->getNotes().rend(); I != E; ++I) {
  2507. PathDiagnosticNotePiece *Piece = I->get();
  2508. auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
  2509. Piece->getLocation(), Piece->getString());
  2510. for (const auto &R: Piece->getRanges())
  2511. ConvertedPiece->addRange(R);
  2512. Pieces.push_front(std::move(ConvertedPiece));
  2513. }
  2514. } else {
  2515. for (auto I = report->getNotes().rbegin(),
  2516. E = report->getNotes().rend(); I != E; ++I)
  2517. Pieces.push_front(*I);
  2518. }
  2519. // Get the meta data.
  2520. const BugReport::ExtraTextList &Meta = report->getExtraText();
  2521. for (const auto &i : Meta)
  2522. PD->addMeta(i);
  2523. updateExecutedLinesWithDiagnosticPieces(*PD);
  2524. Consumer->HandlePathDiagnostic(std::move(PD));
  2525. }
  2526. }
  2527. /// Insert all lines participating in the function signature \p Signature
  2528. /// into \p ExecutedLines.
  2529. static void populateExecutedLinesWithFunctionSignature(
  2530. const Decl *Signature, SourceManager &SM,
  2531. FilesToLineNumsMap &ExecutedLines) {
  2532. SourceRange SignatureSourceRange;
  2533. const Stmt* Body = Signature->getBody();
  2534. if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
  2535. SignatureSourceRange = FD->getSourceRange();
  2536. } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
  2537. SignatureSourceRange = OD->getSourceRange();
  2538. } else {
  2539. return;
  2540. }
  2541. SourceLocation Start = SignatureSourceRange.getBegin();
  2542. SourceLocation End = Body ? Body->getSourceRange().getBegin()
  2543. : SignatureSourceRange.getEnd();
  2544. if (!Start.isValid() || !End.isValid())
  2545. return;
  2546. unsigned StartLine = SM.getExpansionLineNumber(Start);
  2547. unsigned EndLine = SM.getExpansionLineNumber(End);
  2548. FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
  2549. for (unsigned Line = StartLine; Line <= EndLine; Line++)
  2550. ExecutedLines[FID].insert(Line);
  2551. }
  2552. static void populateExecutedLinesWithStmt(
  2553. const Stmt *S, SourceManager &SM,
  2554. FilesToLineNumsMap &ExecutedLines) {
  2555. SourceLocation Loc = S->getSourceRange().getBegin();
  2556. if (!Loc.isValid())
  2557. return;
  2558. SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
  2559. FileID FID = SM.getFileID(ExpansionLoc);
  2560. unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
  2561. ExecutedLines[FID].insert(LineNo);
  2562. }
  2563. /// \return all executed lines including function signatures on the path
  2564. /// starting from \p N.
  2565. static std::unique_ptr<FilesToLineNumsMap>
  2566. findExecutedLines(SourceManager &SM, const ExplodedNode *N) {
  2567. auto ExecutedLines = llvm::make_unique<FilesToLineNumsMap>();
  2568. while (N) {
  2569. if (N->getFirstPred() == nullptr) {
  2570. // First node: show signature of the entrance point.
  2571. const Decl *D = N->getLocationContext()->getDecl();
  2572. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2573. } else if (auto CE = N->getLocationAs<CallEnter>()) {
  2574. // Inlined function: show signature.
  2575. const Decl* D = CE->getCalleeContext()->getDecl();
  2576. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2577. } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
  2578. populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
  2579. // Show extra context for some parent kinds.
  2580. const Stmt *P = N->getParentMap().getParent(S);
  2581. // The path exploration can die before the node with the associated
  2582. // return statement is generated, but we do want to show the whole
  2583. // return.
  2584. if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
  2585. populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
  2586. P = N->getParentMap().getParent(RS);
  2587. }
  2588. if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
  2589. populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
  2590. }
  2591. N = N->getFirstPred();
  2592. }
  2593. return ExecutedLines;
  2594. }
  2595. std::unique_ptr<DiagnosticForConsumerMapTy>
  2596. BugReporter::generateDiagnosticForConsumerMap(
  2597. BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
  2598. ArrayRef<BugReport *> bugReports) {
  2599. if (!report->isPathSensitive()) {
  2600. auto Out = llvm::make_unique<DiagnosticForConsumerMapTy>();
  2601. for (auto *Consumer : consumers)
  2602. (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
  2603. getSourceManager());
  2604. return Out;
  2605. }
  2606. // Generate the full path sensitive diagnostic, using the generation scheme
  2607. // specified by the PathDiagnosticConsumer. Note that we have to generate
  2608. // path diagnostics even for consumers which do not support paths, because
  2609. // the BugReporterVisitors may mark this bug as a false positive.
  2610. assert(!bugReports.empty());
  2611. MaxBugClassSize.updateMax(bugReports.size());
  2612. std::unique_ptr<DiagnosticForConsumerMapTy> Out =
  2613. generatePathDiagnostics(consumers, bugReports);
  2614. if (Out->empty())
  2615. return Out;
  2616. MaxValidBugClassSize.updateMax(bugReports.size());
  2617. // Examine the report and see if the last piece is in a header. Reset the
  2618. // report location to the last piece in the main source file.
  2619. AnalyzerOptions &Opts = getAnalyzerOptions();
  2620. for (auto const &P : *Out)
  2621. if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
  2622. P.second->resetDiagnosticLocationToMainFile();
  2623. return Out;
  2624. }
  2625. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2626. const CheckerBase *Checker,
  2627. StringRef Name, StringRef Category,
  2628. StringRef Str, PathDiagnosticLocation Loc,
  2629. ArrayRef<SourceRange> Ranges) {
  2630. EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
  2631. Loc, Ranges);
  2632. }
  2633. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2634. CheckName CheckName,
  2635. StringRef name, StringRef category,
  2636. StringRef str, PathDiagnosticLocation Loc,
  2637. ArrayRef<SourceRange> Ranges) {
  2638. // 'BT' is owned by BugReporter.
  2639. BugType *BT = getBugTypeForName(CheckName, name, category);
  2640. auto R = llvm::make_unique<BugReport>(*BT, str, Loc);
  2641. R->setDeclWithIssue(DeclWithIssue);
  2642. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
  2643. I != E; ++I)
  2644. R->addRange(*I);
  2645. emitReport(std::move(R));
  2646. }
  2647. BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
  2648. StringRef category) {
  2649. SmallString<136> fullDesc;
  2650. llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
  2651. << ":" << category;
  2652. BugType *&BT = StrBugTypes[fullDesc];
  2653. if (!BT)
  2654. BT = new BugType(CheckName, name, category);
  2655. return BT;
  2656. }