blob: d251e8dcb812e0dcf817f5a5d80e650667ee1c5a [file] [log] [blame]
Alex Lorenza20a5d52014-07-24 23:57:54 +00001//=-- 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/ProfileData/CoverageMappingReader.h"
16#include "llvm/ADT/DenseSet.h"
Justin Bogner43795352015-03-11 02:30:51 +000017#include "llvm/Object/MachOUniversal.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000018#include "llvm/Object/ObjectFile.h"
Justin Bognerf5846492014-09-20 15:31:51 +000019#include "llvm/Support/Debug.h"
Justin Bogner7b33cc92015-03-16 06:55:45 +000020#include "llvm/Support/Endian.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000021#include "llvm/Support/LEB128.h"
Justin Bognerd49d8ee2015-06-05 01:23:42 +000022#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000023#include "llvm/Support/raw_ostream.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000024
25using namespace llvm;
26using namespace coverage;
27using namespace object;
28
Justin Bognerf5846492014-09-20 15:31:51 +000029#define DEBUG_TYPE "coverage-mapping"
30
Alex Lorenza20a5d52014-07-24 23:57:54 +000031void CoverageMappingIterator::increment() {
32 // Check if all the records were read or if an error occurred while reading
33 // the next record.
34 if (Reader->readNextRecord(Record))
35 *this = CoverageMappingIterator();
36}
37
38std::error_code RawCoverageReader::readULEB128(uint64_t &Result) {
39 if (Data.size() < 1)
Justin Bogner367a9f22015-05-06 23:19:35 +000040 return coveragemap_error::truncated;
Alex Lorenza20a5d52014-07-24 23:57:54 +000041 unsigned N = 0;
42 Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
43 if (N > Data.size())
Justin Bogner367a9f22015-05-06 23:19:35 +000044 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +000045 Data = Data.substr(N);
Justin Bogner0b130862015-05-06 23:15:55 +000046 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000047}
48
49std::error_code RawCoverageReader::readIntMax(uint64_t &Result,
50 uint64_t MaxPlus1) {
51 if (auto Err = readULEB128(Result))
52 return Err;
53 if (Result >= MaxPlus1)
Justin Bogner367a9f22015-05-06 23:19:35 +000054 return coveragemap_error::malformed;
Justin Bogner0b130862015-05-06 23:15:55 +000055 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000056}
57
58std::error_code RawCoverageReader::readSize(uint64_t &Result) {
59 if (auto Err = readULEB128(Result))
60 return Err;
61 // Sanity check the number.
62 if (Result > Data.size())
Justin Bogner367a9f22015-05-06 23:19:35 +000063 return coveragemap_error::malformed;
Justin Bogner0b130862015-05-06 23:15:55 +000064 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000065}
66
67std::error_code RawCoverageReader::readString(StringRef &Result) {
68 uint64_t Length;
69 if (auto Err = readSize(Length))
70 return Err;
71 Result = Data.substr(0, Length);
72 Data = Data.substr(Length);
Justin Bogner0b130862015-05-06 23:15:55 +000073 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000074}
75
76std::error_code RawCoverageFilenamesReader::read() {
77 uint64_t NumFilenames;
78 if (auto Err = readSize(NumFilenames))
79 return Err;
80 for (size_t I = 0; I < NumFilenames; ++I) {
81 StringRef Filename;
82 if (auto Err = readString(Filename))
83 return Err;
84 Filenames.push_back(Filename);
85 }
Justin Bogner0b130862015-05-06 23:15:55 +000086 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000087}
88
89std::error_code RawCoverageMappingReader::decodeCounter(unsigned Value,
90 Counter &C) {
91 auto Tag = Value & Counter::EncodingTagMask;
92 switch (Tag) {
93 case Counter::Zero:
94 C = Counter::getZero();
Justin Bogner0b130862015-05-06 23:15:55 +000095 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000096 case Counter::CounterValueReference:
97 C = Counter::getCounter(Value >> Counter::EncodingTagBits);
Justin Bogner0b130862015-05-06 23:15:55 +000098 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +000099 default:
100 break;
101 }
102 Tag -= Counter::Expression;
103 switch (Tag) {
104 case CounterExpression::Subtract:
105 case CounterExpression::Add: {
106 auto ID = Value >> Counter::EncodingTagBits;
107 if (ID >= Expressions.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000108 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000109 Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
110 C = Counter::getExpression(ID);
111 break;
112 }
113 default:
Justin Bogner367a9f22015-05-06 23:19:35 +0000114 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000115 }
Justin Bogner0b130862015-05-06 23:15:55 +0000116 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000117}
118
119std::error_code RawCoverageMappingReader::readCounter(Counter &C) {
120 uint64_t EncodedCounter;
121 if (auto Err =
122 readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
123 return Err;
124 if (auto Err = decodeCounter(EncodedCounter, C))
125 return Err;
Justin Bogner0b130862015-05-06 23:15:55 +0000126 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000127}
128
129static const unsigned EncodingExpansionRegionBit = 1
130 << Counter::EncodingTagBits;
131
132/// \brief Read the sub-array of regions for the given inferred file id.
Ehsan Akhgari29b61ce2014-07-25 02:51:57 +0000133/// \param NumFileIDs the number of file ids that are defined for this
Alex Lorenza20a5d52014-07-24 23:57:54 +0000134/// function.
135std::error_code RawCoverageMappingReader::readMappingRegionsSubArray(
136 std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
137 size_t NumFileIDs) {
138 uint64_t NumRegions;
139 if (auto Err = readSize(NumRegions))
140 return Err;
141 unsigned LineStart = 0;
142 for (size_t I = 0; I < NumRegions; ++I) {
143 Counter C;
144 CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
145
146 // Read the combined counter + region kind.
147 uint64_t EncodedCounterAndRegion;
148 if (auto Err = readIntMax(EncodedCounterAndRegion,
149 std::numeric_limits<unsigned>::max()))
150 return Err;
151 unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
152 uint64_t ExpandedFileID = 0;
153 if (Tag != Counter::Zero) {
154 if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
155 return Err;
156 } else {
157 // Is it an expansion region?
158 if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
159 Kind = CounterMappingRegion::ExpansionRegion;
160 ExpandedFileID = EncodedCounterAndRegion >>
161 Counter::EncodingCounterTagAndExpansionRegionTagBits;
162 if (ExpandedFileID >= NumFileIDs)
Justin Bogner367a9f22015-05-06 23:19:35 +0000163 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000164 } else {
165 switch (EncodedCounterAndRegion >>
166 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
167 case CounterMappingRegion::CodeRegion:
168 // Don't do anything when we have a code region with a zero counter.
169 break;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000170 case CounterMappingRegion::SkippedRegion:
171 Kind = CounterMappingRegion::SkippedRegion;
172 break;
173 default:
Justin Bogner367a9f22015-05-06 23:19:35 +0000174 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000175 }
176 }
177 }
178
179 // Read the source range.
Justin Bognerde158172015-02-03 21:35:36 +0000180 uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000181 if (auto Err =
182 readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
183 return Err;
Justin Bognerde158172015-02-03 21:35:36 +0000184 if (auto Err = readULEB128(ColumnStart))
Alex Lorenza20a5d52014-07-24 23:57:54 +0000185 return Err;
Alex Lorenz1193b5e2014-08-04 18:00:51 +0000186 if (ColumnStart > std::numeric_limits<unsigned>::max())
Justin Bogner367a9f22015-05-06 23:19:35 +0000187 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000188 if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
189 return Err;
190 if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
191 return Err;
192 LineStart += LineStartDelta;
193 // Adjust the column locations for the empty regions that are supposed to
194 // cover whole lines. Those regions should be encoded with the
195 // column range (1 -> std::numeric_limits<unsigned>::max()), but because
196 // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
197 // we set the column range to (0 -> 0) to ensure that the column start and
198 // column end take up one byte each.
199 // The std::numeric_limits<unsigned>::max() is used to represent a column
200 // position at the end of the line without knowing the length of that line.
201 if (ColumnStart == 0 && ColumnEnd == 0) {
202 ColumnStart = 1;
203 ColumnEnd = std::numeric_limits<unsigned>::max();
204 }
Justin Bognerf5846492014-09-20 15:31:51 +0000205
206 DEBUG({
207 dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
208 << ColumnStart << " -> " << (LineStart + NumLines) << ":"
209 << ColumnEnd << ", ";
210 if (Kind == CounterMappingRegion::ExpansionRegion)
211 dbgs() << "Expands to file " << ExpandedFileID;
212 else
213 CounterMappingContext(Expressions).dump(C, dbgs());
214 dbgs() << "\n";
215 });
216
Justin Bogner26b31422015-02-03 23:59:33 +0000217 MappingRegions.push_back(CounterMappingRegion(
218 C, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
219 LineStart + NumLines, ColumnEnd, Kind));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000220 }
Justin Bogner0b130862015-05-06 23:15:55 +0000221 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000222}
223
Justin Bogner195a4f02015-02-03 00:20:11 +0000224std::error_code RawCoverageMappingReader::read() {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000225
226 // Read the virtual file mapping.
227 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
228 uint64_t NumFileMappings;
229 if (auto Err = readSize(NumFileMappings))
230 return Err;
231 for (size_t I = 0; I < NumFileMappings; ++I) {
232 uint64_t FilenameIndex;
233 if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
234 return Err;
235 VirtualFileMapping.push_back(FilenameIndex);
236 }
237
238 // Construct the files using unique filenames and virtual file mapping.
239 for (auto I : VirtualFileMapping) {
240 Filenames.push_back(TranslationUnitFilenames[I]);
241 }
242
243 // Read the expressions.
244 uint64_t NumExpressions;
245 if (auto Err = readSize(NumExpressions))
246 return Err;
247 // Create an array of dummy expressions that get the proper counters
248 // when the expressions are read, and the proper kinds when the counters
249 // are decoded.
250 Expressions.resize(
251 NumExpressions,
252 CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
253 for (size_t I = 0; I < NumExpressions; ++I) {
254 if (auto Err = readCounter(Expressions[I].LHS))
255 return Err;
256 if (auto Err = readCounter(Expressions[I].RHS))
257 return Err;
258 }
259
260 // Read the mapping regions sub-arrays.
261 for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
262 InferredFileID < S; ++InferredFileID) {
263 if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
264 VirtualFileMapping.size()))
265 return Err;
266 }
267
268 // Set the counters for the expansion regions.
269 // i.e. Counter of expansion region = counter of the first region
270 // from the expanded file.
271 // Perform multiple passes to correctly propagate the counters through
272 // all the nested expansion regions.
Alex Lorenz251b3e32014-07-29 21:42:24 +0000273 SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
274 FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000275 for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
Alex Lorenz251b3e32014-07-29 21:42:24 +0000276 for (auto &R : MappingRegions) {
277 if (R.Kind != CounterMappingRegion::ExpansionRegion)
278 continue;
279 assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
280 FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
281 }
282 for (auto &R : MappingRegions) {
283 if (FileIDExpansionRegionMapping[R.FileID]) {
284 FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
285 FileIDExpansionRegionMapping[R.FileID] = nullptr;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000286 }
287 }
288 }
289
Justin Bogner0b130862015-05-06 23:15:55 +0000290 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000291}
292
Xinliang David Li50de45d2015-12-17 00:53:37 +0000293std::error_code InstrProfSymtab::create(SectionRef &Section) {
294 if (auto Err = Section.getContents(Data))
295 return Err;
296 Address = Section.getAddress();
297 return std::error_code();
298}
Alex Lorenza20a5d52014-07-24 23:57:54 +0000299
Xinliang David Li50de45d2015-12-17 00:53:37 +0000300StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
301 if (Pointer < Address)
302 return StringRef();
303 auto Offset = Pointer - Address;
304 if (Offset + Size > Data.size())
305 return StringRef();
306 return Data.substr(Pointer - Address, Size);
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000307}
Alex Lorenza20a5d52014-07-24 23:57:54 +0000308
Xinliang David Lia9d78462016-01-13 23:29:33 +0000309struct CovMapFuncRecordReader {
310 // The interface to read coverage mapping function records for
311 // a module. \p Buf is a reference to the buffer pointer pointing
312 // to the \c CovHeader of coverage mapping data associated with
313 // the module.
314 virtual std::error_code readFunctionRecords(const char *&Buf,
315 const char *End) = 0;
316 template <class IntPtrT, support::endianness Endian>
317 static std::unique_ptr<CovMapFuncRecordReader>
318 get(coverage::CoverageMappingVersion Version, InstrProfSymtab &P,
319 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
320 std::vector<StringRef> &F);
321};
Alex Lorenza20a5d52014-07-24 23:57:54 +0000322
Xinliang David Lia9d78462016-01-13 23:29:33 +0000323// A class for reading coverage mapping function records for a module.
324template <coverage::CoverageMappingVersion CovMapVersion, class IntPtrT,
325 support::endianness Endian>
326class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
327 typedef typename coverage::CovMapTraits<
328 CovMapVersion, IntPtrT>::CovMapFuncRecordType FuncRecordType;
329 typedef typename coverage::CovMapTraits<CovMapVersion, IntPtrT>::NameRefType
330 NameRefType;
331
332 llvm::DenseSet<NameRefType> UniqueFunctionMappingData;
333 InstrProfSymtab &ProfileNames;
334 std::vector<StringRef> &Filenames;
335 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
336
337public:
338 VersionedCovMapFuncRecordReader(
339 InstrProfSymtab &P,
340 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
341 std::vector<StringRef> &F)
342 : ProfileNames(P), Filenames(F), Records(R) {}
343
344 std::error_code readFunctionRecords(const char *&Buf,
345 const char *End) override {
346 using namespace support;
Xinliang David Li946558d2016-01-03 18:57:40 +0000347 if (Buf + sizeof(CovMapHeader) > End)
Justin Bogner367a9f22015-05-06 23:19:35 +0000348 return coveragemap_error::malformed;
Xinliang David Li946558d2016-01-03 18:57:40 +0000349 auto CovHeader = reinterpret_cast<const coverage::CovMapHeader *>(Buf);
Xinliang David Li81f18a52016-01-13 04:36:15 +0000350 uint32_t NRecords = CovHeader->getNRecords<Endian>();
351 uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
352 uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
Xinliang David Lia9d78462016-01-13 23:29:33 +0000353 assert((CoverageMappingVersion)CovHeader->getVersion<Endian>() ==
354 CovMapVersion);
355 Buf = reinterpret_cast<const char *>(CovHeader + 1);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000356
Justin Bogner7b33cc92015-03-16 06:55:45 +0000357 // Skip past the function records, saving the start and end for later.
358 const char *FunBuf = Buf;
Xinliang David Lia9d78462016-01-13 23:29:33 +0000359 Buf += NRecords * sizeof(FuncRecordType);
Justin Bogner7b33cc92015-03-16 06:55:45 +0000360 const char *FunEnd = Buf;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000361
362 // Get the filenames.
Justin Bogner7b33cc92015-03-16 06:55:45 +0000363 if (Buf + FilenamesSize > End)
Justin Bogner367a9f22015-05-06 23:19:35 +0000364 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000365 size_t FilenamesBegin = Filenames.size();
Justin Bogner7b33cc92015-03-16 06:55:45 +0000366 RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000367 if (auto Err = Reader.read())
368 return Err;
Justin Bogner7b33cc92015-03-16 06:55:45 +0000369 Buf += FilenamesSize;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000370
Justin Bogner7b33cc92015-03-16 06:55:45 +0000371 // We'll read the coverage mapping records in the loop below.
372 const char *CovBuf = Buf;
373 Buf += CoverageSize;
374 const char *CovEnd = Buf;
Justin Bognerd49d8ee2015-06-05 01:23:42 +0000375
Justin Bogner7b33cc92015-03-16 06:55:45 +0000376 if (Buf > End)
Justin Bogner367a9f22015-05-06 23:19:35 +0000377 return coveragemap_error::malformed;
Justin Bognerd49d8ee2015-06-05 01:23:42 +0000378 // Each coverage map has an alignment of 8, so we need to adjust alignment
379 // before reading the next map.
380 Buf += alignmentAdjustment(Buf, 8);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000381
Xinliang David Lia9d78462016-01-13 23:29:33 +0000382 auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
Xinliang David Li192c7482015-11-05 00:47:26 +0000383 while ((const char *)CFR < FunEnd) {
Justin Bogner7b33cc92015-03-16 06:55:45 +0000384 // Read the function information
Xinliang David Li81f18a52016-01-13 04:36:15 +0000385 uint32_t DataSize = CFR->template getDataSize<Endian>();
386 uint64_t FuncHash = CFR->template getFuncHash<Endian>();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000387
Justin Bogner7b33cc92015-03-16 06:55:45 +0000388 // Now use that to read the coverage data.
389 if (CovBuf + DataSize > CovEnd)
Justin Bogner367a9f22015-05-06 23:19:35 +0000390 return coveragemap_error::malformed;
Justin Bogner7b33cc92015-03-16 06:55:45 +0000391 auto Mapping = StringRef(CovBuf, DataSize);
392 CovBuf += DataSize;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000393
394 // Ignore this record if we already have a record that points to the same
Justin Bogner7b33cc92015-03-16 06:55:45 +0000395 // function name. This is useful to ignore the redundant records for the
396 // functions with ODR linkage.
Xinliang David Lia9d78462016-01-13 23:29:33 +0000397 NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
Xinliang David Li81f18a52016-01-13 04:36:15 +0000398 if (!UniqueFunctionMappingData.insert(NameRef).second)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000399 continue;
Justin Bogner7b33cc92015-03-16 06:55:45 +0000400
Xinliang David Li81f18a52016-01-13 04:36:15 +0000401 StringRef FuncName;
402 if (std::error_code EC =
403 CFR->template getFuncName<Endian>(ProfileNames, FuncName))
404 return EC;
Justin Bognere84891a2015-02-26 20:06:24 +0000405 Records.push_back(BinaryCoverageReader::ProfileMappingRecord(
Xinliang David Lia9d78462016-01-13 23:29:33 +0000406 CovMapVersion, FuncName, FuncHash, Mapping, FilenamesBegin,
407 Filenames.size() - FilenamesBegin));
Xinliang David Li81f18a52016-01-13 04:36:15 +0000408 CFR++;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000409 }
Xinliang David Lia9d78462016-01-13 23:29:33 +0000410 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000411 }
Xinliang David Lia9d78462016-01-13 23:29:33 +0000412};
Alex Lorenza20a5d52014-07-24 23:57:54 +0000413
Xinliang David Lia9d78462016-01-13 23:29:33 +0000414template <class IntPtrT, support::endianness Endian>
415std::unique_ptr<CovMapFuncRecordReader> CovMapFuncRecordReader::get(
416 coverage::CoverageMappingVersion Version, InstrProfSymtab &P,
417 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
418 std::vector<StringRef> &F) {
419 using namespace coverage;
420 switch (Version) {
421 case CoverageMappingVersion1:
422 return llvm::make_unique<VersionedCovMapFuncRecordReader<
423 CoverageMappingVersion1, IntPtrT, Endian>>(P, R, F);
424 }
425 llvm_unreachable("Unsupported version");
Xinliang David Liaab986f2016-01-13 22:58:42 +0000426}
Xinliang David Lie62595c2016-01-13 23:12:53 +0000427
Xinliang David Lia9d78462016-01-13 23:29:33 +0000428template <typename T, support::endianness Endian>
429static std::error_code readCoverageMappingData(
430 InstrProfSymtab &ProfileNames, StringRef Data,
431 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
432 std::vector<StringRef> &Filenames) {
433 using namespace coverage;
434 // Read the records in the coverage data section.
435 auto CovHeader =
436 reinterpret_cast<const coverage::CovMapHeader *>(Data.data());
437 CoverageMappingVersion Version =
438 (CoverageMappingVersion)CovHeader->getVersion<Endian>();
439 if (Version > coverage::CoverageMappingCurrentVersion)
440 return coveragemap_error::unsupported_version;
441 std::unique_ptr<CovMapFuncRecordReader> Reader =
442 CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
443 Filenames);
444 for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
445 if (std::error_code EC = Reader->readFunctionRecords(Buf, End))
446 return EC;
447 }
448 return std::error_code();
449}
Alex Lorenze82d89c2014-08-22 22:56:03 +0000450static const char *TestingFormatMagic = "llvmcovmtestdata";
451
Justin Bogner43e51632015-02-26 20:06:28 +0000452static std::error_code loadTestingFormat(StringRef Data,
Xinliang David Li50de45d2015-12-17 00:53:37 +0000453 InstrProfSymtab &ProfileNames,
Justin Bogner43e51632015-02-26 20:06:28 +0000454 StringRef &CoverageMapping,
Justin Bognera4387172015-03-16 21:40:18 +0000455 uint8_t &BytesInAddress,
456 support::endianness &Endian) {
Justin Bogner43e51632015-02-26 20:06:28 +0000457 BytesInAddress = 8;
Justin Bognera4387172015-03-16 21:40:18 +0000458 Endian = support::endianness::little;
Justin Bogner43e51632015-02-26 20:06:28 +0000459
Alex Lorenze82d89c2014-08-22 22:56:03 +0000460 Data = Data.substr(StringRef(TestingFormatMagic).size());
461 if (Data.size() < 1)
Justin Bogner367a9f22015-05-06 23:19:35 +0000462 return coveragemap_error::truncated;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000463 unsigned N = 0;
464 auto ProfileNamesSize =
465 decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
466 if (N > Data.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000467 return coveragemap_error::malformed;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000468 Data = Data.substr(N);
469 if (Data.size() < 1)
Justin Bogner367a9f22015-05-06 23:19:35 +0000470 return coveragemap_error::truncated;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000471 N = 0;
Xinliang David Li50de45d2015-12-17 00:53:37 +0000472 uint64_t Address =
Alex Lorenze82d89c2014-08-22 22:56:03 +0000473 decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
474 if (N > Data.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000475 return coveragemap_error::malformed;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000476 Data = Data.substr(N);
477 if (Data.size() < ProfileNamesSize)
Justin Bogner367a9f22015-05-06 23:19:35 +0000478 return coveragemap_error::malformed;
Xinliang David Li50de45d2015-12-17 00:53:37 +0000479 ProfileNames.create(Data.substr(0, ProfileNamesSize), Address);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000480 CoverageMapping = Data.substr(ProfileNamesSize);
Justin Bogner367a9f22015-05-06 23:19:35 +0000481 return std::error_code();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000482}
483
Justin Bogner5a5c3812015-05-07 00:31:58 +0000484static ErrorOr<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
485 StringRef FoundName;
486 for (const auto &Section : OF.sections()) {
487 if (auto EC = Section.getName(FoundName))
488 return EC;
489 if (FoundName == Name)
490 return Section;
491 }
492 return coveragemap_error::no_data_found;
493}
494
Xinliang David Li50de45d2015-12-17 00:53:37 +0000495static std::error_code
496loadBinaryFormat(MemoryBufferRef ObjectBuffer, InstrProfSymtab &ProfileNames,
497 StringRef &CoverageMapping, uint8_t &BytesInAddress,
498 support::endianness &Endian, StringRef Arch) {
Justin Bogner43795352015-03-11 02:30:51 +0000499 auto BinOrErr = object::createBinary(ObjectBuffer);
500 if (std::error_code EC = BinOrErr.getError())
Justin Bogner43e51632015-02-26 20:06:28 +0000501 return EC;
Justin Bogner43795352015-03-11 02:30:51 +0000502 auto Bin = std::move(BinOrErr.get());
503 std::unique_ptr<ObjectFile> OF;
504 if (auto *Universal = dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
505 // If we have a universal binary, try to look up the object for the
506 // appropriate architecture.
507 auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
508 if (std::error_code EC = ObjectFileOrErr.getError())
509 return EC;
510 OF = std::move(ObjectFileOrErr.get());
511 } else if (isa<object::ObjectFile>(Bin.get())) {
512 // For any other object file, upcast and take ownership.
513 OF.reset(cast<object::ObjectFile>(Bin.release()));
514 // If we've asked for a particular arch, make sure they match.
Frederic Rissebc162a2015-06-22 21:33:24 +0000515 if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
Justin Bogner43795352015-03-11 02:30:51 +0000516 return object_error::arch_not_found;
517 } else
518 // We can only handle object files.
Justin Bogner367a9f22015-05-06 23:19:35 +0000519 return coveragemap_error::malformed;
Justin Bogner43795352015-03-11 02:30:51 +0000520
521 // The coverage uses native pointer sizes for the object it's written in.
Justin Bogner43e51632015-02-26 20:06:28 +0000522 BytesInAddress = OF->getBytesInAddress();
Justin Bognera4387172015-03-16 21:40:18 +0000523 Endian = OF->isLittleEndian() ? support::endianness::little
524 : support::endianness::big;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000525
526 // Look for the sections that we are interested in.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000527 auto NamesSection = lookupSection(*OF, getInstrProfNameSectionName(false));
Justin Bogner5a5c3812015-05-07 00:31:58 +0000528 if (auto EC = NamesSection.getError())
529 return EC;
Xinliang David Li83bc4222015-10-22 20:32:12 +0000530 auto CoverageSection =
531 lookupSection(*OF, getInstrProfCoverageSectionName(false));
Justin Bogner5a5c3812015-05-07 00:31:58 +0000532 if (auto EC = CoverageSection.getError())
533 return EC;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000534
Alex Lorenze82d89c2014-08-22 22:56:03 +0000535 // Get the contents of the given sections.
Justin Bogner5a5c3812015-05-07 00:31:58 +0000536 if (std::error_code EC = CoverageSection->getContents(CoverageMapping))
Justin Bogner43e51632015-02-26 20:06:28 +0000537 return EC;
Xinliang David Li50de45d2015-12-17 00:53:37 +0000538 if (std::error_code EC = ProfileNames.create(*NamesSection))
Justin Bogner43e51632015-02-26 20:06:28 +0000539 return EC;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000540
Justin Bogner43e51632015-02-26 20:06:28 +0000541 return std::error_code();
542}
543
544ErrorOr<std::unique_ptr<BinaryCoverageReader>>
Justin Bogner43795352015-03-11 02:30:51 +0000545BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
Frederic Rissebc162a2015-06-22 21:33:24 +0000546 StringRef Arch) {
Justin Bogner43e51632015-02-26 20:06:28 +0000547 std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
548
Xinliang David Li50de45d2015-12-17 00:53:37 +0000549 InstrProfSymtab ProfileNames;
Justin Bogner43e51632015-02-26 20:06:28 +0000550 StringRef Coverage;
551 uint8_t BytesInAddress;
Justin Bognera4387172015-03-16 21:40:18 +0000552 support::endianness Endian;
Justin Bogner43e51632015-02-26 20:06:28 +0000553 std::error_code EC;
554 if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
555 // This is a special format used for testing.
Xinliang David Li50de45d2015-12-17 00:53:37 +0000556 EC = loadTestingFormat(ObjectBuffer->getBuffer(), ProfileNames, Coverage,
Justin Bognera4387172015-03-16 21:40:18 +0000557 BytesInAddress, Endian);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000558 else
Xinliang David Li50de45d2015-12-17 00:53:37 +0000559 EC = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), ProfileNames,
560 Coverage, BytesInAddress, Endian, Arch);
Justin Bogner43e51632015-02-26 20:06:28 +0000561 if (EC)
562 return EC;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000563
Justin Bognera4387172015-03-16 21:40:18 +0000564 if (BytesInAddress == 4 && Endian == support::endianness::little)
565 EC = readCoverageMappingData<uint32_t, support::endianness::little>(
Xinliang David Li50de45d2015-12-17 00:53:37 +0000566 ProfileNames, Coverage, Reader->MappingRecords, Reader->Filenames);
Justin Bognera4387172015-03-16 21:40:18 +0000567 else if (BytesInAddress == 4 && Endian == support::endianness::big)
568 EC = readCoverageMappingData<uint32_t, support::endianness::big>(
Xinliang David Li50de45d2015-12-17 00:53:37 +0000569 ProfileNames, Coverage, Reader->MappingRecords, Reader->Filenames);
Justin Bognera4387172015-03-16 21:40:18 +0000570 else if (BytesInAddress == 8 && Endian == support::endianness::little)
571 EC = readCoverageMappingData<uint64_t, support::endianness::little>(
Xinliang David Li50de45d2015-12-17 00:53:37 +0000572 ProfileNames, Coverage, Reader->MappingRecords, Reader->Filenames);
Justin Bognera4387172015-03-16 21:40:18 +0000573 else if (BytesInAddress == 8 && Endian == support::endianness::big)
574 EC = readCoverageMappingData<uint64_t, support::endianness::big>(
Xinliang David Li50de45d2015-12-17 00:53:37 +0000575 ProfileNames, Coverage, Reader->MappingRecords, Reader->Filenames);
Justin Bogner43e51632015-02-26 20:06:28 +0000576 else
Justin Bogner367a9f22015-05-06 23:19:35 +0000577 return coveragemap_error::malformed;
Justin Bogner43e51632015-02-26 20:06:28 +0000578 if (EC)
579 return EC;
580 return std::move(Reader);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000581}
582
583std::error_code
Justin Bognere84891a2015-02-26 20:06:24 +0000584BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000585 if (CurrentRecord >= MappingRecords.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000586 return coveragemap_error::eof;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000587
588 FunctionsFilenames.clear();
589 Expressions.clear();
590 MappingRegions.clear();
591 auto &R = MappingRecords[CurrentRecord];
592 RawCoverageMappingReader Reader(
Justin Bogner195a4f02015-02-03 00:20:11 +0000593 R.CoverageMapping,
Justin Bogner346359d2015-02-03 00:00:00 +0000594 makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
Alex Lorenza20a5d52014-07-24 23:57:54 +0000595 FunctionsFilenames, Expressions, MappingRegions);
Justin Bogner195a4f02015-02-03 00:20:11 +0000596 if (auto Err = Reader.read())
Alex Lorenza20a5d52014-07-24 23:57:54 +0000597 return Err;
Justin Bogner195a4f02015-02-03 00:20:11 +0000598
599 Record.FunctionName = R.FunctionName;
Alex Lorenz936b99c2014-08-21 19:23:25 +0000600 Record.FunctionHash = R.FunctionHash;
Justin Bogner195a4f02015-02-03 00:20:11 +0000601 Record.Filenames = FunctionsFilenames;
602 Record.Expressions = Expressions;
603 Record.MappingRegions = MappingRegions;
604
Alex Lorenza20a5d52014-07-24 23:57:54 +0000605 ++CurrentRecord;
Justin Bogner43e51632015-02-26 20:06:28 +0000606 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000607}