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/JSON.h"
35 #include "llvm/Support/MD5.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Regex.h"
41 #include "llvm/Support/SHA1.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/SpecialCaseList.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/YAMLParser.h"
48 #include "llvm/Support/raw_ostream.h"
57 // --------- COMMAND LINE FLAGS ---------
60 CoveredFunctionsAction
,
63 NotCoveredFunctionsAction
,
70 cl::opt
<ActionType
> Action(
71 cl::desc("Action (required)"), cl::Required
,
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.")));
88 static cl::list
<std::string
>
89 ClInputFiles(cl::Positional
, cl::OneOrMore
,
90 cl::desc("<action> <binary files...> <.sancov files...> "
91 "<.symcov files...>"));
93 static cl::opt
<bool> ClDemangle("demangle", cl::init(true),
94 cl::desc("Print demangled function name."));
97 ClSkipDeadFiles("skip-dead-files", cl::init(true),
98 cl::desc("Do not list dead source files in reports."));
100 static cl::opt
<std::string
> ClStripPathPrefix(
101 "strip_path_prefix", cl::init(""),
102 cl::desc("Strip this prefix from file paths in reports."));
104 static cl::opt
<std::string
>
105 ClBlacklist("blacklist", cl::init(""),
106 cl::desc("Blacklist file (sanitizer blacklist format)."));
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."));
112 static const char *const DefaultBlacklistStr
= "fun:__sanitizer_.*\n"
113 "src:/usr/include/.*\n"
114 "src:.*/libc\\+\\+/.*\n";
116 // --------- FORMAT SPECIFICATION ---------
123 static const uint32_t BinCoverageMagic
= 0xC0BFFFFF;
124 static const uint32_t Bitness32
= 0xFFFFFF32;
125 static const uint32_t Bitness64
= 0xFFFFFF64;
127 static const Regex
SancovFileRegex("(.*)\\.[0-9]+\\.sancov");
128 static const Regex
SymcovFileRegex(".*\\.symcov");
130 // --------- MAIN DATASTRUCTURES ----------
132 // Contents of .sancov file: list of coverage point addresses that were
135 explicit RawCoverage(std::unique_ptr
<std::set
<uint64_t>> Addrs
)
136 : Addrs(std::move(Addrs
)) {}
138 // Read binary .sancov file.
139 static ErrorOr
<std::unique_ptr
<RawCoverage
>>
140 read(const std::string
&FileName
);
142 std::unique_ptr
<std::set
<uint64_t>> Addrs
;
145 // Coverage point has an opaque Id and corresponds to multiple source locations.
146 struct CoveragePoint
{
147 explicit CoveragePoint(const std::string
&Id
) : Id(Id
) {}
150 SmallVector
<DILineInfo
, 1> Locs
;
153 // Symcov file content: set of covered Ids plus information about all available
155 struct SymbolizedCoverage
{
156 // Read json .symcov file.
157 static std::unique_ptr
<SymbolizedCoverage
> read(const std::string
&InputFile
);
159 std::set
<std::string
> CoveredIds
;
160 std::string BinaryHash
;
161 std::vector
<CoveragePoint
> Points
;
164 struct CoverageStats
{
171 // --------- ERROR HANDLING ---------
173 static void fail(const llvm::Twine
&E
) {
174 errs() << "ERROR: " << E
<< "\n";
178 static void failIf(bool B
, const llvm::Twine
&E
) {
183 static void failIfError(std::error_code Error
) {
186 errs() << "ERROR: " << Error
.message() << "(" << Error
.value() << ")\n";
190 template <typename T
> static void failIfError(const ErrorOr
<T
> &E
) {
191 failIfError(E
.getError());
194 static void failIfError(Error Err
) {
196 logAllUnhandledErrors(std::move(Err
), errs(), "ERROR: ");
201 template <typename T
> static void failIfError(Expected
<T
> &E
) {
202 failIfError(E
.takeError());
205 static void failIfNotEmpty(const llvm::Twine
&E
) {
211 template <typename T
>
212 static void failIfEmpty(const std::unique_ptr
<T
> &Ptr
,
213 const std::string
&Message
) {
219 // ----------- Coverage I/O ----------
220 template <typename T
>
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()));
228 ErrorOr
<std::unique_ptr
<RawCoverage
>>
229 RawCoverage::read(const std::string
&FileName
) {
230 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
231 MemoryBuffer::getFile(FileName
);
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
);
239 const FileHeader
*Header
=
240 reinterpret_cast<const FileHeader
*>(Buf
->getBufferStart());
242 if (Header
->Magic
!= BinCoverageMagic
) {
243 errs() << "Wrong magic: " << Header
->Magic
<< '\n';
244 return make_error_code(errc::illegal_byte_sequence
);
247 auto Addrs
= std::make_unique
<std::set
<uint64_t>>();
249 switch (Header
->Bitness
) {
251 readInts
<uint64_t>(Buf
->getBufferStart() + 8, Buf
->getBufferEnd(),
255 readInts
<uint32_t>(Buf
->getBufferStart() + 8, Buf
->getBufferEnd(),
259 errs() << "Unsupported bitness: " << Header
->Bitness
<< '\n';
260 return make_error_code(errc::illegal_byte_sequence
);
263 // Ignore slots that are zero, so a runtime implementation is not required
264 // to compactify the data.
267 return std::unique_ptr
<RawCoverage
>(new RawCoverage(std::move(Addrs
)));
270 // Print coverage addresses.
271 raw_ostream
&operator<<(raw_ostream
&OS
, const RawCoverage
&CoverageData
) {
272 for (auto Addr
: *CoverageData
.Addrs
) {
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";
288 // Output symbolized information for coverage points in JSON.
292 // '<function_name>' : {
293 // '<point_id'> : '<line_number>:'<column_number'.
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
);
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
);
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
;
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
)
328 if (WrittenIds
.find(Point
->Id
) != WrittenIds
.end())
331 // Output <point_id> : "<line>:<col>".
332 WrittenIds
.insert(Point
->Id
);
333 W
.attribute(Point
->Id
,
334 (utostr(Loc
.Line
) + ":" + utostr(Loc
.Column
)));
343 static void operator<<(json::OStream
&W
, const SymbolizedCoverage
&C
) {
345 W
.attributeArray("covered-points", [&] {
346 for (const std::string
&P
: C
.CoveredIds
) {
350 W
.attribute("binary-hash", C
.BinaryHash
);
351 W
.attributeObject("point-symbol-info", [&] { W
<< C
.Points
; });
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 S
->getValue(StringStorage
);
362 std::unique_ptr
<SymbolizedCoverage
>
363 SymbolizedCoverage::read(const std::string
&InputFile
) {
364 auto Coverage(std::make_unique
<SymbolizedCoverage
>());
366 std::map
<std::string
, CoveragePoint
> Points
;
367 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
368 MemoryBuffer::getFile(InputFile
);
369 failIfError(BufOrErr
);
372 yaml::Stream
S(**BufOrErr
, SM
);
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
);
381 for (auto &KVNode
: *Top
) {
382 auto Key
= parseScalarString(KVNode
.getKey());
384 if (Key
== "covered-points") {
385 yaml::SequenceNode
*Points
=
386 dyn_cast
<yaml::SequenceNode
>(KVNode
.getValue());
387 failIf(!Points
, "expected array: " + InputFile
);
389 for (auto I
= Points
->begin(), E
= Points
->end(); I
!= E
; ++I
) {
390 Coverage
->CoveredIds
.insert(parseScalarString(&*I
));
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
);
399 for (auto &FileKVNode
: *PointSymbolInfo
) {
400 auto Filename
= parseScalarString(FileKVNode
.getKey());
402 yaml::MappingNode
*FileInfo
=
403 dyn_cast
<yaml::MappingNode
>(FileKVNode
.getValue());
404 failIf(!FileInfo
, "expected mapping node: " + InputFile
);
406 for (auto &FunctionKVNode
: *FileInfo
) {
407 auto FunctionName
= parseScalarString(FunctionKVNode
.getKey());
409 yaml::MappingNode
*FunctionInfo
=
410 dyn_cast
<yaml::MappingNode
>(FunctionKVNode
.getValue());
411 failIf(!FunctionInfo
, "expected mapping node: " + InputFile
);
413 for (auto &PointKVNode
: *FunctionInfo
) {
414 auto PointId
= parseScalarString(PointKVNode
.getKey());
415 auto Loc
= parseScalarString(PointKVNode
.getValue());
417 size_t ColonPos
= Loc
.find(':');
418 failIf(ColonPos
== std::string::npos
, "expected ':': " + InputFile
);
420 auto LineStr
= Loc
.substr(0, ColonPos
);
421 auto ColStr
= Loc
.substr(ColonPos
+ 1, Loc
.size());
423 if (Points
.find(PointId
) == Points
.end())
424 Points
.insert(std::make_pair(PointId
, CoveragePoint(PointId
)));
427 LineInfo
.FileName
= Filename
;
428 LineInfo
.FunctionName
= FunctionName
;
430 LineInfo
.Line
= std::strtoul(LineStr
.c_str(), &End
, 10);
431 LineInfo
.Column
= std::strtoul(ColStr
.c_str(), &End
, 10);
433 CoveragePoint
*CoveragePoint
= &Points
.find(PointId
)->second
;
434 CoveragePoint
->Locs
.push_back(LineInfo
);
439 errs() << "Ignoring unknown key: " << Key
<< "\n";
443 for (auto &KV
: Points
) {
444 Coverage
->Points
.push_back(KV
.second
);
450 // ---------- MAIN FUNCTIONALITY ----------
452 std::string
stripPathPrefix(std::string Path
) {
453 if (ClStripPathPrefix
.empty())
455 size_t Pos
= Path
.find(ClStripPathPrefix
);
456 if (Pos
== std::string::npos
)
458 return Path
.substr(Pos
+ ClStripPathPrefix
.size());
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
));
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(S
.str().str());
478 : DefaultBlacklist(createDefaultBlacklist()),
479 UserBlacklist(createUserBlacklist()) {}
481 bool isBlacklisted(const DILineInfo
&I
) {
482 if (DefaultBlacklist
&&
483 DefaultBlacklist
->inSection("sancov", "fun", I
.FunctionName
))
485 if (DefaultBlacklist
&&
486 DefaultBlacklist
->inSection("sancov", "src", I
.FileName
))
489 UserBlacklist
->inSection("sancov", "fun", I
.FunctionName
))
491 if (UserBlacklist
&& UserBlacklist
->inSection("sancov", "src", I
.FileName
))
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
);
503 auto Blacklist
= SpecialCaseList::create(MB
.get(), Error
);
504 failIfNotEmpty(Error
);
508 static std::unique_ptr
<SpecialCaseList
> createUserBlacklist() {
509 if (ClBlacklist
.empty())
510 return std::unique_ptr
<SpecialCaseList
>();
512 return SpecialCaseList::createOrDie({{ClBlacklist
}});
514 std::unique_ptr
<SpecialCaseList
> DefaultBlacklist
;
515 std::unique_ptr
<SpecialCaseList
> UserBlacklist
;
518 static std::vector
<CoveragePoint
>
519 getCoveragePoints(const std::string
&ObjectFile
,
520 const std::set
<uint64_t> &Addrs
,
521 const std::set
<uint64_t> &CoveredAddrs
) {
522 std::vector
<CoveragePoint
> Result
;
523 auto Symbolizer(createSymbolizer());
526 std::set
<std::string
> CoveredFiles
;
527 if (ClSkipDeadFiles
) {
528 for (auto Addr
: CoveredAddrs
) {
529 // TODO: it would be neccessary to set proper section index here.
530 // object::SectionedAddress::UndefSection works for only absolute
532 object::SectionedAddress ModuleAddress
= {
533 Addr
, object::SectionedAddress::UndefSection
};
535 auto LineInfo
= Symbolizer
->symbolizeCode(ObjectFile
, ModuleAddress
);
536 failIfError(LineInfo
);
537 CoveredFiles
.insert(LineInfo
->FileName
);
539 Symbolizer
->symbolizeInlinedCode(ObjectFile
, ModuleAddress
);
540 failIfError(InliningInfo
);
541 for (uint32_t I
= 0; I
< InliningInfo
->getNumberOfFrames(); ++I
) {
542 auto FrameInfo
= InliningInfo
->getFrame(I
);
543 CoveredFiles
.insert(FrameInfo
.FileName
);
548 for (auto Addr
: Addrs
) {
549 std::set
<DILineInfo
> Infos
; // deduplicate debug info.
551 // TODO: it would be neccessary to set proper section index here.
552 // object::SectionedAddress::UndefSection works for only absolute addresses.
553 object::SectionedAddress ModuleAddress
= {
554 Addr
, object::SectionedAddress::UndefSection
};
556 auto LineInfo
= Symbolizer
->symbolizeCode(ObjectFile
, ModuleAddress
);
557 failIfError(LineInfo
);
558 if (ClSkipDeadFiles
&&
559 CoveredFiles
.find(LineInfo
->FileName
) == CoveredFiles
.end())
561 LineInfo
->FileName
= normalizeFilename(LineInfo
->FileName
);
562 if (B
.isBlacklisted(*LineInfo
))
565 auto Id
= utohexstr(Addr
, true);
566 auto Point
= CoveragePoint(Id
);
567 Infos
.insert(*LineInfo
);
568 Point
.Locs
.push_back(*LineInfo
);
571 Symbolizer
->symbolizeInlinedCode(ObjectFile
, ModuleAddress
);
572 failIfError(InliningInfo
);
573 for (uint32_t I
= 0; I
< InliningInfo
->getNumberOfFrames(); ++I
) {
574 auto FrameInfo
= InliningInfo
->getFrame(I
);
575 if (ClSkipDeadFiles
&&
576 CoveredFiles
.find(FrameInfo
.FileName
) == CoveredFiles
.end())
578 FrameInfo
.FileName
= normalizeFilename(FrameInfo
.FileName
);
579 if (B
.isBlacklisted(FrameInfo
))
581 if (Infos
.find(FrameInfo
) == Infos
.end()) {
582 Infos
.insert(FrameInfo
);
583 Point
.Locs
.push_back(FrameInfo
);
587 Result
.push_back(Point
);
593 static bool isCoveragePointSymbol(StringRef Name
) {
594 return Name
== "__sanitizer_cov" || Name
== "__sanitizer_cov_with_check" ||
595 Name
== "__sanitizer_cov_trace_func_enter" ||
596 Name
== "__sanitizer_cov_trace_pc_guard" ||
597 // Mac has '___' prefix
598 Name
== "___sanitizer_cov" || Name
== "___sanitizer_cov_with_check" ||
599 Name
== "___sanitizer_cov_trace_func_enter" ||
600 Name
== "___sanitizer_cov_trace_pc_guard";
603 // Locate __sanitizer_cov* function addresses inside the stubs table on MachO.
604 static void findMachOIndirectCovFunctions(const object::MachOObjectFile
&O
,
605 std::set
<uint64_t> *Result
) {
606 MachO::dysymtab_command Dysymtab
= O
.getDysymtabLoadCommand();
607 MachO::symtab_command Symtab
= O
.getSymtabLoadCommand();
609 for (const auto &Load
: O
.load_commands()) {
610 if (Load
.C
.cmd
== MachO::LC_SEGMENT_64
) {
611 MachO::segment_command_64 Seg
= O
.getSegment64LoadCommand(Load
);
612 for (unsigned J
= 0; J
< Seg
.nsects
; ++J
) {
613 MachO::section_64 Sec
= O
.getSection64(Load
, J
);
615 uint32_t SectionType
= Sec
.flags
& MachO::SECTION_TYPE
;
616 if (SectionType
== MachO::S_SYMBOL_STUBS
) {
617 uint32_t Stride
= Sec
.reserved2
;
618 uint32_t Cnt
= Sec
.size
/ Stride
;
619 uint32_t N
= Sec
.reserved1
;
620 for (uint32_t J
= 0; J
< Cnt
&& N
+ J
< Dysymtab
.nindirectsyms
; J
++) {
621 uint32_t IndirectSymbol
=
622 O
.getIndirectSymbolTableEntry(Dysymtab
, N
+ J
);
623 uint64_t Addr
= Sec
.addr
+ J
* Stride
;
624 if (IndirectSymbol
< Symtab
.nsyms
) {
625 object::SymbolRef Symbol
= *(O
.getSymbolByIndex(IndirectSymbol
));
626 Expected
<StringRef
> Name
= Symbol
.getName();
628 if (isCoveragePointSymbol(Name
.get())) {
629 Result
->insert(Addr
);
636 if (Load
.C
.cmd
== MachO::LC_SEGMENT
) {
637 errs() << "ERROR: 32 bit MachO binaries not supported\n";
642 // Locate __sanitizer_cov* function addresses that are used for coverage
644 static std::set
<uint64_t>
645 findSanitizerCovFunctions(const object::ObjectFile
&O
) {
646 std::set
<uint64_t> Result
;
648 for (const object::SymbolRef
&Symbol
: O
.symbols()) {
649 Expected
<uint64_t> AddressOrErr
= Symbol
.getAddress();
650 failIfError(AddressOrErr
);
651 uint64_t Address
= AddressOrErr
.get();
653 Expected
<StringRef
> NameOrErr
= Symbol
.getName();
654 failIfError(NameOrErr
);
655 StringRef Name
= NameOrErr
.get();
657 if (!(Symbol
.getFlags() & object::BasicSymbolRef::SF_Undefined
) &&
658 isCoveragePointSymbol(Name
)) {
659 Result
.insert(Address
);
663 if (const auto *CO
= dyn_cast
<object::COFFObjectFile
>(&O
)) {
664 for (const object::ExportDirectoryEntryRef
&Export
:
665 CO
->export_directories()) {
667 std::error_code EC
= Export
.getExportRVA(RVA
);
671 EC
= Export
.getSymbolName(Name
);
674 if (isCoveragePointSymbol(Name
))
675 Result
.insert(CO
->getImageBase() + RVA
);
679 if (const auto *MO
= dyn_cast
<object::MachOObjectFile
>(&O
)) {
680 findMachOIndirectCovFunctions(*MO
, &Result
);
686 static uint64_t getPreviousInstructionPc(uint64_t PC
,
688 if (TheTriple
.isARM()) {
689 return (PC
- 3) & (~1);
690 } else if (TheTriple
.isAArch64()) {
692 } else if (TheTriple
.isMIPS()) {
699 // Locate addresses of all coverage points in a file. Coverage point
700 // is defined as the 'address of instruction following __sanitizer_cov
702 static void getObjectCoveragePoints(const object::ObjectFile
&O
,
703 std::set
<uint64_t> *Addrs
) {
704 Triple
TheTriple("unknown-unknown-unknown");
705 TheTriple
.setArch(Triple::ArchType(O
.getArch()));
706 auto TripleName
= TheTriple
.getTriple();
709 const Target
*TheTarget
= TargetRegistry::lookupTarget(TripleName
, Error
);
710 failIfNotEmpty(Error
);
712 std::unique_ptr
<const MCSubtargetInfo
> STI(
713 TheTarget
->createMCSubtargetInfo(TripleName
, "", ""));
714 failIfEmpty(STI
, "no subtarget info for target " + TripleName
);
716 std::unique_ptr
<const MCRegisterInfo
> MRI(
717 TheTarget
->createMCRegInfo(TripleName
));
718 failIfEmpty(MRI
, "no register info for target " + TripleName
);
720 std::unique_ptr
<const MCAsmInfo
> AsmInfo(
721 TheTarget
->createMCAsmInfo(*MRI
, TripleName
));
722 failIfEmpty(AsmInfo
, "no asm info for target " + TripleName
);
724 std::unique_ptr
<const MCObjectFileInfo
> MOFI(new MCObjectFileInfo
);
725 MCContext
Ctx(AsmInfo
.get(), MRI
.get(), MOFI
.get());
726 std::unique_ptr
<MCDisassembler
> DisAsm(
727 TheTarget
->createMCDisassembler(*STI
, Ctx
));
728 failIfEmpty(DisAsm
, "no disassembler info for target " + TripleName
);
730 std::unique_ptr
<const MCInstrInfo
> MII(TheTarget
->createMCInstrInfo());
731 failIfEmpty(MII
, "no instruction info for target " + TripleName
);
733 std::unique_ptr
<const MCInstrAnalysis
> MIA(
734 TheTarget
->createMCInstrAnalysis(MII
.get()));
735 failIfEmpty(MIA
, "no instruction analysis info for target " + TripleName
);
737 auto SanCovAddrs
= findSanitizerCovFunctions(O
);
738 if (SanCovAddrs
.empty())
739 fail("__sanitizer_cov* functions not found");
741 for (object::SectionRef Section
: O
.sections()) {
742 if (Section
.isVirtual() || !Section
.isText()) // llvm-objdump does the same.
744 uint64_t SectionAddr
= Section
.getAddress();
745 uint64_t SectSize
= Section
.getSize();
749 Expected
<StringRef
> BytesStr
= Section
.getContents();
750 failIfError(BytesStr
);
751 ArrayRef
<uint8_t> Bytes
= arrayRefFromStringRef(*BytesStr
);
753 for (uint64_t Index
= 0, Size
= 0; Index
< Section
.getSize();
756 if (!DisAsm
->getInstruction(Inst
, Size
, Bytes
.slice(Index
),
757 SectionAddr
+ Index
, nulls(), nulls())) {
762 uint64_t Addr
= Index
+ SectionAddr
;
763 // Sanitizer coverage uses the address of the next instruction - 1.
764 uint64_t CovPoint
= getPreviousInstructionPc(Addr
+ Size
, TheTriple
);
766 if (MIA
->isCall(Inst
) &&
767 MIA
->evaluateBranch(Inst
, SectionAddr
+ Index
, Size
, Target
) &&
768 SanCovAddrs
.find(Target
) != SanCovAddrs
.end())
769 Addrs
->insert(CovPoint
);
775 visitObjectFiles(const object::Archive
&A
,
776 function_ref
<void(const object::ObjectFile
&)> Fn
) {
777 Error Err
= Error::success();
778 for (auto &C
: A
.children(Err
)) {
779 Expected
<std::unique_ptr
<object::Binary
>> ChildOrErr
= C
.getAsBinary();
780 failIfError(ChildOrErr
);
781 if (auto *O
= dyn_cast
<object::ObjectFile
>(&*ChildOrErr
.get()))
784 failIfError(object::object_error::invalid_file_type
);
786 failIfError(std::move(Err
));
790 visitObjectFiles(const std::string
&FileName
,
791 function_ref
<void(const object::ObjectFile
&)> Fn
) {
792 Expected
<object::OwningBinary
<object::Binary
>> BinaryOrErr
=
793 object::createBinary(FileName
);
795 failIfError(BinaryOrErr
);
797 object::Binary
&Binary
= *BinaryOrErr
.get().getBinary();
798 if (object::Archive
*A
= dyn_cast
<object::Archive
>(&Binary
))
799 visitObjectFiles(*A
, Fn
);
800 else if (object::ObjectFile
*O
= dyn_cast
<object::ObjectFile
>(&Binary
))
803 failIfError(object::object_error::invalid_file_type
);
806 static std::set
<uint64_t>
807 findSanitizerCovFunctions(const std::string
&FileName
) {
808 std::set
<uint64_t> Result
;
809 visitObjectFiles(FileName
, [&](const object::ObjectFile
&O
) {
810 auto Addrs
= findSanitizerCovFunctions(O
);
811 Result
.insert(Addrs
.begin(), Addrs
.end());
816 // Locate addresses of all coverage points in a file. Coverage point
817 // is defined as the 'address of instruction following __sanitizer_cov
819 static std::set
<uint64_t> findCoveragePointAddrs(const std::string
&FileName
) {
820 std::set
<uint64_t> Result
;
821 visitObjectFiles(FileName
, [&](const object::ObjectFile
&O
) {
822 getObjectCoveragePoints(O
, &Result
);
827 static void printCovPoints(const std::string
&ObjFile
, raw_ostream
&OS
) {
828 for (uint64_t Addr
: findCoveragePointAddrs(ObjFile
)) {
835 static ErrorOr
<bool> isCoverageFile(const std::string
&FileName
) {
836 auto ShortFileName
= llvm::sys::path::filename(FileName
);
837 if (!SancovFileRegex
.match(ShortFileName
))
840 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
841 MemoryBuffer::getFile(FileName
);
843 errs() << "Warning: " << BufOrErr
.getError().message() << "("
844 << BufOrErr
.getError().value()
845 << "), filename: " << llvm::sys::path::filename(FileName
) << "\n";
846 return BufOrErr
.getError();
848 std::unique_ptr
<MemoryBuffer
> Buf
= std::move(BufOrErr
.get());
849 if (Buf
->getBufferSize() < 8) {
852 const FileHeader
*Header
=
853 reinterpret_cast<const FileHeader
*>(Buf
->getBufferStart());
854 return Header
->Magic
== BinCoverageMagic
;
857 static bool isSymbolizedCoverageFile(const std::string
&FileName
) {
858 auto ShortFileName
= llvm::sys::path::filename(FileName
);
859 return SymcovFileRegex
.match(ShortFileName
);
862 static std::unique_ptr
<SymbolizedCoverage
>
863 symbolize(const RawCoverage
&Data
, const std::string ObjectFile
) {
864 auto Coverage
= std::make_unique
<SymbolizedCoverage
>();
866 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
867 MemoryBuffer::getFile(ObjectFile
);
868 failIfError(BufOrErr
);
870 Hasher
.update((*BufOrErr
)->getBuffer());
871 Coverage
->BinaryHash
= toHex(Hasher
.final());
874 auto Symbolizer(createSymbolizer());
876 for (uint64_t Addr
: *Data
.Addrs
) {
877 // TODO: it would be neccessary to set proper section index here.
878 // object::SectionedAddress::UndefSection works for only absolute addresses.
879 auto LineInfo
= Symbolizer
->symbolizeCode(
880 ObjectFile
, {Addr
, object::SectionedAddress::UndefSection
});
881 failIfError(LineInfo
);
882 if (B
.isBlacklisted(*LineInfo
))
885 Coverage
->CoveredIds
.insert(utohexstr(Addr
, true));
888 std::set
<uint64_t> AllAddrs
= findCoveragePointAddrs(ObjectFile
);
889 if (!std::includes(AllAddrs
.begin(), AllAddrs
.end(), Data
.Addrs
->begin(),
890 Data
.Addrs
->end())) {
891 fail("Coverage points in binary and .sancov file do not match.");
893 Coverage
->Points
= getCoveragePoints(ObjectFile
, AllAddrs
, *Data
.Addrs
);
898 bool operator<(const FileFn
&RHS
) const {
899 return std::tie(FileName
, FunctionName
) <
900 std::tie(RHS
.FileName
, RHS
.FunctionName
);
903 std::string FileName
;
904 std::string FunctionName
;
907 static std::set
<FileFn
>
908 computeFunctions(const std::vector
<CoveragePoint
> &Points
) {
909 std::set
<FileFn
> Fns
;
910 for (const auto &Point
: Points
) {
911 for (const auto &Loc
: Point
.Locs
) {
912 Fns
.insert(FileFn
{Loc
.FileName
, Loc
.FunctionName
});
918 static std::set
<FileFn
>
919 computeNotCoveredFunctions(const SymbolizedCoverage
&Coverage
) {
920 auto Fns
= computeFunctions(Coverage
.Points
);
922 for (const auto &Point
: Coverage
.Points
) {
923 if (Coverage
.CoveredIds
.find(Point
.Id
) == Coverage
.CoveredIds
.end())
926 for (const auto &Loc
: Point
.Locs
) {
927 Fns
.erase(FileFn
{Loc
.FileName
, Loc
.FunctionName
});
934 static std::set
<FileFn
>
935 computeCoveredFunctions(const SymbolizedCoverage
&Coverage
) {
936 auto AllFns
= computeFunctions(Coverage
.Points
);
937 std::set
<FileFn
> Result
;
939 for (const auto &Point
: Coverage
.Points
) {
940 if (Coverage
.CoveredIds
.find(Point
.Id
) == Coverage
.CoveredIds
.end())
943 for (const auto &Loc
: Point
.Locs
) {
944 Result
.insert(FileFn
{Loc
.FileName
, Loc
.FunctionName
});
951 typedef std::map
<FileFn
, std::pair
<uint32_t, uint32_t>> FunctionLocs
;
952 // finds first location in a file for each function.
953 static FunctionLocs
resolveFunctions(const SymbolizedCoverage
&Coverage
,
954 const std::set
<FileFn
> &Fns
) {
956 for (const auto &Point
: Coverage
.Points
) {
957 for (const auto &Loc
: Point
.Locs
) {
958 FileFn Fn
= FileFn
{Loc
.FileName
, Loc
.FunctionName
};
959 if (Fns
.find(Fn
) == Fns
.end())
962 auto P
= std::make_pair(Loc
.Line
, Loc
.Column
);
963 auto I
= Result
.find(Fn
);
964 if (I
== Result
.end() || I
->second
> P
) {
972 static void printFunctionLocs(const FunctionLocs
&FnLocs
, raw_ostream
&OS
) {
973 for (const auto &P
: FnLocs
) {
974 OS
<< stripPathPrefix(P
.first
.FileName
) << ":" << P
.second
.first
<< " "
975 << P
.first
.FunctionName
<< "\n";
978 CoverageStats
computeStats(const SymbolizedCoverage
&Coverage
) {
979 CoverageStats Stats
= {Coverage
.Points
.size(), Coverage
.CoveredIds
.size(),
980 computeFunctions(Coverage
.Points
).size(),
981 computeCoveredFunctions(Coverage
).size()};
985 // Print list of covered functions.
986 // Line format: <file_name>:<line> <function_name>
987 static void printCoveredFunctions(const SymbolizedCoverage
&CovData
,
989 auto CoveredFns
= computeCoveredFunctions(CovData
);
990 printFunctionLocs(resolveFunctions(CovData
, CoveredFns
), OS
);
993 // Print list of not covered functions.
994 // Line format: <file_name>:<line> <function_name>
995 static void printNotCoveredFunctions(const SymbolizedCoverage
&CovData
,
997 auto NotCoveredFns
= computeNotCoveredFunctions(CovData
);
998 printFunctionLocs(resolveFunctions(CovData
, NotCoveredFns
), OS
);
1001 // Read list of files and merges their coverage info.
1002 static void readAndPrintRawCoverage(const std::vector
<std::string
> &FileNames
,
1004 std::vector
<std::unique_ptr
<RawCoverage
>> Covs
;
1005 for (const auto &FileName
: FileNames
) {
1006 auto Cov
= RawCoverage::read(FileName
);
1013 static std::unique_ptr
<SymbolizedCoverage
>
1014 merge(const std::vector
<std::unique_ptr
<SymbolizedCoverage
>> &Coverages
) {
1015 if (Coverages
.empty())
1018 auto Result
= std::make_unique
<SymbolizedCoverage
>();
1020 for (size_t I
= 0; I
< Coverages
.size(); ++I
) {
1021 const SymbolizedCoverage
&Coverage
= *Coverages
[I
];
1023 if (Coverages
.size() > 1) {
1024 // prefix is not needed when there's only one file.
1028 for (const auto &Id
: Coverage
.CoveredIds
) {
1029 Result
->CoveredIds
.insert(Prefix
+ Id
);
1032 for (const auto &CovPoint
: Coverage
.Points
) {
1033 CoveragePoint
NewPoint(CovPoint
);
1034 NewPoint
.Id
= Prefix
+ CovPoint
.Id
;
1035 Result
->Points
.push_back(NewPoint
);
1039 if (Coverages
.size() == 1) {
1040 Result
->BinaryHash
= Coverages
[0]->BinaryHash
;
1046 static std::unique_ptr
<SymbolizedCoverage
>
1047 readSymbolizeAndMergeCmdArguments(std::vector
<std::string
> FileNames
) {
1048 std::vector
<std::unique_ptr
<SymbolizedCoverage
>> Coverages
;
1051 // Short name => file name.
1052 std::map
<std::string
, std::string
> ObjFiles
;
1053 std::string FirstObjFile
;
1054 std::set
<std::string
> CovFiles
;
1056 // Partition input values into coverage/object files.
1057 for (const auto &FileName
: FileNames
) {
1058 if (isSymbolizedCoverageFile(FileName
)) {
1059 Coverages
.push_back(SymbolizedCoverage::read(FileName
));
1062 auto ErrorOrIsCoverage
= isCoverageFile(FileName
);
1063 if (!ErrorOrIsCoverage
)
1065 if (ErrorOrIsCoverage
.get()) {
1066 CovFiles
.insert(FileName
);
1068 auto ShortFileName
= llvm::sys::path::filename(FileName
);
1069 if (ObjFiles
.find(ShortFileName
) != ObjFiles
.end()) {
1070 fail("Duplicate binary file with a short name: " + ShortFileName
);
1073 ObjFiles
[ShortFileName
] = FileName
;
1074 if (FirstObjFile
.empty())
1075 FirstObjFile
= FileName
;
1079 SmallVector
<StringRef
, 2> Components
;
1081 // Object file => list of corresponding coverage file names.
1082 std::map
<std::string
, std::vector
<std::string
>> CoverageByObjFile
;
1083 for (const auto &FileName
: CovFiles
) {
1084 auto ShortFileName
= llvm::sys::path::filename(FileName
);
1085 auto Ok
= SancovFileRegex
.match(ShortFileName
, &Components
);
1087 fail("Can't match coverage file name against "
1088 "<module_name>.<pid>.sancov pattern: " +
1092 auto Iter
= ObjFiles
.find(Components
[1]);
1093 if (Iter
== ObjFiles
.end()) {
1094 fail("Object file for coverage not found: " + FileName
);
1097 CoverageByObjFile
[Iter
->second
].push_back(FileName
);
1100 for (const auto &Pair
: ObjFiles
) {
1101 auto FileName
= Pair
.second
;
1102 if (CoverageByObjFile
.find(FileName
) == CoverageByObjFile
.end())
1103 errs() << "WARNING: No coverage file for " << FileName
<< "\n";
1106 // Read raw coverage and symbolize it.
1107 for (const auto &Pair
: CoverageByObjFile
) {
1108 if (findSanitizerCovFunctions(Pair
.first
).empty()) {
1110 << "WARNING: Ignoring " << Pair
.first
1111 << " and its coverage because __sanitizer_cov* functions were not "
1116 for (const std::string
&CoverageFile
: Pair
.second
) {
1117 auto DataOrError
= RawCoverage::read(CoverageFile
);
1118 failIfError(DataOrError
);
1119 Coverages
.push_back(symbolize(*DataOrError
.get(), Pair
.first
));
1124 return merge(Coverages
);
1129 int main(int Argc
, char **Argv
) {
1130 // Print stack trace if we signal out.
1131 sys::PrintStackTraceOnErrorSignal(Argv
[0]);
1132 PrettyStackTraceProgram
X(Argc
, Argv
);
1133 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
1135 llvm::InitializeAllTargetInfos();
1136 llvm::InitializeAllTargetMCs();
1137 llvm::InitializeAllDisassemblers();
1139 cl::ParseCommandLineOptions(Argc
, Argv
,
1140 "Sanitizer Coverage Processing Tool (sancov)\n\n"
1141 " This tool can extract various coverage-related information from: \n"
1142 " coverage-instrumented binary files, raw .sancov files and their "
1143 "symbolized .symcov version.\n"
1144 " Depending on chosen action the tool expects different input files:\n"
1145 " -print-coverage-pcs - coverage-instrumented binary files\n"
1146 " -print-coverage - .sancov files\n"
1147 " <other actions> - .sancov files & corresponding binary "
1148 "files, .symcov files\n"
1151 // -print doesn't need object files.
1152 if (Action
== PrintAction
) {
1153 readAndPrintRawCoverage(ClInputFiles
, outs());
1155 } else if (Action
== PrintCovPointsAction
) {
1156 // -print-coverage-points doesn't need coverage files.
1157 for (const std::string
&ObjFile
: ClInputFiles
) {
1158 printCovPoints(ObjFile
, outs());
1163 auto Coverage
= readSymbolizeAndMergeCmdArguments(ClInputFiles
);
1164 failIf(!Coverage
, "No valid coverage files given.");
1167 case CoveredFunctionsAction
: {
1168 printCoveredFunctions(*Coverage
, outs());
1171 case NotCoveredFunctionsAction
: {
1172 printNotCoveredFunctions(*Coverage
, outs());
1176 outs() << computeStats(*Coverage
);
1180 case SymbolizeAction
: { // merge & symbolize are synonims.
1181 json::OStream
W(outs(), 2);
1185 case HtmlReportAction
:
1186 errs() << "-html-report option is removed: "
1187 "use -symbolize & coverage-report-server.py instead\n";
1190 case PrintCovPointsAction
:
1191 llvm_unreachable("unsupported action");