17using namespace object;
19#define STRINGIFY_ENUM_CASE(ns, name) \
23#define ELF_RELOC(name, value) STRINGIFY_ENUM_CASE(ELF, name)
30#include "llvm/BinaryFormat/ELFRelocs/M68k.def"
37#include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
45#include "llvm/BinaryFormat/ELFRelocs/i386.def"
52#include "llvm/BinaryFormat/ELFRelocs/Mips.def"
59#include "llvm/BinaryFormat/ELFRelocs/AArch64.def"
66#include "llvm/BinaryFormat/ELFRelocs/ARM.def"
74#include "llvm/BinaryFormat/ELFRelocs/ARC.def"
81#include "llvm/BinaryFormat/ELFRelocs/AVR.def"
88#include "llvm/BinaryFormat/ELFRelocs/Hexagon.def"
95#include "llvm/BinaryFormat/ELFRelocs/Lanai.def"
102#include "llvm/BinaryFormat/ELFRelocs/PowerPC.def"
109#include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def"
116#include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
123#include "llvm/BinaryFormat/ELFRelocs/SystemZ.def"
132#include "llvm/BinaryFormat/ELFRelocs/Sparc.def"
139#include "llvm/BinaryFormat/ELFRelocs/AMDGPU.def"
146#include "llvm/BinaryFormat/ELFRelocs/BPF.def"
153#include "llvm/BinaryFormat/ELFRelocs/MSP430.def"
160#include "llvm/BinaryFormat/ELFRelocs/VE.def"
167#include "llvm/BinaryFormat/ELFRelocs/CSKY.def"
174#include "llvm/BinaryFormat/ELFRelocs/LoongArch.def"
181#include "llvm/BinaryFormat/ELFRelocs/Xtensa.def"
197 return ELF::R_X86_64_RELATIVE;
200 return ELF::R_386_RELATIVE;
204 return ELF::R_AARCH64_RELATIVE;
206 return ELF::R_ARM_RELATIVE;
209 return ELF::R_ARC_RELATIVE;
213 return ELF::R_HEX_RELATIVE;
219 return ELF::R_PPC64_RELATIVE;
221 return ELF::R_RISCV_RELATIVE;
223 return ELF::R_390_RELATIVE;
227 return ELF::R_SPARC_RELATIVE;
229 return ELF::R_CKCORE_RELATIVE;
231 return ELF::R_VE_RELATIVE;
237 return ELF::R_LARCH_RELATIVE;
337std::vector<typename ELFT::Rel>
371 Rel.setType(getRelativeRelocationType(),
false);
372 std::vector<Elf_Rel> Relocs;
375 using Addr =
typename ELFT::uint;
378 for (Elf_Relr R : relrs) {
379 typename ELFT::uint Entry = R;
380 if ((Entry & 1) == 0) {
382 Rel.r_offset = Entry;
383 Relocs.push_back(Rel);
389 if ((Entry & 1) != 0) {
391 Relocs.push_back(Rel);
393 Base += (CHAR_BIT *
sizeof(Entry) - 1) *
sizeof(
Addr);
406 Hdr = Data.getULEB128(&Hdr, &Err);
415 std::vector<Elf_Rel> Rels;
416 std::vector<Elf_Rela> Relas;
419 Error Err = object::decodeCrel<ELFT::Is64Bits>(
430 Relas[
I].r_offset = Crel.r_offset;
431 Relas[
I].setSymbolAndType(Crel.r_symidx, Crel.r_type,
false);
432 Relas[
I++].r_addend = Crel.r_addend;
434 Rels[
I].r_offset = Crel.r_offset;
435 Rels[
I++].setSymbolAndType(Crel.r_symidx, Crel.r_type,
false);
439 return std::move(Err);
440 return std::make_pair(std::move(Rels), std::move(Relas));
463 return createError(
"invalid packed relocation header");
467 uint64_t NumRelocs = Data.getSLEB128(Cur);
474 std::vector<Elf_Rela> Relocs;
475 Relocs.reserve(NumRelocs);
477 uint64_t NumRelocsInGroup = Data.getSLEB128(Cur);
480 if (NumRelocsInGroup > NumRelocs)
481 return createError(
"relocation group unexpectedly large");
482 NumRelocs -= NumRelocsInGroup;
484 uint64_t GroupFlags = Data.getSLEB128(Cur);
491 if (GroupedByOffsetDelta)
492 GroupOffsetDelta = Data.getSLEB128(Cur);
496 GroupRInfo = Data.getSLEB128(Cur);
498 if (GroupedByAddend && GroupHasAddend)
499 Addend += Data.getSLEB128(Cur);
504 for (
uint64_t I = 0; Cur &&
I != NumRelocsInGroup; ++
I) {
506 Offset += GroupedByOffsetDelta ? GroupOffsetDelta : Data.getSLEB128(Cur);
508 R.r_info = GroupedByInfo ? GroupRInfo : Data.getSLEB128(Cur);
509 if (GroupHasAddend && !GroupedByAddend)
510 Addend += Data.getSLEB128(Cur);
524#define DYNAMIC_STRINGIFY_ENUM(tag, value) \
528#define DYNAMIC_TAG(n, v)
532#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
533#include "llvm/BinaryFormat/DynamicTags.def"
534#undef AARCH64_DYNAMIC_TAG
540#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
541#include "llvm/BinaryFormat/DynamicTags.def"
542#undef HEXAGON_DYNAMIC_TAG
548#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
549#include "llvm/BinaryFormat/DynamicTags.def"
550#undef MIPS_DYNAMIC_TAG
556#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
557#include "llvm/BinaryFormat/DynamicTags.def"
558#undef PPC_DYNAMIC_TAG
564#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
565#include "llvm/BinaryFormat/DynamicTags.def"
566#undef PPC64_DYNAMIC_TAG
572#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
573#include "llvm/BinaryFormat/DynamicTags.def"
574#undef RISCV_DYNAMIC_TAG
581#define AARCH64_DYNAMIC_TAG(name, value)
582#define MIPS_DYNAMIC_TAG(name, value)
583#define HEXAGON_DYNAMIC_TAG(name, value)
584#define PPC_DYNAMIC_TAG(name, value)
585#define PPC64_DYNAMIC_TAG(name, value)
586#define RISCV_DYNAMIC_TAG(name, value)
588#define DYNAMIC_TAG_MARKER(name, value)
589#define DYNAMIC_TAG(name, value) case value: return #name;
590#include "llvm/BinaryFormat/DynamicTags.def"
592#undef AARCH64_DYNAMIC_TAG
593#undef MIPS_DYNAMIC_TAG
594#undef HEXAGON_DYNAMIC_TAG
595#undef PPC_DYNAMIC_TAG
596#undef PPC64_DYNAMIC_TAG
597#undef RISCV_DYNAMIC_TAG
598#undef DYNAMIC_TAG_MARKER
599#undef DYNAMIC_STRINGIFY_ENUM
601 return "<unknown:>0x" + utohexstr(
Type,
true);
607 return getDynamicTagAsString(getHeader().e_machine,
Type);
614 auto ProgramHeadersOrError = program_headers();
615 if (!ProgramHeadersOrError)
616 return ProgramHeadersOrError.takeError();
618 for (
const Elf_Phdr &Phdr : *ProgramHeadersOrError) {
620 const uint8_t *DynOffset = base() + Phdr.p_offset;
621 if (DynOffset > end())
623 "dynamic section offset past file size: corrupted ELF");
624 Dyn =
ArrayRef(
reinterpret_cast<const Elf_Dyn *
>(DynOffset),
625 Phdr.p_filesz /
sizeof(Elf_Dyn));
634 if (!SectionsOrError)
635 return SectionsOrError.takeError();
637 for (
const Elf_Shdr &Sec : *SectionsOrError) {
640 getSectionContentsAsArray<Elf_Dyn>(Sec);
653 return createError(
"invalid empty dynamic section");
655 if (Dyn.
back().d_tag != ELF::DT_NULL)
656 return createError(
"dynamic sections must be DT_NULL terminated");
664 auto ProgramHeadersOrError = program_headers();
665 if (!ProgramHeadersOrError)
666 return ProgramHeadersOrError.takeError();
670 for (
const Elf_Phdr &Phdr : *ProgramHeadersOrError)
672 LoadSegments.
push_back(
const_cast<Elf_Phdr *
>(&Phdr));
676 return A->p_vaddr <
B->p_vaddr;
680 WarnHandler(
"loadable segments are unsorted by virtual address"))
687 return VAddr < Phdr->p_vaddr;
690 if (
I == LoadSegments.
begin())
691 return createError(
"virtual address is not in any segment: 0x" +
694 const Elf_Phdr &Phdr = **
I;
695 uint64_t Delta = VAddr - Phdr.p_vaddr;
696 if (Delta >= Phdr.p_filesz)
697 return createError(
"virtual address is not in any segment: 0x" +
701 if (
Offset >= getBufSize())
702 return createError(
"can't map virtual address 0x" +
704 Twine(&Phdr - (*ProgramHeadersOrError).data() + 1) +
705 ": the segment ends at 0x" +
707 ", which is greater than the file size (0x" +
718template <
typename IntTy, std::enable_if_t<std::is_
unsigned_v<IntTy>,
int> = 0>
720 Error &ULEBSizeErr) {
726 if (
Value > std::numeric_limits<IntTy>::max()) {
727 ULEBSizeErr =
createError(
"ULEB128 value at offset 0x" +
729 Twine(std::numeric_limits<IntTy>::digits) +
733 return static_cast<IntTy
>(
Value);
736template <
typename ELFT>
741 std::vector<PGOAnalysisMap> *PGOAnalyses) {
748 if (IsRelocatable && RelaSec) {
750 "Can't read a SHT_LLVM_BB_ADDR_MAP section in a relocatable "
751 "object file without providing a relocation section.");
755 return createError(
"unable to read CREL relocations for section " +
759 FunctionOffsetTranslations[Rela.r_offset] = Rela.r_addend;
765 return createError(
"unable to read relocations for section " +
769 FunctionOffsetTranslations[Rela.r_offset] = Rela.r_addend;
772 auto GetAddressForRelocation =
775 FunctionOffsetTranslations.
find(RelocationOffsetInSection);
776 if (FOTIterator == FunctionOffsetTranslations.
end()) {
777 return createError(
"failed to get relocation data for offset: " +
779 " in section " +
describe(EF, Sec));
781 return FOTIterator->second;
789 std::unique_ptr<uint8_t[]> DecompressedContent;
792 if (!SectionNameOrErr)
794 auto DecompressorOrErr =
796 EF.
isLE(), ELFT::Is64Bits);
797 if (!DecompressorOrErr)
798 return DecompressorOrErr.takeError();
799 size_t DecompressedSize = DecompressorOrErr->getDecompressedSize();
800 DecompressedContent = std::make_unique<uint8_t[]>(DecompressedSize);
803 if (
Error Err = DecompressorOrErr->decompress(DecompressedContentRef))
804 return std::move(Err);
805 Content = DecompressedContentRef;
809 std::vector<BBAddrMap> FunctionEntries;
826 GetAddressForRelocation(RelocationOffsetInSection);
829 return *AddressOrErr;
835 while (!ULEBSizeErr && !MetadataDecodeErr && Cur &&
837 Version = Data.getU8(Cur);
840 if (Version < 2 || Version > 3)
841 return createError(
"unsupported SHT_LLVM_BB_ADDR_MAP version: " +
842 Twine(
static_cast<int>(Version)));
843 Feature = Data.getU8(Cur);
847 if (!FeatEnableOrErr)
848 return FeatEnableOrErr.takeError();
849 FeatEnable = *FeatEnableOrErr;
850 if (FeatEnable.CallsiteEndOffsets && Version < 3)
851 return createError(
"version should be >= 3 for SHT_LLVM_BB_ADDR_MAP when "
852 "callsite offsets feature is enabled: version = " +
853 Twine(
static_cast<int>(Version)) +
854 " feature = " +
Twine(
static_cast<int>(Feature)));
858 if (FeatEnable.MultiBBRange) {
859 NumBBRanges = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
860 if (!Cur || ULEBSizeErr)
863 return createError(
"invalid zero number of BB ranges at offset " +
867 auto AddressOrErr = ExtractAddress();
869 return AddressOrErr.takeError();
870 RangeBaseAddress = *AddressOrErr;
871 NumBlocksInBBRange = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
873 std::vector<BBAddrMap::BBRangeEntry> BBRangeEntries;
875 for (
uint32_t BBRangeIndex = 0; BBRangeIndex < NumBBRanges;
878 if (FeatEnable.MultiBBRange) {
879 auto AddressOrErr = ExtractAddress();
881 return AddressOrErr.takeError();
882 RangeBaseAddress = *AddressOrErr;
883 NumBlocksInBBRange = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
885 std::vector<BBAddrMap::BBEntry> BBEntries;
886 if (!FeatEnable.OmitBBEntries) {
887 for (
uint32_t BlockIndex = 0; !MetadataDecodeErr && !ULEBSizeErr &&
888 Cur && (BlockIndex < NumBlocksInBBRange);
890 uint32_t ID = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
891 uint32_t Offset = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
895 if (FeatEnable.CallsiteEndOffsets) {
897 readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
898 CallsiteEndOffsets.
reserve(NumCallsites);
902 LastCallsiteEndOffset +=
903 readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
904 CallsiteEndOffsets.
push_back(LastCallsiteEndOffset);
907 uint32_t Size = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr) +
908 LastCallsiteEndOffset;
909 uint32_t MD = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
912 if (!MetadataOrErr) {
913 MetadataDecodeErr = MetadataOrErr.
takeError();
916 BBEntries.push_back({
ID,
Offset + PrevBBEndOffset,
Size,
917 *MetadataOrErr, CallsiteEndOffsets});
920 TotalNumBlocks += BBEntries.size();
922 BBRangeEntries.push_back({RangeBaseAddress, std::move(BBEntries)});
924 FunctionEntries.push_back({std::move(BBRangeEntries)});
926 if (PGOAnalyses || FeatEnable.hasPGOAnalysis()) {
929 FeatEnable.FuncEntryCount
930 ? readULEB128As<uint64_t>(Data, Cur, ULEBSizeErr)
933 std::vector<PGOAnalysisMap::PGOBBEntry> PGOBBEntries;
935 FeatEnable.hasPGOAnalysisBBData() && !MetadataDecodeErr &&
936 !ULEBSizeErr && Cur && (BlockIndex < TotalNumBlocks);
940 ? readULEB128As<uint64_t>(Data, Cur, ULEBSizeErr)
946 if (FeatEnable.BrProb) {
947 auto SuccCount = readULEB128As<uint64_t>(Data, Cur, ULEBSizeErr);
949 uint32_t BBID = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
950 uint32_t BrProb = readULEB128As<uint32_t>(Data, Cur, ULEBSizeErr);
957 PGOBBEntries.push_back({
BlockFrequency(BBF), std::move(Successors)});
961 PGOAnalyses->push_back(
967 if (!Cur || ULEBSizeErr || MetadataDecodeErr)
969 std::move(MetadataDecodeErr));
970 return FunctionEntries;
976 std::vector<PGOAnalysisMap> *PGOAnalyses)
const {
977 size_t OriginalPGOSize = PGOAnalyses ? PGOAnalyses->size() : 0;
980 if (!AddrMapsOrErr && PGOAnalyses)
981 PGOAnalyses->resize(OriginalPGOSize);
982 return std::move(AddrMapsOrErr);
994 if (!DoesSectionMatch) {
998 if (*DoesSectionMatch) {
1011 ": failed to get a relocated section: " +
1015 const Elf_Shdr *ContentsSec = *RelSecOrErr;
1017 if (!DoesRelTargetMatch) {
1021 if (*DoesRelTargetMatch)
1022 SecToRelocMap[ContentsSec] = &Sec;
1025 return std::move(Errors);
1026 return SecToRelocMap;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
bbsections Prepares for basic block sections
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
COFF::MachineTypes Machine
#define LLVM_EXPORT_TEMPLATE
static IntTy readULEB128As(DataExtractor &Data, DataExtractor::Cursor &Cur, Error &ULEBSizeErr)
#define STRINGIFY_ENUM_CASE(ns, name)
static Expected< std::vector< BBAddrMap > > decodeBBAddrMapImpl(const ELFFile< ELFT > &EF, const typename ELFFile< ELFT >::Elf_Shdr &Sec, const typename ELFFile< ELFT >::Elf_Shdr *RelaSec, std::vector< PGOAnalysisMap > *PGOAnalyses)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & back() const
back - Get the last element.
bool empty() const
empty - Check if the array is empty.
static BranchProbability getRaw(uint32_t N)
iterator find(const_arg_type_t< KeyT > Val)
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
This class implements a map that also provides access to all stored values in a deterministic order.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
void reserve(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.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static Twine utohexstr(const uint64_t &Val)
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
An efficient, type-erasing, non-owning reference to a callable.
static LLVM_ABI Expected< Decompressor > create(StringRef Name, StringRef Data, bool IsLE, bool Is64Bit)
Create decompressor object.
const Elf_Ehdr & getHeader() const
Expected< std::vector< Elf_Rela > > android_relas(const Elf_Shdr &Sec) const
std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const
Expected< std::vector< BBAddrMap > > decodeBBAddrMap(const Elf_Shdr &Sec, const Elf_Shdr *RelaSec=nullptr, std::vector< PGOAnalysisMap > *PGOAnalyses=nullptr) const
Returns a vector of BBAddrMap structs corresponding to each function within the text section that the...
Expected< ArrayRef< uint8_t > > getSectionContents(const Elf_Shdr &Sec) const
Expected< Elf_Rela_Range > relas(const Elf_Shdr &Sec) const
Expected< RelsOrRelas > decodeCrel(ArrayRef< uint8_t > Content) const
Expected< uint64_t > getCrelHeader(ArrayRef< uint8_t > Content) const
Expected< Elf_Dyn_Range > dynamicEntries() const
Expected< const uint8_t * > toMappedAddr(uint64_t VAddr, WarningHandler WarnHandler=&defaultWarningHandler) const
Expected< MapVector< const Elf_Shdr *, const Elf_Shdr * > > getSectionAndRelocations(std::function< Expected< bool >(const Elf_Shdr &)> IsMatch) const
Returns a map from every section matching IsMatch to its relocation section, or nullptr if it has no ...
Expected< StringRef > getSectionName(const Elf_Shdr &Section, WarningHandler WarnHandler=&defaultWarningHandler) const
Expected< RelsOrRelas > crels(const Elf_Shdr &Sec) const
std::vector< Elf_Rel > decode_relrs(Elf_Relr_Range relrs) const
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG
@ RELOCATION_GROUPED_BY_INFO_FLAG
@ RELOCATION_GROUPED_BY_ADDEND_FLAG
@ RELOCATION_GROUP_HAS_ADDEND_FLAG
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Error createError(const Twine &Err)
LLVM_ABI StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type)
LLVM_ABI uint32_t getELFRelativeRelocationType(uint32_t Machine)
LLVM_ABI StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type)
static std::string describe(const ELFFile< ELFT > &Obj, const typename ELFT::Shdr &Sec)
static Error decodeCrel(ArrayRef< uint8_t > Content, function_ref< void(uint64_t, bool)> HdrHandler, function_ref< void(Elf_Crel_Impl< Is64 >)> EntryHandler)
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Error joinErrors(Error E1, Error E2)
Concatenate errors.
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...
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
const char * toString(DWARFSectionKind Kind)
static Expected< Metadata > decode(uint32_t V)
static Expected< Features > decode(uint8_t Val)