BugReporter.cpp 113 KB

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