1 //===--- PlistDiagnostics.cpp - Plist Diagnostics for Paths -----*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the PlistDiagnostics object. 11 // 12 //===----------------------------------------------------------------------===// 13 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/Lex/TokenConcatenation.h" 20 #include "clang/Rewrite/Core/HTMLRewrite.h" 21 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 22 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 23 #include "clang/StaticAnalyzer/Core/IssueHash.h" 24 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/Support/Casting.h" 28 29 using namespace clang; 30 using namespace ento; 31 using namespace markup; 32 33 //===----------------------------------------------------------------------===// 34 // Declarations of helper classes and functions for emitting bug reports in 35 // plist format. 36 //===----------------------------------------------------------------------===// 37 38 namespace { 39 class PlistDiagnostics : public PathDiagnosticConsumer { 40 const std::string OutputFile; 41 const Preprocessor &PP; 42 AnalyzerOptions &AnOpts; 43 const bool SupportsCrossFileDiagnostics; 44 public: 45 PlistDiagnostics(AnalyzerOptions &AnalyzerOpts, 46 const std::string& prefix, 47 const Preprocessor &PP, 48 bool supportsMultipleFiles); 49 50 ~PlistDiagnostics() override {} 51 52 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 53 FilesMade *filesMade) override; 54 55 StringRef getName() const override { 56 return "PlistDiagnostics"; 57 } 58 59 PathGenerationScheme getGenerationScheme() const override { 60 return Extensive; 61 } 62 bool supportsLogicalOpControlFlow() const override { return true; } 63 bool supportsCrossFileDiagnostics() const override { 64 return SupportsCrossFileDiagnostics; 65 } 66 }; 67 } // end anonymous namespace 68 69 namespace { 70 71 /// A helper class for emitting a single report. 72 class PlistPrinter { 73 const FIDMap& FM; 74 AnalyzerOptions &AnOpts; 75 const Preprocessor &PP; 76 llvm::SmallVector<const PathDiagnosticMacroPiece *, 0> MacroPieces; 77 78 public: 79 PlistPrinter(const FIDMap& FM, AnalyzerOptions &AnOpts, 80 const Preprocessor &PP) 81 : FM(FM), AnOpts(AnOpts), PP(PP) { 82 } 83 84 void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) { 85 ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true); 86 87 // Don't emit a warning about an unused private field. 88 (void)AnOpts; 89 } 90 91 /// Print the expansions of the collected macro pieces. 92 /// 93 /// Each time ReportDiag is called on a PathDiagnosticMacroPiece (or, if one 94 /// is found through a call piece, etc), it's subpieces are reported, and the 95 /// piece itself is collected. Call this function after the entire bugpath 96 /// was reported. 97 void ReportMacroExpansions(raw_ostream &o, unsigned indent); 98 99 private: 100 void ReportPiece(raw_ostream &o, const PathDiagnosticPiece &P, 101 unsigned indent, unsigned depth, bool includeControlFlow, 102 bool isKeyEvent = false) { 103 switch (P.getKind()) { 104 case PathDiagnosticPiece::ControlFlow: 105 if (includeControlFlow) 106 ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), indent); 107 break; 108 case PathDiagnosticPiece::Call: 109 ReportCall(o, cast<PathDiagnosticCallPiece>(P), indent, 110 depth); 111 break; 112 case PathDiagnosticPiece::Event: 113 ReportEvent(o, cast<PathDiagnosticEventPiece>(P), indent, depth, 114 isKeyEvent); 115 break; 116 case PathDiagnosticPiece::Macro: 117 ReportMacroSubPieces(o, cast<PathDiagnosticMacroPiece>(P), indent, 118 depth); 119 break; 120 case PathDiagnosticPiece::Note: 121 ReportNote(o, cast<PathDiagnosticNotePiece>(P), indent); 122 break; 123 } 124 } 125 126 void EmitRanges(raw_ostream &o, const ArrayRef<SourceRange> Ranges, 127 unsigned indent); 128 void EmitMessage(raw_ostream &o, StringRef Message, unsigned indent); 129 130 void ReportControlFlow(raw_ostream &o, 131 const PathDiagnosticControlFlowPiece& P, 132 unsigned indent); 133 void ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P, 134 unsigned indent, unsigned depth, bool isKeyEvent = false); 135 void ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P, 136 unsigned indent, unsigned depth); 137 void ReportMacroSubPieces(raw_ostream &o, const PathDiagnosticMacroPiece& P, 138 unsigned indent, unsigned depth); 139 void ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P, 140 unsigned indent); 141 }; 142 143 } // end of anonymous namespace 144 145 namespace { 146 147 struct ExpansionInfo { 148 std::string MacroName; 149 std::string Expansion; 150 ExpansionInfo(std::string N, std::string E) 151 : MacroName(std::move(N)), Expansion(std::move(E)) {} 152 }; 153 154 } // end of anonymous namespace 155 156 static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM, 157 AnalyzerOptions &AnOpts, 158 const Preprocessor &PP, 159 const PathPieces &Path); 160 161 /// Print coverage information to output stream {@code o}. 162 /// May modify the used list of files {@code Fids} by inserting new ones. 163 static void printCoverage(const PathDiagnostic *D, 164 unsigned InputIndentLevel, 165 SmallVectorImpl<FileID> &Fids, 166 FIDMap &FM, 167 llvm::raw_fd_ostream &o); 168 169 static ExpansionInfo getExpandedMacro(SourceLocation MacroLoc, 170 const Preprocessor &PP); 171 172 //===----------------------------------------------------------------------===// 173 // Methods of PlistPrinter. 174 //===----------------------------------------------------------------------===// 175 176 void PlistPrinter::EmitRanges(raw_ostream &o, 177 const ArrayRef<SourceRange> Ranges, 178 unsigned indent) { 179 180 if (Ranges.empty()) 181 return; 182 183 Indent(o, indent) << "<key>ranges</key>\n"; 184 Indent(o, indent) << "<array>\n"; 185 ++indent; 186 187 const SourceManager &SM = PP.getSourceManager(); 188 const LangOptions &LangOpts = PP.getLangOpts(); 189 190 for (auto &R : Ranges) 191 EmitRange(o, SM, 192 Lexer::getAsCharRange(SM.getExpansionRange(R), SM, LangOpts), 193 FM, indent + 1); 194 --indent; 195 Indent(o, indent) << "</array>\n"; 196 } 197 198 void PlistPrinter::EmitMessage(raw_ostream &o, StringRef Message, 199 unsigned indent) { 200 // Output the text. 201 assert(!Message.empty()); 202 Indent(o, indent) << "<key>extended_message</key>\n"; 203 Indent(o, indent); 204 EmitString(o, Message) << '\n'; 205 206 // Output the short text. 207 // FIXME: Really use a short string. 208 Indent(o, indent) << "<key>message</key>\n"; 209 Indent(o, indent); 210 EmitString(o, Message) << '\n'; 211 } 212 213 void PlistPrinter::ReportControlFlow(raw_ostream &o, 214 const PathDiagnosticControlFlowPiece& P, 215 unsigned indent) { 216 217 const SourceManager &SM = PP.getSourceManager(); 218 const LangOptions &LangOpts = PP.getLangOpts(); 219 220 Indent(o, indent) << "<dict>\n"; 221 ++indent; 222 223 Indent(o, indent) << "<key>kind</key><string>control</string>\n"; 224 225 // Emit edges. 226 Indent(o, indent) << "<key>edges</key>\n"; 227 ++indent; 228 Indent(o, indent) << "<array>\n"; 229 ++indent; 230 for (PathDiagnosticControlFlowPiece::const_iterator I=P.begin(), E=P.end(); 231 I!=E; ++I) { 232 Indent(o, indent) << "<dict>\n"; 233 ++indent; 234 235 // Make the ranges of the start and end point self-consistent with adjacent edges 236 // by forcing to use only the beginning of the range. This simplifies the layout 237 // logic for clients. 238 Indent(o, indent) << "<key>start</key>\n"; 239 SourceRange StartEdge( 240 SM.getExpansionLoc(I->getStart().asRange().getBegin())); 241 EmitRange(o, SM, Lexer::getAsCharRange(StartEdge, SM, LangOpts), FM, 242 indent + 1); 243 244 Indent(o, indent) << "<key>end</key>\n"; 245 SourceRange EndEdge(SM.getExpansionLoc(I->getEnd().asRange().getBegin())); 246 EmitRange(o, SM, Lexer::getAsCharRange(EndEdge, SM, LangOpts), FM, 247 indent + 1); 248 249 --indent; 250 Indent(o, indent) << "</dict>\n"; 251 } 252 --indent; 253 Indent(o, indent) << "</array>\n"; 254 --indent; 255 256 // Output any helper text. 257 const auto &s = P.getString(); 258 if (!s.empty()) { 259 Indent(o, indent) << "<key>alternate</key>"; 260 EmitString(o, s) << '\n'; 261 } 262 263 --indent; 264 Indent(o, indent) << "</dict>\n"; 265 } 266 267 void PlistPrinter::ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P, 268 unsigned indent, unsigned depth, 269 bool isKeyEvent) { 270 271 const SourceManager &SM = PP.getSourceManager(); 272 273 Indent(o, indent) << "<dict>\n"; 274 ++indent; 275 276 Indent(o, indent) << "<key>kind</key><string>event</string>\n"; 277 278 if (isKeyEvent) { 279 Indent(o, indent) << "<key>key_event</key><true/>\n"; 280 } 281 282 // Output the location. 283 FullSourceLoc L = P.getLocation().asLocation(); 284 285 Indent(o, indent) << "<key>location</key>\n"; 286 EmitLocation(o, SM, L, FM, indent); 287 288 // Output the ranges (if any). 289 ArrayRef<SourceRange> Ranges = P.getRanges(); 290 EmitRanges(o, Ranges, indent); 291 292 // Output the call depth. 293 Indent(o, indent) << "<key>depth</key>"; 294 EmitInteger(o, depth) << '\n'; 295 296 // Output the text. 297 EmitMessage(o, P.getString(), indent); 298 299 // Finish up. 300 --indent; 301 Indent(o, indent); o << "</dict>\n"; 302 } 303 304 void PlistPrinter::ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P, 305 unsigned indent, 306 unsigned depth) { 307 308 if (auto callEnter = P.getCallEnterEvent()) 309 ReportPiece(o, *callEnter, indent, depth, /*includeControlFlow*/ true, 310 P.isLastInMainSourceFile()); 311 312 313 ++depth; 314 315 if (auto callEnterWithinCaller = P.getCallEnterWithinCallerEvent()) 316 ReportPiece(o, *callEnterWithinCaller, indent, depth, 317 /*includeControlFlow*/ true); 318 319 for (PathPieces::const_iterator I = P.path.begin(), E = P.path.end();I!=E;++I) 320 ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ true); 321 322 --depth; 323 324 if (auto callExit = P.getCallExitEvent()) 325 ReportPiece(o, *callExit, indent, depth, /*includeControlFlow*/ true); 326 } 327 328 void PlistPrinter::ReportMacroSubPieces(raw_ostream &o, 329 const PathDiagnosticMacroPiece& P, 330 unsigned indent, unsigned depth) { 331 MacroPieces.push_back(&P); 332 333 for (PathPieces::const_iterator I = P.subPieces.begin(), 334 E = P.subPieces.end(); 335 I != E; ++I) { 336 ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ false); 337 } 338 } 339 340 void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) { 341 342 for (const PathDiagnosticMacroPiece *P : MacroPieces) { 343 const SourceManager &SM = PP.getSourceManager(); 344 ExpansionInfo EI = getExpandedMacro(P->getLocation().asLocation(), PP); 345 346 Indent(o, indent) << "<dict>\n"; 347 ++indent; 348 349 // Output the location. 350 FullSourceLoc L = P->getLocation().asLocation(); 351 352 Indent(o, indent) << "<key>location</key>\n"; 353 EmitLocation(o, SM, L, FM, indent); 354 355 // Output the ranges (if any). 356 ArrayRef<SourceRange> Ranges = P->getRanges(); 357 EmitRanges(o, Ranges, indent); 358 359 // Output the macro name. 360 Indent(o, indent) << "<key>name</key>"; 361 EmitString(o, EI.MacroName) << '\n'; 362 363 // Output what it expands into. 364 Indent(o, indent) << "<key>expansion</key>"; 365 EmitString(o, EI.Expansion) << '\n'; 366 367 // Finish up. 368 --indent; 369 Indent(o, indent); 370 o << "</dict>\n"; 371 } 372 } 373 374 void PlistPrinter::ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P, 375 unsigned indent) { 376 377 const SourceManager &SM = PP.getSourceManager(); 378 379 Indent(o, indent) << "<dict>\n"; 380 ++indent; 381 382 // Output the location. 383 FullSourceLoc L = P.getLocation().asLocation(); 384 385 Indent(o, indent) << "<key>location</key>\n"; 386 EmitLocation(o, SM, L, FM, indent); 387 388 // Output the ranges (if any). 389 ArrayRef<SourceRange> Ranges = P.getRanges(); 390 EmitRanges(o, Ranges, indent); 391 392 // Output the text. 393 EmitMessage(o, P.getString(), indent); 394 395 // Finish up. 396 --indent; 397 Indent(o, indent); o << "</dict>\n"; 398 } 399 400 //===----------------------------------------------------------------------===// 401 // Static function definitions. 402 //===----------------------------------------------------------------------===// 403 404 /// Print coverage information to output stream {@code o}. 405 /// May modify the used list of files {@code Fids} by inserting new ones. 406 static void printCoverage(const PathDiagnostic *D, 407 unsigned InputIndentLevel, 408 SmallVectorImpl<FileID> &Fids, 409 FIDMap &FM, 410 llvm::raw_fd_ostream &o) { 411 unsigned IndentLevel = InputIndentLevel; 412 413 Indent(o, IndentLevel) << "<key>ExecutedLines</key>\n"; 414 Indent(o, IndentLevel) << "<dict>\n"; 415 IndentLevel++; 416 417 // Mapping from file IDs to executed lines. 418 const FilesToLineNumsMap &ExecutedLines = D->getExecutedLines(); 419 for (auto I = ExecutedLines.begin(), E = ExecutedLines.end(); I != E; ++I) { 420 unsigned FileKey = AddFID(FM, Fids, I->first); 421 Indent(o, IndentLevel) << "<key>" << FileKey << "</key>\n"; 422 Indent(o, IndentLevel) << "<array>\n"; 423 IndentLevel++; 424 for (unsigned LineNo : I->second) { 425 Indent(o, IndentLevel); 426 EmitInteger(o, LineNo) << "\n"; 427 } 428 IndentLevel--; 429 Indent(o, IndentLevel) << "</array>\n"; 430 } 431 IndentLevel--; 432 Indent(o, IndentLevel) << "</dict>\n"; 433 434 assert(IndentLevel == InputIndentLevel); 435 } 436 437 static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM, 438 AnalyzerOptions &AnOpts, 439 const Preprocessor &PP, 440 const PathPieces &Path) { 441 PlistPrinter Printer(FM, AnOpts, PP); 442 assert(std::is_partitioned( 443 Path.begin(), Path.end(), 444 [](const std::shared_ptr<PathDiagnosticPiece> &E) 445 { return E->getKind() == PathDiagnosticPiece::Note; }) && 446 "PathDiagnostic is not partitioned so that notes precede the rest"); 447 448 PathPieces::const_iterator FirstNonNote = std::partition_point( 449 Path.begin(), Path.end(), 450 [](const std::shared_ptr<PathDiagnosticPiece> &E) 451 { return E->getKind() == PathDiagnosticPiece::Note; }); 452 453 PathPieces::const_iterator I = Path.begin(); 454 455 if (FirstNonNote != Path.begin()) { 456 o << " <key>notes</key>\n" 457 " <array>\n"; 458 459 for (; I != FirstNonNote; ++I) 460 Printer.ReportDiag(o, **I); 461 462 o << " </array>\n"; 463 } 464 465 o << " <key>path</key>\n"; 466 467 o << " <array>\n"; 468 469 for (PathPieces::const_iterator E = Path.end(); I != E; ++I) 470 Printer.ReportDiag(o, **I); 471 472 o << " </array>\n"; 473 474 if (!AnOpts.shouldDisplayMacroExpansions()) 475 return; 476 477 o << " <key>macro_expansions</key>\n" 478 " <array>\n"; 479 Printer.ReportMacroExpansions(o, /* indent */ 4); 480 o << " </array>\n"; 481 } 482 483 //===----------------------------------------------------------------------===// 484 // Methods of PlistDiagnostics. 485 //===----------------------------------------------------------------------===// 486 487 PlistDiagnostics::PlistDiagnostics(AnalyzerOptions &AnalyzerOpts, 488 const std::string& output, 489 const Preprocessor &PP, 490 bool supportsMultipleFiles) 491 : OutputFile(output), PP(PP), AnOpts(AnalyzerOpts), 492 SupportsCrossFileDiagnostics(supportsMultipleFiles) {} 493 494 void ento::createPlistDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 495 PathDiagnosticConsumers &C, 496 const std::string& s, 497 const Preprocessor &PP) { 498 C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP, 499 /*supportsMultipleFiles*/ false)); 500 } 501 502 void ento::createPlistMultiFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 503 PathDiagnosticConsumers &C, 504 const std::string &s, 505 const Preprocessor &PP) { 506 C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP, 507 /*supportsMultipleFiles*/ true)); 508 } 509 void PlistDiagnostics::FlushDiagnosticsImpl( 510 std::vector<const PathDiagnostic *> &Diags, 511 FilesMade *filesMade) { 512 // Build up a set of FIDs that we use by scanning the locations and 513 // ranges of the diagnostics. 514 FIDMap FM; 515 SmallVector<FileID, 10> Fids; 516 const SourceManager& SM = PP.getSourceManager(); 517 const LangOptions &LangOpts = PP.getLangOpts(); 518 519 auto AddPieceFID = [&FM, &Fids, &SM](const PathDiagnosticPiece &Piece) { 520 AddFID(FM, Fids, SM, Piece.getLocation().asLocation()); 521 ArrayRef<SourceRange> Ranges = Piece.getRanges(); 522 for (const SourceRange &Range : Ranges) { 523 AddFID(FM, Fids, SM, Range.getBegin()); 524 AddFID(FM, Fids, SM, Range.getEnd()); 525 } 526 }; 527 528 for (const PathDiagnostic *D : Diags) { 529 530 SmallVector<const PathPieces *, 5> WorkList; 531 WorkList.push_back(&D->path); 532 533 while (!WorkList.empty()) { 534 const PathPieces &Path = *WorkList.pop_back_val(); 535 536 for (const auto &Iter : Path) { 537 const PathDiagnosticPiece &Piece = *Iter; 538 AddPieceFID(Piece); 539 540 if (const PathDiagnosticCallPiece *Call = 541 dyn_cast<PathDiagnosticCallPiece>(&Piece)) { 542 if (auto CallEnterWithin = Call->getCallEnterWithinCallerEvent()) 543 AddPieceFID(*CallEnterWithin); 544 545 if (auto CallEnterEvent = Call->getCallEnterEvent()) 546 AddPieceFID(*CallEnterEvent); 547 548 WorkList.push_back(&Call->path); 549 } else if (const PathDiagnosticMacroPiece *Macro = 550 dyn_cast<PathDiagnosticMacroPiece>(&Piece)) { 551 WorkList.push_back(&Macro->subPieces); 552 } 553 } 554 } 555 } 556 557 // Open the file. 558 std::error_code EC; 559 llvm::raw_fd_ostream o(OutputFile, EC, llvm::sys::fs::F_Text); 560 if (EC) { 561 llvm::errs() << "warning: could not create file: " << EC.message() << '\n'; 562 return; 563 } 564 565 EmitPlistHeader(o); 566 567 // Write the root object: a <dict> containing... 568 // - "clang_version", the string representation of clang version 569 // - "files", an <array> mapping from FIDs to file names 570 // - "diagnostics", an <array> containing the path diagnostics 571 o << "<dict>\n" << 572 " <key>clang_version</key>\n"; 573 EmitString(o, getClangFullVersion()) << '\n'; 574 o << " <key>diagnostics</key>\n" 575 " <array>\n"; 576 577 for (std::vector<const PathDiagnostic*>::iterator DI=Diags.begin(), 578 DE = Diags.end(); DI!=DE; ++DI) { 579 580 o << " <dict>\n"; 581 582 const PathDiagnostic *D = *DI; 583 printBugPath(o, FM, AnOpts, PP, D->path); 584 585 // Output the bug type and bug category. 586 o << " <key>description</key>"; 587 EmitString(o, D->getShortDescription()) << '\n'; 588 o << " <key>category</key>"; 589 EmitString(o, D->getCategory()) << '\n'; 590 o << " <key>type</key>"; 591 EmitString(o, D->getBugType()) << '\n'; 592 o << " <key>check_name</key>"; 593 EmitString(o, D->getCheckName()) << '\n'; 594 595 o << " <!-- This hash is experimental and going to change! -->\n"; 596 o << " <key>issue_hash_content_of_line_in_context</key>"; 597 PathDiagnosticLocation UPDLoc = D->getUniqueingLoc(); 598 FullSourceLoc L(SM.getExpansionLoc(UPDLoc.isValid() 599 ? UPDLoc.asLocation() 600 : D->getLocation().asLocation()), 601 SM); 602 const Decl *DeclWithIssue = D->getDeclWithIssue(); 603 EmitString(o, GetIssueHash(SM, L, D->getCheckName(), D->getBugType(), 604 DeclWithIssue, LangOpts)) 605 << '\n'; 606 607 // Output information about the semantic context where 608 // the issue occurred. 609 if (const Decl *DeclWithIssue = D->getDeclWithIssue()) { 610 // FIXME: handle blocks, which have no name. 611 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue)) { 612 StringRef declKind; 613 switch (ND->getKind()) { 614 case Decl::CXXRecord: 615 declKind = "C++ class"; 616 break; 617 case Decl::CXXMethod: 618 declKind = "C++ method"; 619 break; 620 case Decl::ObjCMethod: 621 declKind = "Objective-C method"; 622 break; 623 case Decl::Function: 624 declKind = "function"; 625 break; 626 default: 627 break; 628 } 629 if (!declKind.empty()) { 630 const std::string &declName = ND->getDeclName().getAsString(); 631 o << " <key>issue_context_kind</key>"; 632 EmitString(o, declKind) << '\n'; 633 o << " <key>issue_context</key>"; 634 EmitString(o, declName) << '\n'; 635 } 636 637 // Output the bug hash for issue unique-ing. Currently, it's just an 638 // offset from the beginning of the function. 639 if (const Stmt *Body = DeclWithIssue->getBody()) { 640 641 // If the bug uniqueing location exists, use it for the hash. 642 // For example, this ensures that two leaks reported on the same line 643 // will have different issue_hashes and that the hash will identify 644 // the leak location even after code is added between the allocation 645 // site and the end of scope (leak report location). 646 if (UPDLoc.isValid()) { 647 FullSourceLoc UFunL( 648 SM.getExpansionLoc( 649 D->getUniqueingDecl()->getBody()->getBeginLoc()), 650 SM); 651 o << " <key>issue_hash_function_offset</key><string>" 652 << L.getExpansionLineNumber() - UFunL.getExpansionLineNumber() 653 << "</string>\n"; 654 655 // Otherwise, use the location on which the bug is reported. 656 } else { 657 FullSourceLoc FunL(SM.getExpansionLoc(Body->getBeginLoc()), SM); 658 o << " <key>issue_hash_function_offset</key><string>" 659 << L.getExpansionLineNumber() - FunL.getExpansionLineNumber() 660 << "</string>\n"; 661 } 662 663 } 664 } 665 } 666 667 // Output the location of the bug. 668 o << " <key>location</key>\n"; 669 EmitLocation(o, SM, D->getLocation().asLocation(), FM, 2); 670 671 // Output the diagnostic to the sub-diagnostic client, if any. 672 if (!filesMade->empty()) { 673 StringRef lastName; 674 PDFileEntry::ConsumerFiles *files = filesMade->getFiles(*D); 675 if (files) { 676 for (PDFileEntry::ConsumerFiles::const_iterator CI = files->begin(), 677 CE = files->end(); CI != CE; ++CI) { 678 StringRef newName = CI->first; 679 if (newName != lastName) { 680 if (!lastName.empty()) { 681 o << " </array>\n"; 682 } 683 lastName = newName; 684 o << " <key>" << lastName << "_files</key>\n"; 685 o << " <array>\n"; 686 } 687 o << " <string>" << CI->second << "</string>\n"; 688 } 689 o << " </array>\n"; 690 } 691 } 692 693 printCoverage(D, /*IndentLevel=*/2, Fids, FM, o); 694 695 // Close up the entry. 696 o << " </dict>\n"; 697 } 698 699 o << " </array>\n"; 700 701 o << " <key>files</key>\n" 702 " <array>\n"; 703 for (FileID FID : Fids) 704 EmitString(o << " ", SM.getFileEntryForID(FID)->getName()) << '\n'; 705 o << " </array>\n"; 706 707 if (llvm::AreStatisticsEnabled() && AnOpts.shouldSerializeStats()) { 708 o << " <key>statistics</key>\n"; 709 std::string stats; 710 llvm::raw_string_ostream os(stats); 711 llvm::PrintStatisticsJSON(os); 712 os.flush(); 713 EmitString(o, html::EscapeText(stats)) << '\n'; 714 } 715 716 // Finish. 717 o << "</dict>\n</plist>"; 718 } 719 720 //===----------------------------------------------------------------------===// 721 // Declarations of helper functions and data structures for expanding macros. 722 //===----------------------------------------------------------------------===// 723 724 namespace { 725 726 struct MacroNameAndInfo { 727 std::string Name; 728 const MacroInfo *MI = nullptr; 729 730 MacroNameAndInfo(std::string N, const MacroInfo *MI) 731 : Name(std::move(N)), MI(MI) {} 732 }; 733 734 /// Helper class for printing tokens. 735 class TokenPrinter { 736 llvm::raw_ostream &OS; 737 const Preprocessor &PP; 738 739 Token PrevTok, PrevPrevTok; 740 TokenConcatenation ConcatInfo; 741 742 public: 743 TokenPrinter(llvm::raw_ostream &OS, const Preprocessor &PP) 744 : OS(OS), PP(PP), ConcatInfo(PP) { 745 PrevTok.setKind(tok::unknown); 746 PrevPrevTok.setKind(tok::unknown); 747 } 748 749 void printToken(const Token &Tok); 750 }; 751 752 } // end of anonymous namespace 753 754 static std::string getMacroNameAndPrintExpansion(TokenPrinter &Printer, 755 SourceLocation MacroLoc, 756 const Preprocessor &PP); 757 758 /// Retrieves the name of the macro and its MacroInfo. 759 static MacroNameAndInfo getMacroNameAndInfo(SourceLocation ExpanLoc, 760 const Preprocessor &PP); 761 762 /// Retrieves the ')' token that matches '(' \p It points to. 763 static MacroInfo::tokens_iterator getMatchingRParen( 764 MacroInfo::tokens_iterator It, 765 MacroInfo::tokens_iterator End); 766 767 /// Retrieves the macro info for \p II refers to at \p Loc. This is important 768 /// because macros can be redefined or undefined. 769 static const MacroInfo *getMacroInfoForLocation(const Preprocessor &PP, 770 const SourceManager &SM, 771 const IdentifierInfo *II, 772 SourceLocation Loc); 773 774 //===----------------------------------------------------------------------===// 775 // Definitions of helper functions and methods for expanding macros. 776 //===----------------------------------------------------------------------===// 777 778 static ExpansionInfo getExpandedMacro(SourceLocation MacroLoc, 779 const Preprocessor &PP) { 780 781 llvm::SmallString<200> ExpansionBuf; 782 llvm::raw_svector_ostream OS(ExpansionBuf); 783 TokenPrinter Printer(OS, PP); 784 std::string MacroName = getMacroNameAndPrintExpansion(Printer, MacroLoc, PP); 785 return { MacroName, OS.str() }; 786 } 787 788 static std::string getMacroNameAndPrintExpansion(TokenPrinter &Printer, 789 SourceLocation MacroLoc, 790 const Preprocessor &PP) { 791 792 const SourceManager &SM = PP.getSourceManager(); 793 794 MacroNameAndInfo Info = getMacroNameAndInfo(SM.getExpansionLoc(MacroLoc), PP); 795 const MacroInfo *MI = Info.MI; 796 797 // Iterate over the macro's tokens and stringify them. 798 for (auto It = MI->tokens_begin(), E = MI->tokens_end(); It != E; ++It) { 799 Token T = *It; 800 801 // If this token is not an identifier, we only need to print it. 802 if (T.isNot(tok::identifier)) { 803 Printer.printToken(T); 804 continue; 805 } 806 807 const auto *II = T.getIdentifierInfo(); 808 assert(II && 809 "This token is an identifier but has no IdentifierInfo!"); 810 811 // If this token is a macro that should be expanded inside the currect 812 // macro. 813 if (const MacroInfo *MI = 814 getMacroInfoForLocation(PP, SM, II, T.getLocation())) { 815 getMacroNameAndPrintExpansion(Printer, T.getLocation(), PP); 816 817 // If this is a function-like macro, skip its arguments, as 818 // getExpandedMacro() already printed them. If this is the case, let's 819 // first jumo to the '(' token. 820 if (MI->getNumParams() != 0) 821 It = getMatchingRParen(++It, E); 822 continue; 823 } 824 825 // If control reached here, then this token isn't a macro identifier, print 826 // it. 827 Printer.printToken(T); 828 } 829 830 return Info.Name; 831 } 832 833 static MacroNameAndInfo getMacroNameAndInfo(SourceLocation ExpanLoc, 834 const Preprocessor &PP) { 835 836 const SourceManager &SM = PP.getSourceManager(); 837 const LangOptions &LangOpts = PP.getLangOpts(); 838 839 // First, we create a Lexer to lex *at the expansion location* the tokens 840 // referring to the macro's name and its arguments. 841 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ExpanLoc); 842 const llvm::MemoryBuffer *MB = SM.getBuffer(LocInfo.first); 843 const char *MacroNameTokenPos = MB->getBufferStart() + LocInfo.second; 844 845 Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, 846 MB->getBufferStart(), MacroNameTokenPos, MB->getBufferEnd()); 847 848 // Acquire the macro's name. 849 Token TheTok; 850 RawLexer.LexFromRawLexer(TheTok); 851 852 std::string MacroName = PP.getSpelling(TheTok); 853 854 const auto *II = PP.getIdentifierInfo(MacroName); 855 assert(II && "Failed to acquire the IndetifierInfo for the macro!"); 856 857 const MacroInfo *MI = getMacroInfoForLocation(PP, SM, II, ExpanLoc); 858 assert(MI && "The macro must've been defined at it's expansion location!"); 859 860 return { MacroName, MI }; 861 } 862 863 static MacroInfo::tokens_iterator getMatchingRParen( 864 MacroInfo::tokens_iterator It, 865 MacroInfo::tokens_iterator End) { 866 867 assert(It->is(tok::l_paren) && "This token should be '('!"); 868 869 // Skip until we find the closing ')'. 870 int ParanthesesDepth = 1; 871 while (ParanthesesDepth != 0) { 872 ++It; 873 874 assert(It->isNot(tok::eof) && 875 "Encountered EOF while attempting to skip macro arguments!"); 876 assert(It != End && 877 "End of the macro definition reached before finding ')'!"); 878 879 if (It->is(tok::l_paren)) 880 ++ParanthesesDepth; 881 882 if (It->is(tok::r_paren)) 883 --ParanthesesDepth; 884 } 885 return It; 886 } 887 888 static const MacroInfo *getMacroInfoForLocation(const Preprocessor &PP, 889 const SourceManager &SM, 890 const IdentifierInfo *II, 891 SourceLocation Loc) { 892 893 const MacroDirective *MD = PP.getLocalMacroDirectiveHistory(II); 894 if (!MD) 895 return nullptr; 896 897 return MD->findDirectiveAtLoc(Loc, SM).getMacroInfo(); 898 } 899 900 void TokenPrinter::printToken(const Token &Tok) { 901 // If the tokens were already space separated, or if they must be to avoid 902 // them being implicitly pasted, add a space between them. 903 // If this is the first token to be printed, don't print space. 904 if (PrevTok.isNot(tok::unknown) && (Tok.hasLeadingSpace() || 905 ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok))) 906 OS << ' '; 907 908 OS << PP.getSpelling(Tok); 909 910 PrevPrevTok = PrevTok; 911 PrevTok = Tok; 912 } 913