CoverageMappingReader.cpp 31 KB

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