1 //===--- PlistDiagnostics.cpp - Plist Diagnostics for Paths -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the PlistDiagnostics object.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/FileManager.h"
15 #include "clang/Basic/PlistSupport.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/Version.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Rewrite/Core/HTMLRewrite.h"
20 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
22 #include "clang/StaticAnalyzer/Core/IssueHash.h"
23 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Casting.h"
27 using namespace clang;
29 using namespace markup;
32 class PlistDiagnostics : public PathDiagnosticConsumer {
33 const std::string OutputFile;
34 const LangOptions &LangOpts;
35 const bool SupportsCrossFileDiagnostics;
36 const bool SerializeStatistics;
38 PlistDiagnostics(AnalyzerOptions &AnalyzerOpts,
39 const std::string& prefix,
40 const LangOptions &LangOpts,
41 bool supportsMultipleFiles);
43 ~PlistDiagnostics() override {}
45 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
46 FilesMade *filesMade) override;
48 StringRef getName() const override {
49 return "PlistDiagnostics";
52 PathGenerationScheme getGenerationScheme() const override {
55 bool supportsLogicalOpControlFlow() const override { return true; }
56 bool supportsCrossFileDiagnostics() const override {
57 return SupportsCrossFileDiagnostics;
60 } // end anonymous namespace
62 PlistDiagnostics::PlistDiagnostics(AnalyzerOptions &AnalyzerOpts,
63 const std::string& output,
64 const LangOptions &LO,
65 bool supportsMultipleFiles)
68 SupportsCrossFileDiagnostics(supportsMultipleFiles),
69 SerializeStatistics(AnalyzerOpts.shouldSerializeStats()) {}
71 void ento::createPlistDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
72 PathDiagnosticConsumers &C,
74 const Preprocessor &PP) {
75 C.push_back(new PlistDiagnostics(AnalyzerOpts, s,
76 PP.getLangOpts(), false));
79 void ento::createPlistMultiFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
80 PathDiagnosticConsumers &C,
82 const Preprocessor &PP) {
83 C.push_back(new PlistDiagnostics(AnalyzerOpts, s,
84 PP.getLangOpts(), true));
87 static void EmitRanges(raw_ostream &o,
88 const ArrayRef<SourceRange> Ranges,
90 const SourceManager &SM,
91 const LangOptions &LangOpts,
97 Indent(o, indent) << "<key>ranges</key>\n";
98 Indent(o, indent) << "<array>\n";
100 for (auto &R : Ranges)
102 Lexer::getAsCharRange(SM.getExpansionRange(R), SM, LangOpts),
105 Indent(o, indent) << "</array>\n";
108 static void EmitMessage(raw_ostream &o, StringRef Message, unsigned indent) {
110 assert(!Message.empty());
111 Indent(o, indent) << "<key>extended_message</key>\n";
113 EmitString(o, Message) << '\n';
115 // Output the short text.
116 // FIXME: Really use a short string.
117 Indent(o, indent) << "<key>message</key>\n";
119 EmitString(o, Message) << '\n';
122 static void ReportControlFlow(raw_ostream &o,
123 const PathDiagnosticControlFlowPiece& P,
125 const SourceManager &SM,
126 const LangOptions &LangOpts,
129 Indent(o, indent) << "<dict>\n";
132 Indent(o, indent) << "<key>kind</key><string>control</string>\n";
135 Indent(o, indent) << "<key>edges</key>\n";
137 Indent(o, indent) << "<array>\n";
139 for (PathDiagnosticControlFlowPiece::const_iterator I=P.begin(), E=P.end();
141 Indent(o, indent) << "<dict>\n";
144 // Make the ranges of the start and end point self-consistent with adjacent edges
145 // by forcing to use only the beginning of the range. This simplifies the layout
146 // logic for clients.
147 Indent(o, indent) << "<key>start</key>\n";
148 SourceRange StartEdge(
149 SM.getExpansionLoc(I->getStart().asRange().getBegin()));
150 EmitRange(o, SM, Lexer::getAsCharRange(StartEdge, SM, LangOpts), FM,
153 Indent(o, indent) << "<key>end</key>\n";
154 SourceRange EndEdge(SM.getExpansionLoc(I->getEnd().asRange().getBegin()));
155 EmitRange(o, SM, Lexer::getAsCharRange(EndEdge, SM, LangOpts), FM,
159 Indent(o, indent) << "</dict>\n";
162 Indent(o, indent) << "</array>\n";
165 // Output any helper text.
166 const auto &s = P.getString();
168 Indent(o, indent) << "<key>alternate</key>";
169 EmitString(o, s) << '\n';
173 Indent(o, indent) << "</dict>\n";
176 static void ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P,
178 const SourceManager &SM,
179 const LangOptions &LangOpts,
182 bool isKeyEvent = false) {
184 Indent(o, indent) << "<dict>\n";
187 Indent(o, indent) << "<key>kind</key><string>event</string>\n";
190 Indent(o, indent) << "<key>key_event</key><true/>\n";
193 // Output the location.
194 FullSourceLoc L = P.getLocation().asLocation();
196 Indent(o, indent) << "<key>location</key>\n";
197 EmitLocation(o, SM, L, FM, indent);
199 // Output the ranges (if any).
200 ArrayRef<SourceRange> Ranges = P.getRanges();
201 EmitRanges(o, Ranges, FM, SM, LangOpts, indent);
203 // Output the call depth.
204 Indent(o, indent) << "<key>depth</key>";
205 EmitInteger(o, depth) << '\n';
208 EmitMessage(o, P.getString(), indent);
212 Indent(o, indent); o << "</dict>\n";
215 static void ReportPiece(raw_ostream &o,
216 const PathDiagnosticPiece &P,
217 const FIDMap& FM, const SourceManager &SM,
218 const LangOptions &LangOpts,
221 bool includeControlFlow,
222 bool isKeyEvent = false);
224 static void ReportCall(raw_ostream &o,
225 const PathDiagnosticCallPiece &P,
226 const FIDMap& FM, const SourceManager &SM,
227 const LangOptions &LangOpts,
231 if (auto callEnter = P.getCallEnterEvent())
232 ReportPiece(o, *callEnter, FM, SM, LangOpts, indent, depth, true,
233 P.isLastInMainSourceFile());
238 if (auto callEnterWithinCaller = P.getCallEnterWithinCallerEvent())
239 ReportPiece(o, *callEnterWithinCaller, FM, SM, LangOpts,
240 indent, depth, true);
242 for (PathPieces::const_iterator I = P.path.begin(), E = P.path.end();I!=E;++I)
243 ReportPiece(o, **I, FM, SM, LangOpts, indent, depth, true);
247 if (auto callExit = P.getCallExitEvent())
248 ReportPiece(o, *callExit, FM, SM, LangOpts, indent, depth, true);
251 static void ReportMacro(raw_ostream &o,
252 const PathDiagnosticMacroPiece& P,
253 const FIDMap& FM, const SourceManager &SM,
254 const LangOptions &LangOpts,
258 for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
260 ReportPiece(o, **I, FM, SM, LangOpts, indent, depth, false);
264 static void ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P,
266 const SourceManager &SM,
267 const LangOptions &LangOpts,
271 Indent(o, indent) << "<dict>\n";
274 // Output the location.
275 FullSourceLoc L = P.getLocation().asLocation();
277 Indent(o, indent) << "<key>location</key>\n";
278 EmitLocation(o, SM, L, FM, indent);
280 // Output the ranges (if any).
281 ArrayRef<SourceRange> Ranges = P.getRanges();
282 EmitRanges(o, Ranges, FM, SM, LangOpts, indent);
285 EmitMessage(o, P.getString(), indent);
289 Indent(o, indent); o << "</dict>\n";
292 static void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P,
293 const FIDMap& FM, const SourceManager &SM,
294 const LangOptions &LangOpts) {
295 ReportPiece(o, P, FM, SM, LangOpts, 4, 0, true);
298 static void ReportPiece(raw_ostream &o,
299 const PathDiagnosticPiece &P,
300 const FIDMap& FM, const SourceManager &SM,
301 const LangOptions &LangOpts,
304 bool includeControlFlow,
306 switch (P.getKind()) {
307 case PathDiagnosticPiece::ControlFlow:
308 if (includeControlFlow)
309 ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), FM, SM,
312 case PathDiagnosticPiece::Call:
313 ReportCall(o, cast<PathDiagnosticCallPiece>(P), FM, SM, LangOpts,
316 case PathDiagnosticPiece::Event:
317 ReportEvent(o, cast<PathDiagnosticEventPiece>(P), FM, SM, LangOpts,
318 indent, depth, isKeyEvent);
320 case PathDiagnosticPiece::Macro:
321 ReportMacro(o, cast<PathDiagnosticMacroPiece>(P), FM, SM, LangOpts,
324 case PathDiagnosticPiece::Note:
325 ReportNote(o, cast<PathDiagnosticNotePiece>(P), FM, SM, LangOpts,
331 void PlistDiagnostics::FlushDiagnosticsImpl(
332 std::vector<const PathDiagnostic *> &Diags,
333 FilesMade *filesMade) {
334 // Build up a set of FIDs that we use by scanning the locations and
335 // ranges of the diagnostics.
337 SmallVector<FileID, 10> Fids;
338 const SourceManager* SM = nullptr;
341 SM = &Diags.front()->path.front()->getLocation().getManager();
343 auto AddPieceFID = [&FM, &Fids, SM](const PathDiagnosticPiece &Piece) {
344 AddFID(FM, Fids, *SM, Piece.getLocation().asLocation());
345 ArrayRef<SourceRange> Ranges = Piece.getRanges();
346 for (const SourceRange &Range : Ranges) {
347 AddFID(FM, Fids, *SM, Range.getBegin());
348 AddFID(FM, Fids, *SM, Range.getEnd());
352 for (const PathDiagnostic *D : Diags) {
354 SmallVector<const PathPieces *, 5> WorkList;
355 WorkList.push_back(&D->path);
357 while (!WorkList.empty()) {
358 const PathPieces &Path = *WorkList.pop_back_val();
360 for (const auto &Iter : Path) {
361 const PathDiagnosticPiece &Piece = *Iter;
364 if (const PathDiagnosticCallPiece *Call =
365 dyn_cast<PathDiagnosticCallPiece>(&Piece)) {
366 if (auto CallEnterWithin = Call->getCallEnterWithinCallerEvent())
367 AddPieceFID(*CallEnterWithin);
369 if (auto CallEnterEvent = Call->getCallEnterEvent())
370 AddPieceFID(*CallEnterEvent);
372 WorkList.push_back(&Call->path);
373 } else if (const PathDiagnosticMacroPiece *Macro =
374 dyn_cast<PathDiagnosticMacroPiece>(&Piece)) {
375 WorkList.push_back(&Macro->subPieces);
383 llvm::raw_fd_ostream o(OutputFile, EC, llvm::sys::fs::F_Text);
385 llvm::errs() << "warning: could not create file: " << EC.message() << '\n';
391 // Write the root object: a <dict> containing...
392 // - "clang_version", the string representation of clang version
393 // - "files", an <array> mapping from FIDs to file names
394 // - "diagnostics", an <array> containing the path diagnostics
396 " <key>clang_version</key>\n";
397 EmitString(o, getClangFullVersion()) << '\n';
398 o << " <key>files</key>\n"
401 for (FileID FID : Fids)
402 EmitString(o << " ", SM->getFileEntryForID(FID)->getName()) << '\n';
405 " <key>diagnostics</key>\n"
408 for (std::vector<const PathDiagnostic*>::iterator DI=Diags.begin(),
409 DE = Diags.end(); DI!=DE; ++DI) {
413 const PathDiagnostic *D = *DI;
414 const PathPieces &PP = D->path;
416 assert(std::is_partitioned(
417 PP.begin(), PP.end(),
418 [](const std::shared_ptr<PathDiagnosticPiece> &E)
419 { return E->getKind() == PathDiagnosticPiece::Note; }) &&
420 "PathDiagnostic is not partitioned so that notes precede the rest");
422 PathPieces::const_iterator FirstNonNote = std::partition_point(
423 PP.begin(), PP.end(),
424 [](const std::shared_ptr<PathDiagnosticPiece> &E)
425 { return E->getKind() == PathDiagnosticPiece::Note; });
427 PathPieces::const_iterator I = PP.begin();
429 if (FirstNonNote != PP.begin()) {
430 o << " <key>notes</key>\n"
433 for (; I != FirstNonNote; ++I)
434 ReportDiag(o, **I, FM, *SM, LangOpts);
439 o << " <key>path</key>\n";
443 for (PathPieces::const_iterator E = PP.end(); I != E; ++I)
444 ReportDiag(o, **I, FM, *SM, LangOpts);
448 // Output the bug type and bug category.
449 o << " <key>description</key>";
450 EmitString(o, D->getShortDescription()) << '\n';
451 o << " <key>category</key>";
452 EmitString(o, D->getCategory()) << '\n';
453 o << " <key>type</key>";
454 EmitString(o, D->getBugType()) << '\n';
455 o << " <key>check_name</key>";
456 EmitString(o, D->getCheckName()) << '\n';
458 o << " <!-- This hash is experimental and going to change! -->\n";
459 o << " <key>issue_hash_content_of_line_in_context</key>";
460 PathDiagnosticLocation UPDLoc = D->getUniqueingLoc();
461 FullSourceLoc L(SM->getExpansionLoc(UPDLoc.isValid()
462 ? UPDLoc.asLocation()
463 : D->getLocation().asLocation()),
465 const Decl *DeclWithIssue = D->getDeclWithIssue();
466 EmitString(o, GetIssueHash(*SM, L, D->getCheckName(), D->getBugType(),
467 DeclWithIssue, LangOpts))
470 // Output information about the semantic context where
471 // the issue occurred.
472 if (const Decl *DeclWithIssue = D->getDeclWithIssue()) {
473 // FIXME: handle blocks, which have no name.
474 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue)) {
476 switch (ND->getKind()) {
477 case Decl::CXXRecord:
478 declKind = "C++ class";
480 case Decl::CXXMethod:
481 declKind = "C++ method";
483 case Decl::ObjCMethod:
484 declKind = "Objective-C method";
487 declKind = "function";
492 if (!declKind.empty()) {
493 const std::string &declName = ND->getDeclName().getAsString();
494 o << " <key>issue_context_kind</key>";
495 EmitString(o, declKind) << '\n';
496 o << " <key>issue_context</key>";
497 EmitString(o, declName) << '\n';
500 // Output the bug hash for issue unique-ing. Currently, it's just an
501 // offset from the beginning of the function.
502 if (const Stmt *Body = DeclWithIssue->getBody()) {
504 // If the bug uniqueing location exists, use it for the hash.
505 // For example, this ensures that two leaks reported on the same line
506 // will have different issue_hashes and that the hash will identify
507 // the leak location even after code is added between the allocation
508 // site and the end of scope (leak report location).
509 if (UPDLoc.isValid()) {
510 FullSourceLoc UFunL(SM->getExpansionLoc(
511 D->getUniqueingDecl()->getBody()->getLocStart()), *SM);
512 o << " <key>issue_hash_function_offset</key><string>"
513 << L.getExpansionLineNumber() - UFunL.getExpansionLineNumber()
516 // Otherwise, use the location on which the bug is reported.
518 FullSourceLoc FunL(SM->getExpansionLoc(Body->getLocStart()), *SM);
519 o << " <key>issue_hash_function_offset</key><string>"
520 << L.getExpansionLineNumber() - FunL.getExpansionLineNumber()
528 // Output the location of the bug.
529 o << " <key>location</key>\n";
530 EmitLocation(o, *SM, D->getLocation().asLocation(), FM, 2);
532 // Output the diagnostic to the sub-diagnostic client, if any.
533 if (!filesMade->empty()) {
535 PDFileEntry::ConsumerFiles *files = filesMade->getFiles(*D);
537 for (PDFileEntry::ConsumerFiles::const_iterator CI = files->begin(),
538 CE = files->end(); CI != CE; ++CI) {
539 StringRef newName = CI->first;
540 if (newName != lastName) {
541 if (!lastName.empty()) {
545 o << " <key>" << lastName << "_files</key>\n";
548 o << " <string>" << CI->second << "</string>\n";
554 // Close up the entry.
560 if (llvm::AreStatisticsEnabled() && SerializeStatistics) {
561 o << " <key>statistics</key>\n";
563 llvm::raw_string_ostream os(stats);
564 llvm::PrintStatisticsJSON(os);
566 EmitString(o, html::EscapeText(stats)) << '\n';
570 o << "</dict>\n</plist>";