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