CoverageMappingReader.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. //=-- CoverageMappingReader.cpp - Code coverage mapping reader ----*- C++ -*-=//
  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 contains support for reading coverage mapping data for
  11. // instrumentation based coverage.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/Object/MachOUniversal.h"
  17. #include "llvm/Object/ObjectFile.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/Endian.h"
  20. #include "llvm/Support/LEB128.h"
  21. #include "llvm/Support/MathExtras.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace llvm;
  24. using namespace coverage;
  25. using namespace object;
  26. #define DEBUG_TYPE "coverage-mapping"
  27. void CoverageMappingIterator::increment() {
  28. // Check if all the records were read or if an error occurred while reading
  29. // the next record.
  30. if (auto E = Reader->readNextRecord(Record)) {
  31. handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
  32. if (CME.get() == coveragemap_error::eof)
  33. *this = CoverageMappingIterator();
  34. else
  35. llvm_unreachable("Unexpected error in coverage mapping iterator");
  36. });
  37. }
  38. }
  39. Error RawCoverageReader::readULEB128(uint64_t &Result) {
  40. if (Data.size() < 1)
  41. return make_error<CoverageMapError>(coveragemap_error::truncated);
  42. unsigned N = 0;
  43. Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
  44. if (N > Data.size())
  45. return make_error<CoverageMapError>(coveragemap_error::malformed);
  46. Data = Data.substr(N);
  47. return Error::success();
  48. }
  49. Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
  50. if (auto Err = readULEB128(Result))
  51. return Err;
  52. if (Result >= MaxPlus1)
  53. return make_error<CoverageMapError>(coveragemap_error::malformed);
  54. return Error::success();
  55. }
  56. Error RawCoverageReader::readSize(uint64_t &Result) {
  57. if (auto Err = readULEB128(Result))
  58. return Err;
  59. // Sanity check the number.
  60. if (Result > Data.size())
  61. return make_error<CoverageMapError>(coveragemap_error::malformed);
  62. return Error::success();
  63. }
  64. Error RawCoverageReader::readString(StringRef &Result) {
  65. uint64_t Length;
  66. if (auto Err = readSize(Length))
  67. return Err;
  68. Result = Data.substr(0, Length);
  69. Data = Data.substr(Length);
  70. return Error::success();
  71. }
  72. Error RawCoverageFilenamesReader::read() {
  73. uint64_t NumFilenames;
  74. if (auto Err = readSize(NumFilenames))
  75. return Err;
  76. for (size_t I = 0; I < NumFilenames; ++I) {
  77. StringRef Filename;
  78. if (auto Err = readString(Filename))
  79. return Err;
  80. Filenames.push_back(Filename);
  81. }
  82. return Error::success();
  83. }
  84. Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
  85. auto Tag = Value & Counter::EncodingTagMask;
  86. switch (Tag) {
  87. case Counter::Zero:
  88. C = Counter::getZero();
  89. return Error::success();
  90. case Counter::CounterValueReference:
  91. C = Counter::getCounter(Value >> Counter::EncodingTagBits);
  92. return Error::success();
  93. default:
  94. break;
  95. }
  96. Tag -= Counter::Expression;
  97. switch (Tag) {
  98. case CounterExpression::Subtract:
  99. case CounterExpression::Add: {
  100. auto ID = Value >> Counter::EncodingTagBits;
  101. if (ID >= Expressions.size())
  102. return make_error<CoverageMapError>(coveragemap_error::malformed);
  103. Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
  104. C = Counter::getExpression(ID);
  105. break;
  106. }
  107. default:
  108. return make_error<CoverageMapError>(coveragemap_error::malformed);
  109. }
  110. return Error::success();
  111. }
  112. Error RawCoverageMappingReader::readCounter(Counter &C) {
  113. uint64_t EncodedCounter;
  114. if (auto Err =
  115. readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
  116. return Err;
  117. if (auto Err = decodeCounter(EncodedCounter, C))
  118. return Err;
  119. return Error::success();
  120. }
  121. static const unsigned EncodingExpansionRegionBit = 1
  122. << Counter::EncodingTagBits;
  123. /// \brief Read the sub-array of regions for the given inferred file id.
  124. /// \param NumFileIDs the number of file ids that are defined for this
  125. /// function.
  126. Error RawCoverageMappingReader::readMappingRegionsSubArray(
  127. std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
  128. size_t NumFileIDs) {
  129. uint64_t NumRegions;
  130. if (auto Err = readSize(NumRegions))
  131. return Err;
  132. unsigned LineStart = 0;
  133. for (size_t I = 0; I < NumRegions; ++I) {
  134. Counter C;
  135. CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
  136. // Read the combined counter + region kind.
  137. uint64_t EncodedCounterAndRegion;
  138. if (auto Err = readIntMax(EncodedCounterAndRegion,
  139. std::numeric_limits<unsigned>::max()))
  140. return Err;
  141. unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
  142. uint64_t ExpandedFileID = 0;
  143. if (Tag != Counter::Zero) {
  144. if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
  145. return Err;
  146. } else {
  147. // Is it an expansion region?
  148. if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
  149. Kind = CounterMappingRegion::ExpansionRegion;
  150. ExpandedFileID = EncodedCounterAndRegion >>
  151. Counter::EncodingCounterTagAndExpansionRegionTagBits;
  152. if (ExpandedFileID >= NumFileIDs)
  153. return make_error<CoverageMapError>(coveragemap_error::malformed);
  154. } else {
  155. switch (EncodedCounterAndRegion >>
  156. Counter::EncodingCounterTagAndExpansionRegionTagBits) {
  157. case CounterMappingRegion::CodeRegion:
  158. // Don't do anything when we have a code region with a zero counter.
  159. break;
  160. case CounterMappingRegion::SkippedRegion:
  161. Kind = CounterMappingRegion::SkippedRegion;
  162. break;
  163. default:
  164. return make_error<CoverageMapError>(coveragemap_error::malformed);
  165. }
  166. }
  167. }
  168. // Read the source range.
  169. uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
  170. if (auto Err =
  171. readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
  172. return Err;
  173. if (auto Err = readULEB128(ColumnStart))
  174. return Err;
  175. if (ColumnStart > std::numeric_limits<unsigned>::max())
  176. return make_error<CoverageMapError>(coveragemap_error::malformed);
  177. if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
  178. return Err;
  179. if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
  180. return Err;
  181. LineStart += LineStartDelta;
  182. // Adjust the column locations for the empty regions that are supposed to
  183. // cover whole lines. Those regions should be encoded with the
  184. // column range (1 -> std::numeric_limits<unsigned>::max()), but because
  185. // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
  186. // we set the column range to (0 -> 0) to ensure that the column start and
  187. // column end take up one byte each.
  188. // The std::numeric_limits<unsigned>::max() is used to represent a column
  189. // position at the end of the line without knowing the length of that line.
  190. if (ColumnStart == 0 && ColumnEnd == 0) {
  191. ColumnStart = 1;
  192. ColumnEnd = std::numeric_limits<unsigned>::max();
  193. }
  194. DEBUG({
  195. dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
  196. << ColumnStart << " -> " << (LineStart + NumLines) << ":"
  197. << ColumnEnd << ", ";
  198. if (Kind == CounterMappingRegion::ExpansionRegion)
  199. dbgs() << "Expands to file " << ExpandedFileID;
  200. else
  201. CounterMappingContext(Expressions).dump(C, dbgs());
  202. dbgs() << "\n";
  203. });
  204. MappingRegions.push_back(CounterMappingRegion(
  205. C, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
  206. LineStart + NumLines, ColumnEnd, Kind));
  207. }
  208. return Error::success();
  209. }
  210. Error RawCoverageMappingReader::read() {
  211. // Read the virtual file mapping.
  212. llvm::SmallVector<unsigned, 8> VirtualFileMapping;
  213. uint64_t NumFileMappings;
  214. if (auto Err = readSize(NumFileMappings))
  215. return Err;
  216. for (size_t I = 0; I < NumFileMappings; ++I) {
  217. uint64_t FilenameIndex;
  218. if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
  219. return Err;
  220. VirtualFileMapping.push_back(FilenameIndex);
  221. }
  222. // Construct the files using unique filenames and virtual file mapping.
  223. for (auto I : VirtualFileMapping) {
  224. Filenames.push_back(TranslationUnitFilenames[I]);
  225. }
  226. // Read the expressions.
  227. uint64_t NumExpressions;
  228. if (auto Err = readSize(NumExpressions))
  229. return Err;
  230. // Create an array of dummy expressions that get the proper counters
  231. // when the expressions are read, and the proper kinds when the counters
  232. // are decoded.
  233. Expressions.resize(
  234. NumExpressions,
  235. CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
  236. for (size_t I = 0; I < NumExpressions; ++I) {
  237. if (auto Err = readCounter(Expressions[I].LHS))
  238. return Err;
  239. if (auto Err = readCounter(Expressions[I].RHS))
  240. return Err;
  241. }
  242. // Read the mapping regions sub-arrays.
  243. for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
  244. InferredFileID < S; ++InferredFileID) {
  245. if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
  246. VirtualFileMapping.size()))
  247. return Err;
  248. }
  249. // Set the counters for the expansion regions.
  250. // i.e. Counter of expansion region = counter of the first region
  251. // from the expanded file.
  252. // Perform multiple passes to correctly propagate the counters through
  253. // all the nested expansion regions.
  254. SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
  255. FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
  256. for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
  257. for (auto &R : MappingRegions) {
  258. if (R.Kind != CounterMappingRegion::ExpansionRegion)
  259. continue;
  260. assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
  261. FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
  262. }
  263. for (auto &R : MappingRegions) {
  264. if (FileIDExpansionRegionMapping[R.FileID]) {
  265. FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
  266. FileIDExpansionRegionMapping[R.FileID] = nullptr;
  267. }
  268. }
  269. }
  270. return Error::success();
  271. }
  272. Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
  273. // A dummy coverage mapping data consists of just one region with zero count.
  274. uint64_t NumFileMappings;
  275. if (Error Err = readSize(NumFileMappings))
  276. return std::move(Err);
  277. if (NumFileMappings != 1)
  278. return false;
  279. // We don't expect any specific value for the filename index, just skip it.
  280. uint64_t FilenameIndex;
  281. if (Error Err =
  282. readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
  283. return std::move(Err);
  284. uint64_t NumExpressions;
  285. if (Error Err = readSize(NumExpressions))
  286. return std::move(Err);
  287. if (NumExpressions != 0)
  288. return false;
  289. uint64_t NumRegions;
  290. if (Error Err = readSize(NumRegions))
  291. return std::move(Err);
  292. if (NumRegions != 1)
  293. return false;
  294. uint64_t EncodedCounterAndRegion;
  295. if (Error Err = readIntMax(EncodedCounterAndRegion,
  296. std::numeric_limits<unsigned>::max()))
  297. return std::move(Err);
  298. unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
  299. return Tag == Counter::Zero;
  300. }
  301. Error InstrProfSymtab::create(SectionRef &Section) {
  302. if (auto EC = Section.getContents(Data))
  303. return errorCodeToError(EC);
  304. Address = Section.getAddress();
  305. return Error::success();
  306. }
  307. StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
  308. if (Pointer < Address)
  309. return StringRef();
  310. auto Offset = Pointer - Address;
  311. if (Offset + Size > Data.size())
  312. return StringRef();
  313. return Data.substr(Pointer - Address, Size);
  314. }
  315. // Check if the mapping data is a dummy, i.e. is emitted for an unused function.
  316. static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
  317. // The hash value of dummy mapping records is always zero.
  318. if (Hash)
  319. return false;
  320. return RawCoverageMappingDummyChecker(Mapping).isDummy();
  321. }
  322. namespace {
  323. struct CovMapFuncRecordReader {
  324. // The interface to read coverage mapping function records for a module.
  325. //
  326. // \p Buf points to the buffer containing the \c CovHeader of the coverage
  327. // mapping data associated with the module.
  328. //
  329. // Returns a pointer to the next \c CovHeader if it exists, or a pointer
  330. // greater than \p End if not.
  331. virtual Expected<const char *> readFunctionRecords(const char *Buf,
  332. const char *End) = 0;
  333. virtual ~CovMapFuncRecordReader() {}
  334. template <class IntPtrT, support::endianness Endian>
  335. static Expected<std::unique_ptr<CovMapFuncRecordReader>>
  336. get(coverage::CovMapVersion Version, InstrProfSymtab &P,
  337. std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
  338. std::vector<StringRef> &F);
  339. };
  340. // A class for reading coverage mapping function records for a module.
  341. template <coverage::CovMapVersion Version, class IntPtrT,
  342. support::endianness Endian>
  343. class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
  344. typedef typename coverage::CovMapTraits<
  345. Version, IntPtrT>::CovMapFuncRecordType FuncRecordType;
  346. typedef typename coverage::CovMapTraits<Version, IntPtrT>::NameRefType
  347. NameRefType;
  348. // Maps function's name references to the indexes of their records
  349. // in \c Records.
  350. llvm::DenseMap<NameRefType, size_t> FunctionRecords;
  351. InstrProfSymtab &ProfileNames;
  352. std::vector<StringRef> &Filenames;
  353. std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
  354. // Add the record to the collection if we don't already have a record that
  355. // points to the same function name. This is useful to ignore the redundant
  356. // records for the functions with ODR linkage.
  357. // In addition, prefer records with real coverage mapping data to dummy
  358. // records, which were emitted for inline functions which were seen but
  359. // not used in the corresponding translation unit.
  360. Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
  361. StringRef Mapping, size_t FilenamesBegin) {
  362. uint64_t FuncHash = CFR->template getFuncHash<Endian>();
  363. NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
  364. auto InsertResult =
  365. FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
  366. if (InsertResult.second) {
  367. StringRef FuncName;
  368. if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
  369. return Err;
  370. Records.emplace_back(Version, FuncName, FuncHash, Mapping, FilenamesBegin,
  371. Filenames.size() - FilenamesBegin);
  372. return Error::success();
  373. }
  374. // Update the existing record if it's a dummy and the new record is real.
  375. size_t OldRecordIndex = InsertResult.first->second;
  376. BinaryCoverageReader::ProfileMappingRecord &OldRecord =
  377. Records[OldRecordIndex];
  378. Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
  379. OldRecord.FunctionHash, OldRecord.CoverageMapping);
  380. if (Error Err = OldIsDummyExpected.takeError())
  381. return Err;
  382. if (!*OldIsDummyExpected)
  383. return Error::success();
  384. Expected<bool> NewIsDummyExpected =
  385. isCoverageMappingDummy(FuncHash, Mapping);
  386. if (Error Err = NewIsDummyExpected.takeError())
  387. return Err;
  388. if (*NewIsDummyExpected)
  389. return Error::success();
  390. OldRecord.FunctionHash = FuncHash;
  391. OldRecord.CoverageMapping = Mapping;
  392. OldRecord.FilenamesBegin = FilenamesBegin;
  393. OldRecord.FilenamesSize = Filenames.size() - FilenamesBegin;
  394. return Error::success();
  395. }
  396. public:
  397. VersionedCovMapFuncRecordReader(
  398. InstrProfSymtab &P,
  399. std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
  400. std::vector<StringRef> &F)
  401. : ProfileNames(P), Filenames(F), Records(R) {}
  402. ~VersionedCovMapFuncRecordReader() override {}
  403. Expected<const char *> readFunctionRecords(const char *Buf,
  404. const char *End) override {
  405. using namespace support;
  406. if (Buf + sizeof(CovMapHeader) > End)
  407. return make_error<CoverageMapError>(coveragemap_error::malformed);
  408. auto CovHeader = reinterpret_cast<const coverage::CovMapHeader *>(Buf);
  409. uint32_t NRecords = CovHeader->getNRecords<Endian>();
  410. uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
  411. uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
  412. assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
  413. Buf = reinterpret_cast<const char *>(CovHeader + 1);
  414. // Skip past the function records, saving the start and end for later.
  415. const char *FunBuf = Buf;
  416. Buf += NRecords * sizeof(FuncRecordType);
  417. const char *FunEnd = Buf;
  418. // Get the filenames.
  419. if (Buf + FilenamesSize > End)
  420. return make_error<CoverageMapError>(coveragemap_error::malformed);
  421. size_t FilenamesBegin = Filenames.size();
  422. RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
  423. if (auto Err = Reader.read())
  424. return std::move(Err);
  425. Buf += FilenamesSize;
  426. // We'll read the coverage mapping records in the loop below.
  427. const char *CovBuf = Buf;
  428. Buf += CoverageSize;
  429. const char *CovEnd = Buf;
  430. if (Buf > End)
  431. return make_error<CoverageMapError>(coveragemap_error::malformed);
  432. // Each coverage map has an alignment of 8, so we need to adjust alignment
  433. // before reading the next map.
  434. Buf += alignmentAdjustment(Buf, 8);
  435. auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
  436. while ((const char *)CFR < FunEnd) {
  437. // Read the function information
  438. uint32_t DataSize = CFR->template getDataSize<Endian>();
  439. // Now use that to read the coverage data.
  440. if (CovBuf + DataSize > CovEnd)
  441. return make_error<CoverageMapError>(coveragemap_error::malformed);
  442. auto Mapping = StringRef(CovBuf, DataSize);
  443. CovBuf += DataSize;
  444. if (Error Err =
  445. insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
  446. return std::move(Err);
  447. CFR++;
  448. }
  449. return Buf;
  450. }
  451. };
  452. } // end anonymous namespace
  453. template <class IntPtrT, support::endianness Endian>
  454. Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
  455. coverage::CovMapVersion Version, InstrProfSymtab &P,
  456. std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
  457. std::vector<StringRef> &F) {
  458. using namespace coverage;
  459. switch (Version) {
  460. case CovMapVersion::Version1:
  461. return llvm::make_unique<VersionedCovMapFuncRecordReader<
  462. CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
  463. case CovMapVersion::Version2:
  464. // Decompress the name data.
  465. if (Error E = P.create(P.getNameData()))
  466. return std::move(E);
  467. return llvm::make_unique<VersionedCovMapFuncRecordReader<
  468. CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
  469. }
  470. llvm_unreachable("Unsupported version");
  471. }
  472. template <typename T, support::endianness Endian>
  473. static Error readCoverageMappingData(
  474. InstrProfSymtab &ProfileNames, StringRef Data,
  475. std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
  476. std::vector<StringRef> &Filenames) {
  477. using namespace coverage;
  478. // Read the records in the coverage data section.
  479. auto CovHeader =
  480. reinterpret_cast<const coverage::CovMapHeader *>(Data.data());
  481. CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
  482. if (Version > coverage::CovMapVersion::CurrentVersion)
  483. return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
  484. Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
  485. CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
  486. Filenames);
  487. if (Error E = ReaderExpected.takeError())
  488. return E;
  489. auto Reader = std::move(ReaderExpected.get());
  490. for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
  491. auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
  492. if (auto E = NextHeaderOrErr.takeError())
  493. return E;
  494. Buf = NextHeaderOrErr.get();
  495. }
  496. return Error::success();
  497. }
  498. static const char *TestingFormatMagic = "llvmcovmtestdata";
  499. static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames,
  500. StringRef &CoverageMapping,
  501. uint8_t &BytesInAddress,
  502. support::endianness &Endian) {
  503. BytesInAddress = 8;
  504. Endian = support::endianness::little;
  505. Data = Data.substr(StringRef(TestingFormatMagic).size());
  506. if (Data.size() < 1)
  507. return make_error<CoverageMapError>(coveragemap_error::truncated);
  508. unsigned N = 0;
  509. auto ProfileNamesSize =
  510. decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
  511. if (N > Data.size())
  512. return make_error<CoverageMapError>(coveragemap_error::malformed);
  513. Data = Data.substr(N);
  514. if (Data.size() < 1)
  515. return make_error<CoverageMapError>(coveragemap_error::truncated);
  516. N = 0;
  517. uint64_t Address =
  518. decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
  519. if (N > Data.size())
  520. return make_error<CoverageMapError>(coveragemap_error::malformed);
  521. Data = Data.substr(N);
  522. if (Data.size() < ProfileNamesSize)
  523. return make_error<CoverageMapError>(coveragemap_error::malformed);
  524. if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
  525. return E;
  526. CoverageMapping = Data.substr(ProfileNamesSize);
  527. // Skip the padding bytes because coverage map data has an alignment of 8.
  528. if (CoverageMapping.size() < 1)
  529. return make_error<CoverageMapError>(coveragemap_error::truncated);
  530. size_t Pad = alignmentAdjustment(CoverageMapping.data(), 8);
  531. if (CoverageMapping.size() < Pad)
  532. return make_error<CoverageMapError>(coveragemap_error::malformed);
  533. CoverageMapping = CoverageMapping.substr(Pad);
  534. return Error::success();
  535. }
  536. static Expected<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
  537. StringRef FoundName;
  538. for (const auto &Section : OF.sections()) {
  539. if (auto EC = Section.getName(FoundName))
  540. return errorCodeToError(EC);
  541. if (FoundName == Name)
  542. return Section;
  543. }
  544. return make_error<CoverageMapError>(coveragemap_error::no_data_found);
  545. }
  546. static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer,
  547. InstrProfSymtab &ProfileNames,
  548. StringRef &CoverageMapping,
  549. uint8_t &BytesInAddress,
  550. support::endianness &Endian, StringRef Arch) {
  551. auto BinOrErr = object::createBinary(ObjectBuffer);
  552. if (!BinOrErr)
  553. return BinOrErr.takeError();
  554. auto Bin = std::move(BinOrErr.get());
  555. std::unique_ptr<ObjectFile> OF;
  556. if (auto *Universal = dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
  557. // If we have a universal binary, try to look up the object for the
  558. // appropriate architecture.
  559. auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
  560. if (!ObjectFileOrErr)
  561. return ObjectFileOrErr.takeError();
  562. OF = std::move(ObjectFileOrErr.get());
  563. } else if (isa<object::ObjectFile>(Bin.get())) {
  564. // For any other object file, upcast and take ownership.
  565. OF.reset(cast<object::ObjectFile>(Bin.release()));
  566. // If we've asked for a particular arch, make sure they match.
  567. if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
  568. return errorCodeToError(object_error::arch_not_found);
  569. } else
  570. // We can only handle object files.
  571. return make_error<CoverageMapError>(coveragemap_error::malformed);
  572. // The coverage uses native pointer sizes for the object it's written in.
  573. BytesInAddress = OF->getBytesInAddress();
  574. Endian = OF->isLittleEndian() ? support::endianness::little
  575. : support::endianness::big;
  576. // Look for the sections that we are interested in.
  577. auto NamesSection = lookupSection(*OF, getInstrProfNameSectionName(false));
  578. if (auto E = NamesSection.takeError())
  579. return E;
  580. auto CoverageSection =
  581. lookupSection(*OF, getInstrProfCoverageSectionName(false));
  582. if (auto E = CoverageSection.takeError())
  583. return E;
  584. // Get the contents of the given sections.
  585. if (auto EC = CoverageSection->getContents(CoverageMapping))
  586. return errorCodeToError(EC);
  587. if (Error E = ProfileNames.create(*NamesSection))
  588. return E;
  589. return Error::success();
  590. }
  591. Expected<std::unique_ptr<BinaryCoverageReader>>
  592. BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
  593. StringRef Arch) {
  594. std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
  595. StringRef Coverage;
  596. uint8_t BytesInAddress;
  597. support::endianness Endian;
  598. Error E = Error::success();
  599. consumeError(std::move(E));
  600. if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
  601. // This is a special format used for testing.
  602. E = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
  603. Coverage, BytesInAddress, Endian);
  604. else
  605. E = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
  606. Coverage, BytesInAddress, Endian, Arch);
  607. if (E)
  608. return std::move(E);
  609. if (BytesInAddress == 4 && Endian == support::endianness::little)
  610. E = readCoverageMappingData<uint32_t, support::endianness::little>(
  611. Reader->ProfileNames, Coverage, Reader->MappingRecords,
  612. Reader->Filenames);
  613. else if (BytesInAddress == 4 && Endian == support::endianness::big)
  614. E = readCoverageMappingData<uint32_t, support::endianness::big>(
  615. Reader->ProfileNames, Coverage, Reader->MappingRecords,
  616. Reader->Filenames);
  617. else if (BytesInAddress == 8 && Endian == support::endianness::little)
  618. E = readCoverageMappingData<uint64_t, support::endianness::little>(
  619. Reader->ProfileNames, Coverage, Reader->MappingRecords,
  620. Reader->Filenames);
  621. else if (BytesInAddress == 8 && Endian == support::endianness::big)
  622. E = readCoverageMappingData<uint64_t, support::endianness::big>(
  623. Reader->ProfileNames, Coverage, Reader->MappingRecords,
  624. Reader->Filenames);
  625. else
  626. return make_error<CoverageMapError>(coveragemap_error::malformed);
  627. if (E)
  628. return std::move(E);
  629. return std::move(Reader);
  630. }
  631. Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
  632. if (CurrentRecord >= MappingRecords.size())
  633. return make_error<CoverageMapError>(coveragemap_error::eof);
  634. FunctionsFilenames.clear();
  635. Expressions.clear();
  636. MappingRegions.clear();
  637. auto &R = MappingRecords[CurrentRecord];
  638. RawCoverageMappingReader Reader(
  639. R.CoverageMapping,
  640. makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
  641. FunctionsFilenames, Expressions, MappingRegions);
  642. if (auto Err = Reader.read())
  643. return Err;
  644. Record.FunctionName = R.FunctionName;
  645. Record.FunctionHash = R.FunctionHash;
  646. Record.Filenames = FunctionsFilenames;
  647. Record.Expressions = Expressions;
  648. Record.MappingRegions = MappingRegions;
  649. ++CurrentRecord;
  650. return Error::success();
  651. }