sancov -not-covered-functions.
[oota-llvm.git] / tools / sancov / sancov.cc
1 //===-- sancov.cc --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a command-line tool for reading and analyzing sanitizer
11 // coverage.
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"
41
42 #include <set>
43 #include <stdio.h>
44 #include <string>
45 #include <vector>
46
47 using namespace llvm;
48
49 namespace {
50
51 // --------- COMMAND LINE FLAGS ---------
52
53 enum ActionType {
54   PrintAction,
55   CoveredFunctionsAction,
56   NotCoveredFunctionsAction
57 };
58
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."),
66                clEnumValEnd));
67
68 static cl::list<std::string> ClInputFiles(cl::Positional, cl::OneOrMore,
69                                           cl::desc("<filenames...>"));
70
71 static cl::opt<std::string>
72     ClBinaryName("obj", cl::Required,
73                  cl::desc("Path to object file to be symbolized"));
74
75 static cl::opt<bool>
76     ClDemangle("demangle", cl::init(true),
77         cl::desc("Print demangled function name."));
78
79 static cl::opt<std::string> ClStripPathPrefix(
80     "strip_path_prefix", cl::init(""),
81     cl::desc("Strip this prefix from file paths in reports."));
82
83 // --------- FORMAT SPECIFICATION ---------
84
85 struct FileHeader {
86   uint32_t Bitness;
87   uint32_t Magic;
88 };
89
90 static const uint32_t BinCoverageMagic = 0xC0BFFFFF;
91 static const uint32_t Bitness32 = 0xFFFFFF32;
92 static const uint32_t Bitness64 = 0xFFFFFF64;
93
94 // ---------
95
96 static void FailIfError(std::error_code Error) {
97   if (!Error)
98     return;
99   errs() << "Error: " << Error.message() << "(" << Error.value() << ")\n";
100   exit(1);
101 }
102
103 template <typename T> static void FailIfError(const ErrorOr<T> &E) {
104   FailIfError(E.getError());
105 }
106
107 static void FailIfNotEmpty(const std::string &E) {
108   if (E.empty())
109     return;
110   errs() << "Error: " << E << "\n";
111   exit(1);
112 }
113
114 template <typename T>
115 static void FailIfEmpty(const std::unique_ptr<T> &Ptr,
116                         const std::string &Message) {
117   if (Ptr.get())
118     return;
119   errs() << "Error: " << Message << "\n";
120   exit(1);
121 }
122
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()));
129 }
130
131 struct FileLoc {
132   bool operator<(const FileLoc &RHS) const {
133     return std::tie(FileName, Line) < std::tie(RHS.FileName, RHS.Line);
134   }
135
136   std::string FileName;
137   uint32_t Line;
138 };
139
140 struct FunctionLoc {
141   bool operator<(const FunctionLoc &RHS) const {
142     return std::tie(Loc, FunctionName) < std::tie(RHS.Loc, RHS.FunctionName);
143   }
144
145   FileLoc Loc;
146   std::string FunctionName;
147 };
148
149 std::string stripPathPrefix(std::string Path) {
150   if (ClStripPathPrefix.empty())
151     return Path;
152   size_t Pos = Path.find(ClStripPathPrefix);
153   if (Pos == std::string::npos)
154     return Path;
155   return Path.substr(Pos + ClStripPathPrefix.size());
156 }
157
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;
162
163   symbolize::LLVMSymbolizer::Options SymbolizerOptions;
164   SymbolizerOptions.Demangle = ClDemangle;
165   SymbolizerOptions.UseSymbolTable = true;
166   symbolize::LLVMSymbolizer Symbolizer(SymbolizerOptions);
167
168   // Fill in Fns map.
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;
178     }
179   }
180
181   return Fns;
182 }
183
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);
188
189   std::set<FunctionLoc> result;
190   std::string LastFileName;
191   std::set<std::string> ProcessedFunctions;
192
193   for (const auto &P : Fns) {
194     std::string FileName = P.first.FileName;
195     std::string FunctionName = P.second;
196
197     if (LastFileName != FileName)
198       ProcessedFunctions.clear();
199     LastFileName = FileName;
200
201     if (!ProcessedFunctions.insert(FunctionName).second)
202       continue;
203
204     result.insert(FunctionLoc{P.first, P.second});
205   }
206
207   return result;
208 }
209
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);
215
216     ErrorOr<StringRef> Name = Symbol.getName();
217     FailIfError(Name);
218
219     if (Name.get() == "__sanitizer_cov") {
220       return AddressOrErr.get();
221     }
222   }
223   FailIfNotEmpty("__sanitizer_cov not found");
224   return 0; // not reachable.
225 }
226
227 // Locate addresses of all coverage points in a file. Coverage point
228 // is defined as the 'address of instruction following __sanitizer_cov
229 // call - 1'.
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();
235
236   std::string Error;
237   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
238   FailIfNotEmpty(Error);
239
240   std::unique_ptr<const MCSubtargetInfo> STI(
241       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
242   FailIfEmpty(STI, "no subtarget info for target " + TripleName);
243
244   std::unique_ptr<const MCRegisterInfo> MRI(
245       TheTarget->createMCRegInfo(TripleName));
246   FailIfEmpty(MRI, "no register info for target " + TripleName);
247
248   std::unique_ptr<const MCAsmInfo> AsmInfo(
249       TheTarget->createMCAsmInfo(*MRI, TripleName));
250   FailIfEmpty(AsmInfo, "no asm info for target " + TripleName);
251
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);
257
258   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
259   FailIfEmpty(MII, "no instruction info for target " + TripleName);
260
261   std::unique_ptr<const MCInstrAnalysis> MIA(
262       TheTarget->createMCInstrAnalysis(MII.get()));
263   FailIfEmpty(MIA, "no instruction analysis info for target " + TripleName);
264
265   uint64_t SanCovAddr = findSanitizerCovFunction(O);
266
267   for (const auto Section : O.sections()) {
268     if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same.
269       continue;
270     uint64_t SectionAddr = Section.getAddress();
271     uint64_t SectSize = Section.getSize();
272     if (!SectSize)
273       continue;
274
275     StringRef SectionName;
276     FailIfError(Section.getName(SectionName));
277
278     StringRef BytesStr;
279     FailIfError(Section.getContents(BytesStr));
280     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
281                             BytesStr.size());
282
283     for (uint64_t Index = 0, Size = 0; Index < Section.getSize();
284          Index += Size) {
285       MCInst Inst;
286       if (!DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
287                                   SectionAddr + Index, nulls(), nulls())) {
288         if (Size == 0)
289           Size = 1;
290         continue;
291       }
292       uint64_t Target;
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);
298         }
299       }
300     }
301   }
302 }
303
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);
314     else
315       FailIfError(object::object_error::invalid_file_type);
316   }
317 }
318
319 // Locate addresses of all coverage points in a file. Coverage point
320 // is defined as the 'address of instruction following __sanitizer_cov
321 // call - 1'.
322 std::set<uint64_t> getCoveragePoints(std::string FileName) {
323   std::set<uint64_t> Result;
324
325   ErrorOr<object::OwningBinary<object::Binary>> BinaryOrErr =
326       object::createBinary(FileName);
327   FailIfError(BinaryOrErr);
328
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);
334   else
335     FailIfError(object::object_error::invalid_file_type);
336
337   return Result;
338 }
339
340 static void printFunctionLocs(const std::set<FunctionLoc> &FnLocs,
341                               raw_ostream &OS) {
342   for (const FunctionLoc &FnLoc : FnLocs) {
343     OS << stripPathPrefix(FnLoc.Loc.FileName) << ":" << FnLoc.Loc.Line << " "
344        << FnLoc.FunctionName << "\n";
345   }
346 }
347
348 class CoverageData {
349  public:
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);
354     if (!BufOrErr)
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);
360     }
361     const FileHeader *Header =
362         reinterpret_cast<const FileHeader *>(Buf->getBufferStart());
363
364     if (Header->Magic != BinCoverageMagic) {
365       errs() << "Wrong magic: " << Header->Magic;
366       return make_error_code(errc::illegal_byte_sequence);
367     }
368
369     auto Addrs = llvm::make_unique<std::set<uint64_t>>();
370
371     switch (Header->Bitness) {
372     case Bitness64:
373       readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(),
374                          Addrs.get());
375       break;
376     case Bitness32:
377       readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(),
378                          Addrs.get());
379       break;
380     default:
381       errs() << "Unsupported bitness: " << Header->Bitness;
382       return make_error_code(errc::illegal_byte_sequence);
383     }
384
385     return std::unique_ptr<CoverageData>(new CoverageData(std::move(Addrs)));
386   }
387
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>>();
392
393     for (const auto &Cov : Covs)
394       Addrs->insert(Cov->Addrs->begin(), Cov->Addrs->end());
395
396     return std::unique_ptr<CoverageData>(new CoverageData(std::move(Addrs)));
397   }
398
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);
405       if (!Cov)
406         return Cov.getError();
407       Covs.push_back(std::move(Cov.get()));
408     }
409     return merge(Covs);
410   }
411
412   // Print coverage addresses.
413   void printAddrs(raw_ostream &OS) {
414     for (auto Addr : *Addrs) {
415       OS << "0x";
416       OS.write_hex(Addr);
417       OS << "\n";
418     }
419   }
420
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);
425   }
426
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);
433
434     std::set<FunctionLoc> NotCoveredFns;
435     std::set_difference(AllFns.begin(), AllFns.end(), CoveredFns.begin(),
436                         CoveredFns.end(),
437                         std::inserter(NotCoveredFns, NotCoveredFns.end()));
438     printFunctionLocs(NotCoveredFns, OS);
439   }
440
441 private:
442   explicit CoverageData(std::unique_ptr<std::set<uint64_t>> Addrs)
443       : Addrs(std::move(Addrs)) {}
444
445   std::unique_ptr<std::set<uint64_t>> Addrs;
446 };
447 } // namespace
448
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.
454
455   llvm::InitializeAllTargetInfos();
456   llvm::InitializeAllTargetMCs();
457   llvm::InitializeAllDisassemblers();
458
459   cl::ParseCommandLineOptions(argc, argv, "Sanitizer Coverage Processing Tool");
460
461   auto CovData = CoverageData::readAndMerge(ClInputFiles);
462   FailIfError(CovData);
463
464   switch (Action) {
465   case PrintAction: {
466     CovData.get()->printAddrs(outs());
467     return 0;
468   }
469   case CoveredFunctionsAction: {
470     CovData.get()->printCoveredFunctions(outs());
471     return 0;
472   }
473   case NotCoveredFunctionsAction: {
474     CovData.get()->printNotCoveredFunctions(outs());
475     return 0;
476   }
477   }
478
479   llvm_unreachable("unsupported action");
480 }