BugReporter.cpp 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133
  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(/*UseFallback=*/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. const Decl *BugReport::getDeclWithIssue() const {
  1760. if (DeclWithIssue)
  1761. return DeclWithIssue;
  1762. const ExplodedNode *N = getErrorNode();
  1763. if (!N)
  1764. return nullptr;
  1765. const LocationContext *LC = N->getLocationContext();
  1766. return LC->getStackFrame()->getDecl();
  1767. }
  1768. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  1769. hash.AddPointer(&BT);
  1770. hash.AddString(Description);
  1771. PathDiagnosticLocation UL = getUniqueingLocation();
  1772. if (UL.isValid()) {
  1773. UL.Profile(hash);
  1774. } else if (Location.isValid()) {
  1775. Location.Profile(hash);
  1776. } else {
  1777. assert(ErrorNode);
  1778. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  1779. }
  1780. for (SourceRange range : Ranges) {
  1781. if (!range.isValid())
  1782. continue;
  1783. hash.AddInteger(range.getBegin().getRawEncoding());
  1784. hash.AddInteger(range.getEnd().getRawEncoding());
  1785. }
  1786. }
  1787. void BugReport::markInteresting(SymbolRef sym) {
  1788. if (!sym)
  1789. return;
  1790. InterestingSymbols.insert(sym);
  1791. if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
  1792. InterestingRegions.insert(meta->getRegion());
  1793. }
  1794. void BugReport::markInteresting(const MemRegion *R) {
  1795. if (!R)
  1796. return;
  1797. R = R->getBaseRegion();
  1798. InterestingRegions.insert(R);
  1799. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1800. InterestingSymbols.insert(SR->getSymbol());
  1801. }
  1802. void BugReport::markInteresting(SVal V) {
  1803. markInteresting(V.getAsRegion());
  1804. markInteresting(V.getAsSymbol());
  1805. }
  1806. void BugReport::markInteresting(const LocationContext *LC) {
  1807. if (!LC)
  1808. return;
  1809. InterestingLocationContexts.insert(LC);
  1810. }
  1811. bool BugReport::isInteresting(SVal V) {
  1812. return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
  1813. }
  1814. bool BugReport::isInteresting(SymbolRef sym) {
  1815. if (!sym)
  1816. return false;
  1817. // We don't currently consider metadata symbols to be interesting
  1818. // even if we know their region is interesting. Is that correct behavior?
  1819. return InterestingSymbols.count(sym);
  1820. }
  1821. bool BugReport::isInteresting(const MemRegion *R) {
  1822. if (!R)
  1823. return false;
  1824. R = R->getBaseRegion();
  1825. bool b = InterestingRegions.count(R);
  1826. if (b)
  1827. return true;
  1828. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1829. return InterestingSymbols.count(SR->getSymbol());
  1830. return false;
  1831. }
  1832. bool BugReport::isInteresting(const LocationContext *LC) {
  1833. if (!LC)
  1834. return false;
  1835. return InterestingLocationContexts.count(LC);
  1836. }
  1837. const Stmt *BugReport::getStmt() const {
  1838. if (!ErrorNode)
  1839. return nullptr;
  1840. ProgramPoint ProgP = ErrorNode->getLocation();
  1841. const Stmt *S = nullptr;
  1842. if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
  1843. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1844. if (BE->getBlock() == &Exit)
  1845. S = GetPreviousStmt(ErrorNode);
  1846. }
  1847. if (!S)
  1848. S = PathDiagnosticLocation::getStmt(ErrorNode);
  1849. return S;
  1850. }
  1851. llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
  1852. // If no custom ranges, add the range of the statement corresponding to
  1853. // the error node.
  1854. if (Ranges.empty()) {
  1855. if (const auto *E = dyn_cast_or_null<Expr>(getStmt()))
  1856. addRange(E->getSourceRange());
  1857. else
  1858. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1859. }
  1860. // User-specified absence of range info.
  1861. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  1862. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1863. return llvm::make_range(Ranges.begin(), Ranges.end());
  1864. }
  1865. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  1866. if (ErrorNode) {
  1867. assert(!Location.isValid() &&
  1868. "Either Location or ErrorNode should be specified but not both.");
  1869. return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
  1870. }
  1871. assert(Location.isValid());
  1872. return Location;
  1873. }
  1874. //===----------------------------------------------------------------------===//
  1875. // Methods for BugReporter and subclasses.
  1876. //===----------------------------------------------------------------------===//
  1877. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  1878. ProgramStateManager&
  1879. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  1880. BugReporter::~BugReporter() {
  1881. FlushReports();
  1882. // Free the bug reports we are tracking.
  1883. for (const auto I : EQClassesVector)
  1884. delete I;
  1885. }
  1886. void BugReporter::FlushReports() {
  1887. if (BugTypes.isEmpty())
  1888. return;
  1889. // We need to flush reports in deterministic order to ensure the order
  1890. // of the reports is consistent between runs.
  1891. for (const auto EQ : EQClassesVector)
  1892. FlushReport(*EQ);
  1893. // BugReporter owns and deletes only BugTypes created implicitly through
  1894. // EmitBasicReport.
  1895. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1896. // create will be destroyed by the BugReporter.
  1897. llvm::DeleteContainerSeconds(StrBugTypes);
  1898. // Remove all references to the BugType objects.
  1899. BugTypes = F.getEmptySet();
  1900. }
  1901. //===----------------------------------------------------------------------===//
  1902. // PathDiagnostics generation.
  1903. //===----------------------------------------------------------------------===//
  1904. namespace {
  1905. /// A wrapper around an ExplodedGraph that contains a single path from the root
  1906. /// to the error node, and a map that maps the nodes in this path to the ones in
  1907. /// the original ExplodedGraph.
  1908. class BugPathInfo {
  1909. public:
  1910. InterExplodedGraphMap MapToOriginNodes;
  1911. std::unique_ptr<ExplodedGraph> Path;
  1912. BugReport *Report;
  1913. const ExplodedNode *ErrorNode;
  1914. };
  1915. /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
  1916. /// conveniently retrieve bug paths from a single error node to the root.
  1917. class BugPathGetter {
  1918. std::unique_ptr<ExplodedGraph> TrimmedGraph;
  1919. /// Map from the trimmed graph to the original.
  1920. InterExplodedGraphMap InverseMap;
  1921. using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
  1922. /// Assign each node with its distance from the root.
  1923. PriorityMapTy PriorityMap;
  1924. /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
  1925. /// we need to pair it to the error node of the constructed trimmed graph.
  1926. using ReportNewNodePair = std::pair<BugReport *, const ExplodedNode *>;
  1927. SmallVector<ReportNewNodePair, 32> ReportNodes;
  1928. BugPathInfo CurrentBugPath;
  1929. /// A helper class for sorting ExplodedNodes by priority.
  1930. template <bool Descending>
  1931. class PriorityCompare {
  1932. const PriorityMapTy &PriorityMap;
  1933. public:
  1934. PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
  1935. bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
  1936. PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
  1937. PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
  1938. PriorityMapTy::const_iterator E = PriorityMap.end();
  1939. if (LI == E)
  1940. return Descending;
  1941. if (RI == E)
  1942. return !Descending;
  1943. return Descending ? LI->second > RI->second
  1944. : LI->second < RI->second;
  1945. }
  1946. bool operator()(const ReportNewNodePair &LHS,
  1947. const ReportNewNodePair &RHS) const {
  1948. return (*this)(LHS.second, RHS.second);
  1949. }
  1950. };
  1951. public:
  1952. BugPathGetter(const ExplodedGraph *OriginalGraph,
  1953. ArrayRef<BugReport *> &bugReports);
  1954. BugPathInfo *getNextBugPath();
  1955. };
  1956. } // namespace
  1957. BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
  1958. ArrayRef<BugReport *> &bugReports) {
  1959. SmallVector<const ExplodedNode *, 32> Nodes;
  1960. for (const auto I : bugReports) {
  1961. assert(I->isValid() &&
  1962. "We only allow BugReporterVisitors and BugReporter itself to "
  1963. "invalidate reports!");
  1964. Nodes.emplace_back(I->getErrorNode());
  1965. }
  1966. // The trimmed graph is created in the body of the constructor to ensure
  1967. // that the DenseMaps have been initialized already.
  1968. InterExplodedGraphMap ForwardMap;
  1969. TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
  1970. // Find the (first) error node in the trimmed graph. We just need to consult
  1971. // the node map which maps from nodes in the original graph to nodes
  1972. // in the new graph.
  1973. llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
  1974. for (BugReport *Report : bugReports) {
  1975. const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
  1976. assert(NewNode &&
  1977. "Failed to construct a trimmed graph that contains this error "
  1978. "node!");
  1979. ReportNodes.emplace_back(Report, NewNode);
  1980. RemainingNodes.insert(NewNode);
  1981. }
  1982. assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
  1983. // Perform a forward BFS to find all the shortest paths.
  1984. std::queue<const ExplodedNode *> WS;
  1985. assert(TrimmedGraph->num_roots() == 1);
  1986. WS.push(*TrimmedGraph->roots_begin());
  1987. unsigned Priority = 0;
  1988. while (!WS.empty()) {
  1989. const ExplodedNode *Node = WS.front();
  1990. WS.pop();
  1991. PriorityMapTy::iterator PriorityEntry;
  1992. bool IsNew;
  1993. std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
  1994. ++Priority;
  1995. if (!IsNew) {
  1996. assert(PriorityEntry->second <= Priority);
  1997. continue;
  1998. }
  1999. if (RemainingNodes.erase(Node))
  2000. if (RemainingNodes.empty())
  2001. break;
  2002. for (const ExplodedNode *Succ : Node->succs())
  2003. WS.push(Succ);
  2004. }
  2005. // Sort the error paths from longest to shortest.
  2006. llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
  2007. }
  2008. BugPathInfo *BugPathGetter::getNextBugPath() {
  2009. if (ReportNodes.empty())
  2010. return nullptr;
  2011. const ExplodedNode *OrigN;
  2012. std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
  2013. assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
  2014. "error node not accessible from root");
  2015. // Create a new graph with a single path. This is the graph that will be
  2016. // returned to the caller.
  2017. auto GNew = llvm::make_unique<ExplodedGraph>();
  2018. CurrentBugPath.MapToOriginNodes.clear();
  2019. // Now walk from the error node up the BFS path, always taking the
  2020. // predeccessor with the lowest number.
  2021. ExplodedNode *Succ = nullptr;
  2022. while (true) {
  2023. // Create the equivalent node in the new graph with the same state
  2024. // and location.
  2025. ExplodedNode *NewN = GNew->createUncachedNode(
  2026. OrigN->getLocation(), OrigN->getState(), OrigN->isSink());
  2027. // Store the mapping to the original node.
  2028. InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
  2029. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  2030. CurrentBugPath.MapToOriginNodes[NewN] = IMitr->second;
  2031. // Link up the new node with the previous node.
  2032. if (Succ)
  2033. Succ->addPredecessor(NewN, *GNew);
  2034. else
  2035. CurrentBugPath.ErrorNode = NewN;
  2036. Succ = NewN;
  2037. // Are we at the final node?
  2038. if (OrigN->pred_empty()) {
  2039. GNew->addRoot(NewN);
  2040. break;
  2041. }
  2042. // Find the next predeccessor node. We choose the node that is marked
  2043. // with the lowest BFS number.
  2044. OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
  2045. PriorityCompare<false>(PriorityMap));
  2046. }
  2047. CurrentBugPath.Path = std::move(GNew);
  2048. return &CurrentBugPath;
  2049. }
  2050. /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
  2051. /// object and collapses PathDiagosticPieces that are expanded by macros.
  2052. static void CompactMacroExpandedPieces(PathPieces &path,
  2053. const SourceManager& SM) {
  2054. using MacroStackTy =
  2055. std::vector<
  2056. std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
  2057. using PiecesTy = std::vector<std::shared_ptr<PathDiagnosticPiece>>;
  2058. MacroStackTy MacroStack;
  2059. PiecesTy Pieces;
  2060. for (PathPieces::const_iterator I = path.begin(), E = path.end();
  2061. I != E; ++I) {
  2062. const auto &piece = *I;
  2063. // Recursively compact calls.
  2064. if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
  2065. CompactMacroExpandedPieces(call->path, SM);
  2066. }
  2067. // Get the location of the PathDiagnosticPiece.
  2068. const FullSourceLoc Loc = piece->getLocation().asLocation();
  2069. // Determine the instantiation location, which is the location we group
  2070. // related PathDiagnosticPieces.
  2071. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  2072. SM.getExpansionLoc(Loc) :
  2073. SourceLocation();
  2074. if (Loc.isFileID()) {
  2075. MacroStack.clear();
  2076. Pieces.push_back(piece);
  2077. continue;
  2078. }
  2079. assert(Loc.isMacroID());
  2080. // Is the PathDiagnosticPiece within the same macro group?
  2081. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  2082. MacroStack.back().first->subPieces.push_back(piece);
  2083. continue;
  2084. }
  2085. // We aren't in the same group. Are we descending into a new macro
  2086. // or are part of an old one?
  2087. std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
  2088. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  2089. SM.getExpansionLoc(Loc) :
  2090. SourceLocation();
  2091. // Walk the entire macro stack.
  2092. while (!MacroStack.empty()) {
  2093. if (InstantiationLoc == MacroStack.back().second) {
  2094. MacroGroup = MacroStack.back().first;
  2095. break;
  2096. }
  2097. if (ParentInstantiationLoc == MacroStack.back().second) {
  2098. MacroGroup = MacroStack.back().first;
  2099. break;
  2100. }
  2101. MacroStack.pop_back();
  2102. }
  2103. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  2104. // Create a new macro group and add it to the stack.
  2105. auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
  2106. PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
  2107. if (MacroGroup)
  2108. MacroGroup->subPieces.push_back(NewGroup);
  2109. else {
  2110. assert(InstantiationLoc.isFileID());
  2111. Pieces.push_back(NewGroup);
  2112. }
  2113. MacroGroup = NewGroup;
  2114. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  2115. }
  2116. // Finally, add the PathDiagnosticPiece to the group.
  2117. MacroGroup->subPieces.push_back(piece);
  2118. }
  2119. // Now take the pieces and construct a new PathDiagnostic.
  2120. path.clear();
  2121. path.insert(path.end(), Pieces.begin(), Pieces.end());
  2122. }
  2123. /// Generate notes from all visitors.
  2124. /// Notes associated with {@code ErrorNode} are generated using
  2125. /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
  2126. static std::unique_ptr<VisitorsDiagnosticsTy>
  2127. generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
  2128. BugReporterContext &BRC) {
  2129. auto Notes = llvm::make_unique<VisitorsDiagnosticsTy>();
  2130. BugReport::VisitorList visitors;
  2131. // Run visitors on all nodes starting from the node *before* the last one.
  2132. // The last node is reserved for notes generated with {@code getEndPath}.
  2133. const ExplodedNode *NextNode = ErrorNode->getFirstPred();
  2134. while (NextNode) {
  2135. // At each iteration, move all visitors from report to visitor list. This is
  2136. // important, because the Profile() functions of the visitors make sure that
  2137. // a visitor isn't added multiple times for the same node, but it's fine
  2138. // to add the a visitor with Profile() for different nodes (e.g. tracking
  2139. // a region at different points of the symbolic execution).
  2140. for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
  2141. visitors.push_back(std::move(Visitor));
  2142. R->clearVisitors();
  2143. const ExplodedNode *Pred = NextNode->getFirstPred();
  2144. if (!Pred) {
  2145. std::shared_ptr<PathDiagnosticPiece> LastPiece;
  2146. for (auto &V : visitors) {
  2147. V->finalizeVisitor(BRC, ErrorNode, *R);
  2148. if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
  2149. assert(!LastPiece &&
  2150. "There can only be one final piece in a diagnostic.");
  2151. assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
  2152. "The final piece must contain a message!");
  2153. LastPiece = std::move(Piece);
  2154. (*Notes)[ErrorNode].push_back(LastPiece);
  2155. }
  2156. }
  2157. break;
  2158. }
  2159. for (auto &V : visitors) {
  2160. auto P = V->VisitNode(NextNode, BRC, *R);
  2161. if (P)
  2162. (*Notes)[NextNode].push_back(std::move(P));
  2163. }
  2164. if (!R->isValid())
  2165. break;
  2166. NextNode = Pred;
  2167. }
  2168. return Notes;
  2169. }
  2170. class ReportInfo {
  2171. BugPathInfo BugPath;
  2172. std::unique_ptr<VisitorsDiagnosticsTy> VisitorDiagnostics;
  2173. public:
  2174. ReportInfo(BugPathInfo &&BugPath, std::unique_ptr<VisitorsDiagnosticsTy> V)
  2175. : BugPath(std::move(BugPath)), VisitorDiagnostics(std::move(V)) {}
  2176. ReportInfo() = default;
  2177. bool isValid() { return static_cast<bool>(VisitorDiagnostics); }
  2178. BugReport *getBugReport() { return BugPath.Report; }
  2179. const ExplodedNode *getErrorNode() { return BugPath.ErrorNode; }
  2180. InterExplodedGraphMap &getMapToOriginNodes() {
  2181. return BugPath.MapToOriginNodes;
  2182. }
  2183. VisitorsDiagnosticsTy &getVisitorsDiagnostics() {
  2184. return *VisitorDiagnostics;
  2185. }
  2186. };
  2187. /// Find a non-invalidated report for a given equivalence class, and returns
  2188. /// the bug path associated with it together with a cache of visitors notes.
  2189. /// If none found, returns an isInvalid() object.
  2190. static ReportInfo findValidReport(ArrayRef<BugReport *> &bugReports,
  2191. GRBugReporter &Reporter) {
  2192. BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
  2193. while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
  2194. // Find the BugReport with the original location.
  2195. BugReport *R = BugPath->Report;
  2196. assert(R && "No original report found for sliced graph.");
  2197. assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
  2198. const ExplodedNode *ErrorNode = BugPath->ErrorNode;
  2199. // Register refutation visitors first, if they mark the bug invalid no
  2200. // further analysis is required
  2201. R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
  2202. // Register additional node visitors.
  2203. R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
  2204. R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
  2205. R->addVisitor(llvm::make_unique<TagVisitor>());
  2206. BugReporterContext BRC(Reporter, BugPath->MapToOriginNodes);
  2207. // Run all visitors on a given graph, once.
  2208. std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
  2209. generateVisitorsDiagnostics(R, ErrorNode, BRC);
  2210. if (R->isValid()) {
  2211. if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
  2212. // If crosscheck is enabled, remove all visitors, add the refutation
  2213. // visitor and check again
  2214. R->clearVisitors();
  2215. R->addVisitor(llvm::make_unique<FalsePositiveRefutationBRVisitor>());
  2216. // We don't overrite the notes inserted by other visitors because the
  2217. // refutation manager does not add any new note to the path
  2218. generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
  2219. }
  2220. // Check if the bug is still valid
  2221. if (R->isValid())
  2222. return {std::move(*BugPath), std::move(visitorNotes)};
  2223. }
  2224. }
  2225. return {};
  2226. }
  2227. std::unique_ptr<DiagnosticForConsumerMapTy>
  2228. GRBugReporter::generatePathDiagnostics(
  2229. ArrayRef<PathDiagnosticConsumer *> consumers,
  2230. ArrayRef<BugReport *> &bugReports) {
  2231. assert(!bugReports.empty());
  2232. auto Out = llvm::make_unique<DiagnosticForConsumerMapTy>();
  2233. ReportInfo Info = findValidReport(bugReports, *this);
  2234. if (Info.isValid()) {
  2235. for (PathDiagnosticConsumer *PC : consumers) {
  2236. PathDiagnosticBuilder PDB(*this, Info.getBugReport(),
  2237. Info.getMapToOriginNodes(), PC);
  2238. std::unique_ptr<PathDiagnostic> PD = generatePathDiagnosticForConsumer(
  2239. PC->getGenerationScheme(), PDB, Info.getErrorNode(),
  2240. Info.getVisitorsDiagnostics());
  2241. (*Out)[PC] = std::move(PD);
  2242. }
  2243. }
  2244. return Out;
  2245. }
  2246. void BugReporter::Register(const BugType *BT) {
  2247. BugTypes = F.add(BugTypes, BT);
  2248. }
  2249. void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
  2250. if (const ExplodedNode *E = R->getErrorNode()) {
  2251. // An error node must either be a sink or have a tag, otherwise
  2252. // it could get reclaimed before the path diagnostic is created.
  2253. assert((E->isSink() || E->getLocation().getTag()) &&
  2254. "Error node must either be a sink or have a tag");
  2255. const AnalysisDeclContext *DeclCtx =
  2256. E->getLocationContext()->getAnalysisDeclContext();
  2257. // The source of autosynthesized body can be handcrafted AST or a model
  2258. // file. The locations from handcrafted ASTs have no valid source locations
  2259. // and have to be discarded. Locations from model files should be preserved
  2260. // for processing and reporting.
  2261. if (DeclCtx->isBodyAutosynthesized() &&
  2262. !DeclCtx->isBodyAutosynthesizedFromModelFile())
  2263. return;
  2264. }
  2265. bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
  2266. assert(ValidSourceLoc);
  2267. // If we mess up in a release build, we'd still prefer to just drop the bug
  2268. // instead of trying to go on.
  2269. if (!ValidSourceLoc)
  2270. return;
  2271. // Compute the bug report's hash to determine its equivalence class.
  2272. llvm::FoldingSetNodeID ID;
  2273. R->Profile(ID);
  2274. // Lookup the equivance class. If there isn't one, create it.
  2275. const BugType& BT = R->getBugType();
  2276. Register(&BT);
  2277. void *InsertPos;
  2278. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  2279. if (!EQ) {
  2280. EQ = new BugReportEquivClass(std::move(R));
  2281. EQClasses.InsertNode(EQ, InsertPos);
  2282. EQClassesVector.push_back(EQ);
  2283. } else
  2284. EQ->AddReport(std::move(R));
  2285. }
  2286. //===----------------------------------------------------------------------===//
  2287. // Emitting reports in equivalence classes.
  2288. //===----------------------------------------------------------------------===//
  2289. namespace {
  2290. struct FRIEC_WLItem {
  2291. const ExplodedNode *N;
  2292. ExplodedNode::const_succ_iterator I, E;
  2293. FRIEC_WLItem(const ExplodedNode *n)
  2294. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  2295. };
  2296. } // namespace
  2297. static const CFGBlock *findBlockForNode(const ExplodedNode *N) {
  2298. ProgramPoint P = N->getLocation();
  2299. if (auto BEP = P.getAs<BlockEntrance>())
  2300. return BEP->getBlock();
  2301. // Find the node's current statement in the CFG.
  2302. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  2303. return N->getLocationContext()->getAnalysisDeclContext()
  2304. ->getCFGStmtMap()->getBlock(S);
  2305. return nullptr;
  2306. }
  2307. // Returns true if by simply looking at the block, we can be sure that it
  2308. // results in a sink during analysis. This is useful to know when the analysis
  2309. // was interrupted, and we try to figure out if it would sink eventually.
  2310. // There may be many more reasons why a sink would appear during analysis
  2311. // (eg. checkers may generate sinks arbitrarily), but here we only consider
  2312. // sinks that would be obvious by looking at the CFG.
  2313. static bool isImmediateSinkBlock(const CFGBlock *Blk) {
  2314. if (Blk->hasNoReturnElement())
  2315. return true;
  2316. // FIXME: Throw-expressions are currently generating sinks during analysis:
  2317. // they're not supported yet, and also often used for actually terminating
  2318. // the program. So we should treat them as sinks in this analysis as well,
  2319. // at least for now, but once we have better support for exceptions,
  2320. // we'd need to carefully handle the case when the throw is being
  2321. // immediately caught.
  2322. if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
  2323. if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
  2324. if (isa<CXXThrowExpr>(StmtElm->getStmt()))
  2325. return true;
  2326. return false;
  2327. }))
  2328. return true;
  2329. return false;
  2330. }
  2331. // Returns true if by looking at the CFG surrounding the node's program
  2332. // point, we can be sure that any analysis starting from this point would
  2333. // eventually end with a sink. We scan the child CFG blocks in a depth-first
  2334. // manner and see if all paths eventually end up in an immediate sink block.
  2335. static bool isInevitablySinking(const ExplodedNode *N) {
  2336. const CFG &Cfg = N->getCFG();
  2337. const CFGBlock *StartBlk = findBlockForNode(N);
  2338. if (!StartBlk)
  2339. return false;
  2340. if (isImmediateSinkBlock(StartBlk))
  2341. return true;
  2342. llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
  2343. llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
  2344. DFSWorkList.push_back(StartBlk);
  2345. while (!DFSWorkList.empty()) {
  2346. const CFGBlock *Blk = DFSWorkList.back();
  2347. DFSWorkList.pop_back();
  2348. Visited.insert(Blk);
  2349. // If at least one path reaches the CFG exit, it means that control is
  2350. // returned to the caller. For now, say that we are not sure what
  2351. // happens next. If necessary, this can be improved to analyze
  2352. // the parent StackFrameContext's call site in a similar manner.
  2353. if (Blk == &Cfg.getExit())
  2354. return false;
  2355. for (const auto &Succ : Blk->succs()) {
  2356. if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
  2357. if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
  2358. // If the block has reachable child blocks that aren't no-return,
  2359. // add them to the worklist.
  2360. DFSWorkList.push_back(SuccBlk);
  2361. }
  2362. }
  2363. }
  2364. }
  2365. // Nothing reached the exit. It can only mean one thing: there's no return.
  2366. return true;
  2367. }
  2368. static BugReport *
  2369. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  2370. SmallVectorImpl<BugReport*> &bugReports) {
  2371. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  2372. assert(I != E);
  2373. const BugType& BT = I->getBugType();
  2374. // If we don't need to suppress any of the nodes because they are
  2375. // post-dominated by a sink, simply add all the nodes in the equivalence class
  2376. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  2377. if (!BT.isSuppressOnSink()) {
  2378. BugReport *R = &*I;
  2379. for (auto &I : EQ) {
  2380. const ExplodedNode *N = I.getErrorNode();
  2381. if (N) {
  2382. R = &I;
  2383. bugReports.push_back(R);
  2384. }
  2385. }
  2386. return R;
  2387. }
  2388. // For bug reports that should be suppressed when all paths are post-dominated
  2389. // by a sink node, iterate through the reports in the equivalence class
  2390. // until we find one that isn't post-dominated (if one exists). We use a
  2391. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  2392. // this as a recursive function, but we don't want to risk blowing out the
  2393. // stack for very long paths.
  2394. BugReport *exampleReport = nullptr;
  2395. for (; I != E; ++I) {
  2396. const ExplodedNode *errorNode = I->getErrorNode();
  2397. if (!errorNode)
  2398. continue;
  2399. if (errorNode->isSink()) {
  2400. llvm_unreachable(
  2401. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  2402. }
  2403. // No successors? By definition this nodes isn't post-dominated by a sink.
  2404. if (errorNode->succ_empty()) {
  2405. bugReports.push_back(&*I);
  2406. if (!exampleReport)
  2407. exampleReport = &*I;
  2408. continue;
  2409. }
  2410. // See if we are in a no-return CFG block. If so, treat this similarly
  2411. // to being post-dominated by a sink. This works better when the analysis
  2412. // is incomplete and we have never reached the no-return function call(s)
  2413. // that we'd inevitably bump into on this path.
  2414. if (isInevitablySinking(errorNode))
  2415. continue;
  2416. // At this point we know that 'N' is not a sink and it has at least one
  2417. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  2418. using WLItem = FRIEC_WLItem;
  2419. using DFSWorkList = SmallVector<WLItem, 10>;
  2420. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  2421. DFSWorkList WL;
  2422. WL.push_back(errorNode);
  2423. Visited[errorNode] = 1;
  2424. while (!WL.empty()) {
  2425. WLItem &WI = WL.back();
  2426. assert(!WI.N->succ_empty());
  2427. for (; WI.I != WI.E; ++WI.I) {
  2428. const ExplodedNode *Succ = *WI.I;
  2429. // End-of-path node?
  2430. if (Succ->succ_empty()) {
  2431. // If we found an end-of-path node that is not a sink.
  2432. if (!Succ->isSink()) {
  2433. bugReports.push_back(&*I);
  2434. if (!exampleReport)
  2435. exampleReport = &*I;
  2436. WL.clear();
  2437. break;
  2438. }
  2439. // Found a sink? Continue on to the next successor.
  2440. continue;
  2441. }
  2442. // Mark the successor as visited. If it hasn't been explored,
  2443. // enqueue it to the DFS worklist.
  2444. unsigned &mark = Visited[Succ];
  2445. if (!mark) {
  2446. mark = 1;
  2447. WL.push_back(Succ);
  2448. break;
  2449. }
  2450. }
  2451. // The worklist may have been cleared at this point. First
  2452. // check if it is empty before checking the last item.
  2453. if (!WL.empty() && &WL.back() == &WI)
  2454. WL.pop_back();
  2455. }
  2456. }
  2457. // ExampleReport will be NULL if all the nodes in the equivalence class
  2458. // were post-dominated by sinks.
  2459. return exampleReport;
  2460. }
  2461. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  2462. SmallVector<BugReport*, 10> bugReports;
  2463. BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
  2464. if (!report)
  2465. return;
  2466. ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
  2467. std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
  2468. generateDiagnosticForConsumerMap(report, Consumers, bugReports);
  2469. for (auto &P : *Diagnostics) {
  2470. PathDiagnosticConsumer *Consumer = P.first;
  2471. std::unique_ptr<PathDiagnostic> &PD = P.second;
  2472. // If the path is empty, generate a single step path with the location
  2473. // of the issue.
  2474. if (PD->path.empty()) {
  2475. PathDiagnosticLocation L = report->getLocation(getSourceManager());
  2476. auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
  2477. L, report->getDescription());
  2478. for (SourceRange Range : report->getRanges())
  2479. piece->addRange(Range);
  2480. PD->setEndOfPath(std::move(piece));
  2481. }
  2482. PathPieces &Pieces = PD->getMutablePieces();
  2483. if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
  2484. // For path diagnostic consumers that don't support extra notes,
  2485. // we may optionally convert those to path notes.
  2486. for (auto I = report->getNotes().rbegin(),
  2487. E = report->getNotes().rend(); I != E; ++I) {
  2488. PathDiagnosticNotePiece *Piece = I->get();
  2489. auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
  2490. Piece->getLocation(), Piece->getString());
  2491. for (const auto &R: Piece->getRanges())
  2492. ConvertedPiece->addRange(R);
  2493. Pieces.push_front(std::move(ConvertedPiece));
  2494. }
  2495. } else {
  2496. for (auto I = report->getNotes().rbegin(),
  2497. E = report->getNotes().rend(); I != E; ++I)
  2498. Pieces.push_front(*I);
  2499. }
  2500. // Get the meta data.
  2501. const BugReport::ExtraTextList &Meta = report->getExtraText();
  2502. for (const auto &i : Meta)
  2503. PD->addMeta(i);
  2504. updateExecutedLinesWithDiagnosticPieces(*PD);
  2505. Consumer->HandlePathDiagnostic(std::move(PD));
  2506. }
  2507. }
  2508. /// Insert all lines participating in the function signature \p Signature
  2509. /// into \p ExecutedLines.
  2510. static void populateExecutedLinesWithFunctionSignature(
  2511. const Decl *Signature, SourceManager &SM,
  2512. FilesToLineNumsMap &ExecutedLines) {
  2513. SourceRange SignatureSourceRange;
  2514. const Stmt* Body = Signature->getBody();
  2515. if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
  2516. SignatureSourceRange = FD->getSourceRange();
  2517. } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
  2518. SignatureSourceRange = OD->getSourceRange();
  2519. } else {
  2520. return;
  2521. }
  2522. SourceLocation Start = SignatureSourceRange.getBegin();
  2523. SourceLocation End = Body ? Body->getSourceRange().getBegin()
  2524. : SignatureSourceRange.getEnd();
  2525. if (!Start.isValid() || !End.isValid())
  2526. return;
  2527. unsigned StartLine = SM.getExpansionLineNumber(Start);
  2528. unsigned EndLine = SM.getExpansionLineNumber(End);
  2529. FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
  2530. for (unsigned Line = StartLine; Line <= EndLine; Line++)
  2531. ExecutedLines[FID].insert(Line);
  2532. }
  2533. static void populateExecutedLinesWithStmt(
  2534. const Stmt *S, SourceManager &SM,
  2535. FilesToLineNumsMap &ExecutedLines) {
  2536. SourceLocation Loc = S->getSourceRange().getBegin();
  2537. if (!Loc.isValid())
  2538. return;
  2539. SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
  2540. FileID FID = SM.getFileID(ExpansionLoc);
  2541. unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
  2542. ExecutedLines[FID].insert(LineNo);
  2543. }
  2544. /// \return all executed lines including function signatures on the path
  2545. /// starting from \p N.
  2546. static std::unique_ptr<FilesToLineNumsMap>
  2547. findExecutedLines(SourceManager &SM, const ExplodedNode *N) {
  2548. auto ExecutedLines = llvm::make_unique<FilesToLineNumsMap>();
  2549. while (N) {
  2550. if (N->getFirstPred() == nullptr) {
  2551. // First node: show signature of the entrance point.
  2552. const Decl *D = N->getLocationContext()->getDecl();
  2553. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2554. } else if (auto CE = N->getLocationAs<CallEnter>()) {
  2555. // Inlined function: show signature.
  2556. const Decl* D = CE->getCalleeContext()->getDecl();
  2557. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2558. } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
  2559. populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
  2560. // Show extra context for some parent kinds.
  2561. const Stmt *P = N->getParentMap().getParent(S);
  2562. // The path exploration can die before the node with the associated
  2563. // return statement is generated, but we do want to show the whole
  2564. // return.
  2565. if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
  2566. populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
  2567. P = N->getParentMap().getParent(RS);
  2568. }
  2569. if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
  2570. populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
  2571. }
  2572. N = N->getFirstPred();
  2573. }
  2574. return ExecutedLines;
  2575. }
  2576. std::unique_ptr<DiagnosticForConsumerMapTy>
  2577. BugReporter::generateDiagnosticForConsumerMap(
  2578. BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
  2579. ArrayRef<BugReport *> bugReports) {
  2580. if (!report->isPathSensitive()) {
  2581. auto Out = llvm::make_unique<DiagnosticForConsumerMapTy>();
  2582. for (auto *Consumer : consumers)
  2583. (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
  2584. getSourceManager());
  2585. return Out;
  2586. }
  2587. // Generate the full path sensitive diagnostic, using the generation scheme
  2588. // specified by the PathDiagnosticConsumer. Note that we have to generate
  2589. // path diagnostics even for consumers which do not support paths, because
  2590. // the BugReporterVisitors may mark this bug as a false positive.
  2591. assert(!bugReports.empty());
  2592. MaxBugClassSize.updateMax(bugReports.size());
  2593. std::unique_ptr<DiagnosticForConsumerMapTy> Out =
  2594. generatePathDiagnostics(consumers, bugReports);
  2595. if (Out->empty())
  2596. return Out;
  2597. MaxValidBugClassSize.updateMax(bugReports.size());
  2598. // Examine the report and see if the last piece is in a header. Reset the
  2599. // report location to the last piece in the main source file.
  2600. AnalyzerOptions &Opts = getAnalyzerOptions();
  2601. for (auto const &P : *Out)
  2602. if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
  2603. P.second->resetDiagnosticLocationToMainFile();
  2604. return Out;
  2605. }
  2606. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2607. const CheckerBase *Checker,
  2608. StringRef Name, StringRef Category,
  2609. StringRef Str, PathDiagnosticLocation Loc,
  2610. ArrayRef<SourceRange> Ranges) {
  2611. EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
  2612. Loc, Ranges);
  2613. }
  2614. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2615. CheckName CheckName,
  2616. StringRef name, StringRef category,
  2617. StringRef str, PathDiagnosticLocation Loc,
  2618. ArrayRef<SourceRange> Ranges) {
  2619. // 'BT' is owned by BugReporter.
  2620. BugType *BT = getBugTypeForName(CheckName, name, category);
  2621. auto R = llvm::make_unique<BugReport>(*BT, str, Loc);
  2622. R->setDeclWithIssue(DeclWithIssue);
  2623. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
  2624. I != E; ++I)
  2625. R->addRange(*I);
  2626. emitReport(std::move(R));
  2627. }
  2628. BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
  2629. StringRef category) {
  2630. SmallString<136> fullDesc;
  2631. llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
  2632. << ":" << category;
  2633. BugType *&BT = StrBugTypes[fullDesc];
  2634. if (!BT)
  2635. BT = new BugType(CheckName, name, category);
  2636. return BT;
  2637. }