1 //===- CodeCoverage.cpp - Coverage tool based on profiling instrumentation-===// 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 // The 'CodeCoverageTool' class implements a command line tool to analyze and 10 // report coverage information using the profiling instrumentation and code 11 // coverage mapping. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CoverageExporterJson.h" 16 #include "CoverageExporterLcov.h" 17 #include "CoverageFilters.h" 18 #include "CoverageReport.h" 19 #include "CoverageSummaryInfo.h" 20 #include "CoverageViewOptions.h" 21 #include "RenderingSupport.h" 22 #include "SourceCoverageView.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/ProfileData/Coverage/CoverageMapping.h" 27 #include "llvm/ProfileData/InstrProfReader.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/FileSystem.h" 30 #include "llvm/Support/Format.h" 31 #include "llvm/Support/MemoryBuffer.h" 32 #include "llvm/Support/Path.h" 33 #include "llvm/Support/Process.h" 34 #include "llvm/Support/Program.h" 35 #include "llvm/Support/ScopedPrinter.h" 36 #include "llvm/Support/SpecialCaseList.h" 37 #include "llvm/Support/ThreadPool.h" 38 #include "llvm/Support/Threading.h" 39 #include "llvm/Support/ToolOutputFile.h" 40 #include "llvm/Support/VirtualFileSystem.h" 41 42 #include <functional> 43 #include <map> 44 #include <system_error> 45 46 using namespace llvm; 47 using namespace coverage; 48 49 void exportCoverageDataToJson(const coverage::CoverageMapping &CoverageMapping, 50 const CoverageViewOptions &Options, 51 raw_ostream &OS); 52 53 namespace { 54 /// The implementation of the coverage tool. 55 class CodeCoverageTool { 56 public: 57 enum Command { 58 /// The show command. 59 Show, 60 /// The report command. 61 Report, 62 /// The export command. 63 Export 64 }; 65 66 int run(Command Cmd, int argc, const char **argv); 67 68 private: 69 /// Print the error message to the error output stream. 70 void error(const Twine &Message, StringRef Whence = ""); 71 72 /// Print the warning message to the error output stream. 73 void warning(const Twine &Message, StringRef Whence = ""); 74 75 /// Convert \p Path into an absolute path and append it to the list 76 /// of collected paths. 77 void addCollectedPath(const std::string &Path); 78 79 /// If \p Path is a regular file, collect the path. If it's a 80 /// directory, recursively collect all of the paths within the directory. 81 void collectPaths(const std::string &Path); 82 83 /// Check if the two given files are the same file. 84 bool isEquivalentFile(StringRef FilePath1, StringRef FilePath2); 85 86 /// Retrieve a file status with a cache. 87 Optional<sys::fs::file_status> getFileStatus(StringRef FilePath); 88 89 /// Return a memory buffer for the given source file. 90 ErrorOr<const MemoryBuffer &> getSourceFile(StringRef SourceFile); 91 92 /// Create source views for the expansions of the view. 93 void attachExpansionSubViews(SourceCoverageView &View, 94 ArrayRef<ExpansionRecord> Expansions, 95 const CoverageMapping &Coverage); 96 97 /// Create source views for the branches of the view. 98 void attachBranchSubViews(SourceCoverageView &View, StringRef SourceName, 99 ArrayRef<CountedRegion> Branches, 100 const MemoryBuffer &File, 101 CoverageData &CoverageInfo); 102 103 /// Create the source view of a particular function. 104 std::unique_ptr<SourceCoverageView> 105 createFunctionView(const FunctionRecord &Function, 106 const CoverageMapping &Coverage); 107 108 /// Create the main source view of a particular source file. 109 std::unique_ptr<SourceCoverageView> 110 createSourceFileView(StringRef SourceFile, const CoverageMapping &Coverage); 111 112 /// Load the coverage mapping data. Return nullptr if an error occurred. 113 std::unique_ptr<CoverageMapping> load(); 114 115 /// Create a mapping from files in the Coverage data to local copies 116 /// (path-equivalence). 117 void remapPathNames(const CoverageMapping &Coverage); 118 119 /// Remove input source files which aren't mapped by \p Coverage. 120 void removeUnmappedInputs(const CoverageMapping &Coverage); 121 122 /// If a demangler is available, demangle all symbol names. 123 void demangleSymbols(const CoverageMapping &Coverage); 124 125 /// Write out a source file view to the filesystem. 126 void writeSourceFileView(StringRef SourceFile, CoverageMapping *Coverage, 127 CoveragePrinter *Printer, bool ShowFilenames); 128 129 typedef llvm::function_ref<int(int, const char **)> CommandLineParserType; 130 131 int doShow(int argc, const char **argv, 132 CommandLineParserType commandLineParser); 133 134 int doReport(int argc, const char **argv, 135 CommandLineParserType commandLineParser); 136 137 int doExport(int argc, const char **argv, 138 CommandLineParserType commandLineParser); 139 140 std::vector<StringRef> ObjectFilenames; 141 CoverageViewOptions ViewOpts; 142 CoverageFiltersMatchAll Filters; 143 CoverageFilters IgnoreFilenameFilters; 144 145 /// True if InputSourceFiles are provided. 146 bool HadSourceFiles = false; 147 148 /// The path to the indexed profile. 149 std::string PGOFilename; 150 151 /// A list of input source files. 152 std::vector<std::string> SourceFiles; 153 154 /// In -path-equivalence mode, this maps the absolute paths from the coverage 155 /// mapping data to the input source files. 156 StringMap<std::string> RemappedFilenames; 157 158 /// The coverage data path to be remapped from, and the source path to be 159 /// remapped to, when using -path-equivalence. 160 Optional<std::pair<std::string, std::string>> PathRemapping; 161 162 /// File status cache used when finding the same file. 163 StringMap<Optional<sys::fs::file_status>> FileStatusCache; 164 165 /// The architecture the coverage mapping data targets. 166 std::vector<StringRef> CoverageArches; 167 168 /// A cache for demangled symbols. 169 DemangleCache DC; 170 171 /// A lock which guards printing to stderr. 172 std::mutex ErrsLock; 173 174 /// A container for input source file buffers. 175 std::mutex LoadedSourceFilesLock; 176 std::vector<std::pair<std::string, std::unique_ptr<MemoryBuffer>>> 177 LoadedSourceFiles; 178 179 /// Whitelist from -name-whitelist to be used for filtering. 180 std::unique_ptr<SpecialCaseList> NameWhitelist; 181 }; 182 } 183 184 static std::string getErrorString(const Twine &Message, StringRef Whence, 185 bool Warning) { 186 std::string Str = (Warning ? "warning" : "error"); 187 Str += ": "; 188 if (!Whence.empty()) 189 Str += Whence.str() + ": "; 190 Str += Message.str() + "\n"; 191 return Str; 192 } 193 194 void CodeCoverageTool::error(const Twine &Message, StringRef Whence) { 195 std::unique_lock<std::mutex> Guard{ErrsLock}; 196 ViewOpts.colored_ostream(errs(), raw_ostream::RED) 197 << getErrorString(Message, Whence, false); 198 } 199 200 void CodeCoverageTool::warning(const Twine &Message, StringRef Whence) { 201 std::unique_lock<std::mutex> Guard{ErrsLock}; 202 ViewOpts.colored_ostream(errs(), raw_ostream::RED) 203 << getErrorString(Message, Whence, true); 204 } 205 206 void CodeCoverageTool::addCollectedPath(const std::string &Path) { 207 SmallString<128> EffectivePath(Path); 208 if (std::error_code EC = sys::fs::make_absolute(EffectivePath)) { 209 error(EC.message(), Path); 210 return; 211 } 212 sys::path::remove_dots(EffectivePath, /*remove_dot_dots=*/true); 213 if (!IgnoreFilenameFilters.matchesFilename(EffectivePath)) 214 SourceFiles.emplace_back(EffectivePath.str()); 215 HadSourceFiles = !SourceFiles.empty(); 216 } 217 218 void CodeCoverageTool::collectPaths(const std::string &Path) { 219 llvm::sys::fs::file_status Status; 220 llvm::sys::fs::status(Path, Status); 221 if (!llvm::sys::fs::exists(Status)) { 222 if (PathRemapping) 223 addCollectedPath(Path); 224 else 225 warning("Source file doesn't exist, proceeded by ignoring it.", Path); 226 return; 227 } 228 229 if (llvm::sys::fs::is_regular_file(Status)) { 230 addCollectedPath(Path); 231 return; 232 } 233 234 if (llvm::sys::fs::is_directory(Status)) { 235 std::error_code EC; 236 for (llvm::sys::fs::recursive_directory_iterator F(Path, EC), E; 237 F != E; F.increment(EC)) { 238 239 auto Status = F->status(); 240 if (!Status) { 241 warning(Status.getError().message(), F->path()); 242 continue; 243 } 244 245 if (Status->type() == llvm::sys::fs::file_type::regular_file) 246 addCollectedPath(F->path()); 247 } 248 } 249 } 250 251 Optional<sys::fs::file_status> 252 CodeCoverageTool::getFileStatus(StringRef FilePath) { 253 auto It = FileStatusCache.try_emplace(FilePath); 254 auto &CachedStatus = It.first->getValue(); 255 if (!It.second) 256 return CachedStatus; 257 258 sys::fs::file_status Status; 259 if (!sys::fs::status(FilePath, Status)) 260 CachedStatus = Status; 261 return CachedStatus; 262 } 263 264 bool CodeCoverageTool::isEquivalentFile(StringRef FilePath1, 265 StringRef FilePath2) { 266 auto Status1 = getFileStatus(FilePath1); 267 auto Status2 = getFileStatus(FilePath2); 268 return Status1.hasValue() && Status2.hasValue() && 269 sys::fs::equivalent(Status1.getValue(), Status2.getValue()); 270 } 271 272 ErrorOr<const MemoryBuffer &> 273 CodeCoverageTool::getSourceFile(StringRef SourceFile) { 274 // If we've remapped filenames, look up the real location for this file. 275 std::unique_lock<std::mutex> Guard{LoadedSourceFilesLock}; 276 if (!RemappedFilenames.empty()) { 277 auto Loc = RemappedFilenames.find(SourceFile); 278 if (Loc != RemappedFilenames.end()) 279 SourceFile = Loc->second; 280 } 281 for (const auto &Files : LoadedSourceFiles) 282 if (isEquivalentFile(SourceFile, Files.first)) 283 return *Files.second; 284 auto Buffer = MemoryBuffer::getFile(SourceFile); 285 if (auto EC = Buffer.getError()) { 286 error(EC.message(), SourceFile); 287 return EC; 288 } 289 LoadedSourceFiles.emplace_back(std::string(SourceFile), 290 std::move(Buffer.get())); 291 return *LoadedSourceFiles.back().second; 292 } 293 294 void CodeCoverageTool::attachExpansionSubViews( 295 SourceCoverageView &View, ArrayRef<ExpansionRecord> Expansions, 296 const CoverageMapping &Coverage) { 297 if (!ViewOpts.ShowExpandedRegions) 298 return; 299 for (const auto &Expansion : Expansions) { 300 auto ExpansionCoverage = Coverage.getCoverageForExpansion(Expansion); 301 if (ExpansionCoverage.empty()) 302 continue; 303 auto SourceBuffer = getSourceFile(ExpansionCoverage.getFilename()); 304 if (!SourceBuffer) 305 continue; 306 307 auto SubViewBranches = ExpansionCoverage.getBranches(); 308 auto SubViewExpansions = ExpansionCoverage.getExpansions(); 309 auto SubView = 310 SourceCoverageView::create(Expansion.Function.Name, SourceBuffer.get(), 311 ViewOpts, std::move(ExpansionCoverage)); 312 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage); 313 attachBranchSubViews(*SubView, Expansion.Function.Name, SubViewBranches, 314 SourceBuffer.get(), ExpansionCoverage); 315 View.addExpansion(Expansion.Region, std::move(SubView)); 316 } 317 } 318 319 void CodeCoverageTool::attachBranchSubViews(SourceCoverageView &View, 320 StringRef SourceName, 321 ArrayRef<CountedRegion> Branches, 322 const MemoryBuffer &File, 323 CoverageData &CoverageInfo) { 324 if (!ViewOpts.ShowBranchCounts && !ViewOpts.ShowBranchPercents) 325 return; 326 327 const auto *NextBranch = Branches.begin(); 328 const auto *EndBranch = Branches.end(); 329 330 // Group branches that have the same line number into the same subview. 331 while (NextBranch != EndBranch) { 332 std::vector<CountedRegion> ViewBranches; 333 unsigned CurrentLine = NextBranch->LineStart; 334 335 while (NextBranch != EndBranch && CurrentLine == NextBranch->LineStart) 336 ViewBranches.push_back(*NextBranch++); 337 338 if (!ViewBranches.empty()) { 339 auto SubView = SourceCoverageView::create(SourceName, File, ViewOpts, 340 std::move(CoverageInfo)); 341 View.addBranch(CurrentLine, ViewBranches, std::move(SubView)); 342 } 343 } 344 } 345 346 std::unique_ptr<SourceCoverageView> 347 CodeCoverageTool::createFunctionView(const FunctionRecord &Function, 348 const CoverageMapping &Coverage) { 349 auto FunctionCoverage = Coverage.getCoverageForFunction(Function); 350 if (FunctionCoverage.empty()) 351 return nullptr; 352 auto SourceBuffer = getSourceFile(FunctionCoverage.getFilename()); 353 if (!SourceBuffer) 354 return nullptr; 355 356 auto Branches = FunctionCoverage.getBranches(); 357 auto Expansions = FunctionCoverage.getExpansions(); 358 auto View = SourceCoverageView::create(DC.demangle(Function.Name), 359 SourceBuffer.get(), ViewOpts, 360 std::move(FunctionCoverage)); 361 attachExpansionSubViews(*View, Expansions, Coverage); 362 attachBranchSubViews(*View, DC.demangle(Function.Name), Branches, 363 SourceBuffer.get(), FunctionCoverage); 364 365 return View; 366 } 367 368 std::unique_ptr<SourceCoverageView> 369 CodeCoverageTool::createSourceFileView(StringRef SourceFile, 370 const CoverageMapping &Coverage) { 371 auto SourceBuffer = getSourceFile(SourceFile); 372 if (!SourceBuffer) 373 return nullptr; 374 auto FileCoverage = Coverage.getCoverageForFile(SourceFile); 375 if (FileCoverage.empty()) 376 return nullptr; 377 378 auto Branches = FileCoverage.getBranches(); 379 auto Expansions = FileCoverage.getExpansions(); 380 auto View = SourceCoverageView::create(SourceFile, SourceBuffer.get(), 381 ViewOpts, std::move(FileCoverage)); 382 attachExpansionSubViews(*View, Expansions, Coverage); 383 attachBranchSubViews(*View, SourceFile, Branches, SourceBuffer.get(), 384 FileCoverage); 385 if (!ViewOpts.ShowFunctionInstantiations) 386 return View; 387 388 for (const auto &Group : Coverage.getInstantiationGroups(SourceFile)) { 389 // Skip functions which have a single instantiation. 390 if (Group.size() < 2) 391 continue; 392 393 for (const FunctionRecord *Function : Group.getInstantiations()) { 394 std::unique_ptr<SourceCoverageView> SubView{nullptr}; 395 396 StringRef Funcname = DC.demangle(Function->Name); 397 398 if (Function->ExecutionCount > 0) { 399 auto SubViewCoverage = Coverage.getCoverageForFunction(*Function); 400 auto SubViewExpansions = SubViewCoverage.getExpansions(); 401 auto SubViewBranches = SubViewCoverage.getBranches(); 402 SubView = SourceCoverageView::create( 403 Funcname, SourceBuffer.get(), ViewOpts, std::move(SubViewCoverage)); 404 attachExpansionSubViews(*SubView, SubViewExpansions, Coverage); 405 attachBranchSubViews(*SubView, SourceFile, SubViewBranches, 406 SourceBuffer.get(), SubViewCoverage); 407 } 408 409 unsigned FileID = Function->CountedRegions.front().FileID; 410 unsigned Line = 0; 411 for (const auto &CR : Function->CountedRegions) 412 if (CR.FileID == FileID) 413 Line = std::max(CR.LineEnd, Line); 414 View->addInstantiation(Funcname, Line, std::move(SubView)); 415 } 416 } 417 return View; 418 } 419 420 static bool modifiedTimeGT(StringRef LHS, StringRef RHS) { 421 sys::fs::file_status Status; 422 if (sys::fs::status(LHS, Status)) 423 return false; 424 auto LHSTime = Status.getLastModificationTime(); 425 if (sys::fs::status(RHS, Status)) 426 return false; 427 auto RHSTime = Status.getLastModificationTime(); 428 return LHSTime > RHSTime; 429 } 430 431 std::unique_ptr<CoverageMapping> CodeCoverageTool::load() { 432 for (StringRef ObjectFilename : ObjectFilenames) 433 if (modifiedTimeGT(ObjectFilename, PGOFilename)) 434 warning("profile data may be out of date - object is newer", 435 ObjectFilename); 436 auto CoverageOrErr = 437 CoverageMapping::load(ObjectFilenames, PGOFilename, CoverageArches); 438 if (Error E = CoverageOrErr.takeError()) { 439 error("Failed to load coverage: " + toString(std::move(E)), 440 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", ")); 441 return nullptr; 442 } 443 auto Coverage = std::move(CoverageOrErr.get()); 444 unsigned Mismatched = Coverage->getMismatchedCount(); 445 if (Mismatched) { 446 warning(Twine(Mismatched) + " functions have mismatched data"); 447 448 if (ViewOpts.Debug) { 449 for (const auto &HashMismatch : Coverage->getHashMismatches()) 450 errs() << "hash-mismatch: " 451 << "No profile record found for '" << HashMismatch.first << "'" 452 << " with hash = 0x" << Twine::utohexstr(HashMismatch.second) 453 << '\n'; 454 } 455 } 456 457 remapPathNames(*Coverage); 458 459 if (!SourceFiles.empty()) 460 removeUnmappedInputs(*Coverage); 461 462 demangleSymbols(*Coverage); 463 464 return Coverage; 465 } 466 467 void CodeCoverageTool::remapPathNames(const CoverageMapping &Coverage) { 468 if (!PathRemapping) 469 return; 470 471 // Convert remapping paths to native paths with trailing seperators. 472 auto nativeWithTrailing = [](StringRef Path) -> std::string { 473 if (Path.empty()) 474 return ""; 475 SmallString<128> NativePath; 476 sys::path::native(Path, NativePath); 477 sys::path::remove_dots(NativePath, true); 478 if (!NativePath.empty() && !sys::path::is_separator(NativePath.back())) 479 NativePath += sys::path::get_separator(); 480 return NativePath.c_str(); 481 }; 482 std::string RemapFrom = nativeWithTrailing(PathRemapping->first); 483 std::string RemapTo = nativeWithTrailing(PathRemapping->second); 484 485 // Create a mapping from coverage data file paths to local paths. 486 for (StringRef Filename : Coverage.getUniqueSourceFiles()) { 487 SmallString<128> NativeFilename; 488 sys::path::native(Filename, NativeFilename); 489 sys::path::remove_dots(NativeFilename, true); 490 if (NativeFilename.startswith(RemapFrom)) { 491 RemappedFilenames[Filename] = 492 RemapTo + NativeFilename.substr(RemapFrom.size()).str(); 493 } 494 } 495 496 // Convert input files from local paths to coverage data file paths. 497 StringMap<std::string> InvRemappedFilenames; 498 for (const auto &RemappedFilename : RemappedFilenames) 499 InvRemappedFilenames[RemappedFilename.getValue()] = 500 std::string(RemappedFilename.getKey()); 501 502 for (std::string &Filename : SourceFiles) { 503 SmallString<128> NativeFilename; 504 sys::path::native(Filename, NativeFilename); 505 auto CovFileName = InvRemappedFilenames.find(NativeFilename); 506 if (CovFileName != InvRemappedFilenames.end()) 507 Filename = CovFileName->second; 508 } 509 } 510 511 void CodeCoverageTool::removeUnmappedInputs(const CoverageMapping &Coverage) { 512 std::vector<StringRef> CoveredFiles = Coverage.getUniqueSourceFiles(); 513 514 // The user may have specified source files which aren't in the coverage 515 // mapping. Filter these files away. 516 llvm::erase_if(SourceFiles, [&](const std::string &SF) { 517 return !std::binary_search(CoveredFiles.begin(), CoveredFiles.end(), SF); 518 }); 519 } 520 521 void CodeCoverageTool::demangleSymbols(const CoverageMapping &Coverage) { 522 if (!ViewOpts.hasDemangler()) 523 return; 524 525 // Pass function names to the demangler in a temporary file. 526 int InputFD; 527 SmallString<256> InputPath; 528 std::error_code EC = 529 sys::fs::createTemporaryFile("demangle-in", "list", InputFD, InputPath); 530 if (EC) { 531 error(InputPath, EC.message()); 532 return; 533 } 534 ToolOutputFile InputTOF{InputPath, InputFD}; 535 536 unsigned NumSymbols = 0; 537 for (const auto &Function : Coverage.getCoveredFunctions()) { 538 InputTOF.os() << Function.Name << '\n'; 539 ++NumSymbols; 540 } 541 InputTOF.os().close(); 542 543 // Use another temporary file to store the demangler's output. 544 int OutputFD; 545 SmallString<256> OutputPath; 546 EC = sys::fs::createTemporaryFile("demangle-out", "list", OutputFD, 547 OutputPath); 548 if (EC) { 549 error(OutputPath, EC.message()); 550 return; 551 } 552 ToolOutputFile OutputTOF{OutputPath, OutputFD}; 553 OutputTOF.os().close(); 554 555 // Invoke the demangler. 556 std::vector<StringRef> ArgsV; 557 for (StringRef Arg : ViewOpts.DemanglerOpts) 558 ArgsV.push_back(Arg); 559 Optional<StringRef> Redirects[] = {InputPath.str(), OutputPath.str(), {""}}; 560 std::string ErrMsg; 561 int RC = sys::ExecuteAndWait(ViewOpts.DemanglerOpts[0], ArgsV, 562 /*env=*/None, Redirects, /*secondsToWait=*/0, 563 /*memoryLimit=*/0, &ErrMsg); 564 if (RC) { 565 error(ErrMsg, ViewOpts.DemanglerOpts[0]); 566 return; 567 } 568 569 // Parse the demangler's output. 570 auto BufOrError = MemoryBuffer::getFile(OutputPath); 571 if (!BufOrError) { 572 error(OutputPath, BufOrError.getError().message()); 573 return; 574 } 575 576 std::unique_ptr<MemoryBuffer> DemanglerBuf = std::move(*BufOrError); 577 578 SmallVector<StringRef, 8> Symbols; 579 StringRef DemanglerData = DemanglerBuf->getBuffer(); 580 DemanglerData.split(Symbols, '\n', /*MaxSplit=*/NumSymbols, 581 /*KeepEmpty=*/false); 582 if (Symbols.size() != NumSymbols) { 583 error("Demangler did not provide expected number of symbols"); 584 return; 585 } 586 587 // Cache the demangled names. 588 unsigned I = 0; 589 for (const auto &Function : Coverage.getCoveredFunctions()) 590 // On Windows, lines in the demangler's output file end with "\r\n". 591 // Splitting by '\n' keeps '\r's, so cut them now. 592 DC.DemangledNames[Function.Name] = std::string(Symbols[I++].rtrim()); 593 } 594 595 void CodeCoverageTool::writeSourceFileView(StringRef SourceFile, 596 CoverageMapping *Coverage, 597 CoveragePrinter *Printer, 598 bool ShowFilenames) { 599 auto View = createSourceFileView(SourceFile, *Coverage); 600 if (!View) { 601 warning("The file '" + SourceFile + "' isn't covered."); 602 return; 603 } 604 605 auto OSOrErr = Printer->createViewFile(SourceFile, /*InToplevel=*/false); 606 if (Error E = OSOrErr.takeError()) { 607 error("Could not create view file!", toString(std::move(E))); 608 return; 609 } 610 auto OS = std::move(OSOrErr.get()); 611 612 View->print(*OS.get(), /*Wholefile=*/true, 613 /*ShowSourceName=*/ShowFilenames, 614 /*ShowTitle=*/ViewOpts.hasOutputDirectory()); 615 Printer->closeViewFile(std::move(OS)); 616 } 617 618 int CodeCoverageTool::run(Command Cmd, int argc, const char **argv) { 619 cl::opt<std::string> CovFilename( 620 cl::Positional, cl::desc("Covered executable or object file.")); 621 622 cl::list<std::string> CovFilenames( 623 "object", cl::desc("Coverage executable or object file"), cl::ZeroOrMore); 624 625 cl::opt<bool> DebugDumpCollectedObjects( 626 "dump-collected-objects", cl::Optional, cl::Hidden, 627 cl::desc("Show the collected coverage object files")); 628 629 cl::list<std::string> InputSourceFiles( 630 cl::Positional, cl::desc("<Source files>"), cl::ZeroOrMore); 631 632 cl::opt<bool> DebugDumpCollectedPaths( 633 "dump-collected-paths", cl::Optional, cl::Hidden, 634 cl::desc("Show the collected paths to source files")); 635 636 cl::opt<std::string, true> PGOFilename( 637 "instr-profile", cl::Required, cl::location(this->PGOFilename), 638 cl::desc( 639 "File with the profile data obtained after an instrumented run")); 640 641 cl::list<std::string> Arches( 642 "arch", cl::desc("architectures of the coverage mapping binaries")); 643 644 cl::opt<bool> DebugDump("dump", cl::Optional, 645 cl::desc("Show internal debug dump")); 646 647 cl::opt<CoverageViewOptions::OutputFormat> Format( 648 "format", cl::desc("Output format for line-based coverage reports"), 649 cl::values(clEnumValN(CoverageViewOptions::OutputFormat::Text, "text", 650 "Text output"), 651 clEnumValN(CoverageViewOptions::OutputFormat::HTML, "html", 652 "HTML output"), 653 clEnumValN(CoverageViewOptions::OutputFormat::Lcov, "lcov", 654 "lcov tracefile output")), 655 cl::init(CoverageViewOptions::OutputFormat::Text)); 656 657 cl::opt<std::string> PathRemap( 658 "path-equivalence", cl::Optional, 659 cl::desc("<from>,<to> Map coverage data paths to local source file " 660 "paths")); 661 662 cl::OptionCategory FilteringCategory("Function filtering options"); 663 664 cl::list<std::string> NameFilters( 665 "name", cl::Optional, 666 cl::desc("Show code coverage only for functions with the given name"), 667 cl::ZeroOrMore, cl::cat(FilteringCategory)); 668 669 cl::list<std::string> NameFilterFiles( 670 "name-whitelist", cl::Optional, 671 cl::desc("Show code coverage only for functions listed in the given " 672 "file"), 673 cl::ZeroOrMore, cl::cat(FilteringCategory)); 674 675 cl::list<std::string> NameRegexFilters( 676 "name-regex", cl::Optional, 677 cl::desc("Show code coverage only for functions that match the given " 678 "regular expression"), 679 cl::ZeroOrMore, cl::cat(FilteringCategory)); 680 681 cl::list<std::string> IgnoreFilenameRegexFilters( 682 "ignore-filename-regex", cl::Optional, 683 cl::desc("Skip source code files with file paths that match the given " 684 "regular expression"), 685 cl::ZeroOrMore, cl::cat(FilteringCategory)); 686 687 cl::opt<double> RegionCoverageLtFilter( 688 "region-coverage-lt", cl::Optional, 689 cl::desc("Show code coverage only for functions with region coverage " 690 "less than the given threshold"), 691 cl::cat(FilteringCategory)); 692 693 cl::opt<double> RegionCoverageGtFilter( 694 "region-coverage-gt", cl::Optional, 695 cl::desc("Show code coverage only for functions with region coverage " 696 "greater than the given threshold"), 697 cl::cat(FilteringCategory)); 698 699 cl::opt<double> LineCoverageLtFilter( 700 "line-coverage-lt", cl::Optional, 701 cl::desc("Show code coverage only for functions with line coverage less " 702 "than the given threshold"), 703 cl::cat(FilteringCategory)); 704 705 cl::opt<double> LineCoverageGtFilter( 706 "line-coverage-gt", cl::Optional, 707 cl::desc("Show code coverage only for functions with line coverage " 708 "greater than the given threshold"), 709 cl::cat(FilteringCategory)); 710 711 cl::opt<cl::boolOrDefault> UseColor( 712 "use-color", cl::desc("Emit colored output (default=autodetect)"), 713 cl::init(cl::BOU_UNSET)); 714 715 cl::list<std::string> DemanglerOpts( 716 "Xdemangler", cl::desc("<demangler-path>|<demangler-option>")); 717 718 cl::opt<bool> RegionSummary( 719 "show-region-summary", cl::Optional, 720 cl::desc("Show region statistics in summary table"), 721 cl::init(true)); 722 723 cl::opt<bool> BranchSummary( 724 "show-branch-summary", cl::Optional, 725 cl::desc("Show branch condition statistics in summary table"), 726 cl::init(true)); 727 728 cl::opt<bool> InstantiationSummary( 729 "show-instantiation-summary", cl::Optional, 730 cl::desc("Show instantiation statistics in summary table")); 731 732 cl::opt<bool> SummaryOnly( 733 "summary-only", cl::Optional, 734 cl::desc("Export only summary information for each source file")); 735 736 cl::opt<unsigned> NumThreads( 737 "num-threads", cl::init(0), 738 cl::desc("Number of merge threads to use (default: autodetect)")); 739 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"), 740 cl::aliasopt(NumThreads)); 741 742 auto commandLineParser = [&, this](int argc, const char **argv) -> int { 743 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n"); 744 ViewOpts.Debug = DebugDump; 745 746 if (!CovFilename.empty()) 747 ObjectFilenames.emplace_back(CovFilename); 748 for (const std::string &Filename : CovFilenames) 749 ObjectFilenames.emplace_back(Filename); 750 if (ObjectFilenames.empty()) { 751 errs() << "No filenames specified!\n"; 752 ::exit(1); 753 } 754 755 if (DebugDumpCollectedObjects) { 756 for (StringRef OF : ObjectFilenames) 757 outs() << OF << '\n'; 758 ::exit(0); 759 } 760 761 ViewOpts.Format = Format; 762 switch (ViewOpts.Format) { 763 case CoverageViewOptions::OutputFormat::Text: 764 ViewOpts.Colors = UseColor == cl::BOU_UNSET 765 ? sys::Process::StandardOutHasColors() 766 : UseColor == cl::BOU_TRUE; 767 break; 768 case CoverageViewOptions::OutputFormat::HTML: 769 if (UseColor == cl::BOU_FALSE) 770 errs() << "Color output cannot be disabled when generating html.\n"; 771 ViewOpts.Colors = true; 772 break; 773 case CoverageViewOptions::OutputFormat::Lcov: 774 if (UseColor == cl::BOU_TRUE) 775 errs() << "Color output cannot be enabled when generating lcov.\n"; 776 ViewOpts.Colors = false; 777 break; 778 } 779 780 // If path-equivalence was given and is a comma seperated pair then set 781 // PathRemapping. 782 auto EquivPair = StringRef(PathRemap).split(','); 783 if (!(EquivPair.first.empty() && EquivPair.second.empty())) 784 PathRemapping = {std::string(EquivPair.first), 785 std::string(EquivPair.second)}; 786 787 // If a demangler is supplied, check if it exists and register it. 788 if (!DemanglerOpts.empty()) { 789 auto DemanglerPathOrErr = sys::findProgramByName(DemanglerOpts[0]); 790 if (!DemanglerPathOrErr) { 791 error("Could not find the demangler!", 792 DemanglerPathOrErr.getError().message()); 793 return 1; 794 } 795 DemanglerOpts[0] = *DemanglerPathOrErr; 796 ViewOpts.DemanglerOpts.swap(DemanglerOpts); 797 } 798 799 // Read in -name-whitelist files. 800 if (!NameFilterFiles.empty()) { 801 std::string SpecialCaseListErr; 802 NameWhitelist = SpecialCaseList::create( 803 NameFilterFiles, *vfs::getRealFileSystem(), SpecialCaseListErr); 804 if (!NameWhitelist) 805 error(SpecialCaseListErr); 806 } 807 808 // Create the function filters 809 if (!NameFilters.empty() || NameWhitelist || !NameRegexFilters.empty()) { 810 auto NameFilterer = std::make_unique<CoverageFilters>(); 811 for (const auto &Name : NameFilters) 812 NameFilterer->push_back(std::make_unique<NameCoverageFilter>(Name)); 813 if (NameWhitelist) 814 NameFilterer->push_back( 815 std::make_unique<NameWhitelistCoverageFilter>(*NameWhitelist)); 816 for (const auto &Regex : NameRegexFilters) 817 NameFilterer->push_back( 818 std::make_unique<NameRegexCoverageFilter>(Regex)); 819 Filters.push_back(std::move(NameFilterer)); 820 } 821 822 if (RegionCoverageLtFilter.getNumOccurrences() || 823 RegionCoverageGtFilter.getNumOccurrences() || 824 LineCoverageLtFilter.getNumOccurrences() || 825 LineCoverageGtFilter.getNumOccurrences()) { 826 auto StatFilterer = std::make_unique<CoverageFilters>(); 827 if (RegionCoverageLtFilter.getNumOccurrences()) 828 StatFilterer->push_back(std::make_unique<RegionCoverageFilter>( 829 RegionCoverageFilter::LessThan, RegionCoverageLtFilter)); 830 if (RegionCoverageGtFilter.getNumOccurrences()) 831 StatFilterer->push_back(std::make_unique<RegionCoverageFilter>( 832 RegionCoverageFilter::GreaterThan, RegionCoverageGtFilter)); 833 if (LineCoverageLtFilter.getNumOccurrences()) 834 StatFilterer->push_back(std::make_unique<LineCoverageFilter>( 835 LineCoverageFilter::LessThan, LineCoverageLtFilter)); 836 if (LineCoverageGtFilter.getNumOccurrences()) 837 StatFilterer->push_back(std::make_unique<LineCoverageFilter>( 838 RegionCoverageFilter::GreaterThan, LineCoverageGtFilter)); 839 Filters.push_back(std::move(StatFilterer)); 840 } 841 842 // Create the ignore filename filters. 843 for (const auto &RE : IgnoreFilenameRegexFilters) 844 IgnoreFilenameFilters.push_back( 845 std::make_unique<NameRegexCoverageFilter>(RE)); 846 847 if (!Arches.empty()) { 848 for (const std::string &Arch : Arches) { 849 if (Triple(Arch).getArch() == llvm::Triple::ArchType::UnknownArch) { 850 error("Unknown architecture: " + Arch); 851 return 1; 852 } 853 CoverageArches.emplace_back(Arch); 854 } 855 if (CoverageArches.size() != ObjectFilenames.size()) { 856 error("Number of architectures doesn't match the number of objects"); 857 return 1; 858 } 859 } 860 861 // IgnoreFilenameFilters are applied even when InputSourceFiles specified. 862 for (const std::string &File : InputSourceFiles) 863 collectPaths(File); 864 865 if (DebugDumpCollectedPaths) { 866 for (const std::string &SF : SourceFiles) 867 outs() << SF << '\n'; 868 ::exit(0); 869 } 870 871 ViewOpts.ShowBranchSummary = BranchSummary; 872 ViewOpts.ShowRegionSummary = RegionSummary; 873 ViewOpts.ShowInstantiationSummary = InstantiationSummary; 874 ViewOpts.ExportSummaryOnly = SummaryOnly; 875 ViewOpts.NumThreads = NumThreads; 876 877 return 0; 878 }; 879 880 switch (Cmd) { 881 case Show: 882 return doShow(argc, argv, commandLineParser); 883 case Report: 884 return doReport(argc, argv, commandLineParser); 885 case Export: 886 return doExport(argc, argv, commandLineParser); 887 } 888 return 0; 889 } 890 891 int CodeCoverageTool::doShow(int argc, const char **argv, 892 CommandLineParserType commandLineParser) { 893 894 cl::OptionCategory ViewCategory("Viewing options"); 895 896 cl::opt<bool> ShowLineExecutionCounts( 897 "show-line-counts", cl::Optional, 898 cl::desc("Show the execution counts for each line"), cl::init(true), 899 cl::cat(ViewCategory)); 900 901 cl::opt<bool> ShowRegions( 902 "show-regions", cl::Optional, 903 cl::desc("Show the execution counts for each region"), 904 cl::cat(ViewCategory)); 905 906 cl::opt<CoverageViewOptions::BranchOutputType> ShowBranches( 907 "show-branches", cl::Optional, 908 cl::desc("Show coverage for branch conditions"), cl::cat(ViewCategory), 909 cl::values(clEnumValN(CoverageViewOptions::BranchOutputType::Count, 910 "count", "Show True/False counts"), 911 clEnumValN(CoverageViewOptions::BranchOutputType::Percent, 912 "percent", "Show True/False percent")), 913 cl::init(CoverageViewOptions::BranchOutputType::Off)); 914 915 cl::opt<bool> ShowBestLineRegionsCounts( 916 "show-line-counts-or-regions", cl::Optional, 917 cl::desc("Show the execution counts for each line, or the execution " 918 "counts for each region on lines that have multiple regions"), 919 cl::cat(ViewCategory)); 920 921 cl::opt<bool> ShowExpansions("show-expansions", cl::Optional, 922 cl::desc("Show expanded source regions"), 923 cl::cat(ViewCategory)); 924 925 cl::opt<bool> ShowInstantiations("show-instantiations", cl::Optional, 926 cl::desc("Show function instantiations"), 927 cl::init(true), cl::cat(ViewCategory)); 928 929 cl::opt<std::string> ShowOutputDirectory( 930 "output-dir", cl::init(""), 931 cl::desc("Directory in which coverage information is written out")); 932 cl::alias ShowOutputDirectoryA("o", cl::desc("Alias for --output-dir"), 933 cl::aliasopt(ShowOutputDirectory)); 934 935 cl::opt<uint32_t> TabSize( 936 "tab-size", cl::init(2), 937 cl::desc( 938 "Set tab expansion size for html coverage reports (default = 2)")); 939 940 cl::opt<std::string> ProjectTitle( 941 "project-title", cl::Optional, 942 cl::desc("Set project title for the coverage report")); 943 944 auto Err = commandLineParser(argc, argv); 945 if (Err) 946 return Err; 947 948 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) { 949 error("Lcov format should be used with 'llvm-cov export'."); 950 return 1; 951 } 952 953 ViewOpts.ShowLineNumbers = true; 954 ViewOpts.ShowLineStats = ShowLineExecutionCounts.getNumOccurrences() != 0 || 955 !ShowRegions || ShowBestLineRegionsCounts; 956 ViewOpts.ShowRegionMarkers = ShowRegions || ShowBestLineRegionsCounts; 957 ViewOpts.ShowExpandedRegions = ShowExpansions; 958 ViewOpts.ShowBranchCounts = 959 ShowBranches == CoverageViewOptions::BranchOutputType::Count; 960 ViewOpts.ShowBranchPercents = 961 ShowBranches == CoverageViewOptions::BranchOutputType::Percent; 962 ViewOpts.ShowFunctionInstantiations = ShowInstantiations; 963 ViewOpts.ShowOutputDirectory = ShowOutputDirectory; 964 ViewOpts.TabSize = TabSize; 965 ViewOpts.ProjectTitle = ProjectTitle; 966 967 if (ViewOpts.hasOutputDirectory()) { 968 if (auto E = sys::fs::create_directories(ViewOpts.ShowOutputDirectory)) { 969 error("Could not create output directory!", E.message()); 970 return 1; 971 } 972 } 973 974 sys::fs::file_status Status; 975 if (std::error_code EC = sys::fs::status(PGOFilename, Status)) { 976 error("Could not read profile data!", EC.message()); 977 return 1; 978 } 979 980 auto ModifiedTime = Status.getLastModificationTime(); 981 std::string ModifiedTimeStr = to_string(ModifiedTime); 982 size_t found = ModifiedTimeStr.rfind(':'); 983 ViewOpts.CreatedTimeStr = (found != std::string::npos) 984 ? "Created: " + ModifiedTimeStr.substr(0, found) 985 : "Created: " + ModifiedTimeStr; 986 987 auto Coverage = load(); 988 if (!Coverage) 989 return 1; 990 991 auto Printer = CoveragePrinter::create(ViewOpts); 992 993 if (SourceFiles.empty() && !HadSourceFiles) 994 // Get the source files from the function coverage mapping. 995 for (StringRef Filename : Coverage->getUniqueSourceFiles()) { 996 if (!IgnoreFilenameFilters.matchesFilename(Filename)) 997 SourceFiles.push_back(std::string(Filename)); 998 } 999 1000 // Create an index out of the source files. 1001 if (ViewOpts.hasOutputDirectory()) { 1002 if (Error E = Printer->createIndexFile(SourceFiles, *Coverage, Filters)) { 1003 error("Could not create index file!", toString(std::move(E))); 1004 return 1; 1005 } 1006 } 1007 1008 if (!Filters.empty()) { 1009 // Build the map of filenames to functions. 1010 std::map<llvm::StringRef, std::vector<const FunctionRecord *>> 1011 FilenameFunctionMap; 1012 for (const auto &SourceFile : SourceFiles) 1013 for (const auto &Function : Coverage->getCoveredFunctions(SourceFile)) 1014 if (Filters.matches(*Coverage.get(), Function)) 1015 FilenameFunctionMap[SourceFile].push_back(&Function); 1016 1017 // Only print filter matching functions for each file. 1018 for (const auto &FileFunc : FilenameFunctionMap) { 1019 StringRef File = FileFunc.first; 1020 const auto &Functions = FileFunc.second; 1021 1022 auto OSOrErr = Printer->createViewFile(File, /*InToplevel=*/false); 1023 if (Error E = OSOrErr.takeError()) { 1024 error("Could not create view file!", toString(std::move(E))); 1025 return 1; 1026 } 1027 auto OS = std::move(OSOrErr.get()); 1028 1029 bool ShowTitle = ViewOpts.hasOutputDirectory(); 1030 for (const auto *Function : Functions) { 1031 auto FunctionView = createFunctionView(*Function, *Coverage); 1032 if (!FunctionView) { 1033 warning("Could not read coverage for '" + Function->Name + "'."); 1034 continue; 1035 } 1036 FunctionView->print(*OS.get(), /*WholeFile=*/false, 1037 /*ShowSourceName=*/true, ShowTitle); 1038 ShowTitle = false; 1039 } 1040 1041 Printer->closeViewFile(std::move(OS)); 1042 } 1043 return 0; 1044 } 1045 1046 // Show files 1047 bool ShowFilenames = 1048 (SourceFiles.size() != 1) || ViewOpts.hasOutputDirectory() || 1049 (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML); 1050 1051 ThreadPoolStrategy S = hardware_concurrency(ViewOpts.NumThreads); 1052 if (ViewOpts.NumThreads == 0) { 1053 // If NumThreads is not specified, create one thread for each input, up to 1054 // the number of hardware cores. 1055 S = heavyweight_hardware_concurrency(SourceFiles.size()); 1056 S.Limit = true; 1057 } 1058 1059 if (!ViewOpts.hasOutputDirectory() || S.ThreadsRequested == 1) { 1060 for (const std::string &SourceFile : SourceFiles) 1061 writeSourceFileView(SourceFile, Coverage.get(), Printer.get(), 1062 ShowFilenames); 1063 } else { 1064 // In -output-dir mode, it's safe to use multiple threads to print files. 1065 ThreadPool Pool(S); 1066 for (const std::string &SourceFile : SourceFiles) 1067 Pool.async(&CodeCoverageTool::writeSourceFileView, this, SourceFile, 1068 Coverage.get(), Printer.get(), ShowFilenames); 1069 Pool.wait(); 1070 } 1071 1072 return 0; 1073 } 1074 1075 int CodeCoverageTool::doReport(int argc, const char **argv, 1076 CommandLineParserType commandLineParser) { 1077 cl::opt<bool> ShowFunctionSummaries( 1078 "show-functions", cl::Optional, cl::init(false), 1079 cl::desc("Show coverage summaries for each function")); 1080 1081 auto Err = commandLineParser(argc, argv); 1082 if (Err) 1083 return Err; 1084 1085 if (ViewOpts.Format == CoverageViewOptions::OutputFormat::HTML) { 1086 error("HTML output for summary reports is not yet supported."); 1087 return 1; 1088 } else if (ViewOpts.Format == CoverageViewOptions::OutputFormat::Lcov) { 1089 error("Lcov format should be used with 'llvm-cov export'."); 1090 return 1; 1091 } 1092 1093 auto Coverage = load(); 1094 if (!Coverage) 1095 return 1; 1096 1097 CoverageReport Report(ViewOpts, *Coverage.get()); 1098 if (!ShowFunctionSummaries) { 1099 if (SourceFiles.empty()) 1100 Report.renderFileReports(llvm::outs(), IgnoreFilenameFilters); 1101 else 1102 Report.renderFileReports(llvm::outs(), SourceFiles); 1103 } else { 1104 if (SourceFiles.empty()) { 1105 error("Source files must be specified when -show-functions=true is " 1106 "specified"); 1107 return 1; 1108 } 1109 1110 Report.renderFunctionReports(SourceFiles, DC, llvm::outs()); 1111 } 1112 return 0; 1113 } 1114 1115 int CodeCoverageTool::doExport(int argc, const char **argv, 1116 CommandLineParserType commandLineParser) { 1117 1118 cl::OptionCategory ExportCategory("Exporting options"); 1119 1120 cl::opt<bool> SkipExpansions("skip-expansions", cl::Optional, 1121 cl::desc("Don't export expanded source regions"), 1122 cl::cat(ExportCategory)); 1123 1124 cl::opt<bool> SkipFunctions("skip-functions", cl::Optional, 1125 cl::desc("Don't export per-function data"), 1126 cl::cat(ExportCategory)); 1127 1128 auto Err = commandLineParser(argc, argv); 1129 if (Err) 1130 return Err; 1131 1132 ViewOpts.SkipExpansions = SkipExpansions; 1133 ViewOpts.SkipFunctions = SkipFunctions; 1134 1135 if (ViewOpts.Format != CoverageViewOptions::OutputFormat::Text && 1136 ViewOpts.Format != CoverageViewOptions::OutputFormat::Lcov) { 1137 error("Coverage data can only be exported as textual JSON or an " 1138 "lcov tracefile."); 1139 return 1; 1140 } 1141 1142 auto Coverage = load(); 1143 if (!Coverage) { 1144 error("Could not load coverage information"); 1145 return 1; 1146 } 1147 1148 std::unique_ptr<CoverageExporter> Exporter; 1149 1150 switch (ViewOpts.Format) { 1151 case CoverageViewOptions::OutputFormat::Text: 1152 Exporter = std::make_unique<CoverageExporterJson>(*Coverage.get(), 1153 ViewOpts, outs()); 1154 break; 1155 case CoverageViewOptions::OutputFormat::HTML: 1156 // Unreachable because we should have gracefully terminated with an error 1157 // above. 1158 llvm_unreachable("Export in HTML is not supported!"); 1159 case CoverageViewOptions::OutputFormat::Lcov: 1160 Exporter = std::make_unique<CoverageExporterLcov>(*Coverage.get(), 1161 ViewOpts, outs()); 1162 break; 1163 } 1164 1165 if (SourceFiles.empty()) 1166 Exporter->renderRoot(IgnoreFilenameFilters); 1167 else 1168 Exporter->renderRoot(SourceFiles); 1169 1170 return 0; 1171 } 1172 1173 int showMain(int argc, const char *argv[]) { 1174 CodeCoverageTool Tool; 1175 return Tool.run(CodeCoverageTool::Show, argc, argv); 1176 } 1177 1178 int reportMain(int argc, const char *argv[]) { 1179 CodeCoverageTool Tool; 1180 return Tool.run(CodeCoverageTool::Report, argc, argv); 1181 } 1182 1183 int exportMain(int argc, const char *argv[]) { 1184 CodeCoverageTool Tool; 1185 return Tool.run(CodeCoverageTool::Export, argc, argv); 1186 } 1187