CoverageMappingReader.cpp 46 KB

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