CoverageMappingReader.cpp 47 KB

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