sancov.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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/Object/Archive.h"
  26. #include "llvm/Object/Binary.h"
  27. #include "llvm/Object/COFF.h"
  28. #include "llvm/Object/MachO.h"
  29. #include "llvm/Object/ObjectFile.h"
  30. #include "llvm/Support/Casting.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Errc.h"
  33. #include "llvm/Support/ErrorOr.h"
  34. #include "llvm/Support/FileSystem.h"
  35. #include "llvm/Support/InitLLVM.h"
  36. #include "llvm/Support/JSON.h"
  37. #include "llvm/Support/MD5.h"
  38. #include "llvm/Support/MemoryBuffer.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Regex.h"
  41. #include "llvm/Support/SHA1.h"
  42. #include "llvm/Support/SourceMgr.h"
  43. #include "llvm/Support/SpecialCaseList.h"
  44. #include "llvm/Support/TargetRegistry.h"
  45. #include "llvm/Support/TargetSelect.h"
  46. #include "llvm/Support/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. std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
  620. MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
  621. std::unique_ptr<MCDisassembler> DisAsm(
  622. TheTarget->createMCDisassembler(*STI, Ctx));
  623. failIfEmpty(DisAsm, "no disassembler info for target " + TripleName);
  624. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  625. failIfEmpty(MII, "no instruction info for target " + TripleName);
  626. std::unique_ptr<const MCInstrAnalysis> MIA(
  627. TheTarget->createMCInstrAnalysis(MII.get()));
  628. failIfEmpty(MIA, "no instruction analysis info for target " + TripleName);
  629. auto SanCovAddrs = findSanitizerCovFunctions(O);
  630. if (SanCovAddrs.empty())
  631. fail("__sanitizer_cov* functions not found");
  632. for (object::SectionRef Section : O.sections()) {
  633. if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same.
  634. continue;
  635. uint64_t SectionAddr = Section.getAddress();
  636. uint64_t SectSize = Section.getSize();
  637. if (!SectSize)
  638. continue;
  639. Expected<StringRef> BytesStr = Section.getContents();
  640. failIfError(BytesStr);
  641. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(*BytesStr);
  642. for (uint64_t Index = 0, Size = 0; Index < Section.getSize();
  643. Index += Size) {
  644. MCInst Inst;
  645. if (!DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  646. SectionAddr + Index, nulls())) {
  647. if (Size == 0)
  648. Size = 1;
  649. continue;
  650. }
  651. uint64_t Addr = Index + SectionAddr;
  652. // Sanitizer coverage uses the address of the next instruction - 1.
  653. uint64_t CovPoint = getPreviousInstructionPc(Addr + Size, TheTriple);
  654. uint64_t Target;
  655. if (MIA->isCall(Inst) &&
  656. MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target) &&
  657. SanCovAddrs.find(Target) != SanCovAddrs.end())
  658. Addrs->insert(CovPoint);
  659. }
  660. }
  661. }
  662. static void
  663. visitObjectFiles(const object::Archive &A,
  664. function_ref<void(const object::ObjectFile &)> Fn) {
  665. Error Err = Error::success();
  666. for (auto &C : A.children(Err)) {
  667. Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary();
  668. failIfError(ChildOrErr);
  669. if (auto *O = dyn_cast<object::ObjectFile>(&*ChildOrErr.get()))
  670. Fn(*O);
  671. else
  672. failIfError(object::object_error::invalid_file_type);
  673. }
  674. failIfError(std::move(Err));
  675. }
  676. static void
  677. visitObjectFiles(const std::string &FileName,
  678. function_ref<void(const object::ObjectFile &)> Fn) {
  679. Expected<object::OwningBinary<object::Binary>> BinaryOrErr =
  680. object::createBinary(FileName);
  681. if (!BinaryOrErr)
  682. failIfError(BinaryOrErr);
  683. object::Binary &Binary = *BinaryOrErr.get().getBinary();
  684. if (object::Archive *A = dyn_cast<object::Archive>(&Binary))
  685. visitObjectFiles(*A, Fn);
  686. else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(&Binary))
  687. Fn(*O);
  688. else
  689. failIfError(object::object_error::invalid_file_type);
  690. }
  691. static std::set<uint64_t>
  692. findSanitizerCovFunctions(const std::string &FileName) {
  693. std::set<uint64_t> Result;
  694. visitObjectFiles(FileName, [&](const object::ObjectFile &O) {
  695. auto Addrs = findSanitizerCovFunctions(O);
  696. Result.insert(Addrs.begin(), Addrs.end());
  697. });
  698. return Result;
  699. }
  700. // Locate addresses of all coverage points in a file. Coverage point
  701. // is defined as the 'address of instruction following __sanitizer_cov
  702. // call - 1'.
  703. static std::set<uint64_t> findCoveragePointAddrs(const std::string &FileName) {
  704. std::set<uint64_t> Result;
  705. visitObjectFiles(FileName, [&](const object::ObjectFile &O) {
  706. getObjectCoveragePoints(O, &Result);
  707. });
  708. return Result;
  709. }
  710. static void printCovPoints(const std::string &ObjFile, raw_ostream &OS) {
  711. for (uint64_t Addr : findCoveragePointAddrs(ObjFile)) {
  712. OS << "0x";
  713. OS.write_hex(Addr);
  714. OS << "\n";
  715. }
  716. }
  717. static ErrorOr<bool> isCoverageFile(const std::string &FileName) {
  718. auto ShortFileName = llvm::sys::path::filename(FileName);
  719. if (!SancovFileRegex.match(ShortFileName))
  720. return false;
  721. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  722. MemoryBuffer::getFile(FileName);
  723. if (!BufOrErr) {
  724. errs() << "Warning: " << BufOrErr.getError().message() << "("
  725. << BufOrErr.getError().value()
  726. << "), filename: " << llvm::sys::path::filename(FileName) << "\n";
  727. return BufOrErr.getError();
  728. }
  729. std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
  730. if (Buf->getBufferSize() < 8) {
  731. return false;
  732. }
  733. const FileHeader *Header =
  734. reinterpret_cast<const FileHeader *>(Buf->getBufferStart());
  735. return Header->Magic == BinCoverageMagic;
  736. }
  737. static bool isSymbolizedCoverageFile(const std::string &FileName) {
  738. auto ShortFileName = llvm::sys::path::filename(FileName);
  739. return SymcovFileRegex.match(ShortFileName);
  740. }
  741. static std::unique_ptr<SymbolizedCoverage>
  742. symbolize(const RawCoverage &Data, const std::string ObjectFile) {
  743. auto Coverage = std::make_unique<SymbolizedCoverage>();
  744. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  745. MemoryBuffer::getFile(ObjectFile);
  746. failIfError(BufOrErr);
  747. SHA1 Hasher;
  748. Hasher.update((*BufOrErr)->getBuffer());
  749. Coverage->BinaryHash = toHex(Hasher.final());
  750. Blacklists B;
  751. auto Symbolizer(createSymbolizer());
  752. for (uint64_t Addr : *Data.Addrs) {
  753. // TODO: it would be neccessary to set proper section index here.
  754. // object::SectionedAddress::UndefSection works for only absolute addresses.
  755. auto LineInfo = Symbolizer->symbolizeCode(
  756. ObjectFile, {Addr, object::SectionedAddress::UndefSection});
  757. failIfError(LineInfo);
  758. if (B.isBlacklisted(*LineInfo))
  759. continue;
  760. Coverage->CoveredIds.insert(utohexstr(Addr, true));
  761. }
  762. std::set<uint64_t> AllAddrs = findCoveragePointAddrs(ObjectFile);
  763. if (!std::includes(AllAddrs.begin(), AllAddrs.end(), Data.Addrs->begin(),
  764. Data.Addrs->end())) {
  765. fail("Coverage points in binary and .sancov file do not match.");
  766. }
  767. Coverage->Points = getCoveragePoints(ObjectFile, AllAddrs, *Data.Addrs);
  768. return Coverage;
  769. }
  770. struct FileFn {
  771. bool operator<(const FileFn &RHS) const {
  772. return std::tie(FileName, FunctionName) <
  773. std::tie(RHS.FileName, RHS.FunctionName);
  774. }
  775. std::string FileName;
  776. std::string FunctionName;
  777. };
  778. static std::set<FileFn>
  779. computeFunctions(const std::vector<CoveragePoint> &Points) {
  780. std::set<FileFn> Fns;
  781. for (const auto &Point : Points) {
  782. for (const auto &Loc : Point.Locs) {
  783. Fns.insert(FileFn{Loc.FileName, Loc.FunctionName});
  784. }
  785. }
  786. return Fns;
  787. }
  788. static std::set<FileFn>
  789. computeNotCoveredFunctions(const SymbolizedCoverage &Coverage) {
  790. auto Fns = computeFunctions(Coverage.Points);
  791. for (const auto &Point : Coverage.Points) {
  792. if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end())
  793. continue;
  794. for (const auto &Loc : Point.Locs) {
  795. Fns.erase(FileFn{Loc.FileName, Loc.FunctionName});
  796. }
  797. }
  798. return Fns;
  799. }
  800. static std::set<FileFn>
  801. computeCoveredFunctions(const SymbolizedCoverage &Coverage) {
  802. auto AllFns = computeFunctions(Coverage.Points);
  803. std::set<FileFn> Result;
  804. for (const auto &Point : Coverage.Points) {
  805. if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end())
  806. continue;
  807. for (const auto &Loc : Point.Locs) {
  808. Result.insert(FileFn{Loc.FileName, Loc.FunctionName});
  809. }
  810. }
  811. return Result;
  812. }
  813. typedef std::map<FileFn, std::pair<uint32_t, uint32_t>> FunctionLocs;
  814. // finds first location in a file for each function.
  815. static FunctionLocs resolveFunctions(const SymbolizedCoverage &Coverage,
  816. const std::set<FileFn> &Fns) {
  817. FunctionLocs Result;
  818. for (const auto &Point : Coverage.Points) {
  819. for (const auto &Loc : Point.Locs) {
  820. FileFn Fn = FileFn{Loc.FileName, Loc.FunctionName};
  821. if (Fns.find(Fn) == Fns.end())
  822. continue;
  823. auto P = std::make_pair(Loc.Line, Loc.Column);
  824. auto I = Result.find(Fn);
  825. if (I == Result.end() || I->second > P) {
  826. Result[Fn] = P;
  827. }
  828. }
  829. }
  830. return Result;
  831. }
  832. static void printFunctionLocs(const FunctionLocs &FnLocs, raw_ostream &OS) {
  833. for (const auto &P : FnLocs) {
  834. OS << stripPathPrefix(P.first.FileName) << ":" << P.second.first << " "
  835. << P.first.FunctionName << "\n";
  836. }
  837. }
  838. CoverageStats computeStats(const SymbolizedCoverage &Coverage) {
  839. CoverageStats Stats = {Coverage.Points.size(), Coverage.CoveredIds.size(),
  840. computeFunctions(Coverage.Points).size(),
  841. computeCoveredFunctions(Coverage).size()};
  842. return Stats;
  843. }
  844. // Print list of covered functions.
  845. // Line format: <file_name>:<line> <function_name>
  846. static void printCoveredFunctions(const SymbolizedCoverage &CovData,
  847. raw_ostream &OS) {
  848. auto CoveredFns = computeCoveredFunctions(CovData);
  849. printFunctionLocs(resolveFunctions(CovData, CoveredFns), OS);
  850. }
  851. // Print list of not covered functions.
  852. // Line format: <file_name>:<line> <function_name>
  853. static void printNotCoveredFunctions(const SymbolizedCoverage &CovData,
  854. raw_ostream &OS) {
  855. auto NotCoveredFns = computeNotCoveredFunctions(CovData);
  856. printFunctionLocs(resolveFunctions(CovData, NotCoveredFns), OS);
  857. }
  858. // Read list of files and merges their coverage info.
  859. static void readAndPrintRawCoverage(const std::vector<std::string> &FileNames,
  860. raw_ostream &OS) {
  861. std::vector<std::unique_ptr<RawCoverage>> Covs;
  862. for (const auto &FileName : FileNames) {
  863. auto Cov = RawCoverage::read(FileName);
  864. if (!Cov)
  865. continue;
  866. OS << *Cov.get();
  867. }
  868. }
  869. static std::unique_ptr<SymbolizedCoverage>
  870. merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> &Coverages) {
  871. if (Coverages.empty())
  872. return nullptr;
  873. auto Result = std::make_unique<SymbolizedCoverage>();
  874. for (size_t I = 0; I < Coverages.size(); ++I) {
  875. const SymbolizedCoverage &Coverage = *Coverages[I];
  876. std::string Prefix;
  877. if (Coverages.size() > 1) {
  878. // prefix is not needed when there's only one file.
  879. Prefix = utostr(I);
  880. }
  881. for (const auto &Id : Coverage.CoveredIds) {
  882. Result->CoveredIds.insert(Prefix + Id);
  883. }
  884. for (const auto &CovPoint : Coverage.Points) {
  885. CoveragePoint NewPoint(CovPoint);
  886. NewPoint.Id = Prefix + CovPoint.Id;
  887. Result->Points.push_back(NewPoint);
  888. }
  889. }
  890. if (Coverages.size() == 1) {
  891. Result->BinaryHash = Coverages[0]->BinaryHash;
  892. }
  893. return Result;
  894. }
  895. static std::unique_ptr<SymbolizedCoverage>
  896. readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames) {
  897. std::vector<std::unique_ptr<SymbolizedCoverage>> Coverages;
  898. {
  899. // Short name => file name.
  900. std::map<std::string, std::string> ObjFiles;
  901. std::string FirstObjFile;
  902. std::set<std::string> CovFiles;
  903. // Partition input values into coverage/object files.
  904. for (const auto &FileName : FileNames) {
  905. if (isSymbolizedCoverageFile(FileName)) {
  906. Coverages.push_back(SymbolizedCoverage::read(FileName));
  907. }
  908. auto ErrorOrIsCoverage = isCoverageFile(FileName);
  909. if (!ErrorOrIsCoverage)
  910. continue;
  911. if (ErrorOrIsCoverage.get()) {
  912. CovFiles.insert(FileName);
  913. } else {
  914. auto ShortFileName = llvm::sys::path::filename(FileName);
  915. if (ObjFiles.find(std::string(ShortFileName)) != ObjFiles.end()) {
  916. fail("Duplicate binary file with a short name: " + ShortFileName);
  917. }
  918. ObjFiles[std::string(ShortFileName)] = FileName;
  919. if (FirstObjFile.empty())
  920. FirstObjFile = FileName;
  921. }
  922. }
  923. SmallVector<StringRef, 2> Components;
  924. // Object file => list of corresponding coverage file names.
  925. std::map<std::string, std::vector<std::string>> CoverageByObjFile;
  926. for (const auto &FileName : CovFiles) {
  927. auto ShortFileName = llvm::sys::path::filename(FileName);
  928. auto Ok = SancovFileRegex.match(ShortFileName, &Components);
  929. if (!Ok) {
  930. fail("Can't match coverage file name against "
  931. "<module_name>.<pid>.sancov pattern: " +
  932. FileName);
  933. }
  934. auto Iter = ObjFiles.find(std::string(Components[1]));
  935. if (Iter == ObjFiles.end()) {
  936. fail("Object file for coverage not found: " + FileName);
  937. }
  938. CoverageByObjFile[Iter->second].push_back(FileName);
  939. };
  940. for (const auto &Pair : ObjFiles) {
  941. auto FileName = Pair.second;
  942. if (CoverageByObjFile.find(FileName) == CoverageByObjFile.end())
  943. errs() << "WARNING: No coverage file for " << FileName << "\n";
  944. }
  945. // Read raw coverage and symbolize it.
  946. for (const auto &Pair : CoverageByObjFile) {
  947. if (findSanitizerCovFunctions(Pair.first).empty()) {
  948. errs()
  949. << "WARNING: Ignoring " << Pair.first
  950. << " and its coverage because __sanitizer_cov* functions were not "
  951. "found.\n";
  952. continue;
  953. }
  954. for (const std::string &CoverageFile : Pair.second) {
  955. auto DataOrError = RawCoverage::read(CoverageFile);
  956. failIfError(DataOrError);
  957. Coverages.push_back(symbolize(*DataOrError.get(), Pair.first));
  958. }
  959. }
  960. }
  961. return merge(Coverages);
  962. }
  963. } // namespace
  964. int main(int Argc, char **Argv) {
  965. llvm::InitLLVM X(Argc, Argv);
  966. llvm::InitializeAllTargetInfos();
  967. llvm::InitializeAllTargetMCs();
  968. llvm::InitializeAllDisassemblers();
  969. cl::ParseCommandLineOptions(Argc, Argv,
  970. "Sanitizer Coverage Processing Tool (sancov)\n\n"
  971. " This tool can extract various coverage-related information from: \n"
  972. " coverage-instrumented binary files, raw .sancov files and their "
  973. "symbolized .symcov version.\n"
  974. " Depending on chosen action the tool expects different input files:\n"
  975. " -print-coverage-pcs - coverage-instrumented binary files\n"
  976. " -print-coverage - .sancov files\n"
  977. " <other actions> - .sancov files & corresponding binary "
  978. "files, .symcov files\n"
  979. );
  980. // -print doesn't need object files.
  981. if (Action == PrintAction) {
  982. readAndPrintRawCoverage(ClInputFiles, outs());
  983. return 0;
  984. } else if (Action == PrintCovPointsAction) {
  985. // -print-coverage-points doesn't need coverage files.
  986. for (const std::string &ObjFile : ClInputFiles) {
  987. printCovPoints(ObjFile, outs());
  988. }
  989. return 0;
  990. }
  991. auto Coverage = readSymbolizeAndMergeCmdArguments(ClInputFiles);
  992. failIf(!Coverage, "No valid coverage files given.");
  993. switch (Action) {
  994. case CoveredFunctionsAction: {
  995. printCoveredFunctions(*Coverage, outs());
  996. return 0;
  997. }
  998. case NotCoveredFunctionsAction: {
  999. printNotCoveredFunctions(*Coverage, outs());
  1000. return 0;
  1001. }
  1002. case StatsAction: {
  1003. outs() << computeStats(*Coverage);
  1004. return 0;
  1005. }
  1006. case MergeAction:
  1007. case SymbolizeAction: { // merge & symbolize are synonims.
  1008. json::OStream W(outs(), 2);
  1009. W << *Coverage;
  1010. return 0;
  1011. }
  1012. case HtmlReportAction:
  1013. errs() << "-html-report option is removed: "
  1014. "use -symbolize & coverage-report-server.py instead\n";
  1015. return 1;
  1016. case PrintAction:
  1017. case PrintCovPointsAction:
  1018. llvm_unreachable("unsupported action");
  1019. }
  1020. }