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