1 //===-- sancov.cpp --------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
8 // This file is a command-line tool for reading and analyzing sanitizer
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/Object/Archive.h"
25 #include "llvm/Object/Binary.h"
26 #include "llvm/Object/COFF.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Object/ObjectFile.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Errc.h"
32 #include "llvm/Support/ErrorOr.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/MD5.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Regex.h"
40 #include "llvm/Support/SHA1.h"
41 #include "llvm/Support/Signals.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/YAMLParser.h"
47 #include "llvm/Support/raw_ostream.h"
56 // --------- COMMAND LINE FLAGS ---------
59 CoveredFunctionsAction
,
62 NotCoveredFunctionsAction
,
69 cl::opt
<ActionType
> Action(
70 cl::desc("Action (required)"), cl::Required
,
72 clEnumValN(PrintAction
, "print", "Print coverage addresses"),
73 clEnumValN(PrintCovPointsAction
, "print-coverage-pcs",
74 "Print coverage instrumentation points addresses."),
75 clEnumValN(CoveredFunctionsAction
, "covered-functions",
76 "Print all covered funcions."),
77 clEnumValN(NotCoveredFunctionsAction
, "not-covered-functions",
78 "Print all not covered funcions."),
79 clEnumValN(StatsAction
, "print-coverage-stats",
80 "Print coverage statistics."),
81 clEnumValN(HtmlReportAction
, "html-report",
82 "REMOVED. Use -symbolize & coverage-report-server.py."),
83 clEnumValN(SymbolizeAction
, "symbolize",
84 "Produces a symbolized JSON report from binary report."),
85 clEnumValN(MergeAction
, "merge", "Merges reports.")));
87 static cl::list
<std::string
>
88 ClInputFiles(cl::Positional
, cl::OneOrMore
,
89 cl::desc("<action> <binary files...> <.sancov files...> "
90 "<.symcov files...>"));
92 static cl::opt
<bool> ClDemangle("demangle", cl::init(true),
93 cl::desc("Print demangled function name."));
96 ClSkipDeadFiles("skip-dead-files", cl::init(true),
97 cl::desc("Do not list dead source files in reports."));
99 static cl::opt
<std::string
> ClStripPathPrefix(
100 "strip_path_prefix", cl::init(""),
101 cl::desc("Strip this prefix from file paths in reports."));
103 static cl::opt
<std::string
>
104 ClBlacklist("blacklist", cl::init(""),
105 cl::desc("Blacklist file (sanitizer blacklist format)."));
107 static cl::opt
<bool> ClUseDefaultBlacklist(
108 "use_default_blacklist", cl::init(true), cl::Hidden
,
109 cl::desc("Controls if default blacklist should be used."));
111 static const char *const DefaultBlacklistStr
= "fun:__sanitizer_.*\n"
112 "src:/usr/include/.*\n"
113 "src:.*/libc\\+\\+/.*\n";
115 // --------- FORMAT SPECIFICATION ---------
122 static const uint32_t BinCoverageMagic
= 0xC0BFFFFF;
123 static const uint32_t Bitness32
= 0xFFFFFF32;
124 static const uint32_t Bitness64
= 0xFFFFFF64;
126 static Regex
SancovFileRegex("(.*)\\.[0-9]+\\.sancov");
127 static Regex
SymcovFileRegex(".*\\.symcov");
129 // --------- MAIN DATASTRUCTURES ----------
131 // Contents of .sancov file: list of coverage point addresses that were
134 explicit RawCoverage(std::unique_ptr
<std::set
<uint64_t>> Addrs
)
135 : Addrs(std::move(Addrs
)) {}
137 // Read binary .sancov file.
138 static ErrorOr
<std::unique_ptr
<RawCoverage
>>
139 read(const std::string
&FileName
);
141 std::unique_ptr
<std::set
<uint64_t>> Addrs
;
144 // Coverage point has an opaque Id and corresponds to multiple source locations.
145 struct CoveragePoint
{
146 explicit CoveragePoint(const std::string
&Id
) : Id(Id
) {}
149 SmallVector
<DILineInfo
, 1> Locs
;
152 // Symcov file content: set of covered Ids plus information about all available
154 struct SymbolizedCoverage
{
155 // Read json .symcov file.
156 static std::unique_ptr
<SymbolizedCoverage
> read(const std::string
&InputFile
);
158 std::set
<std::string
> CoveredIds
;
159 std::string BinaryHash
;
160 std::vector
<CoveragePoint
> Points
;
163 struct CoverageStats
{
170 // --------- ERROR HANDLING ---------
172 static void fail(const llvm::Twine
&E
) {
173 errs() << "ERROR: " << E
<< "\n";
177 static void failIf(bool B
, const llvm::Twine
&E
) {
182 static void failIfError(std::error_code Error
) {
185 errs() << "ERROR: " << Error
.message() << "(" << Error
.value() << ")\n";
189 template <typename T
> static void failIfError(const ErrorOr
<T
> &E
) {
190 failIfError(E
.getError());
193 static void failIfError(Error Err
) {
195 logAllUnhandledErrors(std::move(Err
), errs(), "ERROR: ");
200 template <typename T
> static void failIfError(Expected
<T
> &E
) {
201 failIfError(E
.takeError());
204 static void failIfNotEmpty(const llvm::Twine
&E
) {
210 template <typename T
>
211 static void failIfEmpty(const std::unique_ptr
<T
> &Ptr
,
212 const std::string
&Message
) {
218 // ----------- Coverage I/O ----------
219 template <typename T
>
220 static void readInts(const char *Start
, const char *End
,
221 std::set
<uint64_t> *Ints
) {
222 const T
*S
= reinterpret_cast<const T
*>(Start
);
223 const T
*E
= reinterpret_cast<const T
*>(End
);
224 std::copy(S
, E
, std::inserter(*Ints
, Ints
->end()));
227 ErrorOr
<std::unique_ptr
<RawCoverage
>>
228 RawCoverage::read(const std::string
&FileName
) {
229 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
230 MemoryBuffer::getFile(FileName
);
232 return BufOrErr
.getError();
233 std::unique_ptr
<MemoryBuffer
> Buf
= std::move(BufOrErr
.get());
234 if (Buf
->getBufferSize() < 8) {
235 errs() << "File too small (<8): " << Buf
->getBufferSize() << '\n';
236 return make_error_code(errc::illegal_byte_sequence
);
238 const FileHeader
*Header
=
239 reinterpret_cast<const FileHeader
*>(Buf
->getBufferStart());
241 if (Header
->Magic
!= BinCoverageMagic
) {
242 errs() << "Wrong magic: " << Header
->Magic
<< '\n';
243 return make_error_code(errc::illegal_byte_sequence
);
246 auto Addrs
= llvm::make_unique
<std::set
<uint64_t>>();
248 switch (Header
->Bitness
) {
250 readInts
<uint64_t>(Buf
->getBufferStart() + 8, Buf
->getBufferEnd(),
254 readInts
<uint32_t>(Buf
->getBufferStart() + 8, Buf
->getBufferEnd(),
258 errs() << "Unsupported bitness: " << Header
->Bitness
<< '\n';
259 return make_error_code(errc::illegal_byte_sequence
);
262 return std::unique_ptr
<RawCoverage
>(new RawCoverage(std::move(Addrs
)));
265 // Print coverage addresses.
266 raw_ostream
&operator<<(raw_ostream
&OS
, const RawCoverage
&CoverageData
) {
267 for (auto Addr
: *CoverageData
.Addrs
) {
275 static raw_ostream
&operator<<(raw_ostream
&OS
, const CoverageStats
&Stats
) {
276 OS
<< "all-edges: " << Stats
.AllPoints
<< "\n";
277 OS
<< "cov-edges: " << Stats
.CovPoints
<< "\n";
278 OS
<< "all-functions: " << Stats
.AllFns
<< "\n";
279 OS
<< "cov-functions: " << Stats
.CovFns
<< "\n";
283 // Helper for writing out JSON. Handles indents and commas using
284 // scope variables for objects and arrays.
287 JSONWriter(raw_ostream
&Out
) : OS(Out
) {}
288 JSONWriter(const JSONWriter
&) = delete;
289 ~JSONWriter() { OS
<< "\n"; }
291 void operator<<(StringRef S
) { printJSONStringLiteral(S
, OS
); }
293 // Helper RAII class to output JSON objects.
296 Object(JSONWriter
*W
, raw_ostream
&OS
) : W(W
), OS(OS
) {
300 Object(const Object
&) = delete;
308 void key(StringRef Key
) {
314 printJSONStringLiteral(Key
, OS
);
324 std::unique_ptr
<Object
> object() { return make_unique
<Object
>(this, OS
); }
326 // Helper RAII class to output JSON arrays.
329 Array(raw_ostream
&OS
) : OS(OS
) { OS
<< "["; }
330 Array(const Array
&) = delete;
331 ~Array() { OS
<< "]"; }
343 std::unique_ptr
<Array
> array() { return make_unique
<Array
>(OS
); }
346 void indent() { OS
.indent(Indent
* 2); }
348 static void printJSONStringLiteral(StringRef S
, raw_ostream
&OS
) {
349 if (S
.find('"') == std::string::npos
) {
350 OS
<< "\"" << S
<< "\"";
354 for (char Ch
: S
.bytes()) {
366 // Output symbolized information for coverage points in JSON.
370 // '<function_name>' : {
371 // '<point_id'> : '<line_number>:'<column_number'.
376 static void operator<<(JSONWriter
&W
,
377 const std::vector
<CoveragePoint
> &Points
) {
378 // Group points by file.
379 auto ByFile(W
.object());
380 std::map
<std::string
, std::vector
<const CoveragePoint
*>> PointsByFile
;
381 for (const auto &Point
: Points
) {
382 for (const DILineInfo
&Loc
: Point
.Locs
) {
383 PointsByFile
[Loc
.FileName
].push_back(&Point
);
387 for (const auto &P
: PointsByFile
) {
388 std::string FileName
= P
.first
;
389 ByFile
->key(FileName
);
391 // Group points by function.
392 auto ByFn(W
.object());
393 std::map
<std::string
, std::vector
<const CoveragePoint
*>> PointsByFn
;
394 for (auto PointPtr
: P
.second
) {
395 for (const DILineInfo
&Loc
: PointPtr
->Locs
) {
396 PointsByFn
[Loc
.FunctionName
].push_back(PointPtr
);
400 for (const auto &P
: PointsByFn
) {
401 std::string FunctionName
= P
.first
;
402 std::set
<std::string
> WrittenIds
;
404 ByFn
->key(FunctionName
);
406 // Output <point_id> : "<line>:<col>".
407 auto ById(W
.object());
408 for (const CoveragePoint
*Point
: P
.second
) {
409 for (const auto &Loc
: Point
->Locs
) {
410 if (Loc
.FileName
!= FileName
|| Loc
.FunctionName
!= FunctionName
)
412 if (WrittenIds
.find(Point
->Id
) != WrittenIds
.end())
415 WrittenIds
.insert(Point
->Id
);
416 ById
->key(Point
->Id
);
417 W
<< (utostr(Loc
.Line
) + ":" + utostr(Loc
.Column
));
424 static void operator<<(JSONWriter
&W
, const SymbolizedCoverage
&C
) {
428 O
->key("covered-points");
429 auto PointsArray(W
.array());
431 for (const auto &P
: C
.CoveredIds
) {
438 if (!C
.BinaryHash
.empty()) {
439 O
->key("binary-hash");
445 O
->key("point-symbol-info");
450 static std::string
parseScalarString(yaml::Node
*N
) {
451 SmallString
<64> StringStorage
;
452 yaml::ScalarNode
*S
= dyn_cast
<yaml::ScalarNode
>(N
);
453 failIf(!S
, "expected string");
454 return S
->getValue(StringStorage
);
457 std::unique_ptr
<SymbolizedCoverage
>
458 SymbolizedCoverage::read(const std::string
&InputFile
) {
459 auto Coverage(make_unique
<SymbolizedCoverage
>());
461 std::map
<std::string
, CoveragePoint
> Points
;
462 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
463 MemoryBuffer::getFile(InputFile
);
464 failIfError(BufOrErr
);
467 yaml::Stream
S(**BufOrErr
, SM
);
469 yaml::document_iterator DI
= S
.begin();
470 failIf(DI
== S
.end(), "empty document: " + InputFile
);
471 yaml::Node
*Root
= DI
->getRoot();
472 failIf(!Root
, "expecting root node: " + InputFile
);
473 yaml::MappingNode
*Top
= dyn_cast
<yaml::MappingNode
>(Root
);
474 failIf(!Top
, "expecting mapping node: " + InputFile
);
476 for (auto &KVNode
: *Top
) {
477 auto Key
= parseScalarString(KVNode
.getKey());
479 if (Key
== "covered-points") {
480 yaml::SequenceNode
*Points
=
481 dyn_cast
<yaml::SequenceNode
>(KVNode
.getValue());
482 failIf(!Points
, "expected array: " + InputFile
);
484 for (auto I
= Points
->begin(), E
= Points
->end(); I
!= E
; ++I
) {
485 Coverage
->CoveredIds
.insert(parseScalarString(&*I
));
487 } else if (Key
== "binary-hash") {
488 Coverage
->BinaryHash
= parseScalarString(KVNode
.getValue());
489 } else if (Key
== "point-symbol-info") {
490 yaml::MappingNode
*PointSymbolInfo
=
491 dyn_cast
<yaml::MappingNode
>(KVNode
.getValue());
492 failIf(!PointSymbolInfo
, "expected mapping node: " + InputFile
);
494 for (auto &FileKVNode
: *PointSymbolInfo
) {
495 auto Filename
= parseScalarString(FileKVNode
.getKey());
497 yaml::MappingNode
*FileInfo
=
498 dyn_cast
<yaml::MappingNode
>(FileKVNode
.getValue());
499 failIf(!FileInfo
, "expected mapping node: " + InputFile
);
501 for (auto &FunctionKVNode
: *FileInfo
) {
502 auto FunctionName
= parseScalarString(FunctionKVNode
.getKey());
504 yaml::MappingNode
*FunctionInfo
=
505 dyn_cast
<yaml::MappingNode
>(FunctionKVNode
.getValue());
506 failIf(!FunctionInfo
, "expected mapping node: " + InputFile
);
508 for (auto &PointKVNode
: *FunctionInfo
) {
509 auto PointId
= parseScalarString(PointKVNode
.getKey());
510 auto Loc
= parseScalarString(PointKVNode
.getValue());
512 size_t ColonPos
= Loc
.find(':');
513 failIf(ColonPos
== std::string::npos
, "expected ':': " + InputFile
);
515 auto LineStr
= Loc
.substr(0, ColonPos
);
516 auto ColStr
= Loc
.substr(ColonPos
+ 1, Loc
.size());
518 if (Points
.find(PointId
) == Points
.end())
519 Points
.insert(std::make_pair(PointId
, CoveragePoint(PointId
)));
522 LineInfo
.FileName
= Filename
;
523 LineInfo
.FunctionName
= FunctionName
;
525 LineInfo
.Line
= std::strtoul(LineStr
.c_str(), &End
, 10);
526 LineInfo
.Column
= std::strtoul(ColStr
.c_str(), &End
, 10);
528 CoveragePoint
*CoveragePoint
= &Points
.find(PointId
)->second
;
529 CoveragePoint
->Locs
.push_back(LineInfo
);
534 errs() << "Ignoring unknown key: " << Key
<< "\n";
538 for (auto &KV
: Points
) {
539 Coverage
->Points
.push_back(KV
.second
);
545 // ---------- MAIN FUNCTIONALITY ----------
547 std::string
stripPathPrefix(std::string Path
) {
548 if (ClStripPathPrefix
.empty())
550 size_t Pos
= Path
.find(ClStripPathPrefix
);
551 if (Pos
== std::string::npos
)
553 return Path
.substr(Pos
+ ClStripPathPrefix
.size());
556 static std::unique_ptr
<symbolize::LLVMSymbolizer
> createSymbolizer() {
557 symbolize::LLVMSymbolizer::Options SymbolizerOptions
;
558 SymbolizerOptions
.Demangle
= ClDemangle
;
559 SymbolizerOptions
.UseSymbolTable
= true;
560 return std::unique_ptr
<symbolize::LLVMSymbolizer
>(
561 new symbolize::LLVMSymbolizer(SymbolizerOptions
));
564 static std::string
normalizeFilename(const std::string
&FileName
) {
565 SmallString
<256> S(FileName
);
566 sys::path::remove_dots(S
, /* remove_dot_dot */ true);
567 return stripPathPrefix(S
.str().str());
573 : DefaultBlacklist(createDefaultBlacklist()),
574 UserBlacklist(createUserBlacklist()) {}
576 bool isBlacklisted(const DILineInfo
&I
) {
577 if (DefaultBlacklist
&&
578 DefaultBlacklist
->inSection("sancov", "fun", I
.FunctionName
))
580 if (DefaultBlacklist
&&
581 DefaultBlacklist
->inSection("sancov", "src", I
.FileName
))
584 UserBlacklist
->inSection("sancov", "fun", I
.FunctionName
))
586 if (UserBlacklist
&& UserBlacklist
->inSection("sancov", "src", I
.FileName
))
592 static std::unique_ptr
<SpecialCaseList
> createDefaultBlacklist() {
593 if (!ClUseDefaultBlacklist
)
594 return std::unique_ptr
<SpecialCaseList
>();
595 std::unique_ptr
<MemoryBuffer
> MB
=
596 MemoryBuffer::getMemBuffer(DefaultBlacklistStr
);
598 auto Blacklist
= SpecialCaseList::create(MB
.get(), Error
);
599 failIfNotEmpty(Error
);
603 static std::unique_ptr
<SpecialCaseList
> createUserBlacklist() {
604 if (ClBlacklist
.empty())
605 return std::unique_ptr
<SpecialCaseList
>();
607 return SpecialCaseList::createOrDie({{ClBlacklist
}});
609 std::unique_ptr
<SpecialCaseList
> DefaultBlacklist
;
610 std::unique_ptr
<SpecialCaseList
> UserBlacklist
;
613 static std::vector
<CoveragePoint
>
614 getCoveragePoints(const std::string
&ObjectFile
,
615 const std::set
<uint64_t> &Addrs
,
616 const std::set
<uint64_t> &CoveredAddrs
) {
617 std::vector
<CoveragePoint
> Result
;
618 auto Symbolizer(createSymbolizer());
621 std::set
<std::string
> CoveredFiles
;
622 if (ClSkipDeadFiles
) {
623 for (auto Addr
: CoveredAddrs
) {
624 auto LineInfo
= Symbolizer
->symbolizeCode(ObjectFile
, Addr
);
625 failIfError(LineInfo
);
626 CoveredFiles
.insert(LineInfo
->FileName
);
627 auto InliningInfo
= Symbolizer
->symbolizeInlinedCode(ObjectFile
, Addr
);
628 failIfError(InliningInfo
);
629 for (uint32_t I
= 0; I
< InliningInfo
->getNumberOfFrames(); ++I
) {
630 auto FrameInfo
= InliningInfo
->getFrame(I
);
631 CoveredFiles
.insert(FrameInfo
.FileName
);
636 for (auto Addr
: Addrs
) {
637 std::set
<DILineInfo
> Infos
; // deduplicate debug info.
639 auto LineInfo
= Symbolizer
->symbolizeCode(ObjectFile
, Addr
);
640 failIfError(LineInfo
);
641 if (ClSkipDeadFiles
&&
642 CoveredFiles
.find(LineInfo
->FileName
) == CoveredFiles
.end())
644 LineInfo
->FileName
= normalizeFilename(LineInfo
->FileName
);
645 if (B
.isBlacklisted(*LineInfo
))
648 auto Id
= utohexstr(Addr
, true);
649 auto Point
= CoveragePoint(Id
);
650 Infos
.insert(*LineInfo
);
651 Point
.Locs
.push_back(*LineInfo
);
653 auto InliningInfo
= Symbolizer
->symbolizeInlinedCode(ObjectFile
, Addr
);
654 failIfError(InliningInfo
);
655 for (uint32_t I
= 0; I
< InliningInfo
->getNumberOfFrames(); ++I
) {
656 auto FrameInfo
= InliningInfo
->getFrame(I
);
657 if (ClSkipDeadFiles
&&
658 CoveredFiles
.find(FrameInfo
.FileName
) == CoveredFiles
.end())
660 FrameInfo
.FileName
= normalizeFilename(FrameInfo
.FileName
);
661 if (B
.isBlacklisted(FrameInfo
))
663 if (Infos
.find(FrameInfo
) == Infos
.end()) {
664 Infos
.insert(FrameInfo
);
665 Point
.Locs
.push_back(FrameInfo
);
669 Result
.push_back(Point
);
675 static bool isCoveragePointSymbol(StringRef Name
) {
676 return Name
== "__sanitizer_cov" || Name
== "__sanitizer_cov_with_check" ||
677 Name
== "__sanitizer_cov_trace_func_enter" ||
678 Name
== "__sanitizer_cov_trace_pc_guard" ||
679 // Mac has '___' prefix
680 Name
== "___sanitizer_cov" || Name
== "___sanitizer_cov_with_check" ||
681 Name
== "___sanitizer_cov_trace_func_enter" ||
682 Name
== "___sanitizer_cov_trace_pc_guard";
685 // Locate __sanitizer_cov* function addresses inside the stubs table on MachO.
686 static void findMachOIndirectCovFunctions(const object::MachOObjectFile
&O
,
687 std::set
<uint64_t> *Result
) {
688 MachO::dysymtab_command Dysymtab
= O
.getDysymtabLoadCommand();
689 MachO::symtab_command Symtab
= O
.getSymtabLoadCommand();
691 for (const auto &Load
: O
.load_commands()) {
692 if (Load
.C
.cmd
== MachO::LC_SEGMENT_64
) {
693 MachO::segment_command_64 Seg
= O
.getSegment64LoadCommand(Load
);
694 for (unsigned J
= 0; J
< Seg
.nsects
; ++J
) {
695 MachO::section_64 Sec
= O
.getSection64(Load
, J
);
697 uint32_t SectionType
= Sec
.flags
& MachO::SECTION_TYPE
;
698 if (SectionType
== MachO::S_SYMBOL_STUBS
) {
699 uint32_t Stride
= Sec
.reserved2
;
700 uint32_t Cnt
= Sec
.size
/ Stride
;
701 uint32_t N
= Sec
.reserved1
;
702 for (uint32_t J
= 0; J
< Cnt
&& N
+ J
< Dysymtab
.nindirectsyms
; J
++) {
703 uint32_t IndirectSymbol
=
704 O
.getIndirectSymbolTableEntry(Dysymtab
, N
+ J
);
705 uint64_t Addr
= Sec
.addr
+ J
* Stride
;
706 if (IndirectSymbol
< Symtab
.nsyms
) {
707 object::SymbolRef Symbol
= *(O
.getSymbolByIndex(IndirectSymbol
));
708 Expected
<StringRef
> Name
= Symbol
.getName();
710 if (isCoveragePointSymbol(Name
.get())) {
711 Result
->insert(Addr
);
718 if (Load
.C
.cmd
== MachO::LC_SEGMENT
) {
719 errs() << "ERROR: 32 bit MachO binaries not supported\n";
724 // Locate __sanitizer_cov* function addresses that are used for coverage
726 static std::set
<uint64_t>
727 findSanitizerCovFunctions(const object::ObjectFile
&O
) {
728 std::set
<uint64_t> Result
;
730 for (const object::SymbolRef
&Symbol
: O
.symbols()) {
731 Expected
<uint64_t> AddressOrErr
= Symbol
.getAddress();
732 failIfError(AddressOrErr
);
733 uint64_t Address
= AddressOrErr
.get();
735 Expected
<StringRef
> NameOrErr
= Symbol
.getName();
736 failIfError(NameOrErr
);
737 StringRef Name
= NameOrErr
.get();
739 if (!(Symbol
.getFlags() & object::BasicSymbolRef::SF_Undefined
) &&
740 isCoveragePointSymbol(Name
)) {
741 Result
.insert(Address
);
745 if (const auto *CO
= dyn_cast
<object::COFFObjectFile
>(&O
)) {
746 for (const object::ExportDirectoryEntryRef
&Export
:
747 CO
->export_directories()) {
749 std::error_code EC
= Export
.getExportRVA(RVA
);
753 EC
= Export
.getSymbolName(Name
);
756 if (isCoveragePointSymbol(Name
))
757 Result
.insert(CO
->getImageBase() + RVA
);
761 if (const auto *MO
= dyn_cast
<object::MachOObjectFile
>(&O
)) {
762 findMachOIndirectCovFunctions(*MO
, &Result
);
768 static uint64_t getPreviousInstructionPc(uint64_t PC
,
770 if (TheTriple
.isARM()) {
771 return (PC
- 3) & (~1);
772 } else if (TheTriple
.isAArch64()) {
774 } else if (TheTriple
.isMIPS()) {
781 // Locate addresses of all coverage points in a file. Coverage point
782 // is defined as the 'address of instruction following __sanitizer_cov
784 static void getObjectCoveragePoints(const object::ObjectFile
&O
,
785 std::set
<uint64_t> *Addrs
) {
786 Triple
TheTriple("unknown-unknown-unknown");
787 TheTriple
.setArch(Triple::ArchType(O
.getArch()));
788 auto TripleName
= TheTriple
.getTriple();
791 const Target
*TheTarget
= TargetRegistry::lookupTarget(TripleName
, Error
);
792 failIfNotEmpty(Error
);
794 std::unique_ptr
<const MCSubtargetInfo
> STI(
795 TheTarget
->createMCSubtargetInfo(TripleName
, "", ""));
796 failIfEmpty(STI
, "no subtarget info for target " + TripleName
);
798 std::unique_ptr
<const MCRegisterInfo
> MRI(
799 TheTarget
->createMCRegInfo(TripleName
));
800 failIfEmpty(MRI
, "no register info for target " + TripleName
);
802 std::unique_ptr
<const MCAsmInfo
> AsmInfo(
803 TheTarget
->createMCAsmInfo(*MRI
, TripleName
));
804 failIfEmpty(AsmInfo
, "no asm info for target " + TripleName
);
806 std::unique_ptr
<const MCObjectFileInfo
> MOFI(new MCObjectFileInfo
);
807 MCContext
Ctx(AsmInfo
.get(), MRI
.get(), MOFI
.get());
808 std::unique_ptr
<MCDisassembler
> DisAsm(
809 TheTarget
->createMCDisassembler(*STI
, Ctx
));
810 failIfEmpty(DisAsm
, "no disassembler info for target " + TripleName
);
812 std::unique_ptr
<const MCInstrInfo
> MII(TheTarget
->createMCInstrInfo());
813 failIfEmpty(MII
, "no instruction info for target " + TripleName
);
815 std::unique_ptr
<const MCInstrAnalysis
> MIA(
816 TheTarget
->createMCInstrAnalysis(MII
.get()));
817 failIfEmpty(MIA
, "no instruction analysis info for target " + TripleName
);
819 auto SanCovAddrs
= findSanitizerCovFunctions(O
);
820 if (SanCovAddrs
.empty())
821 fail("__sanitizer_cov* functions not found");
823 for (object::SectionRef Section
: O
.sections()) {
824 if (Section
.isVirtual() || !Section
.isText()) // llvm-objdump does the same.
826 uint64_t SectionAddr
= Section
.getAddress();
827 uint64_t SectSize
= Section
.getSize();
832 failIfError(Section
.getContents(BytesStr
));
833 ArrayRef
<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr
.data()),
836 for (uint64_t Index
= 0, Size
= 0; Index
< Section
.getSize();
839 if (!DisAsm
->getInstruction(Inst
, Size
, Bytes
.slice(Index
),
840 SectionAddr
+ Index
, nulls(), nulls())) {
845 uint64_t Addr
= Index
+ SectionAddr
;
846 // Sanitizer coverage uses the address of the next instruction - 1.
847 uint64_t CovPoint
= getPreviousInstructionPc(Addr
+ Size
, TheTriple
);
849 if (MIA
->isCall(Inst
) &&
850 MIA
->evaluateBranch(Inst
, SectionAddr
+ Index
, Size
, Target
) &&
851 SanCovAddrs
.find(Target
) != SanCovAddrs
.end())
852 Addrs
->insert(CovPoint
);
858 visitObjectFiles(const object::Archive
&A
,
859 function_ref
<void(const object::ObjectFile
&)> Fn
) {
860 Error Err
= Error::success();
861 for (auto &C
: A
.children(Err
)) {
862 Expected
<std::unique_ptr
<object::Binary
>> ChildOrErr
= C
.getAsBinary();
863 failIfError(ChildOrErr
);
864 if (auto *O
= dyn_cast
<object::ObjectFile
>(&*ChildOrErr
.get()))
867 failIfError(object::object_error::invalid_file_type
);
869 failIfError(std::move(Err
));
873 visitObjectFiles(const std::string
&FileName
,
874 function_ref
<void(const object::ObjectFile
&)> Fn
) {
875 Expected
<object::OwningBinary
<object::Binary
>> BinaryOrErr
=
876 object::createBinary(FileName
);
878 failIfError(BinaryOrErr
);
880 object::Binary
&Binary
= *BinaryOrErr
.get().getBinary();
881 if (object::Archive
*A
= dyn_cast
<object::Archive
>(&Binary
))
882 visitObjectFiles(*A
, Fn
);
883 else if (object::ObjectFile
*O
= dyn_cast
<object::ObjectFile
>(&Binary
))
886 failIfError(object::object_error::invalid_file_type
);
889 static std::set
<uint64_t>
890 findSanitizerCovFunctions(const std::string
&FileName
) {
891 std::set
<uint64_t> Result
;
892 visitObjectFiles(FileName
, [&](const object::ObjectFile
&O
) {
893 auto Addrs
= findSanitizerCovFunctions(O
);
894 Result
.insert(Addrs
.begin(), Addrs
.end());
899 // Locate addresses of all coverage points in a file. Coverage point
900 // is defined as the 'address of instruction following __sanitizer_cov
902 static std::set
<uint64_t> findCoveragePointAddrs(const std::string
&FileName
) {
903 std::set
<uint64_t> Result
;
904 visitObjectFiles(FileName
, [&](const object::ObjectFile
&O
) {
905 getObjectCoveragePoints(O
, &Result
);
910 static void printCovPoints(const std::string
&ObjFile
, raw_ostream
&OS
) {
911 for (uint64_t Addr
: findCoveragePointAddrs(ObjFile
)) {
918 static ErrorOr
<bool> isCoverageFile(const std::string
&FileName
) {
919 auto ShortFileName
= llvm::sys::path::filename(FileName
);
920 if (!SancovFileRegex
.match(ShortFileName
))
923 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
924 MemoryBuffer::getFile(FileName
);
926 errs() << "Warning: " << BufOrErr
.getError().message() << "("
927 << BufOrErr
.getError().value()
928 << "), filename: " << llvm::sys::path::filename(FileName
) << "\n";
929 return BufOrErr
.getError();
931 std::unique_ptr
<MemoryBuffer
> Buf
= std::move(BufOrErr
.get());
932 if (Buf
->getBufferSize() < 8) {
935 const FileHeader
*Header
=
936 reinterpret_cast<const FileHeader
*>(Buf
->getBufferStart());
937 return Header
->Magic
== BinCoverageMagic
;
940 static bool isSymbolizedCoverageFile(const std::string
&FileName
) {
941 auto ShortFileName
= llvm::sys::path::filename(FileName
);
942 return SymcovFileRegex
.match(ShortFileName
);
945 static std::unique_ptr
<SymbolizedCoverage
>
946 symbolize(const RawCoverage
&Data
, const std::string ObjectFile
) {
947 auto Coverage
= make_unique
<SymbolizedCoverage
>();
949 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
950 MemoryBuffer::getFile(ObjectFile
);
951 failIfError(BufOrErr
);
953 Hasher
.update((*BufOrErr
)->getBuffer());
954 Coverage
->BinaryHash
= toHex(Hasher
.final());
957 auto Symbolizer(createSymbolizer());
959 for (uint64_t Addr
: *Data
.Addrs
) {
960 auto LineInfo
= Symbolizer
->symbolizeCode(ObjectFile
, Addr
);
961 failIfError(LineInfo
);
962 if (B
.isBlacklisted(*LineInfo
))
965 Coverage
->CoveredIds
.insert(utohexstr(Addr
, true));
968 std::set
<uint64_t> AllAddrs
= findCoveragePointAddrs(ObjectFile
);
969 if (!std::includes(AllAddrs
.begin(), AllAddrs
.end(), Data
.Addrs
->begin(),
970 Data
.Addrs
->end())) {
971 fail("Coverage points in binary and .sancov file do not match.");
973 Coverage
->Points
= getCoveragePoints(ObjectFile
, AllAddrs
, *Data
.Addrs
);
978 bool operator<(const FileFn
&RHS
) const {
979 return std::tie(FileName
, FunctionName
) <
980 std::tie(RHS
.FileName
, RHS
.FunctionName
);
983 std::string FileName
;
984 std::string FunctionName
;
987 static std::set
<FileFn
>
988 computeFunctions(const std::vector
<CoveragePoint
> &Points
) {
989 std::set
<FileFn
> Fns
;
990 for (const auto &Point
: Points
) {
991 for (const auto &Loc
: Point
.Locs
) {
992 Fns
.insert(FileFn
{Loc
.FileName
, Loc
.FunctionName
});
998 static std::set
<FileFn
>
999 computeNotCoveredFunctions(const SymbolizedCoverage
&Coverage
) {
1000 auto Fns
= computeFunctions(Coverage
.Points
);
1002 for (const auto &Point
: Coverage
.Points
) {
1003 if (Coverage
.CoveredIds
.find(Point
.Id
) == Coverage
.CoveredIds
.end())
1006 for (const auto &Loc
: Point
.Locs
) {
1007 Fns
.erase(FileFn
{Loc
.FileName
, Loc
.FunctionName
});
1014 static std::set
<FileFn
>
1015 computeCoveredFunctions(const SymbolizedCoverage
&Coverage
) {
1016 auto AllFns
= computeFunctions(Coverage
.Points
);
1017 std::set
<FileFn
> Result
;
1019 for (const auto &Point
: Coverage
.Points
) {
1020 if (Coverage
.CoveredIds
.find(Point
.Id
) == Coverage
.CoveredIds
.end())
1023 for (const auto &Loc
: Point
.Locs
) {
1024 Result
.insert(FileFn
{Loc
.FileName
, Loc
.FunctionName
});
1031 typedef std::map
<FileFn
, std::pair
<uint32_t, uint32_t>> FunctionLocs
;
1032 // finds first location in a file for each function.
1033 static FunctionLocs
resolveFunctions(const SymbolizedCoverage
&Coverage
,
1034 const std::set
<FileFn
> &Fns
) {
1035 FunctionLocs Result
;
1036 for (const auto &Point
: Coverage
.Points
) {
1037 for (const auto &Loc
: Point
.Locs
) {
1038 FileFn Fn
= FileFn
{Loc
.FileName
, Loc
.FunctionName
};
1039 if (Fns
.find(Fn
) == Fns
.end())
1042 auto P
= std::make_pair(Loc
.Line
, Loc
.Column
);
1043 auto I
= Result
.find(Fn
);
1044 if (I
== Result
.end() || I
->second
> P
) {
1052 static void printFunctionLocs(const FunctionLocs
&FnLocs
, raw_ostream
&OS
) {
1053 for (const auto &P
: FnLocs
) {
1054 OS
<< stripPathPrefix(P
.first
.FileName
) << ":" << P
.second
.first
<< " "
1055 << P
.first
.FunctionName
<< "\n";
1058 CoverageStats
computeStats(const SymbolizedCoverage
&Coverage
) {
1059 CoverageStats Stats
= {Coverage
.Points
.size(), Coverage
.CoveredIds
.size(),
1060 computeFunctions(Coverage
.Points
).size(),
1061 computeCoveredFunctions(Coverage
).size()};
1065 // Print list of covered functions.
1066 // Line format: <file_name>:<line> <function_name>
1067 static void printCoveredFunctions(const SymbolizedCoverage
&CovData
,
1069 auto CoveredFns
= computeCoveredFunctions(CovData
);
1070 printFunctionLocs(resolveFunctions(CovData
, CoveredFns
), OS
);
1073 // Print list of not covered functions.
1074 // Line format: <file_name>:<line> <function_name>
1075 static void printNotCoveredFunctions(const SymbolizedCoverage
&CovData
,
1077 auto NotCoveredFns
= computeNotCoveredFunctions(CovData
);
1078 printFunctionLocs(resolveFunctions(CovData
, NotCoveredFns
), OS
);
1081 // Read list of files and merges their coverage info.
1082 static void readAndPrintRawCoverage(const std::vector
<std::string
> &FileNames
,
1084 std::vector
<std::unique_ptr
<RawCoverage
>> Covs
;
1085 for (const auto &FileName
: FileNames
) {
1086 auto Cov
= RawCoverage::read(FileName
);
1093 static std::unique_ptr
<SymbolizedCoverage
>
1094 merge(const std::vector
<std::unique_ptr
<SymbolizedCoverage
>> &Coverages
) {
1095 if (Coverages
.empty())
1098 auto Result
= make_unique
<SymbolizedCoverage
>();
1100 for (size_t I
= 0; I
< Coverages
.size(); ++I
) {
1101 const SymbolizedCoverage
&Coverage
= *Coverages
[I
];
1103 if (Coverages
.size() > 1) {
1104 // prefix is not needed when there's only one file.
1108 for (const auto &Id
: Coverage
.CoveredIds
) {
1109 Result
->CoveredIds
.insert(Prefix
+ Id
);
1112 for (const auto &CovPoint
: Coverage
.Points
) {
1113 CoveragePoint
NewPoint(CovPoint
);
1114 NewPoint
.Id
= Prefix
+ CovPoint
.Id
;
1115 Result
->Points
.push_back(NewPoint
);
1119 if (Coverages
.size() == 1) {
1120 Result
->BinaryHash
= Coverages
[0]->BinaryHash
;
1126 static std::unique_ptr
<SymbolizedCoverage
>
1127 readSymbolizeAndMergeCmdArguments(std::vector
<std::string
> FileNames
) {
1128 std::vector
<std::unique_ptr
<SymbolizedCoverage
>> Coverages
;
1131 // Short name => file name.
1132 std::map
<std::string
, std::string
> ObjFiles
;
1133 std::string FirstObjFile
;
1134 std::set
<std::string
> CovFiles
;
1136 // Partition input values into coverage/object files.
1137 for (const auto &FileName
: FileNames
) {
1138 if (isSymbolizedCoverageFile(FileName
)) {
1139 Coverages
.push_back(SymbolizedCoverage::read(FileName
));
1142 auto ErrorOrIsCoverage
= isCoverageFile(FileName
);
1143 if (!ErrorOrIsCoverage
)
1145 if (ErrorOrIsCoverage
.get()) {
1146 CovFiles
.insert(FileName
);
1148 auto ShortFileName
= llvm::sys::path::filename(FileName
);
1149 if (ObjFiles
.find(ShortFileName
) != ObjFiles
.end()) {
1150 fail("Duplicate binary file with a short name: " + ShortFileName
);
1153 ObjFiles
[ShortFileName
] = FileName
;
1154 if (FirstObjFile
.empty())
1155 FirstObjFile
= FileName
;
1159 SmallVector
<StringRef
, 2> Components
;
1161 // Object file => list of corresponding coverage file names.
1162 std::map
<std::string
, std::vector
<std::string
>> CoverageByObjFile
;
1163 for (const auto &FileName
: CovFiles
) {
1164 auto ShortFileName
= llvm::sys::path::filename(FileName
);
1165 auto Ok
= SancovFileRegex
.match(ShortFileName
, &Components
);
1167 fail("Can't match coverage file name against "
1168 "<module_name>.<pid>.sancov pattern: " +
1172 auto Iter
= ObjFiles
.find(Components
[1]);
1173 if (Iter
== ObjFiles
.end()) {
1174 fail("Object file for coverage not found: " + FileName
);
1177 CoverageByObjFile
[Iter
->second
].push_back(FileName
);
1180 for (const auto &Pair
: ObjFiles
) {
1181 auto FileName
= Pair
.second
;
1182 if (CoverageByObjFile
.find(FileName
) == CoverageByObjFile
.end())
1183 errs() << "WARNING: No coverage file for " << FileName
<< "\n";
1186 // Read raw coverage and symbolize it.
1187 for (const auto &Pair
: CoverageByObjFile
) {
1188 if (findSanitizerCovFunctions(Pair
.first
).empty()) {
1190 << "WARNING: Ignoring " << Pair
.first
1191 << " and its coverage because __sanitizer_cov* functions were not "
1196 for (const std::string
&CoverageFile
: Pair
.second
) {
1197 auto DataOrError
= RawCoverage::read(CoverageFile
);
1198 failIfError(DataOrError
);
1199 Coverages
.push_back(symbolize(*DataOrError
.get(), Pair
.first
));
1204 return merge(Coverages
);
1209 int main(int Argc
, char **Argv
) {
1210 // Print stack trace if we signal out.
1211 sys::PrintStackTraceOnErrorSignal(Argv
[0]);
1212 PrettyStackTraceProgram
X(Argc
, Argv
);
1213 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
1215 llvm::InitializeAllTargetInfos();
1216 llvm::InitializeAllTargetMCs();
1217 llvm::InitializeAllDisassemblers();
1219 cl::ParseCommandLineOptions(Argc
, Argv
,
1220 "Sanitizer Coverage Processing Tool (sancov)\n\n"
1221 " This tool can extract various coverage-related information from: \n"
1222 " coverage-instrumented binary files, raw .sancov files and their "
1223 "symbolized .symcov version.\n"
1224 " Depending on chosen action the tool expects different input files:\n"
1225 " -print-coverage-pcs - coverage-instrumented binary files\n"
1226 " -print-coverage - .sancov files\n"
1227 " <other actions> - .sancov files & corresponding binary "
1228 "files, .symcov files\n"
1231 // -print doesn't need object files.
1232 if (Action
== PrintAction
) {
1233 readAndPrintRawCoverage(ClInputFiles
, outs());
1235 } else if (Action
== PrintCovPointsAction
) {
1236 // -print-coverage-points doesn't need coverage files.
1237 for (const std::string
&ObjFile
: ClInputFiles
) {
1238 printCovPoints(ObjFile
, outs());
1243 auto Coverage
= readSymbolizeAndMergeCmdArguments(ClInputFiles
);
1244 failIf(!Coverage
, "No valid coverage files given.");
1247 case CoveredFunctionsAction
: {
1248 printCoveredFunctions(*Coverage
, outs());
1251 case NotCoveredFunctionsAction
: {
1252 printNotCoveredFunctions(*Coverage
, outs());
1256 outs() << computeStats(*Coverage
);
1260 case SymbolizeAction
: { // merge & symbolize are synonims.
1261 JSONWriter
W(outs());
1265 case HtmlReportAction
:
1266 errs() << "-html-report option is removed: "
1267 "use -symbolize & coverage-report-server.py instead\n";
1270 case PrintCovPointsAction
:
1271 llvm_unreachable("unsupported action");