BugReporter.cpp 110 KB

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