1 //===-- sancov.cpp --------------------------------------------------------===//
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 // This file is a command-line tool for reading and analyzing sanitizer
9 // coverage.
10 //===----------------------------------------------------------------------===//
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCInstrAnalysis.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCTargetOptions.h"
25 #include "llvm/Object/Archive.h"
26 #include "llvm/Object/Binary.h"
27 #include "llvm/Object/COFF.h"
28 #include "llvm/Object/MachO.h"
29 #include "llvm/Object/ObjectFile.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Errc.h"
33 #include "llvm/Support/ErrorOr.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/InitLLVM.h"
36 #include "llvm/Support/JSON.h"
37 #include "llvm/Support/MD5.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Regex.h"
41 #include "llvm/Support/SHA1.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/SpecialCaseList.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/VirtualFileSystem.h"
47 #include "llvm/Support/YAMLParser.h"
48 #include "llvm/Support/raw_ostream.h"
49
50 #include <set>
51 #include <vector>
52
53 using namespace llvm;
54
55 namespace {
56
57 // --------- COMMAND LINE FLAGS ---------
58
59 enum ActionType {
60 CoveredFunctionsAction,
61 HtmlReportAction,
62 MergeAction,
63 NotCoveredFunctionsAction,
64 PrintAction,
65 PrintCovPointsAction,
66 StatsAction,
67 SymbolizeAction
68 };
69
70 cl::opt<ActionType> Action(
71 cl::desc("Action (required)"), cl::Required,
72 cl::values(
73 clEnumValN(PrintAction, "print", "Print coverage addresses"),
74 clEnumValN(PrintCovPointsAction, "print-coverage-pcs",
75 "Print coverage instrumentation points addresses."),
76 clEnumValN(CoveredFunctionsAction, "covered-functions",
77 "Print all covered funcions."),
78 clEnumValN(NotCoveredFunctionsAction, "not-covered-functions",
79 "Print all not covered funcions."),
80 clEnumValN(StatsAction, "print-coverage-stats",
81 "Print coverage statistics."),
82 clEnumValN(HtmlReportAction, "html-report",
83 "REMOVED. Use -symbolize & coverage-report-server.py."),
84 clEnumValN(SymbolizeAction, "symbolize",
85 "Produces a symbolized JSON report from binary report."),
86 clEnumValN(MergeAction, "merge", "Merges reports.")));
87
88 static cl::list<std::string>
89 ClInputFiles(cl::Positional, cl::OneOrMore,
90 cl::desc("<action> <binary files...> <.sancov files...> "
91 "<.symcov files...>"));
92
93 static cl::opt<bool> ClDemangle("demangle", cl::init(true),
94 cl::desc("Print demangled function name."));
95
96 static cl::opt<bool>
97 ClSkipDeadFiles("skip-dead-files", cl::init(true),
98 cl::desc("Do not list dead source files in reports."));
99
100 static cl::opt<std::string> ClStripPathPrefix(
101 "strip_path_prefix", cl::init(""),
102 cl::desc("Strip this prefix from file paths in reports."));
103
104 static cl::opt<std::string>
105 ClBlacklist("blacklist", cl::init(""),
106 cl::desc("Blacklist file (sanitizer blacklist format)."));
107
108 static cl::opt<bool> ClUseDefaultBlacklist(
109 "use_default_blacklist", cl::init(true), cl::Hidden,
110 cl::desc("Controls if default blacklist should be used."));
111
112 static const char *const DefaultBlacklistStr = "fun:__sanitizer_.*\n"
113 "src:/usr/include/.*\n"
114 "src:.*/libc\\+\\+/.*\n";
115
116 // --------- FORMAT SPECIFICATION ---------
117
118 struct FileHeader {
119 uint32_t Bitness;
120 uint32_t Magic;
121 };
122
123 static const uint32_t BinCoverageMagic = 0xC0BFFFFF;
124 static const uint32_t Bitness32 = 0xFFFFFF32;
125 static const uint32_t Bitness64 = 0xFFFFFF64;
126
127 static const Regex SancovFileRegex("(.*)\\.[0-9]+\\.sancov");
128 static const Regex SymcovFileRegex(".*\\.symcov");
129
130 // --------- MAIN DATASTRUCTURES ----------
131
132 // Contents of .sancov file: list of coverage point addresses that were
133 // executed.
134 struct RawCoverage {
RawCoverage__anon8452dda40111::RawCoverage135 explicit RawCoverage(std::unique_ptr<std::set<uint64_t>> Addrs)
136 : Addrs(std::move(Addrs)) {}
137
138 // Read binary .sancov file.
139 static ErrorOr<std::unique_ptr<RawCoverage>>
140 read(const std::string &FileName);
141
142 std::unique_ptr<std::set<uint64_t>> Addrs;
143 };
144
145 // Coverage point has an opaque Id and corresponds to multiple source locations.
146 struct CoveragePoint {
CoveragePoint__anon8452dda40111::CoveragePoint147 explicit CoveragePoint(const std::string &Id) : Id(Id) {}
148
149 std::string Id;
150 SmallVector<DILineInfo, 1> Locs;
151 };
152
153 // Symcov file content: set of covered Ids plus information about all available
154 // coverage points.
155 struct SymbolizedCoverage {
156 // Read json .symcov file.
157 static std::unique_ptr<SymbolizedCoverage> read(const std::string &InputFile);
158
159 std::set<std::string> CoveredIds;
160 std::string BinaryHash;
161 std::vector<CoveragePoint> Points;
162 };
163
164 struct CoverageStats {
165 size_t AllPoints;
166 size_t CovPoints;
167 size_t AllFns;
168 size_t CovFns;
169 };
170
171 // --------- ERROR HANDLING ---------
172
fail(const llvm::Twine & E)173 static void fail(const llvm::Twine &E) {
174 errs() << "ERROR: " << E << "\n";
175 exit(1);
176 }
177
failIf(bool B,const llvm::Twine & E)178 static void failIf(bool B, const llvm::Twine &E) {
179 if (B)
180 fail(E);
181 }
182
failIfError(std::error_code Error)183 static void failIfError(std::error_code Error) {
184 if (!Error)
185 return;
186 errs() << "ERROR: " << Error.message() << "(" << Error.value() << ")\n";
187 exit(1);
188 }
189
failIfError(const ErrorOr<T> & E)190 template <typename T> static void failIfError(const ErrorOr<T> &E) {
191 failIfError(E.getError());
192 }
193
failIfError(Error Err)194 static void failIfError(Error Err) {
195 if (Err) {
196 logAllUnhandledErrors(std::move(Err), errs(), "ERROR: ");
197 exit(1);
198 }
199 }
200
failIfError(Expected<T> & E)201 template <typename T> static void failIfError(Expected<T> &E) {
202 failIfError(E.takeError());
203 }
204
failIfNotEmpty(const llvm::Twine & E)205 static void failIfNotEmpty(const llvm::Twine &E) {
206 if (E.str().empty())
207 return;
208 fail(E);
209 }
210
211 template <typename T>
failIfEmpty(const std::unique_ptr<T> & Ptr,const std::string & Message)212 static void failIfEmpty(const std::unique_ptr<T> &Ptr,
213 const std::string &Message) {
214 if (Ptr.get())
215 return;
216 fail(Message);
217 }
218
219 // ----------- Coverage I/O ----------
220 template <typename T>
readInts(const char * Start,const char * End,std::set<uint64_t> * Ints)221 static void readInts(const char *Start, const char *End,
222 std::set<uint64_t> *Ints) {
223 const T *S = reinterpret_cast<const T *>(Start);
224 const T *E = reinterpret_cast<const T *>(End);
225 std::copy(S, E, std::inserter(*Ints, Ints->end()));
226 }
227
228 ErrorOr<std::unique_ptr<RawCoverage>>
read(const std::string & FileName)229 RawCoverage::read(const std::string &FileName) {
230 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
231 MemoryBuffer::getFile(FileName);
232 if (!BufOrErr)
233 return BufOrErr.getError();
234 std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
235 if (Buf->getBufferSize() < 8) {
236 errs() << "File too small (<8): " << Buf->getBufferSize() << '\n';
237 return make_error_code(errc::illegal_byte_sequence);
238 }
239 const FileHeader *Header =
240 reinterpret_cast<const FileHeader *>(Buf->getBufferStart());
241
242 if (Header->Magic != BinCoverageMagic) {
243 errs() << "Wrong magic: " << Header->Magic << '\n';
244 return make_error_code(errc::illegal_byte_sequence);
245 }
246
247 auto Addrs = std::make_unique<std::set<uint64_t>>();
248
249 switch (Header->Bitness) {
250 case Bitness64:
251 readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(),
252 Addrs.get());
253 break;
254 case Bitness32:
255 readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(),
256 Addrs.get());
257 break;
258 default:
259 errs() << "Unsupported bitness: " << Header->Bitness << '\n';
260 return make_error_code(errc::illegal_byte_sequence);
261 }
262
263 // Ignore slots that are zero, so a runtime implementation is not required
264 // to compactify the data.
265 Addrs->erase(0);
266
267 return std::unique_ptr<RawCoverage>(new RawCoverage(std::move(Addrs)));
268 }
269
270 // Print coverage addresses.
operator <<(raw_ostream & OS,const RawCoverage & CoverageData)271 raw_ostream &operator<<(raw_ostream &OS, const RawCoverage &CoverageData) {
272 for (auto Addr : *CoverageData.Addrs) {
273 OS << "0x";
274 OS.write_hex(Addr);
275 OS << "\n";
276 }
277 return OS;
278 }
279
operator <<(raw_ostream & OS,const CoverageStats & Stats)280 static raw_ostream &operator<<(raw_ostream &OS, const CoverageStats &Stats) {
281 OS << "all-edges: " << Stats.AllPoints << "\n";
282 OS << "cov-edges: " << Stats.CovPoints << "\n";
283 OS << "all-functions: " << Stats.AllFns << "\n";
284 OS << "cov-functions: " << Stats.CovFns << "\n";
285 return OS;
286 }
287
288 // Output symbolized information for coverage points in JSON.
289 // Format:
290 // {
291 // '<file_name>' : {
292 // '<function_name>' : {
293 // '<point_id'> : '<line_number>:'<column_number'.
294 // ....
295 // }
296 // }
297 // }
operator <<(json::OStream & W,const std::vector<CoveragePoint> & Points)298 static void operator<<(json::OStream &W,
299 const std::vector<CoveragePoint> &Points) {
300 // Group points by file.
301 std::map<std::string, std::vector<const CoveragePoint *>> PointsByFile;
302 for (const auto &Point : Points) {
303 for (const DILineInfo &Loc : Point.Locs) {
304 PointsByFile[Loc.FileName].push_back(&Point);
305 }
306 }
307
308 for (const auto &P : PointsByFile) {
309 std::string FileName = P.first;
310 std::map<std::string, std::vector<const CoveragePoint *>> PointsByFn;
311 for (auto PointPtr : P.second) {
312 for (const DILineInfo &Loc : PointPtr->Locs) {
313 PointsByFn[Loc.FunctionName].push_back(PointPtr);
314 }
315 }
316
317 W.attributeObject(P.first, [&] {
318 // Group points by function.
319 for (const auto &P : PointsByFn) {
320 std::string FunctionName = P.first;
321 std::set<std::string> WrittenIds;
322
323 W.attributeObject(FunctionName, [&] {
324 for (const CoveragePoint *Point : P.second) {
325 for (const auto &Loc : Point->Locs) {
326 if (Loc.FileName != FileName || Loc.FunctionName != FunctionName)
327 continue;
328 if (WrittenIds.find(Point->Id) != WrittenIds.end())
329 continue;
330
331 // Output <point_id> : "<line>:<col>".
332 WrittenIds.insert(Point->Id);
333 W.attribute(Point->Id,
334 (utostr(Loc.Line) + ":" + utostr(Loc.Column)));
335 }
336 }
337 });
338 }
339 });
340 }
341 }
342
operator <<(json::OStream & W,const SymbolizedCoverage & C)343 static void operator<<(json::OStream &W, const SymbolizedCoverage &C) {
344 W.object([&] {
345 W.attributeArray("covered-points", [&] {
346 for (const std::string &P : C.CoveredIds) {
347 W.value(P);
348 }
349 });
350 W.attribute("binary-hash", C.BinaryHash);
351 W.attributeObject("point-symbol-info", [&] { W << C.Points; });
352 });
353 }
354
parseScalarString(yaml::Node * N)355 static std::string parseScalarString(yaml::Node *N) {
356 SmallString<64> StringStorage;
357 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
358 failIf(!S, "expected string");
359 return std::string(S->getValue(StringStorage));
360 }
361
362 std::unique_ptr<SymbolizedCoverage>
read(const std::string & InputFile)363 SymbolizedCoverage::read(const std::string &InputFile) {
364 auto Coverage(std::make_unique<SymbolizedCoverage>());
365
366 std::map<std::string, CoveragePoint> Points;
367 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
368 MemoryBuffer::getFile(InputFile);
369 failIfError(BufOrErr);
370
371 SourceMgr SM;
372 yaml::Stream S(**BufOrErr, SM);
373
374 yaml::document_iterator DI = S.begin();
375 failIf(DI == S.end(), "empty document: " + InputFile);
376 yaml::Node *Root = DI->getRoot();
377 failIf(!Root, "expecting root node: " + InputFile);
378 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
379 failIf(!Top, "expecting mapping node: " + InputFile);
380
381 for (auto &KVNode : *Top) {
382 auto Key = parseScalarString(KVNode.getKey());
383
384 if (Key == "covered-points") {
385 yaml::SequenceNode *Points =
386 dyn_cast<yaml::SequenceNode>(KVNode.getValue());
387 failIf(!Points, "expected array: " + InputFile);
388
389 for (auto I = Points->begin(), E = Points->end(); I != E; ++I) {
390 Coverage->CoveredIds.insert(parseScalarString(&*I));
391 }
392 } else if (Key == "binary-hash") {
393 Coverage->BinaryHash = parseScalarString(KVNode.getValue());
394 } else if (Key == "point-symbol-info") {
395 yaml::MappingNode *PointSymbolInfo =
396 dyn_cast<yaml::MappingNode>(KVNode.getValue());
397 failIf(!PointSymbolInfo, "expected mapping node: " + InputFile);
398
399 for (auto &FileKVNode : *PointSymbolInfo) {
400 auto Filename = parseScalarString(FileKVNode.getKey());
401
402 yaml::MappingNode *FileInfo =
403 dyn_cast<yaml::MappingNode>(FileKVNode.getValue());
404 failIf(!FileInfo, "expected mapping node: " + InputFile);
405
406 for (auto &FunctionKVNode : *FileInfo) {
407 auto FunctionName = parseScalarString(FunctionKVNode.getKey());
408
409 yaml::MappingNode *FunctionInfo =
410 dyn_cast<yaml::MappingNode>(FunctionKVNode.getValue());
411 failIf(!FunctionInfo, "expected mapping node: " + InputFile);
412
413 for (auto &PointKVNode : *FunctionInfo) {
414 auto PointId = parseScalarString(PointKVNode.getKey());
415 auto Loc = parseScalarString(PointKVNode.getValue());
416
417 size_t ColonPos = Loc.find(':');
418 failIf(ColonPos == std::string::npos, "expected ':': " + InputFile);
419
420 auto LineStr = Loc.substr(0, ColonPos);
421 auto ColStr = Loc.substr(ColonPos + 1, Loc.size());
422
423 if (Points.find(PointId) == Points.end())
424 Points.insert(std::make_pair(PointId, CoveragePoint(PointId)));
425
426 DILineInfo LineInfo;
427 LineInfo.FileName = Filename;
428 LineInfo.FunctionName = FunctionName;
429 char *End;
430 LineInfo.Line = std::strtoul(LineStr.c_str(), &End, 10);
431 LineInfo.Column = std::strtoul(ColStr.c_str(), &End, 10);
432
433 CoveragePoint *CoveragePoint = &Points.find(PointId)->second;
434 CoveragePoint->Locs.push_back(LineInfo);
435 }
436 }
437 }
438 } else {
439 errs() << "Ignoring unknown key: " << Key << "\n";
440 }
441 }
442
443 for (auto &KV : Points) {
444 Coverage->Points.push_back(KV.second);
445 }
446
447 return Coverage;
448 }
449
450 // ---------- MAIN FUNCTIONALITY ----------
451
stripPathPrefix(std::string Path)452 std::string stripPathPrefix(std::string Path) {
453 if (ClStripPathPrefix.empty())
454 return Path;
455 size_t Pos = Path.find(ClStripPathPrefix);
456 if (Pos == std::string::npos)
457 return Path;
458 return Path.substr(Pos + ClStripPathPrefix.size());
459 }
460
createSymbolizer()461 static std::unique_ptr<symbolize::LLVMSymbolizer> createSymbolizer() {
462 symbolize::LLVMSymbolizer::Options SymbolizerOptions;
463 SymbolizerOptions.Demangle = ClDemangle;
464 SymbolizerOptions.UseSymbolTable = true;
465 return std::unique_ptr<symbolize::LLVMSymbolizer>(
466 new symbolize::LLVMSymbolizer(SymbolizerOptions));
467 }
468
normalizeFilename(const std::string & FileName)469 static std::string normalizeFilename(const std::string &FileName) {
470 SmallString<256> S(FileName);
471 sys::path::remove_dots(S, /* remove_dot_dot */ true);
472 return stripPathPrefix(sys::path::convert_to_slash(std::string(S)));
473 }
474
475 class Blacklists {
476 public:
Blacklists()477 Blacklists()
478 : DefaultBlacklist(createDefaultBlacklist()),
479 UserBlacklist(createUserBlacklist()) {}
480
isBlacklisted(const DILineInfo & I)481 bool isBlacklisted(const DILineInfo &I) {
482 if (DefaultBlacklist &&
483 DefaultBlacklist->inSection("sancov", "fun", I.FunctionName))
484 return true;
485 if (DefaultBlacklist &&
486 DefaultBlacklist->inSection("sancov", "src", I.FileName))
487 return true;
488 if (UserBlacklist &&
489 UserBlacklist->inSection("sancov", "fun", I.FunctionName))
490 return true;
491 if (UserBlacklist && UserBlacklist->inSection("sancov", "src", I.FileName))
492 return true;
493 return false;
494 }
495
496 private:
createDefaultBlacklist()497 static std::unique_ptr<SpecialCaseList> createDefaultBlacklist() {
498 if (!ClUseDefaultBlacklist)
499 return std::unique_ptr<SpecialCaseList>();
500 std::unique_ptr<MemoryBuffer> MB =
501 MemoryBuffer::getMemBuffer(DefaultBlacklistStr);
502 std::string Error;
503 auto Blacklist = SpecialCaseList::create(MB.get(), Error);
504 failIfNotEmpty(Error);
505 return Blacklist;
506 }
507
createUserBlacklist()508 static std::unique_ptr<SpecialCaseList> createUserBlacklist() {
509 if (ClBlacklist.empty())
510 return std::unique_ptr<SpecialCaseList>();
511
512 return SpecialCaseList::createOrDie({{ClBlacklist}},
513 *vfs::getRealFileSystem());
514 }
515 std::unique_ptr<SpecialCaseList> DefaultBlacklist;
516 std::unique_ptr<SpecialCaseList> UserBlacklist;
517 };
518
519 static std::vector<CoveragePoint>
getCoveragePoints(const std::string & ObjectFile,const std::set<uint64_t> & Addrs,const std::set<uint64_t> & CoveredAddrs)520 getCoveragePoints(const std::string &ObjectFile,
521 const std::set<uint64_t> &Addrs,
522 const std::set<uint64_t> &CoveredAddrs) {
523 std::vector<CoveragePoint> Result;
524 auto Symbolizer(createSymbolizer());
525 Blacklists B;
526
527 std::set<std::string> CoveredFiles;
528 if (ClSkipDeadFiles) {
529 for (auto Addr : CoveredAddrs) {
530 // TODO: it would be neccessary to set proper section index here.
531 // object::SectionedAddress::UndefSection works for only absolute
532 // addresses.
533 object::SectionedAddress ModuleAddress = {
534 Addr, object::SectionedAddress::UndefSection};
535
536 auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, ModuleAddress);
537 failIfError(LineInfo);
538 CoveredFiles.insert(LineInfo->FileName);
539 auto InliningInfo =
540 Symbolizer->symbolizeInlinedCode(ObjectFile, ModuleAddress);
541 failIfError(InliningInfo);
542 for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) {
543 auto FrameInfo = InliningInfo->getFrame(I);
544 CoveredFiles.insert(FrameInfo.FileName);
545 }
546 }
547 }
548
549 for (auto Addr : Addrs) {
550 std::set<DILineInfo> Infos; // deduplicate debug info.
551
552 // TODO: it would be neccessary to set proper section index here.
553 // object::SectionedAddress::UndefSection works for only absolute addresses.
554 object::SectionedAddress ModuleAddress = {
555 Addr, object::SectionedAddress::UndefSection};
556
557 auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, ModuleAddress);
558 failIfError(LineInfo);
559 if (ClSkipDeadFiles &&
560 CoveredFiles.find(LineInfo->FileName) == CoveredFiles.end())
561 continue;
562 LineInfo->FileName = normalizeFilename(LineInfo->FileName);
563 if (B.isBlacklisted(*LineInfo))
564 continue;
565
566 auto Id = utohexstr(Addr, true);
567 auto Point = CoveragePoint(Id);
568 Infos.insert(*LineInfo);
569 Point.Locs.push_back(*LineInfo);
570
571 auto InliningInfo =
572 Symbolizer->symbolizeInlinedCode(ObjectFile, ModuleAddress);
573 failIfError(InliningInfo);
574 for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) {
575 auto FrameInfo = InliningInfo->getFrame(I);
576 if (ClSkipDeadFiles &&
577 CoveredFiles.find(FrameInfo.FileName) == CoveredFiles.end())
578 continue;
579 FrameInfo.FileName = normalizeFilename(FrameInfo.FileName);
580 if (B.isBlacklisted(FrameInfo))
581 continue;
582 if (Infos.find(FrameInfo) == Infos.end()) {
583 Infos.insert(FrameInfo);
584 Point.Locs.push_back(FrameInfo);
585 }
586 }
587
588 Result.push_back(Point);
589 }
590
591 return Result;
592 }
593
isCoveragePointSymbol(StringRef Name)594 static bool isCoveragePointSymbol(StringRef Name) {
595 return Name == "__sanitizer_cov" || Name == "__sanitizer_cov_with_check" ||
596 Name == "__sanitizer_cov_trace_func_enter" ||
597 Name == "__sanitizer_cov_trace_pc_guard" ||
598 // Mac has '___' prefix
599 Name == "___sanitizer_cov" || Name == "___sanitizer_cov_with_check" ||
600 Name == "___sanitizer_cov_trace_func_enter" ||
601 Name == "___sanitizer_cov_trace_pc_guard";
602 }
603
604 // Locate __sanitizer_cov* function addresses inside the stubs table on MachO.
findMachOIndirectCovFunctions(const object::MachOObjectFile & O,std::set<uint64_t> * Result)605 static void findMachOIndirectCovFunctions(const object::MachOObjectFile &O,
606 std::set<uint64_t> *Result) {
607 MachO::dysymtab_command Dysymtab = O.getDysymtabLoadCommand();
608 MachO::symtab_command Symtab = O.getSymtabLoadCommand();
609
610 for (const auto &Load : O.load_commands()) {
611 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
612 MachO::segment_command_64 Seg = O.getSegment64LoadCommand(Load);
613 for (unsigned J = 0; J < Seg.nsects; ++J) {
614 MachO::section_64 Sec = O.getSection64(Load, J);
615
616 uint32_t SectionType = Sec.flags & MachO::SECTION_TYPE;
617 if (SectionType == MachO::S_SYMBOL_STUBS) {
618 uint32_t Stride = Sec.reserved2;
619 uint32_t Cnt = Sec.size / Stride;
620 uint32_t N = Sec.reserved1;
621 for (uint32_t J = 0; J < Cnt && N + J < Dysymtab.nindirectsyms; J++) {
622 uint32_t IndirectSymbol =
623 O.getIndirectSymbolTableEntry(Dysymtab, N + J);
624 uint64_t Addr = Sec.addr + J * Stride;
625 if (IndirectSymbol < Symtab.nsyms) {
626 object::SymbolRef Symbol = *(O.getSymbolByIndex(IndirectSymbol));
627 Expected<StringRef> Name = Symbol.getName();
628 failIfError(Name);
629 if (isCoveragePointSymbol(Name.get())) {
630 Result->insert(Addr);
631 }
632 }
633 }
634 }
635 }
636 }
637 if (Load.C.cmd == MachO::LC_SEGMENT) {
638 errs() << "ERROR: 32 bit MachO binaries not supported\n";
639 }
640 }
641 }
642
643 // Locate __sanitizer_cov* function addresses that are used for coverage
644 // reporting.
645 static std::set<uint64_t>
findSanitizerCovFunctions(const object::ObjectFile & O)646 findSanitizerCovFunctions(const object::ObjectFile &O) {
647 std::set<uint64_t> Result;
648
649 for (const object::SymbolRef &Symbol : O.symbols()) {
650 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
651 failIfError(AddressOrErr);
652 uint64_t Address = AddressOrErr.get();
653
654 Expected<StringRef> NameOrErr = Symbol.getName();
655 failIfError(NameOrErr);
656 StringRef Name = NameOrErr.get();
657
658 Expected<uint32_t> FlagsOrErr = Symbol.getFlags();
659 // TODO: Test this error.
660 failIfError(FlagsOrErr);
661 uint32_t Flags = FlagsOrErr.get();
662
663 if (!(Flags & object::BasicSymbolRef::SF_Undefined) &&
664 isCoveragePointSymbol(Name)) {
665 Result.insert(Address);
666 }
667 }
668
669 if (const auto *CO = dyn_cast<object::COFFObjectFile>(&O)) {
670 for (const object::ExportDirectoryEntryRef &Export :
671 CO->export_directories()) {
672 uint32_t RVA;
673 failIfError(Export.getExportRVA(RVA));
674
675 StringRef Name;
676 failIfError(Export.getSymbolName(Name));
677
678 if (isCoveragePointSymbol(Name))
679 Result.insert(CO->getImageBase() + RVA);
680 }
681 }
682
683 if (const auto *MO = dyn_cast<object::MachOObjectFile>(&O)) {
684 findMachOIndirectCovFunctions(*MO, &Result);
685 }
686
687 return Result;
688 }
689
getPreviousInstructionPc(uint64_t PC,Triple TheTriple)690 static uint64_t getPreviousInstructionPc(uint64_t PC,
691 Triple TheTriple) {
692 if (TheTriple.isARM()) {
693 return (PC - 3) & (~1);
694 } else if (TheTriple.isAArch64()) {
695 return PC - 4;
696 } else if (TheTriple.isMIPS()) {
697 return PC - 8;
698 } else {
699 return PC - 1;
700 }
701 }
702
703 // Locate addresses of all coverage points in a file. Coverage point
704 // is defined as the 'address of instruction following __sanitizer_cov
705 // call - 1'.
getObjectCoveragePoints(const object::ObjectFile & O,std::set<uint64_t> * Addrs)706 static void getObjectCoveragePoints(const object::ObjectFile &O,
707 std::set<uint64_t> *Addrs) {
708 Triple TheTriple("unknown-unknown-unknown");
709 TheTriple.setArch(Triple::ArchType(O.getArch()));
710 auto TripleName = TheTriple.getTriple();
711
712 std::string Error;
713 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
714 failIfNotEmpty(Error);
715
716 std::unique_ptr<const MCSubtargetInfo> STI(
717 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
718 failIfEmpty(STI, "no subtarget info for target " + TripleName);
719
720 std::unique_ptr<const MCRegisterInfo> MRI(
721 TheTarget->createMCRegInfo(TripleName));
722 failIfEmpty(MRI, "no register info for target " + TripleName);
723
724 MCTargetOptions MCOptions;
725 std::unique_ptr<const MCAsmInfo> AsmInfo(
726 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
727 failIfEmpty(AsmInfo, "no asm info for target " + TripleName);
728
729 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
730 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
731 std::unique_ptr<MCDisassembler> DisAsm(
732 TheTarget->createMCDisassembler(*STI, Ctx));
733 failIfEmpty(DisAsm, "no disassembler info for target " + TripleName);
734
735 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
736 failIfEmpty(MII, "no instruction info for target " + TripleName);
737
738 std::unique_ptr<const MCInstrAnalysis> MIA(
739 TheTarget->createMCInstrAnalysis(MII.get()));
740 failIfEmpty(MIA, "no instruction analysis info for target " + TripleName);
741
742 auto SanCovAddrs = findSanitizerCovFunctions(O);
743 if (SanCovAddrs.empty())
744 fail("__sanitizer_cov* functions not found");
745
746 for (object::SectionRef Section : O.sections()) {
747 if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same.
748 continue;
749 uint64_t SectionAddr = Section.getAddress();
750 uint64_t SectSize = Section.getSize();
751 if (!SectSize)
752 continue;
753
754 Expected<StringRef> BytesStr = Section.getContents();
755 failIfError(BytesStr);
756 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(*BytesStr);
757
758 for (uint64_t Index = 0, Size = 0; Index < Section.getSize();
759 Index += Size) {
760 MCInst Inst;
761 if (!DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
762 SectionAddr + Index, nulls())) {
763 if (Size == 0)
764 Size = 1;
765 continue;
766 }
767 uint64_t Addr = Index + SectionAddr;
768 // Sanitizer coverage uses the address of the next instruction - 1.
769 uint64_t CovPoint = getPreviousInstructionPc(Addr + Size, TheTriple);
770 uint64_t Target;
771 if (MIA->isCall(Inst) &&
772 MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target) &&
773 SanCovAddrs.find(Target) != SanCovAddrs.end())
774 Addrs->insert(CovPoint);
775 }
776 }
777 }
778
779 static void
visitObjectFiles(const object::Archive & A,function_ref<void (const object::ObjectFile &)> Fn)780 visitObjectFiles(const object::Archive &A,
781 function_ref<void(const object::ObjectFile &)> Fn) {
782 Error Err = Error::success();
783 for (auto &C : A.children(Err)) {
784 Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary();
785 failIfError(ChildOrErr);
786 if (auto *O = dyn_cast<object::ObjectFile>(&*ChildOrErr.get()))
787 Fn(*O);
788 else
789 failIfError(object::object_error::invalid_file_type);
790 }
791 failIfError(std::move(Err));
792 }
793
794 static void
visitObjectFiles(const std::string & FileName,function_ref<void (const object::ObjectFile &)> Fn)795 visitObjectFiles(const std::string &FileName,
796 function_ref<void(const object::ObjectFile &)> Fn) {
797 Expected<object::OwningBinary<object::Binary>> BinaryOrErr =
798 object::createBinary(FileName);
799 if (!BinaryOrErr)
800 failIfError(BinaryOrErr);
801
802 object::Binary &Binary = *BinaryOrErr.get().getBinary();
803 if (object::Archive *A = dyn_cast<object::Archive>(&Binary))
804 visitObjectFiles(*A, Fn);
805 else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(&Binary))
806 Fn(*O);
807 else
808 failIfError(object::object_error::invalid_file_type);
809 }
810
811 static std::set<uint64_t>
findSanitizerCovFunctions(const std::string & FileName)812 findSanitizerCovFunctions(const std::string &FileName) {
813 std::set<uint64_t> Result;
814 visitObjectFiles(FileName, [&](const object::ObjectFile &O) {
815 auto Addrs = findSanitizerCovFunctions(O);
816 Result.insert(Addrs.begin(), Addrs.end());
817 });
818 return Result;
819 }
820
821 // Locate addresses of all coverage points in a file. Coverage point
822 // is defined as the 'address of instruction following __sanitizer_cov
823 // call - 1'.
findCoveragePointAddrs(const std::string & FileName)824 static std::set<uint64_t> findCoveragePointAddrs(const std::string &FileName) {
825 std::set<uint64_t> Result;
826 visitObjectFiles(FileName, [&](const object::ObjectFile &O) {
827 getObjectCoveragePoints(O, &Result);
828 });
829 return Result;
830 }
831
printCovPoints(const std::string & ObjFile,raw_ostream & OS)832 static void printCovPoints(const std::string &ObjFile, raw_ostream &OS) {
833 for (uint64_t Addr : findCoveragePointAddrs(ObjFile)) {
834 OS << "0x";
835 OS.write_hex(Addr);
836 OS << "\n";
837 }
838 }
839
isCoverageFile(const std::string & FileName)840 static ErrorOr<bool> isCoverageFile(const std::string &FileName) {
841 auto ShortFileName = llvm::sys::path::filename(FileName);
842 if (!SancovFileRegex.match(ShortFileName))
843 return false;
844
845 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
846 MemoryBuffer::getFile(FileName);
847 if (!BufOrErr) {
848 errs() << "Warning: " << BufOrErr.getError().message() << "("
849 << BufOrErr.getError().value()
850 << "), filename: " << llvm::sys::path::filename(FileName) << "\n";
851 return BufOrErr.getError();
852 }
853 std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
854 if (Buf->getBufferSize() < 8) {
855 return false;
856 }
857 const FileHeader *Header =
858 reinterpret_cast<const FileHeader *>(Buf->getBufferStart());
859 return Header->Magic == BinCoverageMagic;
860 }
861
isSymbolizedCoverageFile(const std::string & FileName)862 static bool isSymbolizedCoverageFile(const std::string &FileName) {
863 auto ShortFileName = llvm::sys::path::filename(FileName);
864 return SymcovFileRegex.match(ShortFileName);
865 }
866
867 static std::unique_ptr<SymbolizedCoverage>
symbolize(const RawCoverage & Data,const std::string ObjectFile)868 symbolize(const RawCoverage &Data, const std::string ObjectFile) {
869 auto Coverage = std::make_unique<SymbolizedCoverage>();
870
871 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
872 MemoryBuffer::getFile(ObjectFile);
873 failIfError(BufOrErr);
874 SHA1 Hasher;
875 Hasher.update((*BufOrErr)->getBuffer());
876 Coverage->BinaryHash = toHex(Hasher.final());
877
878 Blacklists B;
879 auto Symbolizer(createSymbolizer());
880
881 for (uint64_t Addr : *Data.Addrs) {
882 // TODO: it would be neccessary to set proper section index here.
883 // object::SectionedAddress::UndefSection works for only absolute addresses.
884 auto LineInfo = Symbolizer->symbolizeCode(
885 ObjectFile, {Addr, object::SectionedAddress::UndefSection});
886 failIfError(LineInfo);
887 if (B.isBlacklisted(*LineInfo))
888 continue;
889
890 Coverage->CoveredIds.insert(utohexstr(Addr, true));
891 }
892
893 std::set<uint64_t> AllAddrs = findCoveragePointAddrs(ObjectFile);
894 if (!std::includes(AllAddrs.begin(), AllAddrs.end(), Data.Addrs->begin(),
895 Data.Addrs->end())) {
896 fail("Coverage points in binary and .sancov file do not match.");
897 }
898 Coverage->Points = getCoveragePoints(ObjectFile, AllAddrs, *Data.Addrs);
899 return Coverage;
900 }
901
902 struct FileFn {
operator <__anon8452dda40111::FileFn903 bool operator<(const FileFn &RHS) const {
904 return std::tie(FileName, FunctionName) <
905 std::tie(RHS.FileName, RHS.FunctionName);
906 }
907
908 std::string FileName;
909 std::string FunctionName;
910 };
911
912 static std::set<FileFn>
computeFunctions(const std::vector<CoveragePoint> & Points)913 computeFunctions(const std::vector<CoveragePoint> &Points) {
914 std::set<FileFn> Fns;
915 for (const auto &Point : Points) {
916 for (const auto &Loc : Point.Locs) {
917 Fns.insert(FileFn{Loc.FileName, Loc.FunctionName});
918 }
919 }
920 return Fns;
921 }
922
923 static std::set<FileFn>
computeNotCoveredFunctions(const SymbolizedCoverage & Coverage)924 computeNotCoveredFunctions(const SymbolizedCoverage &Coverage) {
925 auto Fns = computeFunctions(Coverage.Points);
926
927 for (const auto &Point : Coverage.Points) {
928 if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end())
929 continue;
930
931 for (const auto &Loc : Point.Locs) {
932 Fns.erase(FileFn{Loc.FileName, Loc.FunctionName});
933 }
934 }
935
936 return Fns;
937 }
938
939 static std::set<FileFn>
computeCoveredFunctions(const SymbolizedCoverage & Coverage)940 computeCoveredFunctions(const SymbolizedCoverage &Coverage) {
941 auto AllFns = computeFunctions(Coverage.Points);
942 std::set<FileFn> Result;
943
944 for (const auto &Point : Coverage.Points) {
945 if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end())
946 continue;
947
948 for (const auto &Loc : Point.Locs) {
949 Result.insert(FileFn{Loc.FileName, Loc.FunctionName});
950 }
951 }
952
953 return Result;
954 }
955
956 typedef std::map<FileFn, std::pair<uint32_t, uint32_t>> FunctionLocs;
957 // finds first location in a file for each function.
resolveFunctions(const SymbolizedCoverage & Coverage,const std::set<FileFn> & Fns)958 static FunctionLocs resolveFunctions(const SymbolizedCoverage &Coverage,
959 const std::set<FileFn> &Fns) {
960 FunctionLocs Result;
961 for (const auto &Point : Coverage.Points) {
962 for (const auto &Loc : Point.Locs) {
963 FileFn Fn = FileFn{Loc.FileName, Loc.FunctionName};
964 if (Fns.find(Fn) == Fns.end())
965 continue;
966
967 auto P = std::make_pair(Loc.Line, Loc.Column);
968 auto I = Result.find(Fn);
969 if (I == Result.end() || I->second > P) {
970 Result[Fn] = P;
971 }
972 }
973 }
974 return Result;
975 }
976
printFunctionLocs(const FunctionLocs & FnLocs,raw_ostream & OS)977 static void printFunctionLocs(const FunctionLocs &FnLocs, raw_ostream &OS) {
978 for (const auto &P : FnLocs) {
979 OS << stripPathPrefix(P.first.FileName) << ":" << P.second.first << " "
980 << P.first.FunctionName << "\n";
981 }
982 }
computeStats(const SymbolizedCoverage & Coverage)983 CoverageStats computeStats(const SymbolizedCoverage &Coverage) {
984 CoverageStats Stats = {Coverage.Points.size(), Coverage.CoveredIds.size(),
985 computeFunctions(Coverage.Points).size(),
986 computeCoveredFunctions(Coverage).size()};
987 return Stats;
988 }
989
990 // Print list of covered functions.
991 // Line format: <file_name>:<line> <function_name>
printCoveredFunctions(const SymbolizedCoverage & CovData,raw_ostream & OS)992 static void printCoveredFunctions(const SymbolizedCoverage &CovData,
993 raw_ostream &OS) {
994 auto CoveredFns = computeCoveredFunctions(CovData);
995 printFunctionLocs(resolveFunctions(CovData, CoveredFns), OS);
996 }
997
998 // Print list of not covered functions.
999 // Line format: <file_name>:<line> <function_name>
printNotCoveredFunctions(const SymbolizedCoverage & CovData,raw_ostream & OS)1000 static void printNotCoveredFunctions(const SymbolizedCoverage &CovData,
1001 raw_ostream &OS) {
1002 auto NotCoveredFns = computeNotCoveredFunctions(CovData);
1003 printFunctionLocs(resolveFunctions(CovData, NotCoveredFns), OS);
1004 }
1005
1006 // Read list of files and merges their coverage info.
readAndPrintRawCoverage(const std::vector<std::string> & FileNames,raw_ostream & OS)1007 static void readAndPrintRawCoverage(const std::vector<std::string> &FileNames,
1008 raw_ostream &OS) {
1009 std::vector<std::unique_ptr<RawCoverage>> Covs;
1010 for (const auto &FileName : FileNames) {
1011 auto Cov = RawCoverage::read(FileName);
1012 if (!Cov)
1013 continue;
1014 OS << *Cov.get();
1015 }
1016 }
1017
1018 static std::unique_ptr<SymbolizedCoverage>
merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> & Coverages)1019 merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> &Coverages) {
1020 if (Coverages.empty())
1021 return nullptr;
1022
1023 auto Result = std::make_unique<SymbolizedCoverage>();
1024
1025 for (size_t I = 0; I < Coverages.size(); ++I) {
1026 const SymbolizedCoverage &Coverage = *Coverages[I];
1027 std::string Prefix;
1028 if (Coverages.size() > 1) {
1029 // prefix is not needed when there's only one file.
1030 Prefix = utostr(I);
1031 }
1032
1033 for (const auto &Id : Coverage.CoveredIds) {
1034 Result->CoveredIds.insert(Prefix + Id);
1035 }
1036
1037 for (const auto &CovPoint : Coverage.Points) {
1038 CoveragePoint NewPoint(CovPoint);
1039 NewPoint.Id = Prefix + CovPoint.Id;
1040 Result->Points.push_back(NewPoint);
1041 }
1042 }
1043
1044 if (Coverages.size() == 1) {
1045 Result->BinaryHash = Coverages[0]->BinaryHash;
1046 }
1047
1048 return Result;
1049 }
1050
1051 static std::unique_ptr<SymbolizedCoverage>
readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames)1052 readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames) {
1053 std::vector<std::unique_ptr<SymbolizedCoverage>> Coverages;
1054
1055 {
1056 // Short name => file name.
1057 std::map<std::string, std::string> ObjFiles;
1058 std::string FirstObjFile;
1059 std::set<std::string> CovFiles;
1060
1061 // Partition input values into coverage/object files.
1062 for (const auto &FileName : FileNames) {
1063 if (isSymbolizedCoverageFile(FileName)) {
1064 Coverages.push_back(SymbolizedCoverage::read(FileName));
1065 }
1066
1067 auto ErrorOrIsCoverage = isCoverageFile(FileName);
1068 if (!ErrorOrIsCoverage)
1069 continue;
1070 if (ErrorOrIsCoverage.get()) {
1071 CovFiles.insert(FileName);
1072 } else {
1073 auto ShortFileName = llvm::sys::path::filename(FileName);
1074 if (ObjFiles.find(std::string(ShortFileName)) != ObjFiles.end()) {
1075 fail("Duplicate binary file with a short name: " + ShortFileName);
1076 }
1077
1078 ObjFiles[std::string(ShortFileName)] = FileName;
1079 if (FirstObjFile.empty())
1080 FirstObjFile = FileName;
1081 }
1082 }
1083
1084 SmallVector<StringRef, 2> Components;
1085
1086 // Object file => list of corresponding coverage file names.
1087 std::map<std::string, std::vector<std::string>> CoverageByObjFile;
1088 for (const auto &FileName : CovFiles) {
1089 auto ShortFileName = llvm::sys::path::filename(FileName);
1090 auto Ok = SancovFileRegex.match(ShortFileName, &Components);
1091 if (!Ok) {
1092 fail("Can't match coverage file name against "
1093 "<module_name>.<pid>.sancov pattern: " +
1094 FileName);
1095 }
1096
1097 auto Iter = ObjFiles.find(std::string(Components[1]));
1098 if (Iter == ObjFiles.end()) {
1099 fail("Object file for coverage not found: " + FileName);
1100 }
1101
1102 CoverageByObjFile[Iter->second].push_back(FileName);
1103 };
1104
1105 for (const auto &Pair : ObjFiles) {
1106 auto FileName = Pair.second;
1107 if (CoverageByObjFile.find(FileName) == CoverageByObjFile.end())
1108 errs() << "WARNING: No coverage file for " << FileName << "\n";
1109 }
1110
1111 // Read raw coverage and symbolize it.
1112 for (const auto &Pair : CoverageByObjFile) {
1113 if (findSanitizerCovFunctions(Pair.first).empty()) {
1114 errs()
1115 << "WARNING: Ignoring " << Pair.first
1116 << " and its coverage because __sanitizer_cov* functions were not "
1117 "found.\n";
1118 continue;
1119 }
1120
1121 for (const std::string &CoverageFile : Pair.second) {
1122 auto DataOrError = RawCoverage::read(CoverageFile);
1123 failIfError(DataOrError);
1124 Coverages.push_back(symbolize(*DataOrError.get(), Pair.first));
1125 }
1126 }
1127 }
1128
1129 return merge(Coverages);
1130 }
1131
1132 } // namespace
1133
main(int Argc,char ** Argv)1134 int main(int Argc, char **Argv) {
1135 llvm::InitLLVM X(Argc, Argv);
1136
1137 llvm::InitializeAllTargetInfos();
1138 llvm::InitializeAllTargetMCs();
1139 llvm::InitializeAllDisassemblers();
1140
1141 cl::ParseCommandLineOptions(Argc, Argv,
1142 "Sanitizer Coverage Processing Tool (sancov)\n\n"
1143 " This tool can extract various coverage-related information from: \n"
1144 " coverage-instrumented binary files, raw .sancov files and their "
1145 "symbolized .symcov version.\n"
1146 " Depending on chosen action the tool expects different input files:\n"
1147 " -print-coverage-pcs - coverage-instrumented binary files\n"
1148 " -print-coverage - .sancov files\n"
1149 " <other actions> - .sancov files & corresponding binary "
1150 "files, .symcov files\n"
1151 );
1152
1153 // -print doesn't need object files.
1154 if (Action == PrintAction) {
1155 readAndPrintRawCoverage(ClInputFiles, outs());
1156 return 0;
1157 } else if (Action == PrintCovPointsAction) {
1158 // -print-coverage-points doesn't need coverage files.
1159 for (const std::string &ObjFile : ClInputFiles) {
1160 printCovPoints(ObjFile, outs());
1161 }
1162 return 0;
1163 }
1164
1165 auto Coverage = readSymbolizeAndMergeCmdArguments(ClInputFiles);
1166 failIf(!Coverage, "No valid coverage files given.");
1167
1168 switch (Action) {
1169 case CoveredFunctionsAction: {
1170 printCoveredFunctions(*Coverage, outs());
1171 return 0;
1172 }
1173 case NotCoveredFunctionsAction: {
1174 printNotCoveredFunctions(*Coverage, outs());
1175 return 0;
1176 }
1177 case StatsAction: {
1178 outs() << computeStats(*Coverage);
1179 return 0;
1180 }
1181 case MergeAction:
1182 case SymbolizeAction: { // merge & symbolize are synonims.
1183 json::OStream W(outs(), 2);
1184 W << *Coverage;
1185 return 0;
1186 }
1187 case HtmlReportAction:
1188 errs() << "-html-report option is removed: "
1189 "use -symbolize & coverage-report-server.py instead\n";
1190 return 1;
1191 case PrintAction:
1192 case PrintCovPointsAction:
1193 llvm_unreachable("unsupported action");
1194 }
1195 }
1196