blob: 617ec9e0ee13946388a6f0c9c1d5b732e89e49d4 [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
Benjamin Kramer85c824f2016-02-05 13:50:53 +0000309namespace {
Xinliang David Lia9d78462016-01-13 23:29:33 +0000310struct CovMapFuncRecordReader {
311 // The interface to read coverage mapping function records for
312 // a module. \p Buf is a reference to the buffer pointer pointing
313 // to the \c CovHeader of coverage mapping data associated with
314 // the module.
315 virtual std::error_code readFunctionRecords(const char *&Buf,
316 const char *End) = 0;
Xinliang David Lie7268c12016-01-14 02:10:49 +0000317 virtual ~CovMapFuncRecordReader() {}
Xinliang David Lia9d78462016-01-13 23:29:33 +0000318 template <class IntPtrT, support::endianness Endian>
319 static std::unique_ptr<CovMapFuncRecordReader>
Xinliang David Lid5d88872016-01-14 06:21:25 +0000320 get(coverage::CovMapVersion Version, InstrProfSymtab &P,
Xinliang David Lia9d78462016-01-13 23:29:33 +0000321 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
322 std::vector<StringRef> &F);
323};
Alex Lorenza20a5d52014-07-24 23:57:54 +0000324
Xinliang David Lia9d78462016-01-13 23:29:33 +0000325// A class for reading coverage mapping function records for a module.
Xinliang David Li84a2df32016-01-14 06:38:52 +0000326template <coverage::CovMapVersion Version, class IntPtrT,
Xinliang David Lia9d78462016-01-13 23:29:33 +0000327 support::endianness Endian>
328class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
329 typedef typename coverage::CovMapTraits<
Xinliang David Li84a2df32016-01-14 06:38:52 +0000330 Version, IntPtrT>::CovMapFuncRecordType FuncRecordType;
331 typedef typename coverage::CovMapTraits<Version, IntPtrT>::NameRefType
Xinliang David Lia9d78462016-01-13 23:29:33 +0000332 NameRefType;
333
334 llvm::DenseSet<NameRefType> UniqueFunctionMappingData;
335 InstrProfSymtab &ProfileNames;
336 std::vector<StringRef> &Filenames;
337 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
338
339public:
340 VersionedCovMapFuncRecordReader(
341 InstrProfSymtab &P,
342 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
343 std::vector<StringRef> &F)
344 : ProfileNames(P), Filenames(F), Records(R) {}
Xinliang David Lie7268c12016-01-14 02:10:49 +0000345 ~VersionedCovMapFuncRecordReader() override {}
Xinliang David Lia9d78462016-01-13 23:29:33 +0000346
347 std::error_code readFunctionRecords(const char *&Buf,
348 const char *End) override {
349 using namespace support;
Xinliang David Li946558d2016-01-03 18:57:40 +0000350 if (Buf + sizeof(CovMapHeader) > End)
Justin Bogner367a9f22015-05-06 23:19:35 +0000351 return coveragemap_error::malformed;
Xinliang David Li946558d2016-01-03 18:57:40 +0000352 auto CovHeader = reinterpret_cast<const coverage::CovMapHeader *>(Buf);
Xinliang David Li81f18a52016-01-13 04:36:15 +0000353 uint32_t NRecords = CovHeader->getNRecords<Endian>();
354 uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
355 uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
Xinliang David Li84a2df32016-01-14 06:38:52 +0000356 assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
Xinliang David Lia9d78462016-01-13 23:29:33 +0000357 Buf = reinterpret_cast<const char *>(CovHeader + 1);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000358
Justin Bogner7b33cc92015-03-16 06:55:45 +0000359 // Skip past the function records, saving the start and end for later.
360 const char *FunBuf = Buf;
Xinliang David Lia9d78462016-01-13 23:29:33 +0000361 Buf += NRecords * sizeof(FuncRecordType);
Justin Bogner7b33cc92015-03-16 06:55:45 +0000362 const char *FunEnd = Buf;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000363
364 // Get the filenames.
Justin Bogner7b33cc92015-03-16 06:55:45 +0000365 if (Buf + FilenamesSize > End)
Justin Bogner367a9f22015-05-06 23:19:35 +0000366 return coveragemap_error::malformed;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000367 size_t FilenamesBegin = Filenames.size();
Justin Bogner7b33cc92015-03-16 06:55:45 +0000368 RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000369 if (auto Err = Reader.read())
370 return Err;
Justin Bogner7b33cc92015-03-16 06:55:45 +0000371 Buf += FilenamesSize;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000372
Justin Bogner7b33cc92015-03-16 06:55:45 +0000373 // We'll read the coverage mapping records in the loop below.
374 const char *CovBuf = Buf;
375 Buf += CoverageSize;
376 const char *CovEnd = Buf;
Justin Bognerd49d8ee2015-06-05 01:23:42 +0000377
Justin Bogner7b33cc92015-03-16 06:55:45 +0000378 if (Buf > End)
Justin Bogner367a9f22015-05-06 23:19:35 +0000379 return coveragemap_error::malformed;
Justin Bognerd49d8ee2015-06-05 01:23:42 +0000380 // Each coverage map has an alignment of 8, so we need to adjust alignment
381 // before reading the next map.
382 Buf += alignmentAdjustment(Buf, 8);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000383
Xinliang David Lia9d78462016-01-13 23:29:33 +0000384 auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
Xinliang David Li192c7482015-11-05 00:47:26 +0000385 while ((const char *)CFR < FunEnd) {
Justin Bogner7b33cc92015-03-16 06:55:45 +0000386 // Read the function information
Xinliang David Li81f18a52016-01-13 04:36:15 +0000387 uint32_t DataSize = CFR->template getDataSize<Endian>();
388 uint64_t FuncHash = CFR->template getFuncHash<Endian>();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000389
Justin Bogner7b33cc92015-03-16 06:55:45 +0000390 // Now use that to read the coverage data.
391 if (CovBuf + DataSize > CovEnd)
Justin Bogner367a9f22015-05-06 23:19:35 +0000392 return coveragemap_error::malformed;
Justin Bogner7b33cc92015-03-16 06:55:45 +0000393 auto Mapping = StringRef(CovBuf, DataSize);
394 CovBuf += DataSize;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000395
396 // Ignore this record if we already have a record that points to the same
Justin Bogner7b33cc92015-03-16 06:55:45 +0000397 // function name. This is useful to ignore the redundant records for the
398 // functions with ODR linkage.
Xinliang David Lia9d78462016-01-13 23:29:33 +0000399 NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
Xinliang David Li0a83b1b2016-01-19 21:18:12 +0000400 if (!UniqueFunctionMappingData.insert(NameRef).second) {
401 CFR++;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000402 continue;
Xinliang David Li0a83b1b2016-01-19 21:18:12 +0000403 }
Justin Bogner7b33cc92015-03-16 06:55:45 +0000404
Xinliang David Li81f18a52016-01-13 04:36:15 +0000405 StringRef FuncName;
406 if (std::error_code EC =
407 CFR->template getFuncName<Endian>(ProfileNames, FuncName))
408 return EC;
Justin Bognere84891a2015-02-26 20:06:24 +0000409 Records.push_back(BinaryCoverageReader::ProfileMappingRecord(
Xinliang David Li84a2df32016-01-14 06:38:52 +0000410 Version, FuncName, FuncHash, Mapping, FilenamesBegin,
Xinliang David Lia9d78462016-01-13 23:29:33 +0000411 Filenames.size() - FilenamesBegin));
Xinliang David Li81f18a52016-01-13 04:36:15 +0000412 CFR++;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000413 }
Xinliang David Lia9d78462016-01-13 23:29:33 +0000414 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000415 }
Xinliang David Lia9d78462016-01-13 23:29:33 +0000416};
Benjamin Kramer85c824f2016-02-05 13:50:53 +0000417} // end anonymous namespace
Alex Lorenza20a5d52014-07-24 23:57:54 +0000418
Xinliang David Lia9d78462016-01-13 23:29:33 +0000419template <class IntPtrT, support::endianness Endian>
420std::unique_ptr<CovMapFuncRecordReader> CovMapFuncRecordReader::get(
Xinliang David Lid5d88872016-01-14 06:21:25 +0000421 coverage::CovMapVersion Version, InstrProfSymtab &P,
Xinliang David Lia9d78462016-01-13 23:29:33 +0000422 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
423 std::vector<StringRef> &F) {
424 using namespace coverage;
425 switch (Version) {
Xinliang David Lid5d88872016-01-14 06:21:25 +0000426 case CovMapVersion::Version1:
Xinliang David Lia9d78462016-01-13 23:29:33 +0000427 return llvm::make_unique<VersionedCovMapFuncRecordReader<
Xinliang David Lid5d88872016-01-14 06:21:25 +0000428 CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000429 case CovMapVersion::Version2:
430 // Decompress the name data.
431 P.create(P.getNameData());
432 return llvm::make_unique<VersionedCovMapFuncRecordReader<
433 CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
Xinliang David Lia9d78462016-01-13 23:29:33 +0000434 }
435 llvm_unreachable("Unsupported version");
Xinliang David Liaab986f2016-01-13 22:58:42 +0000436}
Xinliang David Lie62595c2016-01-13 23:12:53 +0000437
Xinliang David Lia9d78462016-01-13 23:29:33 +0000438template <typename T, support::endianness Endian>
439static std::error_code readCoverageMappingData(
440 InstrProfSymtab &ProfileNames, StringRef Data,
441 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
442 std::vector<StringRef> &Filenames) {
443 using namespace coverage;
444 // Read the records in the coverage data section.
445 auto CovHeader =
446 reinterpret_cast<const coverage::CovMapHeader *>(Data.data());
Xinliang David Lid5d88872016-01-14 06:21:25 +0000447 CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
448 if (Version > coverage::CovMapVersion::CurrentVersion)
Xinliang David Lia9d78462016-01-13 23:29:33 +0000449 return coveragemap_error::unsupported_version;
450 std::unique_ptr<CovMapFuncRecordReader> Reader =
451 CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
452 Filenames);
453 for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
454 if (std::error_code EC = Reader->readFunctionRecords(Buf, End))
455 return EC;
456 }
457 return std::error_code();
458}
Alex Lorenze82d89c2014-08-22 22:56:03 +0000459static const char *TestingFormatMagic = "llvmcovmtestdata";
460
Justin Bogner43e51632015-02-26 20:06:28 +0000461static std::error_code loadTestingFormat(StringRef Data,
Xinliang David Li50de45d2015-12-17 00:53:37 +0000462 InstrProfSymtab &ProfileNames,
Justin Bogner43e51632015-02-26 20:06:28 +0000463 StringRef &CoverageMapping,
Justin Bognera4387172015-03-16 21:40:18 +0000464 uint8_t &BytesInAddress,
465 support::endianness &Endian) {
Justin Bogner43e51632015-02-26 20:06:28 +0000466 BytesInAddress = 8;
Justin Bognera4387172015-03-16 21:40:18 +0000467 Endian = support::endianness::little;
Justin Bogner43e51632015-02-26 20:06:28 +0000468
Alex Lorenze82d89c2014-08-22 22:56:03 +0000469 Data = Data.substr(StringRef(TestingFormatMagic).size());
470 if (Data.size() < 1)
Justin Bogner367a9f22015-05-06 23:19:35 +0000471 return coveragemap_error::truncated;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000472 unsigned N = 0;
473 auto ProfileNamesSize =
474 decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
475 if (N > Data.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000476 return coveragemap_error::malformed;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000477 Data = Data.substr(N);
478 if (Data.size() < 1)
Justin Bogner367a9f22015-05-06 23:19:35 +0000479 return coveragemap_error::truncated;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000480 N = 0;
Xinliang David Li50de45d2015-12-17 00:53:37 +0000481 uint64_t Address =
Alex Lorenze82d89c2014-08-22 22:56:03 +0000482 decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
483 if (N > Data.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000484 return coveragemap_error::malformed;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000485 Data = Data.substr(N);
486 if (Data.size() < ProfileNamesSize)
Justin Bogner367a9f22015-05-06 23:19:35 +0000487 return coveragemap_error::malformed;
Xinliang David Li50de45d2015-12-17 00:53:37 +0000488 ProfileNames.create(Data.substr(0, ProfileNamesSize), Address);
Alex Lorenze82d89c2014-08-22 22:56:03 +0000489 CoverageMapping = Data.substr(ProfileNamesSize);
Justin Bogner367a9f22015-05-06 23:19:35 +0000490 return std::error_code();
Alex Lorenze82d89c2014-08-22 22:56:03 +0000491}
492
Justin Bogner5a5c3812015-05-07 00:31:58 +0000493static ErrorOr<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
494 StringRef FoundName;
495 for (const auto &Section : OF.sections()) {
496 if (auto EC = Section.getName(FoundName))
497 return EC;
498 if (FoundName == Name)
499 return Section;
500 }
501 return coveragemap_error::no_data_found;
502}
503
Xinliang David Li50de45d2015-12-17 00:53:37 +0000504static std::error_code
505loadBinaryFormat(MemoryBufferRef ObjectBuffer, InstrProfSymtab &ProfileNames,
506 StringRef &CoverageMapping, uint8_t &BytesInAddress,
507 support::endianness &Endian, StringRef Arch) {
Justin Bogner43795352015-03-11 02:30:51 +0000508 auto BinOrErr = object::createBinary(ObjectBuffer);
509 if (std::error_code EC = BinOrErr.getError())
Justin Bogner43e51632015-02-26 20:06:28 +0000510 return EC;
Justin Bogner43795352015-03-11 02:30:51 +0000511 auto Bin = std::move(BinOrErr.get());
512 std::unique_ptr<ObjectFile> OF;
513 if (auto *Universal = dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
514 // If we have a universal binary, try to look up the object for the
515 // appropriate architecture.
516 auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
517 if (std::error_code EC = ObjectFileOrErr.getError())
518 return EC;
519 OF = std::move(ObjectFileOrErr.get());
520 } else if (isa<object::ObjectFile>(Bin.get())) {
521 // For any other object file, upcast and take ownership.
522 OF.reset(cast<object::ObjectFile>(Bin.release()));
523 // If we've asked for a particular arch, make sure they match.
Frederic Rissebc162a2015-06-22 21:33:24 +0000524 if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
Justin Bogner43795352015-03-11 02:30:51 +0000525 return object_error::arch_not_found;
526 } else
527 // We can only handle object files.
Justin Bogner367a9f22015-05-06 23:19:35 +0000528 return coveragemap_error::malformed;
Justin Bogner43795352015-03-11 02:30:51 +0000529
530 // The coverage uses native pointer sizes for the object it's written in.
Justin Bogner43e51632015-02-26 20:06:28 +0000531 BytesInAddress = OF->getBytesInAddress();
Justin Bognera4387172015-03-16 21:40:18 +0000532 Endian = OF->isLittleEndian() ? support::endianness::little
533 : support::endianness::big;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000534
535 // Look for the sections that we are interested in.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000536 auto NamesSection = lookupSection(*OF, getInstrProfNameSectionName(false));
Justin Bogner5a5c3812015-05-07 00:31:58 +0000537 if (auto EC = NamesSection.getError())
538 return EC;
Xinliang David Li83bc4222015-10-22 20:32:12 +0000539 auto CoverageSection =
540 lookupSection(*OF, getInstrProfCoverageSectionName(false));
Justin Bogner5a5c3812015-05-07 00:31:58 +0000541 if (auto EC = CoverageSection.getError())
542 return EC;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000543
Alex Lorenze82d89c2014-08-22 22:56:03 +0000544 // Get the contents of the given sections.
Justin Bogner5a5c3812015-05-07 00:31:58 +0000545 if (std::error_code EC = CoverageSection->getContents(CoverageMapping))
Justin Bogner43e51632015-02-26 20:06:28 +0000546 return EC;
Xinliang David Li50de45d2015-12-17 00:53:37 +0000547 if (std::error_code EC = ProfileNames.create(*NamesSection))
Justin Bogner43e51632015-02-26 20:06:28 +0000548 return EC;
Alex Lorenze82d89c2014-08-22 22:56:03 +0000549
Justin Bogner43e51632015-02-26 20:06:28 +0000550 return std::error_code();
551}
552
553ErrorOr<std::unique_ptr<BinaryCoverageReader>>
Justin Bogner43795352015-03-11 02:30:51 +0000554BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
Frederic Rissebc162a2015-06-22 21:33:24 +0000555 StringRef Arch) {
Justin Bogner43e51632015-02-26 20:06:28 +0000556 std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
557
Justin Bogner43e51632015-02-26 20:06:28 +0000558 StringRef Coverage;
559 uint8_t BytesInAddress;
Justin Bognera4387172015-03-16 21:40:18 +0000560 support::endianness Endian;
Justin Bogner43e51632015-02-26 20:06:28 +0000561 std::error_code EC;
562 if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
563 // This is a special format used for testing.
Xinliang David Li42a13302016-01-18 06:48:01 +0000564 EC = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
565 Coverage, BytesInAddress, Endian);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000566 else
Xinliang David Li42a13302016-01-18 06:48:01 +0000567 EC = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
Xinliang David Li50de45d2015-12-17 00:53:37 +0000568 Coverage, BytesInAddress, Endian, Arch);
Justin Bogner43e51632015-02-26 20:06:28 +0000569 if (EC)
570 return EC;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000571
Justin Bognera4387172015-03-16 21:40:18 +0000572 if (BytesInAddress == 4 && Endian == support::endianness::little)
573 EC = readCoverageMappingData<uint32_t, support::endianness::little>(
Xinliang David Li42a13302016-01-18 06:48:01 +0000574 Reader->ProfileNames, Coverage, Reader->MappingRecords,
575 Reader->Filenames);
Justin Bognera4387172015-03-16 21:40:18 +0000576 else if (BytesInAddress == 4 && Endian == support::endianness::big)
577 EC = readCoverageMappingData<uint32_t, support::endianness::big>(
Xinliang David Li42a13302016-01-18 06:48:01 +0000578 Reader->ProfileNames, Coverage, Reader->MappingRecords,
579 Reader->Filenames);
Justin Bognera4387172015-03-16 21:40:18 +0000580 else if (BytesInAddress == 8 && Endian == support::endianness::little)
581 EC = readCoverageMappingData<uint64_t, support::endianness::little>(
Xinliang David Li42a13302016-01-18 06:48:01 +0000582 Reader->ProfileNames, Coverage, Reader->MappingRecords,
583 Reader->Filenames);
Justin Bognera4387172015-03-16 21:40:18 +0000584 else if (BytesInAddress == 8 && Endian == support::endianness::big)
585 EC = readCoverageMappingData<uint64_t, support::endianness::big>(
Xinliang David Li42a13302016-01-18 06:48:01 +0000586 Reader->ProfileNames, Coverage, Reader->MappingRecords,
587 Reader->Filenames);
Justin Bogner43e51632015-02-26 20:06:28 +0000588 else
Justin Bogner367a9f22015-05-06 23:19:35 +0000589 return coveragemap_error::malformed;
Justin Bogner43e51632015-02-26 20:06:28 +0000590 if (EC)
591 return EC;
592 return std::move(Reader);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000593}
594
595std::error_code
Justin Bognere84891a2015-02-26 20:06:24 +0000596BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000597 if (CurrentRecord >= MappingRecords.size())
Justin Bogner367a9f22015-05-06 23:19:35 +0000598 return coveragemap_error::eof;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000599
600 FunctionsFilenames.clear();
601 Expressions.clear();
602 MappingRegions.clear();
603 auto &R = MappingRecords[CurrentRecord];
604 RawCoverageMappingReader Reader(
Justin Bogner195a4f02015-02-03 00:20:11 +0000605 R.CoverageMapping,
Justin Bogner346359d2015-02-03 00:00:00 +0000606 makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
Alex Lorenza20a5d52014-07-24 23:57:54 +0000607 FunctionsFilenames, Expressions, MappingRegions);
Justin Bogner195a4f02015-02-03 00:20:11 +0000608 if (auto Err = Reader.read())
Alex Lorenza20a5d52014-07-24 23:57:54 +0000609 return Err;
Justin Bogner195a4f02015-02-03 00:20:11 +0000610
611 Record.FunctionName = R.FunctionName;
Alex Lorenz936b99c2014-08-21 19:23:25 +0000612 Record.FunctionHash = R.FunctionHash;
Justin Bogner195a4f02015-02-03 00:20:11 +0000613 Record.Filenames = FunctionsFilenames;
614 Record.Expressions = Expressions;
615 Record.MappingRegions = MappingRegions;
616
Alex Lorenza20a5d52014-07-24 23:57:54 +0000617 ++CurrentRecord;
Justin Bogner43e51632015-02-26 20:06:28 +0000618 return std::error_code();
Alex Lorenza20a5d52014-07-24 23:57:54 +0000619}