sancov.cpp 38 KB

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