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