CoverageMappingReader.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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/Statistic.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Object/Binary.h"
  22. #include "llvm/Object/Error.h"
  23. #include "llvm/Object/MachOUniversal.h"
  24. #include "llvm/Object/ObjectFile.h"
  25. #include "llvm/Object/COFF.h"
  26. #include "llvm/ProfileData/InstrProf.h"
  27. #include "llvm/Support/Casting.h"
  28. #include "llvm/Support/Compression.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/Endian.h"
  31. #include "llvm/Support/Error.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/LEB128.h"
  34. #include "llvm/Support/MathExtras.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <vector>
  37. using namespace llvm;
  38. using namespace coverage;
  39. using namespace object;
  40. #define DEBUG_TYPE "coverage-mapping"
  41. STATISTIC(CovMapNumRecords, "The # of coverage function records");
  42. STATISTIC(CovMapNumUsedRecords, "The # of used coverage function records");
  43. void CoverageMappingIterator::increment() {
  44. if (ReadErr != coveragemap_error::success)
  45. return;
  46. // Check if all the records were read or if an error occurred while reading
  47. // the next record.
  48. if (auto E = Reader->readNextRecord(Record))
  49. handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
  50. if (CME.get() == coveragemap_error::eof)
  51. *this = CoverageMappingIterator();
  52. else
  53. ReadErr = CME.get();
  54. });
  55. }
  56. Error RawCoverageReader::readULEB128(uint64_t &Result) {
  57. if (Data.empty())
  58. return make_error<CoverageMapError>(coveragemap_error::truncated);
  59. unsigned N = 0;
  60. Result = decodeULEB128(Data.bytes_begin(), &N);
  61. if (N > Data.size())
  62. return make_error<CoverageMapError>(coveragemap_error::malformed);
  63. Data = Data.substr(N);
  64. return Error::success();
  65. }
  66. Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
  67. if (auto Err = readULEB128(Result))
  68. return Err;
  69. if (Result >= MaxPlus1)
  70. return make_error<CoverageMapError>(coveragemap_error::malformed);
  71. return Error::success();
  72. }
  73. Error RawCoverageReader::readSize(uint64_t &Result) {
  74. if (auto Err = readULEB128(Result))
  75. return Err;
  76. // Sanity check the number.
  77. if (Result > Data.size())
  78. return make_error<CoverageMapError>(coveragemap_error::malformed);
  79. return Error::success();
  80. }
  81. Error RawCoverageReader::readString(StringRef &Result) {
  82. uint64_t Length;
  83. if (auto Err = readSize(Length))
  84. return Err;
  85. Result = Data.substr(0, Length);
  86. Data = Data.substr(Length);
  87. return Error::success();
  88. }
  89. Error RawCoverageFilenamesReader::read(
  90. CovMapVersion Version,
  91. BinaryCoverageReader::DecompressedData &Decompressed) {
  92. uint64_t NumFilenames;
  93. if (auto Err = readSize(NumFilenames))
  94. return Err;
  95. if (!NumFilenames)
  96. return make_error<CoverageMapError>(coveragemap_error::malformed);
  97. if (Version < CovMapVersion::Version4)
  98. return readUncompressed(NumFilenames);
  99. // The uncompressed length may exceed the size of the encoded filenames.
  100. // Skip size validation.
  101. uint64_t UncompressedLen;
  102. if (auto Err = readULEB128(UncompressedLen))
  103. return Err;
  104. uint64_t CompressedLen;
  105. if (auto Err = readSize(CompressedLen))
  106. return Err;
  107. if (CompressedLen > 0) {
  108. if (!zlib::isAvailable())
  109. return make_error<CoverageMapError>(
  110. coveragemap_error::decompression_failed);
  111. // Allocate memory for the decompressed filenames. Transfer ownership of
  112. // the memory to BinaryCoverageReader.
  113. auto DecompressedStorage = std::make_unique<SmallVector<char, 0>>();
  114. SmallVectorImpl<char> &StorageBuf = *DecompressedStorage.get();
  115. Decompressed.push_back(std::move(DecompressedStorage));
  116. // Read compressed filenames.
  117. StringRef CompressedFilenames = Data.substr(0, CompressedLen);
  118. Data = Data.substr(CompressedLen);
  119. auto Err =
  120. zlib::uncompress(CompressedFilenames, StorageBuf, UncompressedLen);
  121. if (Err) {
  122. consumeError(std::move(Err));
  123. return make_error<CoverageMapError>(
  124. coveragemap_error::decompression_failed);
  125. }
  126. StringRef UncompressedFilenames(StorageBuf.data(), StorageBuf.size());
  127. RawCoverageFilenamesReader Delegate(UncompressedFilenames, Filenames);
  128. return Delegate.readUncompressed(NumFilenames);
  129. }
  130. return readUncompressed(NumFilenames);
  131. }
  132. Error RawCoverageFilenamesReader::readUncompressed(uint64_t NumFilenames) {
  133. // Read uncompressed filenames.
  134. for (size_t I = 0; I < NumFilenames; ++I) {
  135. StringRef Filename;
  136. if (auto Err = readString(Filename))
  137. return Err;
  138. Filenames.push_back(Filename);
  139. }
  140. return Error::success();
  141. }
  142. Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
  143. auto Tag = Value & Counter::EncodingTagMask;
  144. switch (Tag) {
  145. case Counter::Zero:
  146. C = Counter::getZero();
  147. return Error::success();
  148. case Counter::CounterValueReference:
  149. C = Counter::getCounter(Value >> Counter::EncodingTagBits);
  150. return Error::success();
  151. default:
  152. break;
  153. }
  154. Tag -= Counter::Expression;
  155. switch (Tag) {
  156. case CounterExpression::Subtract:
  157. case CounterExpression::Add: {
  158. auto ID = Value >> Counter::EncodingTagBits;
  159. if (ID >= Expressions.size())
  160. return make_error<CoverageMapError>(coveragemap_error::malformed);
  161. Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
  162. C = Counter::getExpression(ID);
  163. break;
  164. }
  165. default:
  166. return make_error<CoverageMapError>(coveragemap_error::malformed);
  167. }
  168. return Error::success();
  169. }
  170. Error RawCoverageMappingReader::readCounter(Counter &C) {
  171. uint64_t EncodedCounter;
  172. if (auto Err =
  173. readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
  174. return Err;
  175. if (auto Err = decodeCounter(EncodedCounter, C))
  176. return Err;
  177. return Error::success();
  178. }
  179. static const unsigned EncodingExpansionRegionBit = 1
  180. << Counter::EncodingTagBits;
  181. /// Read the sub-array of regions for the given inferred file id.
  182. /// \param NumFileIDs the number of file ids that are defined for this
  183. /// function.
  184. Error RawCoverageMappingReader::readMappingRegionsSubArray(
  185. std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
  186. size_t NumFileIDs) {
  187. uint64_t NumRegions;
  188. if (auto Err = readSize(NumRegions))
  189. return Err;
  190. unsigned LineStart = 0;
  191. for (size_t I = 0; I < NumRegions; ++I) {
  192. Counter C, C2;
  193. CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
  194. // Read the combined counter + region kind.
  195. uint64_t EncodedCounterAndRegion;
  196. if (auto Err = readIntMax(EncodedCounterAndRegion,
  197. std::numeric_limits<unsigned>::max()))
  198. return Err;
  199. unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
  200. uint64_t ExpandedFileID = 0;
  201. // If Tag does not represent a ZeroCounter, then it is understood to refer
  202. // to a counter or counter expression with region kind assumed to be
  203. // "CodeRegion". In that case, EncodedCounterAndRegion actually encodes the
  204. // referenced counter or counter expression (and nothing else).
  205. //
  206. // If Tag represents a ZeroCounter and EncodingExpansionRegionBit is set,
  207. // then EncodedCounterAndRegion is interpreted to represent an
  208. // ExpansionRegion. In all other cases, EncodedCounterAndRegion is
  209. // interpreted to refer to a specific region kind, after which additional
  210. // fields may be read (e.g. BranchRegions have two encoded counters that
  211. // follow an encoded region kind value).
  212. if (Tag != Counter::Zero) {
  213. if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
  214. return Err;
  215. } else {
  216. // Is it an expansion region?
  217. if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
  218. Kind = CounterMappingRegion::ExpansionRegion;
  219. ExpandedFileID = EncodedCounterAndRegion >>
  220. Counter::EncodingCounterTagAndExpansionRegionTagBits;
  221. if (ExpandedFileID >= NumFileIDs)
  222. return make_error<CoverageMapError>(coveragemap_error::malformed);
  223. } else {
  224. switch (EncodedCounterAndRegion >>
  225. Counter::EncodingCounterTagAndExpansionRegionTagBits) {
  226. case CounterMappingRegion::CodeRegion:
  227. // Don't do anything when we have a code region with a zero counter.
  228. break;
  229. case CounterMappingRegion::SkippedRegion:
  230. Kind = CounterMappingRegion::SkippedRegion;
  231. break;
  232. case CounterMappingRegion::BranchRegion:
  233. // For a Branch Region, read two successive counters.
  234. Kind = CounterMappingRegion::BranchRegion;
  235. if (auto Err = readCounter(C))
  236. return Err;
  237. if (auto Err = readCounter(C2))
  238. return Err;
  239. break;
  240. default:
  241. return make_error<CoverageMapError>(coveragemap_error::malformed);
  242. }
  243. }
  244. }
  245. // Read the source range.
  246. uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
  247. if (auto Err =
  248. readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
  249. return Err;
  250. if (auto Err = readULEB128(ColumnStart))
  251. return Err;
  252. if (ColumnStart > std::numeric_limits<unsigned>::max())
  253. return make_error<CoverageMapError>(coveragemap_error::malformed);
  254. if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
  255. return Err;
  256. if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
  257. return Err;
  258. LineStart += LineStartDelta;
  259. // If the high bit of ColumnEnd is set, this is a gap region.
  260. if (ColumnEnd & (1U << 31)) {
  261. Kind = CounterMappingRegion::GapRegion;
  262. ColumnEnd &= ~(1U << 31);
  263. }
  264. // Adjust the column locations for the empty regions that are supposed to
  265. // cover whole lines. Those regions should be encoded with the
  266. // column range (1 -> std::numeric_limits<unsigned>::max()), but because
  267. // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
  268. // we set the column range to (0 -> 0) to ensure that the column start and
  269. // column end take up one byte each.
  270. // The std::numeric_limits<unsigned>::max() is used to represent a column
  271. // position at the end of the line without knowing the length of that line.
  272. if (ColumnStart == 0 && ColumnEnd == 0) {
  273. ColumnStart = 1;
  274. ColumnEnd = std::numeric_limits<unsigned>::max();
  275. }
  276. LLVM_DEBUG({
  277. dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
  278. << ColumnStart << " -> " << (LineStart + NumLines) << ":"
  279. << ColumnEnd << ", ";
  280. if (Kind == CounterMappingRegion::ExpansionRegion)
  281. dbgs() << "Expands to file " << ExpandedFileID;
  282. else
  283. CounterMappingContext(Expressions).dump(C, dbgs());
  284. dbgs() << "\n";
  285. });
  286. auto CMR = CounterMappingRegion(C, C2, InferredFileID, ExpandedFileID,
  287. LineStart, ColumnStart,
  288. LineStart + NumLines, ColumnEnd, Kind);
  289. if (CMR.startLoc() > CMR.endLoc())
  290. return make_error<CoverageMapError>(coveragemap_error::malformed);
  291. MappingRegions.push_back(CMR);
  292. }
  293. return Error::success();
  294. }
  295. Error RawCoverageMappingReader::read() {
  296. // Read the virtual file mapping.
  297. SmallVector<unsigned, 8> VirtualFileMapping;
  298. uint64_t NumFileMappings;
  299. if (auto Err = readSize(NumFileMappings))
  300. return Err;
  301. for (size_t I = 0; I < NumFileMappings; ++I) {
  302. uint64_t FilenameIndex;
  303. if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
  304. return Err;
  305. VirtualFileMapping.push_back(FilenameIndex);
  306. }
  307. // Construct the files using unique filenames and virtual file mapping.
  308. for (auto I : VirtualFileMapping) {
  309. Filenames.push_back(TranslationUnitFilenames[I]);
  310. }
  311. // Read the expressions.
  312. uint64_t NumExpressions;
  313. if (auto Err = readSize(NumExpressions))
  314. return Err;
  315. // Create an array of dummy expressions that get the proper counters
  316. // when the expressions are read, and the proper kinds when the counters
  317. // are decoded.
  318. Expressions.resize(
  319. NumExpressions,
  320. CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
  321. for (size_t I = 0; I < NumExpressions; ++I) {
  322. if (auto Err = readCounter(Expressions[I].LHS))
  323. return Err;
  324. if (auto Err = readCounter(Expressions[I].RHS))
  325. return Err;
  326. }
  327. // Read the mapping regions sub-arrays.
  328. for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
  329. InferredFileID < S; ++InferredFileID) {
  330. if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
  331. VirtualFileMapping.size()))
  332. return Err;
  333. }
  334. // Set the counters for the expansion regions.
  335. // i.e. Counter of expansion region = counter of the first region
  336. // from the expanded file.
  337. // Perform multiple passes to correctly propagate the counters through
  338. // all the nested expansion regions.
  339. SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
  340. FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
  341. for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
  342. for (auto &R : MappingRegions) {
  343. if (R.Kind != CounterMappingRegion::ExpansionRegion)
  344. continue;
  345. assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
  346. FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
  347. }
  348. for (auto &R : MappingRegions) {
  349. if (FileIDExpansionRegionMapping[R.FileID]) {
  350. FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
  351. FileIDExpansionRegionMapping[R.FileID] = nullptr;
  352. }
  353. }
  354. }
  355. return Error::success();
  356. }
  357. Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
  358. // A dummy coverage mapping data consists of just one region with zero count.
  359. uint64_t NumFileMappings;
  360. if (Error Err = readSize(NumFileMappings))
  361. return std::move(Err);
  362. if (NumFileMappings != 1)
  363. return false;
  364. // We don't expect any specific value for the filename index, just skip it.
  365. uint64_t FilenameIndex;
  366. if (Error Err =
  367. readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
  368. return std::move(Err);
  369. uint64_t NumExpressions;
  370. if (Error Err = readSize(NumExpressions))
  371. return std::move(Err);
  372. if (NumExpressions != 0)
  373. return false;
  374. uint64_t NumRegions;
  375. if (Error Err = readSize(NumRegions))
  376. return std::move(Err);
  377. if (NumRegions != 1)
  378. return false;
  379. uint64_t EncodedCounterAndRegion;
  380. if (Error Err = readIntMax(EncodedCounterAndRegion,
  381. std::numeric_limits<unsigned>::max()))
  382. return std::move(Err);
  383. unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
  384. return Tag == Counter::Zero;
  385. }
  386. Error InstrProfSymtab::create(SectionRef &Section) {
  387. Expected<StringRef> DataOrErr = Section.getContents();
  388. if (!DataOrErr)
  389. return DataOrErr.takeError();
  390. Data = *DataOrErr;
  391. Address = Section.getAddress();
  392. // If this is a linked PE/COFF file, then we have to skip over the null byte
  393. // that is allocated in the .lprfn$A section in the LLVM profiling runtime.
  394. const ObjectFile *Obj = Section.getObject();
  395. if (isa<COFFObjectFile>(Obj) && !Obj->isRelocatableObject())
  396. Data = Data.drop_front(1);
  397. return Error::success();
  398. }
  399. StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
  400. if (Pointer < Address)
  401. return StringRef();
  402. auto Offset = Pointer - Address;
  403. if (Offset + Size > Data.size())
  404. return StringRef();
  405. return Data.substr(Pointer - Address, Size);
  406. }
  407. // Check if the mapping data is a dummy, i.e. is emitted for an unused function.
  408. static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
  409. // The hash value of dummy mapping records is always zero.
  410. if (Hash)
  411. return false;
  412. return RawCoverageMappingDummyChecker(Mapping).isDummy();
  413. }
  414. /// A range of filename indices. Used to specify the location of a batch of
  415. /// filenames in a vector-like container.
  416. struct FilenameRange {
  417. unsigned StartingIndex;
  418. unsigned Length;
  419. FilenameRange(unsigned StartingIndex, unsigned Length)
  420. : StartingIndex(StartingIndex), Length(Length) {}
  421. void markInvalid() { Length = 0; }
  422. bool isInvalid() const { return Length == 0; }
  423. };
  424. namespace {
  425. /// The interface to read coverage mapping function records for a module.
  426. struct CovMapFuncRecordReader {
  427. virtual ~CovMapFuncRecordReader() = default;
  428. // Read a coverage header.
  429. //
  430. // \p CovBuf points to the buffer containing the \c CovHeader of the coverage
  431. // mapping data associated with the module.
  432. //
  433. // Returns a pointer to the next \c CovHeader if it exists, or to an address
  434. // greater than \p CovEnd if not.
  435. virtual Expected<const char *>
  436. readCoverageHeader(const char *CovBuf, const char *CovBufEnd,
  437. BinaryCoverageReader::DecompressedData &Decompressed) = 0;
  438. // Read function records.
  439. //
  440. // \p FuncRecBuf points to the buffer containing a batch of function records.
  441. // \p FuncRecBufEnd points past the end of the batch of records.
  442. //
  443. // Prior to Version4, \p OutOfLineFileRange points to a sequence of filenames
  444. // associated with the function records. It is unused in Version4.
  445. //
  446. // Prior to Version4, \p OutOfLineMappingBuf points to a sequence of coverage
  447. // mappings associated with the function records. It is unused in Version4.
  448. virtual Error readFunctionRecords(const char *FuncRecBuf,
  449. const char *FuncRecBufEnd,
  450. Optional<FilenameRange> OutOfLineFileRange,
  451. const char *OutOfLineMappingBuf,
  452. const char *OutOfLineMappingBufEnd) = 0;
  453. template <class IntPtrT, support::endianness Endian>
  454. static Expected<std::unique_ptr<CovMapFuncRecordReader>>
  455. get(CovMapVersion Version, InstrProfSymtab &P,
  456. std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
  457. std::vector<StringRef> &F);
  458. };
  459. // A class for reading coverage mapping function records for a module.
  460. template <CovMapVersion Version, class IntPtrT, support::endianness Endian>
  461. class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
  462. using FuncRecordType =
  463. typename CovMapTraits<Version, IntPtrT>::CovMapFuncRecordType;
  464. using NameRefType = typename CovMapTraits<Version, IntPtrT>::NameRefType;
  465. // Maps function's name references to the indexes of their records
  466. // in \c Records.
  467. DenseMap<NameRefType, size_t> FunctionRecords;
  468. InstrProfSymtab &ProfileNames;
  469. std::vector<StringRef> &Filenames;
  470. std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
  471. // Maps a hash of the filenames in a TU to a \c FileRange. The range
  472. // specifies the location of the hashed filenames in \c Filenames.
  473. DenseMap<uint64_t, FilenameRange> FileRangeMap;
  474. // Add the record to the collection if we don't already have a record that
  475. // points to the same function name. This is useful to ignore the redundant
  476. // records for the functions with ODR linkage.
  477. // In addition, prefer records with real coverage mapping data to dummy
  478. // records, which were emitted for inline functions which were seen but
  479. // not used in the corresponding translation unit.
  480. Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
  481. StringRef Mapping,
  482. FilenameRange FileRange) {
  483. ++CovMapNumRecords;
  484. uint64_t FuncHash = CFR->template getFuncHash<Endian>();
  485. NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
  486. auto InsertResult =
  487. FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
  488. if (InsertResult.second) {
  489. StringRef FuncName;
  490. if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
  491. return Err;
  492. if (FuncName.empty())
  493. return make_error<InstrProfError>(instrprof_error::malformed);
  494. ++CovMapNumUsedRecords;
  495. Records.emplace_back(Version, FuncName, FuncHash, Mapping,
  496. FileRange.StartingIndex, FileRange.Length);
  497. return Error::success();
  498. }
  499. // Update the existing record if it's a dummy and the new record is real.
  500. size_t OldRecordIndex = InsertResult.first->second;
  501. BinaryCoverageReader::ProfileMappingRecord &OldRecord =
  502. Records[OldRecordIndex];
  503. Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
  504. OldRecord.FunctionHash, OldRecord.CoverageMapping);
  505. if (Error Err = OldIsDummyExpected.takeError())
  506. return Err;
  507. if (!*OldIsDummyExpected)
  508. return Error::success();
  509. Expected<bool> NewIsDummyExpected =
  510. isCoverageMappingDummy(FuncHash, Mapping);
  511. if (Error Err = NewIsDummyExpected.takeError())
  512. return Err;
  513. if (*NewIsDummyExpected)
  514. return Error::success();
  515. ++CovMapNumUsedRecords;
  516. OldRecord.FunctionHash = FuncHash;
  517. OldRecord.CoverageMapping = Mapping;
  518. OldRecord.FilenamesBegin = FileRange.StartingIndex;
  519. OldRecord.FilenamesSize = FileRange.Length;
  520. return Error::success();
  521. }
  522. public:
  523. VersionedCovMapFuncRecordReader(
  524. InstrProfSymtab &P,
  525. std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
  526. std::vector<StringRef> &F)
  527. : ProfileNames(P), Filenames(F), Records(R) {}
  528. ~VersionedCovMapFuncRecordReader() override = default;
  529. Expected<const char *> readCoverageHeader(
  530. const char *CovBuf, const char *CovBufEnd,
  531. BinaryCoverageReader::DecompressedData &Decompressed) override {
  532. using namespace support;
  533. if (CovBuf + sizeof(CovMapHeader) > CovBufEnd)
  534. return make_error<CoverageMapError>(coveragemap_error::malformed);
  535. auto CovHeader = reinterpret_cast<const CovMapHeader *>(CovBuf);
  536. uint32_t NRecords = CovHeader->getNRecords<Endian>();
  537. uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
  538. uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
  539. assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
  540. CovBuf = reinterpret_cast<const char *>(CovHeader + 1);
  541. // Skip past the function records, saving the start and end for later.
  542. // This is a no-op in Version4 (function records are read after all headers
  543. // are read).
  544. const char *FuncRecBuf = nullptr;
  545. const char *FuncRecBufEnd = nullptr;
  546. if (Version < CovMapVersion::Version4)
  547. FuncRecBuf = CovBuf;
  548. CovBuf += NRecords * sizeof(FuncRecordType);
  549. if (Version < CovMapVersion::Version4)
  550. FuncRecBufEnd = CovBuf;
  551. // Get the filenames.
  552. if (CovBuf + FilenamesSize > CovBufEnd)
  553. return make_error<CoverageMapError>(coveragemap_error::malformed);
  554. size_t FilenamesBegin = Filenames.size();
  555. StringRef FilenameRegion(CovBuf, FilenamesSize);
  556. RawCoverageFilenamesReader Reader(FilenameRegion, Filenames);
  557. if (auto Err = Reader.read(Version, Decompressed))
  558. return std::move(Err);
  559. CovBuf += FilenamesSize;
  560. FilenameRange FileRange(FilenamesBegin, Filenames.size() - FilenamesBegin);
  561. if (Version >= CovMapVersion::Version4) {
  562. // Map a hash of the filenames region to the filename range associated
  563. // with this coverage header.
  564. int64_t FilenamesRef =
  565. llvm::IndexedInstrProf::ComputeHash(FilenameRegion);
  566. auto Insert =
  567. FileRangeMap.insert(std::make_pair(FilenamesRef, FileRange));
  568. if (!Insert.second) {
  569. // The same filenames ref was encountered twice. It's possible that
  570. // the associated filenames are the same.
  571. auto It = Filenames.begin();
  572. FilenameRange &OrigRange = Insert.first->getSecond();
  573. if (std::equal(It + OrigRange.StartingIndex,
  574. It + OrigRange.StartingIndex + OrigRange.Length,
  575. It + FileRange.StartingIndex,
  576. It + FileRange.StartingIndex + FileRange.Length))
  577. // Map the new range to the original one.
  578. FileRange = OrigRange;
  579. else
  580. // This is a hash collision. Mark the filenames ref invalid.
  581. OrigRange.markInvalid();
  582. }
  583. }
  584. // We'll read the coverage mapping records in the loop below.
  585. // This is a no-op in Version4 (coverage mappings are not affixed to the
  586. // coverage header).
  587. const char *MappingBuf = CovBuf;
  588. if (Version >= CovMapVersion::Version4 && CoverageSize != 0)
  589. return make_error<CoverageMapError>(coveragemap_error::malformed);
  590. CovBuf += CoverageSize;
  591. const char *MappingEnd = CovBuf;
  592. if (CovBuf > CovBufEnd)
  593. return make_error<CoverageMapError>(coveragemap_error::malformed);
  594. if (Version < CovMapVersion::Version4) {
  595. // Read each function record.
  596. if (Error E = readFunctionRecords(FuncRecBuf, FuncRecBufEnd, FileRange,
  597. MappingBuf, MappingEnd))
  598. return std::move(E);
  599. }
  600. // Each coverage map has an alignment of 8, so we need to adjust alignment
  601. // before reading the next map.
  602. CovBuf += offsetToAlignedAddr(CovBuf, Align(8));
  603. return CovBuf;
  604. }
  605. Error readFunctionRecords(const char *FuncRecBuf, const char *FuncRecBufEnd,
  606. Optional<FilenameRange> OutOfLineFileRange,
  607. const char *OutOfLineMappingBuf,
  608. const char *OutOfLineMappingBufEnd) override {
  609. auto CFR = reinterpret_cast<const FuncRecordType *>(FuncRecBuf);
  610. while ((const char *)CFR < FuncRecBufEnd) {
  611. // Validate the length of the coverage mapping for this function.
  612. const char *NextMappingBuf;
  613. const FuncRecordType *NextCFR;
  614. std::tie(NextMappingBuf, NextCFR) =
  615. CFR->template advanceByOne<Endian>(OutOfLineMappingBuf);
  616. if (Version < CovMapVersion::Version4)
  617. if (NextMappingBuf > OutOfLineMappingBufEnd)
  618. return make_error<CoverageMapError>(coveragemap_error::malformed);
  619. // Look up the set of filenames associated with this function record.
  620. Optional<FilenameRange> FileRange;
  621. if (Version < CovMapVersion::Version4) {
  622. FileRange = OutOfLineFileRange;
  623. } else {
  624. uint64_t FilenamesRef = CFR->template getFilenamesRef<Endian>();
  625. auto It = FileRangeMap.find(FilenamesRef);
  626. if (It == FileRangeMap.end())
  627. return make_error<CoverageMapError>(coveragemap_error::malformed);
  628. else
  629. FileRange = It->getSecond();
  630. }
  631. // Now, read the coverage data.
  632. if (FileRange && !FileRange->isInvalid()) {
  633. StringRef Mapping =
  634. CFR->template getCoverageMapping<Endian>(OutOfLineMappingBuf);
  635. if (Version >= CovMapVersion::Version4 &&
  636. Mapping.data() + Mapping.size() > FuncRecBufEnd)
  637. return make_error<CoverageMapError>(coveragemap_error::malformed);
  638. if (Error Err = insertFunctionRecordIfNeeded(CFR, Mapping, *FileRange))
  639. return Err;
  640. }
  641. std::tie(OutOfLineMappingBuf, CFR) = std::tie(NextMappingBuf, NextCFR);
  642. }
  643. return Error::success();
  644. }
  645. };
  646. } // end anonymous namespace
  647. template <class IntPtrT, support::endianness Endian>
  648. Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
  649. CovMapVersion Version, InstrProfSymtab &P,
  650. std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
  651. std::vector<StringRef> &F) {
  652. using namespace coverage;
  653. switch (Version) {
  654. case CovMapVersion::Version1:
  655. return std::make_unique<VersionedCovMapFuncRecordReader<
  656. CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
  657. case CovMapVersion::Version2:
  658. case CovMapVersion::Version3:
  659. case CovMapVersion::Version4:
  660. case CovMapVersion::Version5:
  661. // Decompress the name data.
  662. if (Error E = P.create(P.getNameData()))
  663. return std::move(E);
  664. if (Version == CovMapVersion::Version2)
  665. return std::make_unique<VersionedCovMapFuncRecordReader<
  666. CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
  667. else if (Version == CovMapVersion::Version3)
  668. return std::make_unique<VersionedCovMapFuncRecordReader<
  669. CovMapVersion::Version3, IntPtrT, Endian>>(P, R, F);
  670. else if (Version == CovMapVersion::Version4)
  671. return std::make_unique<VersionedCovMapFuncRecordReader<
  672. CovMapVersion::Version4, IntPtrT, Endian>>(P, R, F);
  673. else if (Version == CovMapVersion::Version5)
  674. return std::make_unique<VersionedCovMapFuncRecordReader<
  675. CovMapVersion::Version5, IntPtrT, Endian>>(P, R, F);
  676. }
  677. llvm_unreachable("Unsupported version");
  678. }
  679. template <typename T, support::endianness Endian>
  680. static Error readCoverageMappingData(
  681. InstrProfSymtab &ProfileNames, StringRef CovMap, StringRef FuncRecords,
  682. std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
  683. std::vector<StringRef> &Filenames,
  684. BinaryCoverageReader::DecompressedData &Decompressed) {
  685. using namespace coverage;
  686. // Read the records in the coverage data section.
  687. auto CovHeader =
  688. reinterpret_cast<const CovMapHeader *>(CovMap.data());
  689. CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
  690. if (Version > CovMapVersion::CurrentVersion)
  691. return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
  692. Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
  693. CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
  694. Filenames);
  695. if (Error E = ReaderExpected.takeError())
  696. return E;
  697. auto Reader = std::move(ReaderExpected.get());
  698. const char *CovBuf = CovMap.data();
  699. const char *CovBufEnd = CovBuf + CovMap.size();
  700. const char *FuncRecBuf = FuncRecords.data();
  701. const char *FuncRecBufEnd = FuncRecords.data() + FuncRecords.size();
  702. while (CovBuf < CovBufEnd) {
  703. // Read the current coverage header & filename data.
  704. //
  705. // Prior to Version4, this also reads all function records affixed to the
  706. // header.
  707. //
  708. // Return a pointer to the next coverage header.
  709. auto NextOrErr =
  710. Reader->readCoverageHeader(CovBuf, CovBufEnd, Decompressed);
  711. if (auto E = NextOrErr.takeError())
  712. return E;
  713. CovBuf = NextOrErr.get();
  714. }
  715. // In Version4, function records are not affixed to coverage headers. Read
  716. // the records from their dedicated section.
  717. if (Version >= CovMapVersion::Version4)
  718. return Reader->readFunctionRecords(FuncRecBuf, FuncRecBufEnd, None, nullptr,
  719. nullptr);
  720. return Error::success();
  721. }
  722. static const char *TestingFormatMagic = "llvmcovmtestdata";
  723. Expected<std::unique_ptr<BinaryCoverageReader>>
  724. BinaryCoverageReader::createCoverageReaderFromBuffer(
  725. StringRef Coverage, std::string &&FuncRecords, InstrProfSymtab &&ProfileNames,
  726. uint8_t BytesInAddress, support::endianness Endian) {
  727. std::unique_ptr<BinaryCoverageReader> Reader(
  728. new BinaryCoverageReader(std::move(FuncRecords)));
  729. Reader->ProfileNames = std::move(ProfileNames);
  730. StringRef FuncRecordsRef = Reader->FuncRecords;
  731. if (BytesInAddress == 4 && Endian == support::endianness::little) {
  732. if (Error E =
  733. readCoverageMappingData<uint32_t, support::endianness::little>(
  734. Reader->ProfileNames, Coverage, FuncRecordsRef,
  735. Reader->MappingRecords, Reader->Filenames,
  736. Reader->Decompressed))
  737. return std::move(E);
  738. } else if (BytesInAddress == 4 && Endian == support::endianness::big) {
  739. if (Error E = readCoverageMappingData<uint32_t, support::endianness::big>(
  740. Reader->ProfileNames, Coverage, FuncRecordsRef,
  741. Reader->MappingRecords, Reader->Filenames, Reader->Decompressed))
  742. return std::move(E);
  743. } else if (BytesInAddress == 8 && Endian == support::endianness::little) {
  744. if (Error E =
  745. readCoverageMappingData<uint64_t, support::endianness::little>(
  746. Reader->ProfileNames, Coverage, FuncRecordsRef,
  747. Reader->MappingRecords, Reader->Filenames,
  748. Reader->Decompressed))
  749. return std::move(E);
  750. } else if (BytesInAddress == 8 && Endian == support::endianness::big) {
  751. if (Error E = readCoverageMappingData<uint64_t, support::endianness::big>(
  752. Reader->ProfileNames, Coverage, FuncRecordsRef,
  753. Reader->MappingRecords, Reader->Filenames, Reader->Decompressed))
  754. return std::move(E);
  755. } else
  756. return make_error<CoverageMapError>(coveragemap_error::malformed);
  757. return std::move(Reader);
  758. }
  759. static Expected<std::unique_ptr<BinaryCoverageReader>>
  760. loadTestingFormat(StringRef Data) {
  761. uint8_t BytesInAddress = 8;
  762. support::endianness Endian = support::endianness::little;
  763. Data = Data.substr(StringRef(TestingFormatMagic).size());
  764. if (Data.empty())
  765. return make_error<CoverageMapError>(coveragemap_error::truncated);
  766. unsigned N = 0;
  767. uint64_t ProfileNamesSize = decodeULEB128(Data.bytes_begin(), &N);
  768. if (N > Data.size())
  769. return make_error<CoverageMapError>(coveragemap_error::malformed);
  770. Data = Data.substr(N);
  771. if (Data.empty())
  772. return make_error<CoverageMapError>(coveragemap_error::truncated);
  773. N = 0;
  774. uint64_t Address = decodeULEB128(Data.bytes_begin(), &N);
  775. if (N > Data.size())
  776. return make_error<CoverageMapError>(coveragemap_error::malformed);
  777. Data = Data.substr(N);
  778. if (Data.size() < ProfileNamesSize)
  779. return make_error<CoverageMapError>(coveragemap_error::malformed);
  780. InstrProfSymtab ProfileNames;
  781. if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
  782. return std::move(E);
  783. StringRef CoverageMapping = Data.substr(ProfileNamesSize);
  784. // Skip the padding bytes because coverage map data has an alignment of 8.
  785. if (CoverageMapping.empty())
  786. return make_error<CoverageMapError>(coveragemap_error::truncated);
  787. size_t Pad = offsetToAlignedAddr(CoverageMapping.data(), Align(8));
  788. if (CoverageMapping.size() < Pad)
  789. return make_error<CoverageMapError>(coveragemap_error::malformed);
  790. CoverageMapping = CoverageMapping.substr(Pad);
  791. return BinaryCoverageReader::createCoverageReaderFromBuffer(
  792. CoverageMapping, "", std::move(ProfileNames), BytesInAddress, Endian);
  793. }
  794. /// Find all sections that match \p Name. There may be more than one if comdats
  795. /// are in use, e.g. for the __llvm_covfun section on ELF.
  796. static Expected<std::vector<SectionRef>> lookupSections(ObjectFile &OF,
  797. StringRef Name) {
  798. // On COFF, the object file section name may end in "$M". This tells the
  799. // linker to sort these sections between "$A" and "$Z". The linker removes the
  800. // dollar and everything after it in the final binary. Do the same to match.
  801. bool IsCOFF = isa<COFFObjectFile>(OF);
  802. auto stripSuffix = [IsCOFF](StringRef N) {
  803. return IsCOFF ? N.split('$').first : N;
  804. };
  805. Name = stripSuffix(Name);
  806. std::vector<SectionRef> Sections;
  807. for (const auto &Section : OF.sections()) {
  808. Expected<StringRef> NameOrErr = Section.getName();
  809. if (!NameOrErr)
  810. return NameOrErr.takeError();
  811. if (stripSuffix(*NameOrErr) == Name)
  812. Sections.push_back(Section);
  813. }
  814. if (Sections.empty())
  815. return make_error<CoverageMapError>(coveragemap_error::no_data_found);
  816. return Sections;
  817. }
  818. static Expected<std::unique_ptr<BinaryCoverageReader>>
  819. loadBinaryFormat(std::unique_ptr<Binary> Bin, StringRef Arch) {
  820. std::unique_ptr<ObjectFile> OF;
  821. if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
  822. // If we have a universal binary, try to look up the object for the
  823. // appropriate architecture.
  824. auto ObjectFileOrErr = Universal->getMachOObjectForArch(Arch);
  825. if (!ObjectFileOrErr)
  826. return ObjectFileOrErr.takeError();
  827. OF = std::move(ObjectFileOrErr.get());
  828. } else if (isa<ObjectFile>(Bin.get())) {
  829. // For any other object file, upcast and take ownership.
  830. OF.reset(cast<ObjectFile>(Bin.release()));
  831. // If we've asked for a particular arch, make sure they match.
  832. if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
  833. return errorCodeToError(object_error::arch_not_found);
  834. } else
  835. // We can only handle object files.
  836. return make_error<CoverageMapError>(coveragemap_error::malformed);
  837. // The coverage uses native pointer sizes for the object it's written in.
  838. uint8_t BytesInAddress = OF->getBytesInAddress();
  839. support::endianness Endian = OF->isLittleEndian()
  840. ? support::endianness::little
  841. : support::endianness::big;
  842. // Look for the sections that we are interested in.
  843. auto ObjFormat = OF->getTripleObjectFormat();
  844. auto NamesSection =
  845. lookupSections(*OF, getInstrProfSectionName(IPSK_name, ObjFormat,
  846. /*AddSegmentInfo=*/false));
  847. if (auto E = NamesSection.takeError())
  848. return std::move(E);
  849. auto CoverageSection =
  850. lookupSections(*OF, getInstrProfSectionName(IPSK_covmap, ObjFormat,
  851. /*AddSegmentInfo=*/false));
  852. if (auto E = CoverageSection.takeError())
  853. return std::move(E);
  854. std::vector<SectionRef> CoverageSectionRefs = *CoverageSection;
  855. if (CoverageSectionRefs.size() != 1)
  856. return make_error<CoverageMapError>(coveragemap_error::malformed);
  857. auto CoverageMappingOrErr = CoverageSectionRefs.back().getContents();
  858. if (!CoverageMappingOrErr)
  859. return CoverageMappingOrErr.takeError();
  860. StringRef CoverageMapping = CoverageMappingOrErr.get();
  861. InstrProfSymtab ProfileNames;
  862. std::vector<SectionRef> NamesSectionRefs = *NamesSection;
  863. if (NamesSectionRefs.size() != 1)
  864. return make_error<CoverageMapError>(coveragemap_error::malformed);
  865. if (Error E = ProfileNames.create(NamesSectionRefs.back()))
  866. return std::move(E);
  867. // Look for the coverage records section (Version4 only).
  868. std::string FuncRecords;
  869. auto CoverageRecordsSections =
  870. lookupSections(*OF, getInstrProfSectionName(IPSK_covfun, ObjFormat,
  871. /*AddSegmentInfo=*/false));
  872. if (auto E = CoverageRecordsSections.takeError())
  873. consumeError(std::move(E));
  874. else {
  875. for (SectionRef Section : *CoverageRecordsSections) {
  876. auto CoverageRecordsOrErr = Section.getContents();
  877. if (!CoverageRecordsOrErr)
  878. return CoverageRecordsOrErr.takeError();
  879. FuncRecords += CoverageRecordsOrErr.get();
  880. while (FuncRecords.size() % 8 != 0)
  881. FuncRecords += '\0';
  882. }
  883. }
  884. return BinaryCoverageReader::createCoverageReaderFromBuffer(
  885. CoverageMapping, std::move(FuncRecords), std::move(ProfileNames),
  886. BytesInAddress, Endian);
  887. }
  888. /// Determine whether \p Arch is invalid or empty, given \p Bin.
  889. static bool isArchSpecifierInvalidOrMissing(Binary *Bin, StringRef Arch) {
  890. // If we have a universal binary and Arch doesn't identify any of its slices,
  891. // it's user error.
  892. if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin)) {
  893. for (auto &ObjForArch : Universal->objects())
  894. if (Arch == ObjForArch.getArchFlagName())
  895. return false;
  896. return true;
  897. }
  898. return false;
  899. }
  900. Expected<std::vector<std::unique_ptr<BinaryCoverageReader>>>
  901. BinaryCoverageReader::create(
  902. MemoryBufferRef ObjectBuffer, StringRef Arch,
  903. SmallVectorImpl<std::unique_ptr<MemoryBuffer>> &ObjectFileBuffers) {
  904. std::vector<std::unique_ptr<BinaryCoverageReader>> Readers;
  905. if (ObjectBuffer.getBuffer().startswith(TestingFormatMagic)) {
  906. // This is a special format used for testing.
  907. auto ReaderOrErr = loadTestingFormat(ObjectBuffer.getBuffer());
  908. if (!ReaderOrErr)
  909. return ReaderOrErr.takeError();
  910. Readers.push_back(std::move(ReaderOrErr.get()));
  911. return std::move(Readers);
  912. }
  913. auto BinOrErr = createBinary(ObjectBuffer);
  914. if (!BinOrErr)
  915. return BinOrErr.takeError();
  916. std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
  917. if (isArchSpecifierInvalidOrMissing(Bin.get(), Arch))
  918. return make_error<CoverageMapError>(
  919. coveragemap_error::invalid_or_missing_arch_specifier);
  920. // MachO universal binaries which contain archives need to be treated as
  921. // archives, not as regular binaries.
  922. if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
  923. for (auto &ObjForArch : Universal->objects()) {
  924. // Skip slices within the universal binary which target the wrong arch.
  925. std::string ObjArch = ObjForArch.getArchFlagName();
  926. if (Arch != ObjArch)
  927. continue;
  928. auto ArchiveOrErr = ObjForArch.getAsArchive();
  929. if (!ArchiveOrErr) {
  930. // If this is not an archive, try treating it as a regular object.
  931. consumeError(ArchiveOrErr.takeError());
  932. break;
  933. }
  934. return BinaryCoverageReader::create(
  935. ArchiveOrErr.get()->getMemoryBufferRef(), Arch, ObjectFileBuffers);
  936. }
  937. }
  938. // Load coverage out of archive members.
  939. if (auto *Ar = dyn_cast<Archive>(Bin.get())) {
  940. Error Err = Error::success();
  941. for (auto &Child : Ar->children(Err)) {
  942. Expected<MemoryBufferRef> ChildBufOrErr = Child.getMemoryBufferRef();
  943. if (!ChildBufOrErr)
  944. return ChildBufOrErr.takeError();
  945. auto ChildReadersOrErr = BinaryCoverageReader::create(
  946. ChildBufOrErr.get(), Arch, ObjectFileBuffers);
  947. if (!ChildReadersOrErr)
  948. return ChildReadersOrErr.takeError();
  949. for (auto &Reader : ChildReadersOrErr.get())
  950. Readers.push_back(std::move(Reader));
  951. }
  952. if (Err)
  953. return std::move(Err);
  954. // Thin archives reference object files outside of the archive file, i.e.
  955. // files which reside in memory not owned by the caller. Transfer ownership
  956. // to the caller.
  957. if (Ar->isThin())
  958. for (auto &Buffer : Ar->takeThinBuffers())
  959. ObjectFileBuffers.push_back(std::move(Buffer));
  960. return std::move(Readers);
  961. }
  962. auto ReaderOrErr = loadBinaryFormat(std::move(Bin), Arch);
  963. if (!ReaderOrErr)
  964. return ReaderOrErr.takeError();
  965. Readers.push_back(std::move(ReaderOrErr.get()));
  966. return std::move(Readers);
  967. }
  968. Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
  969. if (CurrentRecord >= MappingRecords.size())
  970. return make_error<CoverageMapError>(coveragemap_error::eof);
  971. FunctionsFilenames.clear();
  972. Expressions.clear();
  973. MappingRegions.clear();
  974. auto &R = MappingRecords[CurrentRecord];
  975. RawCoverageMappingReader Reader(
  976. R.CoverageMapping,
  977. makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
  978. FunctionsFilenames, Expressions, MappingRegions);
  979. if (auto Err = Reader.read())
  980. return Err;
  981. Record.FunctionName = R.FunctionName;
  982. Record.FunctionHash = R.FunctionHash;
  983. Record.Filenames = FunctionsFilenames;
  984. Record.Expressions = Expressions;
  985. Record.MappingRegions = MappingRegions;
  986. ++CurrentRecord;
  987. return Error::success();
  988. }