xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-cov/gcov.cpp (revision 6be3386466ab79a84b48429ae66244f21526d3df)
1 //===- gcov.cpp - GCOV compatible LLVM coverage tool ----------------------===//
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 // llvm-cov is a command line tools to analyze and report coverage information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ProfileData/GCOV.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
19 #include <system_error>
20 using namespace llvm;
21 
22 static void reportCoverage(StringRef SourceFile, StringRef ObjectDir,
23                            const std::string &InputGCNO,
24                            const std::string &InputGCDA, bool DumpGCOV,
25                            const GCOV::Options &Options) {
26   SmallString<128> CoverageFileStem(ObjectDir);
27   if (CoverageFileStem.empty()) {
28     // If no directory was specified with -o, look next to the source file.
29     CoverageFileStem = sys::path::parent_path(SourceFile);
30     sys::path::append(CoverageFileStem, sys::path::stem(SourceFile));
31   } else if (sys::fs::is_directory(ObjectDir))
32     // A directory name was given. Use it and the source file name.
33     sys::path::append(CoverageFileStem, sys::path::stem(SourceFile));
34   else
35     // A file was given. Ignore the source file and look next to this file.
36     sys::path::replace_extension(CoverageFileStem, "");
37 
38   std::string GCNO = InputGCNO.empty()
39                          ? std::string(CoverageFileStem.str()) + ".gcno"
40                          : InputGCNO;
41   std::string GCDA = InputGCDA.empty()
42                          ? std::string(CoverageFileStem.str()) + ".gcda"
43                          : InputGCDA;
44   GCOVFile GF;
45 
46   ErrorOr<std::unique_ptr<MemoryBuffer>> GCNO_Buff =
47       MemoryBuffer::getFileOrSTDIN(GCNO);
48   if (std::error_code EC = GCNO_Buff.getError()) {
49     errs() << GCNO << ": " << EC.message() << "\n";
50     return;
51   }
52   GCOVBuffer GCNO_GB(GCNO_Buff.get().get());
53   if (!GF.readGCNO(GCNO_GB)) {
54     errs() << "Invalid .gcno File!\n";
55     return;
56   }
57 
58   ErrorOr<std::unique_ptr<MemoryBuffer>> GCDA_Buff =
59       MemoryBuffer::getFileOrSTDIN(GCDA);
60   if (std::error_code EC = GCDA_Buff.getError()) {
61     if (EC != errc::no_such_file_or_directory) {
62       errs() << GCDA << ": " << EC.message() << "\n";
63       return;
64     }
65     // Clear the filename to make it clear we didn't read anything.
66     GCDA = "-";
67   } else {
68     GCOVBuffer gcda_buf(GCDA_Buff.get().get());
69     if (!gcda_buf.readGCDAFormat())
70       errs() << GCDA << ":not a gcov data file\n";
71     else if (!GF.readGCDA(gcda_buf))
72       errs() << "Invalid .gcda File!\n";
73   }
74 
75   if (DumpGCOV)
76     GF.print(errs());
77 
78   FileInfo FI(Options);
79   GF.collectLineCounts(FI);
80   FI.print(llvm::outs(), SourceFile, GCNO, GCDA, GF);
81 }
82 
83 int gcovMain(int argc, const char *argv[]) {
84   cl::list<std::string> SourceFiles(cl::Positional, cl::OneOrMore,
85                                     cl::desc("SOURCEFILE"));
86 
87   cl::opt<bool> AllBlocks("a", cl::Grouping, cl::init(false),
88                           cl::desc("Display all basic blocks"));
89   cl::alias AllBlocksA("all-blocks", cl::aliasopt(AllBlocks));
90 
91   cl::opt<bool> BranchProb("b", cl::Grouping, cl::init(false),
92                            cl::desc("Display branch probabilities"));
93   cl::alias BranchProbA("branch-probabilities", cl::aliasopt(BranchProb));
94 
95   cl::opt<bool> BranchCount("c", cl::Grouping, cl::init(false),
96                             cl::desc("Display branch counts instead "
97                                      "of percentages (requires -b)"));
98   cl::alias BranchCountA("branch-counts", cl::aliasopt(BranchCount));
99 
100   cl::opt<bool> LongNames("l", cl::Grouping, cl::init(false),
101                           cl::desc("Prefix filenames with the main file"));
102   cl::alias LongNamesA("long-file-names", cl::aliasopt(LongNames));
103 
104   cl::opt<bool> FuncSummary("f", cl::Grouping, cl::init(false),
105                             cl::desc("Show coverage for each function"));
106   cl::alias FuncSummaryA("function-summaries", cl::aliasopt(FuncSummary));
107 
108   // Supported by gcov 4.9~8. gcov 9 (GCC r265587) removed --intermediate-format
109   // and -i was changed to mean --json-format. We consider this format still
110   // useful and support -i.
111   cl::opt<bool> Intermediate(
112       "intermediate-format", cl::init(false),
113       cl::desc("Output .gcov in intermediate text format"));
114   cl::alias IntermediateA("i", cl::desc("Alias for --intermediate-format"),
115                           cl::Grouping, cl::NotHidden,
116                           cl::aliasopt(Intermediate));
117 
118   cl::opt<bool> NoOutput("n", cl::Grouping, cl::init(false),
119                          cl::desc("Do not output any .gcov files"));
120   cl::alias NoOutputA("no-output", cl::aliasopt(NoOutput));
121 
122   cl::opt<std::string> ObjectDir(
123       "o", cl::value_desc("DIR|FILE"), cl::init(""),
124       cl::desc("Find objects in DIR or based on FILE's path"));
125   cl::alias ObjectDirA("object-directory", cl::aliasopt(ObjectDir));
126   cl::alias ObjectDirB("object-file", cl::aliasopt(ObjectDir));
127 
128   cl::opt<bool> PreservePaths("p", cl::Grouping, cl::init(false),
129                               cl::desc("Preserve path components"));
130   cl::alias PreservePathsA("preserve-paths", cl::aliasopt(PreservePaths));
131 
132   cl::opt<bool> UseStdout("t", cl::Grouping, cl::init(false),
133                           cl::desc("Print to stdout"));
134   cl::alias UseStdoutA("stdout", cl::aliasopt(UseStdout));
135 
136   cl::opt<bool> UncondBranch("u", cl::Grouping, cl::init(false),
137                              cl::desc("Display unconditional branch info "
138                                       "(requires -b)"));
139   cl::alias UncondBranchA("unconditional-branches", cl::aliasopt(UncondBranch));
140 
141   cl::opt<bool> HashFilenames("x", cl::Grouping, cl::init(false),
142                               cl::desc("Hash long pathnames"));
143   cl::alias HashFilenamesA("hash-filenames", cl::aliasopt(HashFilenames));
144 
145 
146   cl::OptionCategory DebugCat("Internal and debugging options");
147   cl::opt<bool> DumpGCOV("dump", cl::init(false), cl::cat(DebugCat),
148                          cl::desc("Dump the gcov file to stderr"));
149   cl::opt<std::string> InputGCNO("gcno", cl::cat(DebugCat), cl::init(""),
150                                  cl::desc("Override inferred gcno file"));
151   cl::opt<std::string> InputGCDA("gcda", cl::cat(DebugCat), cl::init(""),
152                                  cl::desc("Override inferred gcda file"));
153 
154   cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
155 
156   GCOV::Options Options(AllBlocks, BranchProb, BranchCount, FuncSummary,
157                         PreservePaths, UncondBranch, Intermediate, LongNames,
158                         NoOutput, UseStdout, HashFilenames);
159 
160   for (const auto &SourceFile : SourceFiles)
161     reportCoverage(SourceFile, ObjectDir, InputGCNO, InputGCDA, DumpGCOV,
162                    Options);
163   return 0;
164 }
165