1 //===-- sancov.cc --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a command-line tool for reading and analyzing sanitizer
12 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/STLExtras.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.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrAnalysis.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Object/Binary.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Errc.h"
29 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/LineIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Support/raw_ostream.h"
51 // --------- COMMAND LINE FLAGS ---------
55 CoveredFunctionsAction,
56 NotCoveredFunctionsAction
59 cl::opt<ActionType> Action(
60 cl::desc("Action (required)"), cl::Required,
61 cl::values(clEnumValN(PrintAction, "print", "Print coverage addresses"),
62 clEnumValN(CoveredFunctionsAction, "covered-functions",
63 "Print all covered funcions."),
64 clEnumValN(NotCoveredFunctionsAction, "not-covered-functions",
65 "Print all not covered funcions."),
68 static cl::list<std::string> ClInputFiles(cl::Positional, cl::OneOrMore,
69 cl::desc("<filenames...>"));
71 static cl::opt<std::string>
72 ClBinaryName("obj", cl::Required,
73 cl::desc("Path to object file to be symbolized"));
76 ClDemangle("demangle", cl::init(true),
77 cl::desc("Print demangled function name."));
79 static cl::opt<std::string> ClStripPathPrefix(
80 "strip_path_prefix", cl::init(""),
81 cl::desc("Strip this prefix from file paths in reports."));
83 // --------- FORMAT SPECIFICATION ---------
90 static const uint32_t BinCoverageMagic = 0xC0BFFFFF;
91 static const uint32_t Bitness32 = 0xFFFFFF32;
92 static const uint32_t Bitness64 = 0xFFFFFF64;
96 static void FailIfError(std::error_code Error) {
99 errs() << "Error: " << Error.message() << "(" << Error.value() << ")\n";
103 template <typename T> static void FailIfError(const ErrorOr<T> &E) {
104 FailIfError(E.getError());
107 static void FailIfNotEmpty(const std::string &E) {
110 errs() << "Error: " << E << "\n";
114 template <typename T>
115 static void FailIfEmpty(const std::unique_ptr<T> &Ptr,
116 const std::string &Message) {
119 errs() << "Error: " << Message << "\n";
123 template <typename T>
124 static void readInts(const char *Start, const char *End,
125 std::set<uint64_t> *Ints) {
126 const T *S = reinterpret_cast<const T *>(Start);
127 const T *E = reinterpret_cast<const T *>(End);
128 std::copy(S, E, std::inserter(*Ints, Ints->end()));
132 bool operator<(const FileLoc &RHS) const {
133 return std::tie(FileName, Line) < std::tie(RHS.FileName, RHS.Line);
136 std::string FileName;
141 bool operator<(const FunctionLoc &RHS) const {
142 return std::tie(Loc, FunctionName) < std::tie(RHS.Loc, RHS.FunctionName);
146 std::string FunctionName;
149 std::string stripPathPrefix(std::string Path) {
150 if (ClStripPathPrefix.empty())
152 size_t Pos = Path.find(ClStripPathPrefix);
153 if (Pos == std::string::npos)
155 return Path.substr(Pos + ClStripPathPrefix.size());
158 // Compute [FileLoc -> FunctionName] map for given addresses.
159 static std::map<FileLoc, std::string>
160 computeFunctionsMap(const std::set<uint64_t> &Addrs) {
161 std::map<FileLoc, std::string> Fns;
163 symbolize::LLVMSymbolizer::Options SymbolizerOptions;
164 SymbolizerOptions.Demangle = ClDemangle;
165 SymbolizerOptions.UseSymbolTable = true;
166 symbolize::LLVMSymbolizer Symbolizer(SymbolizerOptions);
169 for (auto Addr : Addrs) {
170 auto InliningInfo = Symbolizer.symbolizeInlinedCode(ClBinaryName, Addr);
171 FailIfError(InliningInfo);
172 for (uint32_t i = 0; i < InliningInfo->getNumberOfFrames(); ++i) {
173 auto FrameInfo = InliningInfo->getFrame(i);
174 SmallString<256> FileName(FrameInfo.FileName);
175 sys::path::remove_dots(FileName, /* remove_dot_dot */ true);
176 FileLoc Loc = {FileName.str(), FrameInfo.Line};
177 Fns[Loc] = FrameInfo.FunctionName;
184 // Compute functions for given addresses. It keeps only the first
185 // occurence of a function within a file.
186 std::set<FunctionLoc> computeFunctionLocs(const std::set<uint64_t> &Addrs) {
187 std::map<FileLoc, std::string> Fns = computeFunctionsMap(Addrs);
189 std::set<FunctionLoc> result;
190 std::string LastFileName;
191 std::set<std::string> ProcessedFunctions;
193 for (const auto &P : Fns) {
194 std::string FileName = P.first.FileName;
195 std::string FunctionName = P.second;
197 if (LastFileName != FileName)
198 ProcessedFunctions.clear();
199 LastFileName = FileName;
201 if (!ProcessedFunctions.insert(FunctionName).second)
204 result.insert(FunctionLoc{P.first, P.second});
210 // Locate __sanitizer_cov function address.
211 static uint64_t findSanitizerCovFunction(const object::ObjectFile &O) {
212 for (const object::SymbolRef &Symbol : O.symbols()) {
213 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
214 FailIfError(AddressOrErr);
216 ErrorOr<StringRef> Name = Symbol.getName();
219 if (Name.get() == "__sanitizer_cov") {
220 return AddressOrErr.get();
223 FailIfNotEmpty("__sanitizer_cov not found");
224 return 0; // not reachable.
227 // Locate addresses of all coverage points in a file. Coverage point
228 // is defined as the 'address of instruction following __sanitizer_cov
230 static void getObjectCoveragePoints(const object::ObjectFile &O,
231 std::set<uint64_t> *Addrs) {
232 Triple TheTriple("unknown-unknown-unknown");
233 TheTriple.setArch(Triple::ArchType(O.getArch()));
234 auto TripleName = TheTriple.getTriple();
237 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
238 FailIfNotEmpty(Error);
240 std::unique_ptr<const MCSubtargetInfo> STI(
241 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
242 FailIfEmpty(STI, "no subtarget info for target " + TripleName);
244 std::unique_ptr<const MCRegisterInfo> MRI(
245 TheTarget->createMCRegInfo(TripleName));
246 FailIfEmpty(MRI, "no register info for target " + TripleName);
248 std::unique_ptr<const MCAsmInfo> AsmInfo(
249 TheTarget->createMCAsmInfo(*MRI, TripleName));
250 FailIfEmpty(AsmInfo, "no asm info for target " + TripleName);
252 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
253 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
254 std::unique_ptr<MCDisassembler> DisAsm(
255 TheTarget->createMCDisassembler(*STI, Ctx));
256 FailIfEmpty(DisAsm, "no disassembler info for target " + TripleName);
258 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
259 FailIfEmpty(MII, "no instruction info for target " + TripleName);
261 std::unique_ptr<const MCInstrAnalysis> MIA(
262 TheTarget->createMCInstrAnalysis(MII.get()));
263 FailIfEmpty(MIA, "no instruction analysis info for target " + TripleName);
265 uint64_t SanCovAddr = findSanitizerCovFunction(O);
267 for (const auto Section : O.sections()) {
268 if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same.
270 uint64_t SectionAddr = Section.getAddress();
271 uint64_t SectSize = Section.getSize();
275 StringRef SectionName;
276 FailIfError(Section.getName(SectionName));
279 FailIfError(Section.getContents(BytesStr));
280 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
283 for (uint64_t Index = 0, Size = 0; Index < Section.getSize();
286 if (!DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
287 SectionAddr + Index, nulls(), nulls())) {
293 if (MIA->isCall(Inst) &&
294 MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
295 if (Target == SanCovAddr) {
296 // Sanitizer coverage uses the address of the next instruction - 1.
297 Addrs->insert(Index + SectionAddr + Size - 1);
304 static void getArchiveCoveragePoints(const object::Archive &A,
305 std::set<uint64_t> *Addrs) {
306 for (auto &ErrorOrChild : A.children()) {
307 FailIfError(ErrorOrChild);
308 const object::Archive::Child &C = *ErrorOrChild;
309 ErrorOr<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary();
310 FailIfError(ChildOrErr);
311 if (object::ObjectFile *O =
312 dyn_cast<object::ObjectFile>(&*ChildOrErr.get()))
313 getObjectCoveragePoints(*O, Addrs);
315 FailIfError(object::object_error::invalid_file_type);
319 // Locate addresses of all coverage points in a file. Coverage point
320 // is defined as the 'address of instruction following __sanitizer_cov
322 std::set<uint64_t> getCoveragePoints(std::string FileName) {
323 std::set<uint64_t> Result;
325 ErrorOr<object::OwningBinary<object::Binary>> BinaryOrErr =
326 object::createBinary(FileName);
327 FailIfError(BinaryOrErr);
329 object::Binary &Binary = *BinaryOrErr.get().getBinary();
330 if (object::Archive *A = dyn_cast<object::Archive>(&Binary))
331 getArchiveCoveragePoints(*A, &Result);
332 else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(&Binary))
333 getObjectCoveragePoints(*O, &Result);
335 FailIfError(object::object_error::invalid_file_type);
340 static void printFunctionLocs(const std::set<FunctionLoc> &FnLocs,
342 for (const FunctionLoc &FnLoc : FnLocs) {
343 OS << stripPathPrefix(FnLoc.Loc.FileName) << ":" << FnLoc.Loc.Line << " "
344 << FnLoc.FunctionName << "\n";
350 // Read single file coverage data.
351 static ErrorOr<std::unique_ptr<CoverageData>> read(std::string FileName) {
352 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
353 MemoryBuffer::getFile(FileName);
355 return BufOrErr.getError();
356 std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
357 if (Buf->getBufferSize() < 8) {
358 errs() << "File too small (<8): " << Buf->getBufferSize();
359 return make_error_code(errc::illegal_byte_sequence);
361 const FileHeader *Header =
362 reinterpret_cast<const FileHeader *>(Buf->getBufferStart());
364 if (Header->Magic != BinCoverageMagic) {
365 errs() << "Wrong magic: " << Header->Magic;
366 return make_error_code(errc::illegal_byte_sequence);
369 auto Addrs = llvm::make_unique<std::set<uint64_t>>();
371 switch (Header->Bitness) {
373 readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(),
377 readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(),
381 errs() << "Unsupported bitness: " << Header->Bitness;
382 return make_error_code(errc::illegal_byte_sequence);
385 return std::unique_ptr<CoverageData>(new CoverageData(std::move(Addrs)));
388 // Merge multiple coverage data together.
389 static std::unique_ptr<CoverageData>
390 merge(const std::vector<std::unique_ptr<CoverageData>> &Covs) {
391 auto Addrs = llvm::make_unique<std::set<uint64_t>>();
393 for (const auto &Cov : Covs)
394 Addrs->insert(Cov->Addrs->begin(), Cov->Addrs->end());
396 return std::unique_ptr<CoverageData>(new CoverageData(std::move(Addrs)));
399 // Read list of files and merges their coverage info.
400 static ErrorOr<std::unique_ptr<CoverageData>>
401 readAndMerge(const std::vector<std::string> &FileNames) {
402 std::vector<std::unique_ptr<CoverageData>> Covs;
403 for (const auto &FileName : FileNames) {
404 auto Cov = read(FileName);
406 return Cov.getError();
407 Covs.push_back(std::move(Cov.get()));
412 // Print coverage addresses.
413 void printAddrs(raw_ostream &OS) {
414 for (auto Addr : *Addrs) {
421 // Print list of covered functions.
422 // Line format: <file_name>:<line> <function_name>
423 void printCoveredFunctions(raw_ostream &OS) {
424 printFunctionLocs(computeFunctionLocs(*Addrs), OS);
427 // Print list of not covered functions.
428 // Line format: <file_name>:<line> <function_name>
429 void printNotCoveredFunctions(raw_ostream &OS) {
430 std::set<FunctionLoc> AllFns =
431 computeFunctionLocs(getCoveragePoints(ClBinaryName));
432 std::set<FunctionLoc> CoveredFns = computeFunctionLocs(*Addrs);
434 std::set<FunctionLoc> NotCoveredFns;
435 std::set_difference(AllFns.begin(), AllFns.end(), CoveredFns.begin(),
437 std::inserter(NotCoveredFns, NotCoveredFns.end()));
438 printFunctionLocs(NotCoveredFns, OS);
442 explicit CoverageData(std::unique_ptr<std::set<uint64_t>> Addrs)
443 : Addrs(std::move(Addrs)) {}
445 std::unique_ptr<std::set<uint64_t>> Addrs;
449 int main(int argc, char **argv) {
450 // Print stack trace if we signal out.
451 sys::PrintStackTraceOnErrorSignal();
452 PrettyStackTraceProgram X(argc, argv);
453 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
455 llvm::InitializeAllTargetInfos();
456 llvm::InitializeAllTargetMCs();
457 llvm::InitializeAllDisassemblers();
459 cl::ParseCommandLineOptions(argc, argv, "Sanitizer Coverage Processing Tool");
461 auto CovData = CoverageData::readAndMerge(ClInputFiles);
462 FailIfError(CovData);
466 CovData.get()->printAddrs(outs());
469 case CoveredFunctionsAction: {
470 CovData.get()->printCoveredFunctions(outs());
473 case NotCoveredFunctionsAction: {
474 CovData.get()->printNotCoveredFunctions(outs());
479 llvm_unreachable("unsupported action");