LLVM 24.0.0git
CoverageMappingReader.cpp
Go to the documentation of this file.
1//===- CoverageMappingReader.cpp - Code coverage mapping reader -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for reading coverage mapping data for
10// instrumentation based coverage.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
22#include "llvm/Object/Archive.h"
23#include "llvm/Object/Binary.h"
24#include "llvm/Object/COFF.h"
25#include "llvm/Object/Error.h"
28#include "llvm/Object/Wasm.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/Endian.h"
34#include "llvm/Support/Error.h"
36#include "llvm/Support/LEB128.h"
37#include "llvm/Support/Path.h"
40#include <vector>
41
42using namespace llvm;
43using namespace coverage;
44using namespace object;
45
46#define DEBUG_TYPE "coverage-mapping"
47
48STATISTIC(CovMapNumRecords, "The # of coverage function records");
49STATISTIC(CovMapNumUsedRecords, "The # of used coverage function records");
50
51void CoverageMappingIterator::increment() {
52 if (ReadErr != coveragemap_error::success)
53 return;
54
55 // Check if all the records were read or if an error occurred while reading
56 // the next record.
57 if (auto E = Reader->readNextRecord(Record))
58 handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
59 if (CME.get() == coveragemap_error::eof)
61 else
62 ReadErr = CME.get();
63 });
64}
65
67 if (Data.empty())
69 unsigned N = 0;
70 Result = decodeULEB128(Data.bytes_begin(), &N);
71 if (N > Data.size())
73 "the size of ULEB128 is too big");
74 Data = Data.substr(N);
75 return Error::success();
76}
77
78Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
79 if (auto Err = readULEB128(Result))
80 return Err;
81 if (Result >= MaxPlus1)
84 "the value of ULEB128 is greater than or equal to MaxPlus1");
85 return Error::success();
86}
87
89 if (auto Err = readULEB128(Result))
90 return Err;
91 if (Result > Data.size())
93 "the value of ULEB128 is too big");
94 return Error::success();
95}
96
98 uint64_t Length;
99 if (auto Err = readSize(Length))
100 return Err;
101 Result = Data.substr(0, Length);
102 Data = Data.substr(Length);
103 return Error::success();
104}
105
107 uint64_t NumFilenames;
108 if (auto Err = readSize(NumFilenames))
109 return Err;
110 if (!NumFilenames)
112 "number of filenames is zero");
113
115 return readUncompressed(Version, NumFilenames);
116
117 // The uncompressed length may exceed the size of the encoded filenames.
118 // Skip size validation.
119 uint64_t UncompressedLen;
120 if (auto Err = readULEB128(UncompressedLen))
121 return Err;
122
123 uint64_t CompressedLen;
124 if (auto Err = readSize(CompressedLen))
125 return Err;
126
127 if (CompressedLen > 0) {
131
132 // Allocate memory for the decompressed filenames.
133 SmallVector<uint8_t, 0> StorageBuf;
134
135 // Read compressed filenames.
136 StringRef CompressedFilenames = Data.substr(0, CompressedLen);
137 Data = Data.substr(CompressedLen);
139 arrayRefFromStringRef(CompressedFilenames), StorageBuf,
140 UncompressedLen);
141 if (Err) {
142 consumeError(std::move(Err));
145 }
146
147 RawCoverageFilenamesReader Delegate(toStringRef(StorageBuf), Filenames,
148 CompilationDir);
149 return Delegate.readUncompressed(Version, NumFilenames);
150 }
151
152 return readUncompressed(Version, NumFilenames);
153}
154
155Error RawCoverageFilenamesReader::readUncompressed(CovMapVersion Version,
156 uint64_t NumFilenames) {
157 // Read uncompressed filenames.
159 for (size_t I = 0; I < NumFilenames; ++I) {
161 if (auto Err = readString(Filename))
162 return Err;
163 Filenames.push_back(Filename.str());
164 }
165 } else {
166 StringRef CWD;
167 if (auto Err = readString(CWD))
168 return Err;
169 Filenames.push_back(CWD.str());
170
171 for (size_t I = 1; I < NumFilenames; ++I) {
173 if (auto Err = readString(Filename))
174 return Err;
176 Filenames.push_back(Filename.str());
177 } else {
178 SmallString<256> P;
179 if (!CompilationDir.empty())
180 P.assign(CompilationDir);
181 else
182 P.assign(CWD);
184 sys::path::remove_dots(P, /*remove_dot_dot=*/true);
185 Filenames.push_back(static_cast<std::string>(P.str()));
186 }
187 }
188 }
189 return Error::success();
190}
191
192Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
194 switch (Tag) {
195 case Counter::Zero:
197 return Error::success();
200 return Error::success();
201 default:
202 break;
203 }
205 switch (Tag) {
209 if (ID >= Expressions.size())
211 "counter expression is invalid");
212 Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
214 break;
215 }
216 default:
218 "counter expression kind is invalid");
219 }
220 return Error::success();
221}
222
223Error RawCoverageMappingReader::readCounter(Counter &C) {
224 uint64_t EncodedCounter;
225 if (auto Err =
226 readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
227 return Err;
228 if (auto Err = decodeCounter(EncodedCounter, C))
229 return Err;
230 return Error::success();
231}
232
233static const unsigned EncodingExpansionRegionBit = 1
235
236/// Read the sub-array of regions for the given inferred file id.
237/// \param NumFileIDs the number of file ids that are defined for this
238/// function.
239Error RawCoverageMappingReader::readMappingRegionsSubArray(
240 std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
241 size_t NumFileIDs) {
242 uint64_t NumRegions;
243 if (auto Err = readSize(NumRegions))
244 return Err;
245 unsigned LineStart = 0;
246 for (size_t I = 0; I < NumRegions; ++I) {
247 Counter C, C2;
248 uint64_t BIDX, NC;
249 // They are stored as internal values plus 1 (min is -1)
250 uint64_t ID1, TID1, FID1;
251 mcdc::Parameters Params;
253
254 // Read the combined counter + region kind.
255 uint64_t EncodedCounterAndRegion;
256 if (auto Err = readIntMax(EncodedCounterAndRegion,
257 std::numeric_limits<unsigned>::max()))
258 return Err;
259 unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
260 uint64_t ExpandedFileID = 0;
261
262 // If Tag does not represent a ZeroCounter, then it is understood to refer
263 // to a counter or counter expression with region kind assumed to be
264 // "CodeRegion". In that case, EncodedCounterAndRegion actually encodes the
265 // referenced counter or counter expression (and nothing else).
266 //
267 // If Tag represents a ZeroCounter and EncodingExpansionRegionBit is set,
268 // then EncodedCounterAndRegion is interpreted to represent an
269 // ExpansionRegion. In all other cases, EncodedCounterAndRegion is
270 // interpreted to refer to a specific region kind, after which additional
271 // fields may be read (e.g. BranchRegions have two encoded counters that
272 // follow an encoded region kind value).
273 if (Tag != Counter::Zero) {
274 if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
275 return Err;
276 } else {
277 // Is it an expansion region?
278 if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
280 ExpandedFileID = EncodedCounterAndRegion >>
282 if (ExpandedFileID >= NumFileIDs)
284 "ExpandedFileID is invalid");
285 } else {
286 switch (EncodedCounterAndRegion >>
289 // Don't do anything when we have a code region with a zero counter.
290 break;
293 break;
295 // For a Branch Region, read two successive counters.
297 if (auto Err = readCounter(C))
298 return Err;
299 if (auto Err = readCounter(C2))
300 return Err;
301 break;
303 // For a MCDC Branch Region, read two successive counters and 3 IDs.
305 if (auto Err = readCounter(C))
306 return Err;
307 if (auto Err = readCounter(C2))
308 return Err;
309 if (auto Err = readIntMax(ID1, std::numeric_limits<int16_t>::max()))
310 return Err;
311 if (auto Err = readIntMax(TID1, std::numeric_limits<int16_t>::max()))
312 return Err;
313 if (auto Err = readIntMax(FID1, std::numeric_limits<int16_t>::max()))
314 return Err;
315 if (ID1 == 0)
318 "MCDCConditionID shouldn't be zero");
319 Params = mcdc::BranchParameters{
320 static_cast<int16_t>(static_cast<int16_t>(ID1) - 1),
321 {static_cast<int16_t>(static_cast<int16_t>(FID1) - 1),
322 static_cast<int16_t>(static_cast<int16_t>(TID1) - 1)}};
323 break;
326 if (auto Err = readIntMax(BIDX, std::numeric_limits<unsigned>::max()))
327 return Err;
328 if (auto Err = readIntMax(NC, std::numeric_limits<int16_t>::max()))
329 return Err;
330 Params = mcdc::DecisionParameters{static_cast<unsigned>(BIDX),
331 static_cast<uint16_t>(NC)};
332 break;
333 default:
335 "region kind is incorrect");
336 }
337 }
338 }
339
340 // Read the source range.
341 uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
342 if (auto Err =
343 readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
344 return Err;
345 if (auto Err = readULEB128(ColumnStart))
346 return Err;
347 if (ColumnStart > std::numeric_limits<unsigned>::max())
349 "start column is too big");
350 if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
351 return Err;
352 if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
353 return Err;
354 LineStart += LineStartDelta;
355
356 // If the high bit of ColumnEnd is set, this is a gap region.
357 if (ColumnEnd & (1U << 31)) {
359 ColumnEnd &= ~(1U << 31);
360 }
361
362 // Adjust the column locations for the empty regions that are supposed to
363 // cover whole lines. Those regions should be encoded with the
364 // column range (1 -> std::numeric_limits<unsigned>::max()), but because
365 // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
366 // we set the column range to (0 -> 0) to ensure that the column start and
367 // column end take up one byte each.
368 // The std::numeric_limits<unsigned>::max() is used to represent a column
369 // position at the end of the line without knowing the length of that line.
370 if (ColumnStart == 0 && ColumnEnd == 0) {
371 ColumnStart = 1;
372 ColumnEnd = std::numeric_limits<unsigned>::max();
373 }
374
375 LLVM_DEBUG({
376 dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
377 << ColumnStart << " -> " << (LineStart + NumLines) << ":"
378 << ColumnEnd << ", ";
380 dbgs() << "Expands to file " << ExpandedFileID;
381 else
382 CounterMappingContext(Expressions).dump(C, dbgs());
383 dbgs() << "\n";
384 });
385
386 auto CMR = CounterMappingRegion(
387 C, C2, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
388 LineStart + NumLines, ColumnEnd, Kind, Params);
389 if (CMR.startLoc() > CMR.endLoc())
392 "counter mapping region locations are incorrect");
393 MappingRegions.push_back(CMR);
394 }
395 return Error::success();
396}
397
399 // Read the virtual file mapping.
400 SmallVector<unsigned, 8> VirtualFileMapping;
401 uint64_t NumFileMappings;
402 if (auto Err = readSize(NumFileMappings))
403 return Err;
404 for (size_t I = 0; I < NumFileMappings; ++I) {
405 uint64_t FilenameIndex;
406 if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
407 return Err;
408 VirtualFileMapping.push_back(FilenameIndex);
409 }
410
411 // Construct the files using unique filenames and virtual file mapping.
412 for (auto I : VirtualFileMapping) {
413 Filenames.push_back(TranslationUnitFilenames[I]);
414 }
415
416 // Read the expressions.
417 uint64_t NumExpressions;
418 if (auto Err = readSize(NumExpressions))
419 return Err;
420 // Create an array of dummy expressions that get the proper counters
421 // when the expressions are read, and the proper kinds when the counters
422 // are decoded.
423 Expressions.resize(
424 NumExpressions,
426 for (size_t I = 0; I < NumExpressions; ++I) {
427 if (auto Err = readCounter(Expressions[I].LHS))
428 return Err;
429 if (auto Err = readCounter(Expressions[I].RHS))
430 return Err;
431 }
432
433 // Read the mapping regions sub-arrays.
434 for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
435 InferredFileID < S; ++InferredFileID) {
436 if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
437 VirtualFileMapping.size()))
438 return Err;
439 }
440
441 // Set the counters for the expansion regions.
442 // i.e. Counter of expansion region = counter of the first region
443 // from the expanded file.
444 // Perform multiple passes to correctly propagate the counters through all the
445 // nested expansion regions. Iterate until no count changes.
446 SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
447 FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
448 for (;;) {
449 for (auto &R : MappingRegions) {
451 continue;
452 assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
453 FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
454 }
455 bool Changed = false;
456 for (auto &R : MappingRegions) {
457 auto *&Slot = FileIDExpansionRegionMapping[R.FileID];
458 if (Slot) {
459 if (Slot->Count != R.Count) {
460 Slot->Count = R.Count;
461 Changed = true;
462 }
463 Slot = nullptr;
464 }
465 }
466 if (!Changed)
467 break;
468 }
469
471 MappingRegions,
472 [](const CounterMappingRegion &L, const CounterMappingRegion &R) {
473 return L.FileID < R.FileID;
474 }) &&
475 "Coverage mapping regions must be sorted by FileID");
476
477 return Error::success();
478}
479
481 // A dummy coverage mapping data consists of just one region with zero count.
482 uint64_t NumFileMappings;
483 if (Error Err = readSize(NumFileMappings))
484 return std::move(Err);
485 if (NumFileMappings != 1)
486 return false;
487 // We don't expect any specific value for the filename index, just skip it.
488 uint64_t FilenameIndex;
489 if (Error Err =
490 readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
491 return std::move(Err);
492 uint64_t NumExpressions;
493 if (Error Err = readSize(NumExpressions))
494 return std::move(Err);
495 if (NumExpressions != 0)
496 return false;
497 uint64_t NumRegions;
498 if (Error Err = readSize(NumRegions))
499 return std::move(Err);
500 if (NumRegions != 1)
501 return false;
502 uint64_t EncodedCounterAndRegion;
503 if (Error Err = readIntMax(EncodedCounterAndRegion,
504 std::numeric_limits<unsigned>::max()))
505 return std::move(Err);
506 unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
507 return Tag == Counter::Zero;
508}
509
510/// Determine if we should skip the first byte of the section content
512 const ObjectFile *Obj = Section.getObject();
513 // If this is a linked PE/COFF file, then we have to skip over the null byte
514 // that is allocated in the .lprfn$A section in the LLVM profiling runtime.
515 // If the name section is .lprfcovnames, it doesn't have the null byte at the
516 // beginning.
517 if (isa<COFFObjectFile>(Obj) && !Obj->isRelocatableObject())
518 if (Expected<StringRef> NameOrErr = Section.getName())
519 if (*NameOrErr != getInstrProfSectionName(IPSK_covname, Triple::COFF))
520 return true;
521 return false;
522}
523
525 Expected<StringRef> DataOrErr = Section.getContents();
526 if (!DataOrErr)
527 return DataOrErr.takeError();
528 Data = *DataOrErr;
529 Address = Section.getAddress();
530
531 if (shouldSkipSectionFirstByte(Section))
532 Data = Data.substr(1);
533
534 return Error::success();
535}
536
537StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) const {
538 if (Pointer < Address)
539 return StringRef();
540 auto Offset = Pointer - Address;
541 if (Offset + Size > Data.size())
542 return StringRef();
543 return Data.substr(Pointer - Address, Size);
544}
545
546// Check if the mapping data is a dummy, i.e. is emitted for an unused function.
548 // The hash value of dummy mapping records is always zero.
549 if (Hash)
550 return false;
551 return RawCoverageMappingDummyChecker(Mapping).isDummy();
552}
553
554/// A range of filename indices. Used to specify the location of a batch of
555/// filenames in a vector-like container.
558 unsigned Length;
559
562
563 void markInvalid() { Length = 0; }
564 bool isInvalid() const { return Length == 0; }
565};
566
567namespace {
568
569/// The interface to read coverage mapping function records for a module.
570struct CovMapFuncRecordReader {
571 virtual ~CovMapFuncRecordReader() = default;
572
573 // Read a coverage header.
574 //
575 // \p CovBuf points to the buffer containing the \c CovHeader of the coverage
576 // mapping data associated with the module.
577 //
578 // Returns a pointer to the next \c CovHeader if it exists, or to an address
579 // greater than \p CovEnd if not.
580 virtual Expected<const char *> readCoverageHeader(const char *CovBuf,
581 const char *CovBufEnd) = 0;
582
583 // Read function records.
584 //
585 // \p FuncRecBuf points to the buffer containing a batch of function records.
586 // \p FuncRecBufEnd points past the end of the batch of records.
587 //
588 // Prior to Version4, \p OutOfLineFileRange points to a sequence of filenames
589 // associated with the function records. It is unused in Version4.
590 //
591 // Prior to Version4, \p OutOfLineMappingBuf points to a sequence of coverage
592 // mappings associated with the function records. It is unused in Version4.
593 virtual Error
594 readFunctionRecords(const char *FuncRecBuf, const char *FuncRecBufEnd,
595 std::optional<FilenameRange> OutOfLineFileRange,
596 const char *OutOfLineMappingBuf,
597 const char *OutOfLineMappingBufEnd) = 0;
598
599 template <class IntPtrT, llvm::endianness Endian>
600 static Expected<std::unique_ptr<CovMapFuncRecordReader>>
601 get(CovMapVersion Version, InstrProfSymtab &P,
602 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R, StringRef D,
603 std::vector<std::string> &F);
604};
605
606// A class for reading coverage mapping function records for a module.
607template <CovMapVersion Version, class IntPtrT, llvm::endianness Endian>
608class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
609 using FuncRecordType =
611 using NameRefType = typename CovMapTraits<Version, IntPtrT>::NameRefType;
612
613 // Maps function's name references to the indexes of their records
614 // in \c Records.
615 DenseMap<NameRefType, size_t> FunctionRecords;
616 InstrProfSymtab &ProfileNames;
617 StringRef CompilationDir;
618 std::vector<std::string> &Filenames;
619 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
620
621 // Maps a hash of the filenames in a TU to a \c FileRange. The range
622 // specifies the location of the hashed filenames in \c Filenames.
623 DenseMap<uint64_t, FilenameRange> FileRangeMap;
624
625 // Add the record to the collection if we don't already have a record that
626 // points to the same function name. This is useful to ignore the redundant
627 // records for the functions with ODR linkage.
628 // In addition, prefer records with real coverage mapping data to dummy
629 // records, which were emitted for inline functions which were seen but
630 // not used in the corresponding translation unit.
631 Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
632 StringRef Mapping,
633 FilenameRange FileRange) {
634 ++CovMapNumRecords;
635 uint64_t FuncHash = CFR->template getFuncHash<Endian>();
636 NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
637 auto InsertResult =
638 FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
639 if (InsertResult.second) {
640 StringRef FuncName;
641 if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
642 return Err;
643 if (FuncName.empty())
644 return make_error<InstrProfError>(instrprof_error::malformed,
645 "function name is empty");
646 ++CovMapNumUsedRecords;
647 Records.emplace_back(Version, FuncName, FuncHash, Mapping,
648 FileRange.StartingIndex, FileRange.Length);
649 return Error::success();
650 }
651 // Update the existing record if it's a dummy and the new record is real.
652 size_t OldRecordIndex = InsertResult.first->second;
653 BinaryCoverageReader::ProfileMappingRecord &OldRecord =
654 Records[OldRecordIndex];
655 Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
656 OldRecord.FunctionHash, OldRecord.CoverageMapping);
657 if (Error Err = OldIsDummyExpected.takeError())
658 return Err;
659 if (!*OldIsDummyExpected)
660 return Error::success();
661 Expected<bool> NewIsDummyExpected =
663 if (Error Err = NewIsDummyExpected.takeError())
664 return Err;
665 if (*NewIsDummyExpected)
666 return Error::success();
667 ++CovMapNumUsedRecords;
668 OldRecord.FunctionHash = FuncHash;
669 OldRecord.CoverageMapping = Mapping;
670 OldRecord.FilenamesBegin = FileRange.StartingIndex;
671 OldRecord.FilenamesSize = FileRange.Length;
672 return Error::success();
673 }
674
675public:
676 VersionedCovMapFuncRecordReader(
677 InstrProfSymtab &P,
678 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R, StringRef D,
679 std::vector<std::string> &F)
680 : ProfileNames(P), CompilationDir(D), Filenames(F), Records(R) {}
681
682 ~VersionedCovMapFuncRecordReader() override = default;
683
684 Expected<const char *> readCoverageHeader(const char *CovBuf,
685 const char *CovBufEnd) override {
686 using namespace support;
687
688 if (CovBuf + sizeof(CovMapHeader) > CovBufEnd)
690 coveragemap_error::malformed,
691 "coverage mapping header section is larger than buffer size");
692 auto CovHeader = reinterpret_cast<const CovMapHeader *>(CovBuf);
693 uint32_t NRecords = CovHeader->getNRecords<Endian>();
694 uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
695 uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
696 assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
697 CovBuf = reinterpret_cast<const char *>(CovHeader + 1);
698
699 // Skip past the function records, saving the start and end for later.
700 // This is a no-op in Version4 (function records are read after all headers
701 // are read).
702 const char *FuncRecBuf = nullptr;
703 const char *FuncRecBufEnd = nullptr;
704 if (Version < CovMapVersion::Version4)
705 FuncRecBuf = CovBuf;
706 CovBuf += NRecords * sizeof(FuncRecordType);
707 if (Version < CovMapVersion::Version4)
708 FuncRecBufEnd = CovBuf;
709
710 // Get the filenames.
711 if (CovBuf + FilenamesSize > CovBufEnd)
713 coveragemap_error::malformed,
714 "filenames section is larger than buffer size");
715 size_t FilenamesBegin = Filenames.size();
716 StringRef FilenameRegion(CovBuf, FilenamesSize);
717 RawCoverageFilenamesReader Reader(FilenameRegion, Filenames,
718 CompilationDir);
719 if (auto Err = Reader.read(Version))
720 return std::move(Err);
721 CovBuf += FilenamesSize;
722 FilenameRange FileRange(FilenamesBegin, Filenames.size() - FilenamesBegin);
723
724 if (Version >= CovMapVersion::Version4) {
725 // Map a hash of the filenames region to the filename range associated
726 // with this coverage header.
727 int64_t FilenamesRef =
729 auto Insert =
730 FileRangeMap.insert(std::make_pair(FilenamesRef, FileRange));
731 if (!Insert.second) {
732 // The same filenames ref was encountered twice. It's possible that
733 // the associated filenames are the same.
734 auto It = Filenames.begin();
735 FilenameRange &OrigRange = Insert.first->getSecond();
736 if (std::equal(It + OrigRange.StartingIndex,
737 It + OrigRange.StartingIndex + OrigRange.Length,
738 It + FileRange.StartingIndex,
739 It + FileRange.StartingIndex + FileRange.Length))
740 // Map the new range to the original one.
741 FileRange = OrigRange;
742 else
743 // This is a hash collision. Mark the filenames ref invalid.
744 OrigRange.markInvalid();
745 }
746 }
747
748 // We'll read the coverage mapping records in the loop below.
749 // This is a no-op in Version4 (coverage mappings are not affixed to the
750 // coverage header).
751 const char *MappingBuf = CovBuf;
752 if (Version >= CovMapVersion::Version4 && CoverageSize != 0)
753 return make_error<CoverageMapError>(coveragemap_error::malformed,
754 "coverage mapping size is not zero");
755 CovBuf += CoverageSize;
756 const char *MappingEnd = CovBuf;
757
758 if (CovBuf > CovBufEnd)
760 coveragemap_error::malformed,
761 "function records section is larger than buffer size");
762
763 if (Version < CovMapVersion::Version4) {
764 // Read each function record.
765 if (Error E = readFunctionRecords(FuncRecBuf, FuncRecBufEnd, FileRange,
766 MappingBuf, MappingEnd))
767 return std::move(E);
768 }
769
770 // Each coverage map has an alignment of 8, so we need to adjust alignment
771 // before reading the next map.
772 CovBuf += offsetToAlignedAddr(CovBuf, Align(8));
773
774 return CovBuf;
775 }
776
777 Error readFunctionRecords(const char *FuncRecBuf, const char *FuncRecBufEnd,
778 std::optional<FilenameRange> OutOfLineFileRange,
779 const char *OutOfLineMappingBuf,
780 const char *OutOfLineMappingBufEnd) override {
781 auto CFR = reinterpret_cast<const FuncRecordType *>(FuncRecBuf);
782 while ((const char *)CFR < FuncRecBufEnd) {
783 // Validate the length of the coverage mapping for this function.
784 const char *NextMappingBuf;
785 const FuncRecordType *NextCFR;
786 std::tie(NextMappingBuf, NextCFR) =
787 CFR->template advanceByOne<Endian>(OutOfLineMappingBuf);
788 if (Version < CovMapVersion::Version4)
789 if (NextMappingBuf > OutOfLineMappingBufEnd)
791 coveragemap_error::malformed,
792 "next mapping buffer is larger than buffer size");
793
794 // Look up the set of filenames associated with this function record.
795 std::optional<FilenameRange> FileRange;
796 if (Version < CovMapVersion::Version4) {
797 FileRange = OutOfLineFileRange;
798 } else {
799 uint64_t FilenamesRef = CFR->template getFilenamesRef<Endian>();
800 auto It = FileRangeMap.find(FilenamesRef);
801 if (It == FileRangeMap.end())
803 coveragemap_error::malformed,
804 "no filename found for function with hash=0x" +
805 Twine::utohexstr(FilenamesRef));
806 else
807 FileRange = It->getSecond();
808 }
809
810 // Now, read the coverage data.
811 if (FileRange && !FileRange->isInvalid()) {
812 StringRef Mapping =
813 CFR->template getCoverageMapping<Endian>(OutOfLineMappingBuf);
814 if (Version >= CovMapVersion::Version4 &&
815 Mapping.data() + Mapping.size() > FuncRecBufEnd)
817 coveragemap_error::malformed,
818 "coverage mapping data is larger than buffer size");
819 if (Error Err = insertFunctionRecordIfNeeded(CFR, Mapping, *FileRange))
820 return Err;
821 }
822
823 std::tie(OutOfLineMappingBuf, CFR) = std::tie(NextMappingBuf, NextCFR);
824 }
825 return Error::success();
826 }
827};
828
829} // end anonymous namespace
830
831template <class IntPtrT, llvm::endianness Endian>
832Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
833 CovMapVersion Version, InstrProfSymtab &P,
834 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R, StringRef D,
835 std::vector<std::string> &F) {
836 using namespace coverage;
837
838 switch (Version) {
840 return std::make_unique<VersionedCovMapFuncRecordReader<
841 CovMapVersion::Version1, IntPtrT, Endian>>(P, R, D, F);
848 // Decompress the name data.
849 if (Error E = P.create(P.getNameData()))
850 return std::move(E);
852 return std::make_unique<VersionedCovMapFuncRecordReader<
853 CovMapVersion::Version2, IntPtrT, Endian>>(P, R, D, F);
855 return std::make_unique<VersionedCovMapFuncRecordReader<
856 CovMapVersion::Version3, IntPtrT, Endian>>(P, R, D, F);
858 return std::make_unique<VersionedCovMapFuncRecordReader<
859 CovMapVersion::Version4, IntPtrT, Endian>>(P, R, D, F);
861 return std::make_unique<VersionedCovMapFuncRecordReader<
862 CovMapVersion::Version5, IntPtrT, Endian>>(P, R, D, F);
864 return std::make_unique<VersionedCovMapFuncRecordReader<
865 CovMapVersion::Version6, IntPtrT, Endian>>(P, R, D, F);
867 return std::make_unique<VersionedCovMapFuncRecordReader<
868 CovMapVersion::Version7, IntPtrT, Endian>>(P, R, D, F);
869 }
870 llvm_unreachable("Unsupported version");
871}
872
873template <typename T, llvm::endianness Endian>
875 InstrProfSymtab &ProfileNames, StringRef CovMap, StringRef FuncRecords,
876 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
877 StringRef CompilationDir, std::vector<std::string> &Filenames) {
878 using namespace coverage;
879
880 // Read the records in the coverage data section.
881 auto CovHeader =
882 reinterpret_cast<const CovMapHeader *>(CovMap.data());
883 CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
884 if (Version > CovMapVersion::CurrentVersion)
887 CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
888 CompilationDir, Filenames);
889 if (Error E = ReaderExpected.takeError())
890 return E;
891 auto Reader = std::move(ReaderExpected.get());
892 const char *CovBuf = CovMap.data();
893 const char *CovBufEnd = CovBuf + CovMap.size();
894 const char *FuncRecBuf = FuncRecords.data();
895 const char *FuncRecBufEnd = FuncRecords.data() + FuncRecords.size();
896 while (CovBuf < CovBufEnd) {
897 // Read the current coverage header & filename data.
898 //
899 // Prior to Version4, this also reads all function records affixed to the
900 // header.
901 //
902 // Return a pointer to the next coverage header.
903 auto NextOrErr = Reader->readCoverageHeader(CovBuf, CovBufEnd);
904 if (auto E = NextOrErr.takeError())
905 return E;
906 CovBuf = NextOrErr.get();
907 }
908 // In Version4, function records are not affixed to coverage headers. Read
909 // the records from their dedicated section.
910 if (Version >= CovMapVersion::Version4)
911 return Reader->readFunctionRecords(FuncRecBuf, FuncRecBufEnd, std::nullopt,
912 nullptr, nullptr);
913 return Error::success();
914}
915
916Expected<std::unique_ptr<BinaryCoverageReader>>
918 StringRef Coverage, FuncRecordsStorage &&FuncRecords,
919 CoverageMapCopyStorage &&CoverageMap,
920 std::unique_ptr<InstrProfSymtab> ProfileNamesPtr, uint8_t BytesInAddress,
921 llvm::endianness Endian, StringRef CompilationDir) {
922 if (ProfileNamesPtr == nullptr)
924 "Caller must provide ProfileNames");
925 std::unique_ptr<BinaryCoverageReader> Reader(
926 new BinaryCoverageReader(std::move(ProfileNamesPtr),
927 std::move(FuncRecords), std::move(CoverageMap)));
928 InstrProfSymtab &ProfileNames = *Reader->ProfileNames;
929 StringRef FuncRecordsRef = Reader->FuncRecords->getBuffer();
930 if (BytesInAddress == 4 && Endian == llvm::endianness::little) {
932 ProfileNames, Coverage, FuncRecordsRef, Reader->MappingRecords,
933 CompilationDir, Reader->Filenames))
934 return std::move(E);
935 } else if (BytesInAddress == 4 && Endian == llvm::endianness::big) {
937 ProfileNames, Coverage, FuncRecordsRef, Reader->MappingRecords,
938 CompilationDir, Reader->Filenames))
939 return std::move(E);
940 } else if (BytesInAddress == 8 && Endian == llvm::endianness::little) {
942 ProfileNames, Coverage, FuncRecordsRef, Reader->MappingRecords,
943 CompilationDir, Reader->Filenames))
944 return std::move(E);
945 } else if (BytesInAddress == 8 && Endian == llvm::endianness::big) {
947 ProfileNames, Coverage, FuncRecordsRef, Reader->MappingRecords,
948 CompilationDir, Reader->Filenames))
949 return std::move(E);
950 } else
953 "not supported endianness or bytes in address");
954 return std::move(Reader);
955}
956
959 uint8_t BytesInAddress = 8;
961
962 // Read the magic and version.
963 Data = Data.substr(sizeof(TestingFormatMagic));
964 if (Data.size() < sizeof(uint64_t))
966 "the size of data is too small");
967 auto TestingVersion = support::endian::byte_swap<uint64_t>(
968 *reinterpret_cast<const uint64_t *>(Data.data()),
970 Data = Data.substr(sizeof(uint64_t));
971
972 // Read the ProfileNames data.
973 if (Data.empty())
975 unsigned N = 0;
976 uint64_t ProfileNamesSize = decodeULEB128(Data.bytes_begin(), &N);
977 if (N > Data.size())
980 "the size of TestingFormatMagic is too big");
981 Data = Data.substr(N);
982 if (Data.empty())
984 N = 0;
985 uint64_t Address = decodeULEB128(Data.bytes_begin(), &N);
986 if (N > Data.size())
988 "the size of ULEB128 is too big");
989 Data = Data.substr(N);
990 if (Data.size() < ProfileNamesSize)
992 "the size of ProfileNames is too big");
993 auto ProfileNames = std::make_unique<InstrProfSymtab>();
994 if (Error E = ProfileNames->create(Data.substr(0, ProfileNamesSize), Address))
995 return std::move(E);
996 Data = Data.substr(ProfileNamesSize);
997
998 // In Version2, the size of CoverageMapping is stored directly.
999 uint64_t CoverageMappingSize;
1000 if (TestingVersion == uint64_t(TestingFormatVersion::Version2)) {
1001 N = 0;
1002 CoverageMappingSize = decodeULEB128(Data.bytes_begin(), &N);
1003 if (N > Data.size())
1005 "the size of ULEB128 is too big");
1006 Data = Data.substr(N);
1007 if (CoverageMappingSize < sizeof(CovMapHeader))
1010 "the size of CoverageMapping is teoo small");
1011 } else if (TestingVersion != uint64_t(TestingFormatVersion::Version1)) {
1013 }
1014
1015 // Skip the padding bytes because coverage map data has an alignment of 8.
1016 auto Pad = offsetToAlignedAddr(Data.data(), Align(8));
1017 if (Data.size() < Pad)
1019 "insufficient padding");
1020 Data = Data.substr(Pad);
1021 if (Data.size() < sizeof(CovMapHeader))
1024 "coverage mapping header section is larger than data size");
1025 auto const *CovHeader = reinterpret_cast<const CovMapHeader *>(
1026 Data.substr(0, sizeof(CovMapHeader)).data());
1027 auto Version =
1028 CovMapVersion(CovHeader->getVersion<llvm::endianness::little>());
1029
1030 // In Version1, the size of CoverageMapping is calculated.
1031 if (TestingVersion == uint64_t(TestingFormatVersion::Version1)) {
1032 if (Version < CovMapVersion::Version4) {
1033 CoverageMappingSize = Data.size();
1034 } else {
1035 auto FilenamesSize =
1036 CovHeader->getFilenamesSize<llvm::endianness::little>();
1037 CoverageMappingSize = sizeof(CovMapHeader) + FilenamesSize;
1038 }
1039 }
1040
1041 auto CoverageMapping = Data.substr(0, CoverageMappingSize);
1042 Data = Data.substr(CoverageMappingSize);
1043
1044 // Read the CoverageRecords data.
1045 if (Version < CovMapVersion::Version4) {
1046 if (!Data.empty())
1048 "data is not empty");
1049 } else {
1050 // Skip the padding bytes because coverage records data has an alignment
1051 // of 8.
1052 Pad = offsetToAlignedAddr(Data.data(), Align(8));
1053 if (Data.size() < Pad)
1055 "insufficient padding");
1056 Data = Data.substr(Pad);
1057 }
1060
1062 CoverageMapping, std::move(CoverageRecords), nullptr,
1063 std::move(ProfileNames), BytesInAddress, Endian, CompilationDir);
1064}
1065
1066/// Find all sections that match \p IPSK name. There may be more than one if
1067/// comdats are in use, e.g. for the __llvm_covfun section on ELF.
1068static Expected<std::vector<SectionRef>>
1070 auto ObjFormat = OF.getTripleObjectFormat();
1071 auto Name =
1072 getInstrProfSectionName(IPSK, ObjFormat, /*AddSegmentInfo=*/false);
1073 // On COFF, the object file section name may end in "$M". This tells the
1074 // linker to sort these sections between "$A" and "$Z". The linker removes the
1075 // dollar and everything after it in the final binary. Do the same to match.
1076 bool IsCOFF = isa<COFFObjectFile>(OF);
1077 auto stripSuffix = [IsCOFF](StringRef N) {
1078 return IsCOFF ? N.split('$').first : N;
1079 };
1080 Name = stripSuffix(Name);
1081
1082 std::vector<SectionRef> Sections;
1083 for (const auto &Section : OF.sections()) {
1084 Expected<StringRef> NameOrErr = Section.getName();
1085 if (!NameOrErr)
1086 return NameOrErr.takeError();
1087 if (stripSuffix(*NameOrErr) == Name) {
1088 // Skip empty profile name section.
1089 // COFF profile name section contains two null bytes indicating the
1090 // start/end of the section. If its size is 2 bytes, it's empty.
1091 if (IPSK == IPSK_name &&
1092 (Section.getSize() == 0 || (IsCOFF && Section.getSize() == 2)))
1093 continue;
1094 Sections.push_back(Section);
1095 }
1096 }
1097 if (Sections.empty())
1099 return Sections;
1100}
1101
1102/// Find a section that matches \p Name and is allocatable at runtime.
1103///
1104/// Returns the contents of the section and its start offset in the object file.
1105static Expected<std::pair<StringRef, uint64_t>>
1107 // On Wasm, allocatable sections can live only in data segments.
1108 if (auto *WOF = dyn_cast<WasmObjectFile>(&OF)) {
1109 std::vector<const WasmSegment *> Segments;
1110 auto ObjFormat = OF.getTripleObjectFormat();
1111 auto Name =
1112 getInstrProfSectionName(IPSK, ObjFormat, /*AddSegmentInfo=*/false);
1113 for (const auto &DebugName : WOF->debugNames()) {
1114 if (DebugName.Type != wasm::NameType::DATA_SEGMENT ||
1115 DebugName.Name != Name)
1116 continue;
1117 if (DebugName.Index >= WOF->dataSegments().size())
1119 auto &Segment = WOF->dataSegments()[DebugName.Index];
1120 Segments.push_back(&Segment);
1121 }
1122 if (Segments.empty())
1124 if (Segments.size() != 1)
1126
1127 const auto &Segment = *Segments.front();
1128 auto &Data = Segment.Data;
1129 StringRef Content(reinterpret_cast<const char *>(Data.Content.data()),
1130 Data.Content.size());
1131 return std::make_pair(Content, Segment.SectionOffset);
1132 }
1133
1134 // On other object file types, delegate to lookupSections to find the section.
1135 auto Sections = lookupSections(OF, IPSK);
1136 if (!Sections)
1137 return Sections.takeError();
1138 if (Sections->size() != 1)
1141 "the size of coverage mapping section is not one");
1142 auto &Section = Sections->front();
1143 auto ContentsOrErr = Section.getContents();
1144 if (!ContentsOrErr)
1145 return ContentsOrErr.takeError();
1146 auto Content = *ContentsOrErr;
1147 if (shouldSkipSectionFirstByte(Section))
1148 Content = Content.drop_front(1);
1149 return std::make_pair(Content, Section.getAddress());
1150}
1151
1152static Expected<std::unique_ptr<BinaryCoverageReader>>
1153loadBinaryFormat(std::unique_ptr<Binary> Bin, StringRef Arch,
1154 StringRef CompilationDir = "",
1155 object::BuildIDRef *BinaryID = nullptr) {
1156 std::unique_ptr<ObjectFile> OF;
1157 if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
1158 // If we have a universal binary, try to look up the object for the
1159 // appropriate architecture.
1160 auto ObjectFileOrErr = Universal->getMachOObjectForArch(Arch);
1161 if (!ObjectFileOrErr)
1162 return ObjectFileOrErr.takeError();
1163 OF = std::move(ObjectFileOrErr.get());
1164 } else if (isa<ObjectFile>(Bin.get())) {
1165 // For any other object file, upcast and take ownership.
1166 OF.reset(cast<ObjectFile>(Bin.release()));
1167 // If we've asked for a particular arch, make sure they match.
1168 if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
1169 return errorCodeToError(object_error::arch_not_found);
1170 } else
1171 // We can only handle object files.
1173 "binary is not an object file");
1174
1175 // The coverage uses native pointer sizes for the object it's written in.
1176 uint8_t BytesInAddress = OF->getBytesInAddress();
1177 llvm::endianness Endian =
1178 OF->isLittleEndian() ? llvm::endianness::little : llvm::endianness::big;
1179
1180 // Look for the sections that we are interested in.
1181 auto ProfileNames = std::make_unique<InstrProfSymtab>();
1182 // If IPSK_name is not found, fallback to search for IPK_covname, which is
1183 // used when binary correlation is enabled.
1184 auto NamesSection = lookupAllocatableSection(*OF, IPSK_name);
1185 if (auto E = NamesSection.takeError()) {
1186 consumeError(std::move(E));
1187 NamesSection = lookupAllocatableSection(*OF, IPSK_covname);
1188 if (auto E = NamesSection.takeError())
1189 return std::move(E);
1190 }
1191
1192 uint64_t NamesAddress;
1193 StringRef NamesContent;
1194 std::tie(NamesContent, NamesAddress) = *NamesSection;
1195 if (Error E = ProfileNames->create(NamesContent, NamesAddress))
1196 return std::move(E);
1197
1198 auto CoverageSection = lookupSections(*OF, IPSK_covmap);
1199 if (auto E = CoverageSection.takeError())
1200 return std::move(E);
1201 std::vector<SectionRef> CoverageSectionRefs = *CoverageSection;
1202 if (CoverageSectionRefs.size() != 1)
1204 "the size of name section is not one");
1205 auto CoverageMappingOrErr = CoverageSectionRefs.back().getContents();
1206 if (!CoverageMappingOrErr)
1207 return CoverageMappingOrErr.takeError();
1208 StringRef CoverageMapping = CoverageMappingOrErr.get();
1209
1210 // If the coverage mapping section is not aligned to 8 bytes, copy it to a
1211 // new buffer that is. Wasm format typically has unaligned section contents
1212 // because it doesn't have a good way to insert padding bytes.
1213 std::unique_ptr<MemoryBuffer> CoverageMapCopy;
1214 if (!isAddrAligned(Align(8), CoverageMapping.data())) {
1216 CoverageMapping = CoverageMapCopy->getBuffer();
1217 }
1218
1219 // Look for the coverage records section (Version4 only).
1220 auto CoverageRecordsSections = lookupSections(*OF, IPSK_covfun);
1221
1223 if (auto E = CoverageRecordsSections.takeError()) {
1224 consumeError(std::move(E));
1225 FuncRecords = MemoryBuffer::getMemBuffer("");
1226 } else {
1227 // Compute the FuncRecordsBuffer of the buffer, taking into account the
1228 // padding between each record, and making sure the first block is aligned
1229 // in memory to maintain consistency between buffer address and size
1230 // alignment.
1231 const Align RecordAlignment(8);
1232 uint64_t FuncRecordsSize = 0;
1233 for (SectionRef Section : *CoverageRecordsSections) {
1234 auto CoverageRecordsOrErr = Section.getContents();
1235 if (!CoverageRecordsOrErr)
1236 return CoverageRecordsOrErr.takeError();
1237 FuncRecordsSize += alignTo(CoverageRecordsOrErr->size(), RecordAlignment);
1238 }
1239 auto WritableBuffer =
1241 char *FuncRecordsBuffer = WritableBuffer->getBufferStart();
1242 assert(isAddrAligned(RecordAlignment, FuncRecordsBuffer) &&
1243 "Allocated memory is correctly aligned");
1244
1245 for (SectionRef Section : *CoverageRecordsSections) {
1246 auto CoverageRecordsOrErr = Section.getContents();
1247 if (!CoverageRecordsOrErr)
1248 return CoverageRecordsOrErr.takeError();
1249 const auto &CoverageRecords = CoverageRecordsOrErr.get();
1250 FuncRecordsBuffer = llvm::copy(CoverageRecords, FuncRecordsBuffer);
1251 FuncRecordsBuffer =
1252 std::fill_n(FuncRecordsBuffer,
1253 alignAddr(FuncRecordsBuffer, RecordAlignment) -
1254 (uintptr_t)FuncRecordsBuffer,
1255 '\0');
1256 }
1257 assert(FuncRecordsBuffer == WritableBuffer->getBufferEnd() &&
1258 "consistent init");
1259 FuncRecords = std::move(WritableBuffer);
1260 }
1261
1262 if (BinaryID)
1263 *BinaryID = getBuildID(OF.get());
1264
1266 CoverageMapping, std::move(FuncRecords), std::move(CoverageMapCopy),
1267 std::move(ProfileNames), BytesInAddress, Endian, CompilationDir);
1268}
1269
1270/// Determine whether \p Arch is invalid or empty, given \p Bin.
1272 // If we have a universal binary and Arch doesn't identify any of its slices,
1273 // it's user error.
1274 if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin)) {
1275 for (auto &ObjForArch : Universal->objects())
1276 if (Arch == ObjForArch.getArchFlagName())
1277 return false;
1278 return true;
1279 }
1280 return false;
1281}
1282
1283Expected<std::vector<std::unique_ptr<BinaryCoverageReader>>>
1285 MemoryBufferRef ObjectBuffer, StringRef Arch,
1286 SmallVectorImpl<std::unique_ptr<MemoryBuffer>> &ObjectFileBuffers,
1287 StringRef CompilationDir, SmallVectorImpl<object::BuildIDRef> *BinaryIDs) {
1288 std::vector<std::unique_ptr<BinaryCoverageReader>> Readers;
1289
1290 if (ObjectBuffer.getBuffer().size() > sizeof(TestingFormatMagic)) {
1291 uint64_t Magic = support::endian::byte_swap<uint64_t>(
1292 *reinterpret_cast<const uint64_t *>(ObjectBuffer.getBufferStart()),
1294 if (Magic == TestingFormatMagic) {
1295 // This is a special format used for testing.
1296 auto ReaderOrErr =
1297 loadTestingFormat(ObjectBuffer.getBuffer(), CompilationDir);
1298 if (!ReaderOrErr)
1299 return ReaderOrErr.takeError();
1300 Readers.push_back(std::move(ReaderOrErr.get()));
1301 return std::move(Readers);
1302 }
1303 }
1304
1305 auto BinOrErr = createBinary(ObjectBuffer);
1306 if (!BinOrErr)
1307 return BinOrErr.takeError();
1308 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
1309
1310 if (isArchSpecifierInvalidOrMissing(Bin.get(), Arch))
1313
1314 // MachO universal binaries which contain archives need to be treated as
1315 // archives, not as regular binaries.
1316 if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
1317 for (auto &ObjForArch : Universal->objects()) {
1318 // Skip slices within the universal binary which target the wrong arch.
1319 std::string ObjArch = ObjForArch.getArchFlagName();
1320 if (Arch != ObjArch)
1321 continue;
1322
1323 auto ArchiveOrErr = ObjForArch.getAsArchive();
1324 if (!ArchiveOrErr) {
1325 // If this is not an archive, try treating it as a regular object.
1326 consumeError(ArchiveOrErr.takeError());
1327 break;
1328 }
1329
1331 ArchiveOrErr.get()->getMemoryBufferRef(), Arch, ObjectFileBuffers,
1332 CompilationDir, BinaryIDs);
1333 }
1334 }
1335
1336 // Load coverage out of archive members.
1337 if (auto *Ar = dyn_cast<Archive>(Bin.get())) {
1338 Error Err = Error::success();
1339 for (auto &Child : Ar->children(Err)) {
1340 Expected<MemoryBufferRef> ChildBufOrErr = Child.getMemoryBufferRef();
1341 if (!ChildBufOrErr)
1342 return ChildBufOrErr.takeError();
1343
1344 auto ChildReadersOrErr = BinaryCoverageReader::create(
1345 ChildBufOrErr.get(), Arch, ObjectFileBuffers, CompilationDir,
1346 BinaryIDs);
1347 if (!ChildReadersOrErr)
1348 return ChildReadersOrErr.takeError();
1349 for (auto &Reader : ChildReadersOrErr.get())
1350 Readers.push_back(std::move(Reader));
1351 }
1352 if (Err)
1353 return std::move(Err);
1354
1355 // Thin archives reference object files outside of the archive file, i.e.
1356 // files which reside in memory not owned by the caller. Transfer ownership
1357 // to the caller.
1358 if (Ar->isThin())
1359 for (auto &Buffer : Ar->takeThinBuffers())
1360 ObjectFileBuffers.push_back(std::move(Buffer));
1361
1362 return std::move(Readers);
1363 }
1364
1365 object::BuildIDRef BinaryID;
1366 auto ReaderOrErr = loadBinaryFormat(std::move(Bin), Arch, CompilationDir,
1367 BinaryIDs ? &BinaryID : nullptr);
1368 if (!ReaderOrErr)
1369 return ReaderOrErr.takeError();
1370 Readers.push_back(std::move(ReaderOrErr.get()));
1371 if (!BinaryID.empty())
1372 BinaryIDs->push_back(BinaryID);
1373 return std::move(Readers);
1374}
1375
1377 if (CurrentRecord >= MappingRecords.size())
1379
1380 FunctionsFilenames.clear();
1381 Expressions.clear();
1382 MappingRegions.clear();
1383 auto &R = MappingRecords[CurrentRecord];
1384 auto F = ArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize);
1385 RawCoverageMappingReader Reader(R.CoverageMapping, F, FunctionsFilenames,
1386 Expressions, MappingRegions);
1387 if (auto Err = Reader.read())
1388 return Err;
1389
1390 Record.FunctionName = R.FunctionName;
1391 Record.FunctionHash = R.FunctionHash;
1392 Record.Filenames = FunctionsFilenames;
1393 Record.Expressions = Expressions;
1394 Record.MappingRegions = MappingRegions;
1395
1396 ++CurrentRecord;
1397 return Error::success();
1398}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static Error readCoverageMappingData(InstrProfSymtab &ProfileNames, StringRef CovMap, StringRef FuncRecords, std::vector< BinaryCoverageReader::ProfileMappingRecord > &Records, StringRef CompilationDir, std::vector< std::string > &Filenames)
static Expected< std::pair< StringRef, uint64_t > > lookupAllocatableSection(ObjectFile &OF, InstrProfSectKind IPSK)
Find a section that matches Name and is allocatable at runtime.
static Expected< std::unique_ptr< BinaryCoverageReader > > loadBinaryFormat(std::unique_ptr< Binary > Bin, StringRef Arch, StringRef CompilationDir="", object::BuildIDRef *BinaryID=nullptr)
static Expected< std::unique_ptr< BinaryCoverageReader > > loadTestingFormat(StringRef Data, StringRef CompilationDir)
static Expected< std::vector< SectionRef > > lookupSections(ObjectFile &OF, InstrProfSectKind IPSK)
Find all sections that match IPSK name.
static bool isArchSpecifierInvalidOrMissing(Binary *Bin, StringRef Arch)
Determine whether Arch is invalid or empty, given Bin.
static bool shouldSkipSectionFirstByte(SectionRef &Section)
Determine if we should skip the first byte of the section content.
static Expected< bool > isCoverageMappingDummy(uint64_t Hash, StringRef Mapping)
static const unsigned EncodingExpansionRegionBit
This file defines the DenseMap class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr StringLiteral Filename
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static Split data
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:499
LLVM_ABI StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize) const
Return function's PGO name from the function name's symbol address in the object file.
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
const char * getBufferStart() const
StringRef getBuffer() const
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
static LLVM_ABI std::unique_ptr< WritableMemoryBuffer > getNewUninitMemBuffer(size_t Size, const Twine &BufferName="", std::optional< Align > Alignment=std::nullopt)
Allocate a new MemoryBuffer of the specified size that is not initialized.
static Expected< std::unique_ptr< BinaryCoverageReader > > createCoverageReaderFromBuffer(StringRef Coverage, FuncRecordsStorage &&FuncRecords, CoverageMapCopyStorage &&CoverageMap, std::unique_ptr< InstrProfSymtab > ProfileNamesPtr, uint8_t BytesInAddress, llvm::endianness Endian, StringRef CompilationDir="")
std::unique_ptr< MemoryBuffer > CoverageMapCopyStorage
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer > > &ObjectFileBuffers, StringRef CompilationDir="", SmallVectorImpl< object::BuildIDRef > *BinaryIDs=nullptr)
std::unique_ptr< MemoryBuffer > FuncRecordsStorage
Error readNextRecord(CoverageMappingRecord &Record) override
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
LLVM_ABI void dump(const Counter &C, raw_ostream &OS) const
coveragemap_error get() const
virtual Error readNextRecord(CoverageMappingRecord &Record)=0
The mapping of profile information to coverage data.
RawCoverageFilenamesReader(StringRef Data, std::vector< std::string > &Filenames, StringRef CompilationDir="")
LLVM_ABI Error read(CovMapVersion Version)
Checks if the given coverage mapping data is exported for an unused function.
Reader for the raw coverage mapping data.
LLVM_ABI Error readSize(uint64_t &Result)
LLVM_ABI Error readIntMax(uint64_t &Result, uint64_t MaxPlus1)
LLVM_ABI Error readULEB128(uint64_t &Result)
LLVM_ABI Error readString(StringRef &Result)
This class is the base class for all object file types.
Definition ObjectFile.h:231
Represents a GOFF physical record.
Definition GOFF.h:31
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1239
llvm::SmallVector< std::shared_ptr< RecordsSlice >, 4 > Records
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
std::variant< std::monostate, DecisionParameters, BranchParameters > Parameters
The type of MC/DC-specific parameters.
Definition MCDCTypes.h:56
constexpr uint64_t TestingFormatMagic
LLVM_ABI BuildIDRef getBuildID(const ObjectFile *Obj)
Returns the build ID, if any, contained in the given object file.
Definition BuildID.cpp:71
ArrayRef< uint8_t > BuildIDRef
A reference to a BuildID in binary form.
Definition BuildID.h:30
LLVM_ABI Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
Definition Endian.h:45
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
Definition Path.cpp:779
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
uint64_t offsetToAlignedAddr(const void *Addr, Align Alignment)
Returns the necessary adjustment for aligning Addr to Alignment bytes, rounding up.
Definition Alignment.h:197
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
FuncHash
Definition InstrProf.h:78
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
InstrProfSectKind
Definition InstrProf.h:90
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
endianness
Definition bit.h:71
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
uint64_t decodeULEB128(const uint8_t *p, unsigned *n, const uint8_t *end, const char **error, ULEB128DecodeError *errorCode)
Utility function to decode a ULEB128 value and report a typed error.
Definition LEB128.h:145
bool isAddrAligned(Align Lhs, const void *Addr)
Checks that Addr is a multiple of the alignment.
Definition Alignment.h:144
uintptr_t alignAddr(const void *Addr, Align Alignment)
Aligns Addr to Alignment bytes, rounding up.
Definition Alignment.h:181
#define N
#define NC
Definition regutils.h:42
FilenameRange(unsigned StartingIndex, unsigned Length)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A Counter expression is a value that represents an arithmetic operation with two counters.
A Counter mapping region associates a source range with a specific counter.
@ ExpansionRegion
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
@ MCDCDecisionRegion
A DecisionRegion represents a top-level boolean expression and is associated with a variable length b...
@ MCDCBranchRegion
A Branch Region can be extended to include IDs to facilitate MC/DC.
@ SkippedRegion
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
@ GapRegion
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
@ BranchRegion
A BranchRegion represents leaf-level boolean expressions and is associated with two counters,...
@ CodeRegion
A CodeRegion associates some code with a counter.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static const unsigned EncodingTagBits
static Counter getZero()
Return the counter that represents the number zero.
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
static const unsigned EncodingCounterTagAndExpansionRegionTagBits
static const unsigned EncodingTagMask
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
CovMapFunctionRecordV3 CovMapFuncRecordType
Coverage mapping information for a single function.