1 //===- ELFObjectFile.h - ELF object file implementation ---------*- C++ -*-===//
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 declares the ELFObjectFile template class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_OBJECT_ELFOBJECTFILE_H
14 #define LLVM_OBJECT_ELFOBJECTFILE_H
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/Object/Binary.h"
23 #include "llvm/Object/ELF.h"
24 #include "llvm/Object/ELFTypes.h"
25 #include "llvm/Object/Error.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Object/SymbolicFile.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ELFAttributeParser.h"
31 #include "llvm/Support/ELFAttributes.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/LEB128.h"
35 #include "llvm/Support/MemoryBufferRef.h"
36 #include "llvm/Support/ScopedPrinter.h"
37 #include "llvm/TargetParser/SubtargetFeature.h"
38 #include "llvm/TargetParser/Triple.h"
39 #include <cassert>
40 #include <cstdint>
41
42 namespace llvm {
43
44 template <typename T> class SmallVectorImpl;
45
46 namespace object {
47
48 constexpr int NumElfSymbolTypes = 16;
49 LLVM_ABI extern const llvm::EnumEntry<unsigned>
50 ElfSymbolTypes[NumElfSymbolTypes];
51
52 class elf_symbol_iterator;
53
54 struct ELFPltEntry {
55 StringRef Section;
56 std::optional<DataRefImpl> Symbol;
57 uint64_t Address;
58 };
59
60 class LLVM_ABI ELFObjectFileBase : public ObjectFile {
61 friend class ELFRelocationRef;
62 friend class ELFSectionRef;
63 friend class ELFSymbolRef;
64
65 SubtargetFeatures getMIPSFeatures() const;
66 SubtargetFeatures getARMFeatures() const;
67 SubtargetFeatures getHexagonFeatures() const;
68 Expected<SubtargetFeatures> getRISCVFeatures() const;
69 SubtargetFeatures getLoongArchFeatures() const;
70
71 StringRef getAMDGPUCPUName() const;
72 StringRef getNVPTXCPUName() const;
73
74 protected:
75 ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
76
77 virtual uint64_t getSymbolSize(DataRefImpl Symb) const = 0;
78 virtual uint8_t getSymbolBinding(DataRefImpl Symb) const = 0;
79 virtual uint8_t getSymbolOther(DataRefImpl Symb) const = 0;
80 virtual uint8_t getSymbolELFType(DataRefImpl Symb) const = 0;
81
82 virtual uint32_t getSectionType(DataRefImpl Sec) const = 0;
83 virtual uint64_t getSectionFlags(DataRefImpl Sec) const = 0;
84 virtual uint64_t getSectionOffset(DataRefImpl Sec) const = 0;
85
86 virtual Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const = 0;
87 virtual Error getBuildAttributes(ELFAttributeParser &Attributes) const = 0;
88
89 public:
90 using elf_symbol_iterator_range = iterator_range<elf_symbol_iterator>;
91
92 virtual elf_symbol_iterator_range getDynamicSymbolIterators() const = 0;
93
94 /// Returns platform-specific object flags, if any.
95 virtual unsigned getPlatformFlags() const = 0;
96
97 elf_symbol_iterator_range symbols() const;
98
classof(const Binary * v)99 static bool classof(const Binary *v) { return v->isELF(); }
100
101 Expected<SubtargetFeatures> getFeatures() const override;
102
103 std::optional<StringRef> tryGetCPUName() const override;
104
105 void setARMSubArch(Triple &TheTriple) const override;
106
107 virtual uint16_t getEType() const = 0;
108
109 virtual uint16_t getEMachine() const = 0;
110
111 virtual uint8_t getEIdentABIVersion() const = 0;
112
113 std::vector<ELFPltEntry> getPltEntries(const MCSubtargetInfo &STI) const;
114
115 /// Returns a vector containing a symbol version for each dynamic symbol.
116 /// Returns an empty vector if version sections do not exist.
117 Expected<std::vector<VersionEntry>> readDynsymVersions() const;
118
119 /// Returns a vector of all BB address maps in the object file. When
120 /// `TextSectionIndex` is specified, only returns the BB address maps
121 /// corresponding to the section with that index. When `PGOAnalyses`is
122 /// specified (PGOAnalyses is not nullptr), the vector is cleared then filled
123 /// with extra PGO data. `PGOAnalyses` will always be the same length as the
124 /// return value when it is requested assuming no error occurs. Upon failure,
125 /// `PGOAnalyses` will be emptied.
126 Expected<std::vector<BBAddrMap>>
127 readBBAddrMap(std::optional<unsigned> TextSectionIndex = std::nullopt,
128 std::vector<PGOAnalysisMap> *PGOAnalyses = nullptr) const;
129
130 StringRef getCrelDecodeProblem(SectionRef Sec) const;
131 };
132
133 class ELFSectionRef : public SectionRef {
134 public:
ELFSectionRef(const SectionRef & B)135 ELFSectionRef(const SectionRef &B) : SectionRef(B) {
136 assert(isa<ELFObjectFileBase>(SectionRef::getObject()));
137 }
138
getObject()139 const ELFObjectFileBase *getObject() const {
140 return cast<ELFObjectFileBase>(SectionRef::getObject());
141 }
142
getType()143 uint32_t getType() const {
144 return getObject()->getSectionType(getRawDataRefImpl());
145 }
146
getFlags()147 uint64_t getFlags() const {
148 return getObject()->getSectionFlags(getRawDataRefImpl());
149 }
150
getOffset()151 uint64_t getOffset() const {
152 return getObject()->getSectionOffset(getRawDataRefImpl());
153 }
154 };
155
156 class elf_section_iterator : public section_iterator {
157 public:
elf_section_iterator(const section_iterator & B)158 elf_section_iterator(const section_iterator &B) : section_iterator(B) {
159 assert(isa<ELFObjectFileBase>(B->getObject()));
160 }
161
162 const ELFSectionRef *operator->() const {
163 return static_cast<const ELFSectionRef *>(section_iterator::operator->());
164 }
165
166 const ELFSectionRef &operator*() const {
167 return static_cast<const ELFSectionRef &>(section_iterator::operator*());
168 }
169 };
170
171 class ELFSymbolRef : public SymbolRef {
172 public:
ELFSymbolRef(const SymbolRef & B)173 ELFSymbolRef(const SymbolRef &B) : SymbolRef(B) {
174 assert(isa<ELFObjectFileBase>(SymbolRef::getObject()));
175 }
176
getObject()177 const ELFObjectFileBase *getObject() const {
178 return cast<ELFObjectFileBase>(BasicSymbolRef::getObject());
179 }
180
getSize()181 uint64_t getSize() const {
182 return getObject()->getSymbolSize(getRawDataRefImpl());
183 }
184
getBinding()185 uint8_t getBinding() const {
186 return getObject()->getSymbolBinding(getRawDataRefImpl());
187 }
188
getOther()189 uint8_t getOther() const {
190 return getObject()->getSymbolOther(getRawDataRefImpl());
191 }
192
getELFType()193 uint8_t getELFType() const {
194 return getObject()->getSymbolELFType(getRawDataRefImpl());
195 }
196
getELFTypeName()197 StringRef getELFTypeName() const {
198 uint8_t Type = getELFType();
199 for (const auto &EE : ElfSymbolTypes) {
200 if (EE.Value == Type) {
201 return EE.AltName;
202 }
203 }
204 return "";
205 }
206 };
207
208 inline bool operator<(const ELFSymbolRef &A, const ELFSymbolRef &B) {
209 const DataRefImpl &DRIA = A.getRawDataRefImpl();
210 const DataRefImpl &DRIB = B.getRawDataRefImpl();
211 if (DRIA.d.a == DRIB.d.a)
212 return DRIA.d.b < DRIB.d.b;
213 return DRIA.d.a < DRIB.d.a;
214 }
215
216 class elf_symbol_iterator : public symbol_iterator {
217 public:
elf_symbol_iterator(const basic_symbol_iterator & B)218 elf_symbol_iterator(const basic_symbol_iterator &B)
219 : symbol_iterator(SymbolRef(B->getRawDataRefImpl(),
220 cast<ELFObjectFileBase>(B->getObject()))) {}
221
222 const ELFSymbolRef *operator->() const {
223 return static_cast<const ELFSymbolRef *>(symbol_iterator::operator->());
224 }
225
226 const ELFSymbolRef &operator*() const {
227 return static_cast<const ELFSymbolRef &>(symbol_iterator::operator*());
228 }
229 };
230
231 class ELFRelocationRef : public RelocationRef {
232 public:
ELFRelocationRef(const RelocationRef & B)233 ELFRelocationRef(const RelocationRef &B) : RelocationRef(B) {
234 assert(isa<ELFObjectFileBase>(RelocationRef::getObject()));
235 }
236
getObject()237 const ELFObjectFileBase *getObject() const {
238 return cast<ELFObjectFileBase>(RelocationRef::getObject());
239 }
240
getAddend()241 Expected<int64_t> getAddend() const {
242 return getObject()->getRelocationAddend(getRawDataRefImpl());
243 }
244 };
245
246 class elf_relocation_iterator : public relocation_iterator {
247 public:
elf_relocation_iterator(const relocation_iterator & B)248 elf_relocation_iterator(const relocation_iterator &B)
249 : relocation_iterator(RelocationRef(
250 B->getRawDataRefImpl(), cast<ELFObjectFileBase>(B->getObject()))) {}
251
252 const ELFRelocationRef *operator->() const {
253 return static_cast<const ELFRelocationRef *>(
254 relocation_iterator::operator->());
255 }
256
257 const ELFRelocationRef &operator*() const {
258 return static_cast<const ELFRelocationRef &>(
259 relocation_iterator::operator*());
260 }
261 };
262
263 inline ELFObjectFileBase::elf_symbol_iterator_range
symbols()264 ELFObjectFileBase::symbols() const {
265 return elf_symbol_iterator_range(symbol_begin(), symbol_end());
266 }
267
268 template <class ELFT> class ELFObjectFile : public ELFObjectFileBase {
269 uint16_t getEMachine() const override;
270 uint16_t getEType() const override;
271 uint8_t getEIdentABIVersion() const override;
272 uint64_t getSymbolSize(DataRefImpl Sym) const override;
273
274 public:
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)275 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
276
277 SectionRef toSectionRef(const Elf_Shdr *Sec) const {
278 return SectionRef(toDRI(Sec), this);
279 }
280
toSymbolRef(const Elf_Shdr * SymTable,unsigned SymbolNum)281 ELFSymbolRef toSymbolRef(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
282 return ELFSymbolRef({toDRI(SymTable, SymbolNum), this});
283 }
284
IsContentValid()285 bool IsContentValid() const { return ContentValid; }
286
287 private:
288 ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
289 const Elf_Shdr *DotDynSymSec, const Elf_Shdr *DotSymtabSec,
290 const Elf_Shdr *DotSymtabShndxSec);
291
292 bool ContentValid = false;
293
294 protected:
295 ELFFile<ELFT> EF;
296
297 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
298 const Elf_Shdr *DotSymtabSec = nullptr; // Symbol table section.
299 const Elf_Shdr *DotSymtabShndxSec = nullptr; // SHT_SYMTAB_SHNDX section.
300
301 // Hold CREL relocations for SectionRef::relocations().
302 mutable SmallVector<SmallVector<Elf_Crel, 0>, 0> Crels;
303 mutable SmallVector<std::string, 0> CrelDecodeProblems;
304
305 Error initContent() override;
306
307 void moveSymbolNext(DataRefImpl &Symb) const override;
308 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
309 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
310 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
311 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
312 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
313 Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
314 uint8_t getSymbolBinding(DataRefImpl Symb) const override;
315 uint8_t getSymbolOther(DataRefImpl Symb) const override;
316 uint8_t getSymbolELFType(DataRefImpl Symb) const override;
317 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
318 Expected<section_iterator> getSymbolSection(const Elf_Sym *Symb,
319 const Elf_Shdr *SymTab) const;
320 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
321
322 void moveSectionNext(DataRefImpl &Sec) const override;
323 Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
324 uint64_t getSectionAddress(DataRefImpl Sec) const override;
325 uint64_t getSectionIndex(DataRefImpl Sec) const override;
326 uint64_t getSectionSize(DataRefImpl Sec) const override;
327 Expected<ArrayRef<uint8_t>>
328 getSectionContents(DataRefImpl Sec) const override;
329 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
330 bool isSectionCompressed(DataRefImpl Sec) const override;
331 bool isSectionText(DataRefImpl Sec) const override;
332 bool isSectionData(DataRefImpl Sec) const override;
333 bool isSectionBSS(DataRefImpl Sec) const override;
334 bool isSectionVirtual(DataRefImpl Sec) const override;
335 bool isBerkeleyText(DataRefImpl Sec) const override;
336 bool isBerkeleyData(DataRefImpl Sec) const override;
337 bool isDebugSection(DataRefImpl Sec) const override;
338 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
339 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
340 std::vector<SectionRef> dynamic_relocation_sections() const override;
341 Expected<section_iterator>
342 getRelocatedSection(DataRefImpl Sec) const override;
343
344 void moveRelocationNext(DataRefImpl &Rel) const override;
345 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
346 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
347 uint64_t getRelocationType(DataRefImpl Rel) const override;
348 void getRelocationTypeName(DataRefImpl Rel,
349 SmallVectorImpl<char> &Result) const override;
350
351 uint32_t getSectionType(DataRefImpl Sec) const override;
352 uint64_t getSectionFlags(DataRefImpl Sec) const override;
353 uint64_t getSectionOffset(DataRefImpl Sec) const override;
354 StringRef getRelocationTypeName(uint32_t Type) const;
355
toDRI(const Elf_Shdr * SymTable,unsigned SymbolNum)356 DataRefImpl toDRI(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
357 DataRefImpl DRI;
358 if (!SymTable) {
359 DRI.d.a = 0;
360 DRI.d.b = 0;
361 return DRI;
362 }
363 assert(SymTable->sh_type == ELF::SHT_SYMTAB ||
364 SymTable->sh_type == ELF::SHT_DYNSYM);
365
366 auto SectionsOrErr = EF.sections();
367 if (!SectionsOrErr) {
368 DRI.d.a = 0;
369 DRI.d.b = 0;
370 return DRI;
371 }
372 uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
373 unsigned SymTableIndex =
374 (reinterpret_cast<uintptr_t>(SymTable) - SHT) / sizeof(Elf_Shdr);
375
376 DRI.d.a = SymTableIndex;
377 DRI.d.b = SymbolNum;
378 return DRI;
379 }
380
toELFShdrIter(DataRefImpl Sec)381 const Elf_Shdr *toELFShdrIter(DataRefImpl Sec) const {
382 return reinterpret_cast<const Elf_Shdr *>(Sec.p);
383 }
384
toDRI(const Elf_Shdr * Sec)385 DataRefImpl toDRI(const Elf_Shdr *Sec) const {
386 DataRefImpl DRI;
387 DRI.p = reinterpret_cast<uintptr_t>(Sec);
388 return DRI;
389 }
390
toDRI(const Elf_Dyn * Dyn)391 DataRefImpl toDRI(const Elf_Dyn *Dyn) const {
392 DataRefImpl DRI;
393 DRI.p = reinterpret_cast<uintptr_t>(Dyn);
394 return DRI;
395 }
396
isExportedToOtherDSO(const Elf_Sym * ESym)397 bool isExportedToOtherDSO(const Elf_Sym *ESym) const {
398 unsigned char Binding = ESym->getBinding();
399 unsigned char Visibility = ESym->getVisibility();
400
401 // A symbol is exported if its binding is either GLOBAL or WEAK, and its
402 // visibility is either DEFAULT or PROTECTED. All other symbols are not
403 // exported.
404 return (
405 (Binding == ELF::STB_GLOBAL || Binding == ELF::STB_WEAK ||
406 Binding == ELF::STB_GNU_UNIQUE) &&
407 (Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_PROTECTED));
408 }
409
getBuildAttributes(ELFAttributeParser & Attributes)410 Error getBuildAttributes(ELFAttributeParser &Attributes) const override {
411 uint32_t Type;
412 switch (getEMachine()) {
413 case ELF::EM_ARM:
414 Type = ELF::SHT_ARM_ATTRIBUTES;
415 break;
416 case ELF::EM_AARCH64:
417 Type = ELF::SHT_AARCH64_ATTRIBUTES;
418 break;
419 case ELF::EM_RISCV:
420 Type = ELF::SHT_RISCV_ATTRIBUTES;
421 break;
422 case ELF::EM_HEXAGON:
423 Type = ELF::SHT_HEXAGON_ATTRIBUTES;
424 break;
425 default:
426 return Error::success();
427 }
428
429 auto SectionsOrErr = EF.sections();
430 if (!SectionsOrErr)
431 return SectionsOrErr.takeError();
432 for (const Elf_Shdr &Sec : *SectionsOrErr) {
433 if (Sec.sh_type != Type)
434 continue;
435 auto ErrorOrContents = EF.getSectionContents(Sec);
436 if (!ErrorOrContents)
437 return ErrorOrContents.takeError();
438
439 auto Contents = ErrorOrContents.get();
440 if (Contents[0] != ELFAttrs::Format_Version || Contents.size() == 1)
441 return Error::success();
442
443 if (Error E = Attributes.parse(Contents, ELFT::Endianness))
444 return E;
445 break;
446 }
447 return Error::success();
448 }
449
450 // This flag is used for classof, to distinguish ELFObjectFile from
451 // its subclass. If more subclasses will be created, this flag will
452 // have to become an enum.
453 bool isDyldELFObject = false;
454
455 public:
456 ELFObjectFile(ELFObjectFile<ELFT> &&Other);
457 static Expected<ELFObjectFile<ELFT>> create(MemoryBufferRef Object,
458 bool InitContent = true);
459
460 const Elf_Rel *getRel(DataRefImpl Rel) const;
461 const Elf_Rela *getRela(DataRefImpl Rela) const;
462 Elf_Crel getCrel(DataRefImpl Crel) const;
463
getSymbol(DataRefImpl Sym)464 Expected<const Elf_Sym *> getSymbol(DataRefImpl Sym) const {
465 return EF.template getEntry<Elf_Sym>(Sym.d.a, Sym.d.b);
466 }
467
468 /// Get the relocation section that contains \a Rel.
getRelSection(DataRefImpl Rel)469 const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
470 auto RelSecOrErr = EF.getSection(Rel.d.a);
471 if (!RelSecOrErr)
472 report_fatal_error(
473 Twine(errorToErrorCode(RelSecOrErr.takeError()).message()));
474 return *RelSecOrErr;
475 }
476
getSection(DataRefImpl Sec)477 const Elf_Shdr *getSection(DataRefImpl Sec) const {
478 return reinterpret_cast<const Elf_Shdr *>(Sec.p);
479 }
480
481 basic_symbol_iterator symbol_begin() const override;
482 basic_symbol_iterator symbol_end() const override;
483
is64Bit()484 bool is64Bit() const override { return getBytesInAddress() == 8; }
485
486 elf_symbol_iterator dynamic_symbol_begin() const;
487 elf_symbol_iterator dynamic_symbol_end() const;
488
489 section_iterator section_begin() const override;
490 section_iterator section_end() const override;
491
492 Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const override;
493
494 uint8_t getBytesInAddress() const override;
495 StringRef getFileFormatName() const override;
496 Triple::ArchType getArch() const override;
497 Triple::OSType getOS() const override;
498 Expected<uint64_t> getStartAddress() const override;
499
getPlatformFlags()500 unsigned getPlatformFlags() const override { return EF.getHeader().e_flags; }
501
getELFFile()502 const ELFFile<ELFT> &getELFFile() const { return EF; }
503
isDyldType()504 bool isDyldType() const { return isDyldELFObject; }
classof(const Binary * v)505 static bool classof(const Binary *v) {
506 return v->getType() ==
507 getELFType(ELFT::Endianness == llvm::endianness::little,
508 ELFT::Is64Bits);
509 }
510
511 elf_symbol_iterator_range getDynamicSymbolIterators() const override;
512
513 bool isRelocatableObject() const override;
514
createFakeSections()515 void createFakeSections() { EF.createFakeSections(); }
516
517 StringRef getCrelDecodeProblem(DataRefImpl Sec) const;
518 };
519
520 using ELF32LEObjectFile = ELFObjectFile<ELF32LE>;
521 using ELF64LEObjectFile = ELFObjectFile<ELF64LE>;
522 using ELF32BEObjectFile = ELFObjectFile<ELF32BE>;
523 using ELF64BEObjectFile = ELFObjectFile<ELF64BE>;
524
525 template <class ELFT>
moveSymbolNext(DataRefImpl & Sym)526 void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Sym) const {
527 ++Sym.d.b;
528 }
529
initContent()530 template <class ELFT> Error ELFObjectFile<ELFT>::initContent() {
531 auto SectionsOrErr = EF.sections();
532 if (!SectionsOrErr)
533 return SectionsOrErr.takeError();
534
535 for (const Elf_Shdr &Sec : *SectionsOrErr) {
536 switch (Sec.sh_type) {
537 case ELF::SHT_DYNSYM: {
538 if (!DotDynSymSec)
539 DotDynSymSec = &Sec;
540 break;
541 }
542 case ELF::SHT_SYMTAB: {
543 if (!DotSymtabSec)
544 DotSymtabSec = &Sec;
545 break;
546 }
547 case ELF::SHT_SYMTAB_SHNDX: {
548 if (!DotSymtabShndxSec)
549 DotSymtabShndxSec = &Sec;
550 break;
551 }
552 }
553 }
554
555 ContentValid = true;
556 return Error::success();
557 }
558
559 template <class ELFT>
getSymbolName(DataRefImpl Sym)560 Expected<StringRef> ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Sym) const {
561 Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
562 if (!SymOrErr)
563 return SymOrErr.takeError();
564 auto SymTabOrErr = EF.getSection(Sym.d.a);
565 if (!SymTabOrErr)
566 return SymTabOrErr.takeError();
567 const Elf_Shdr *SymTableSec = *SymTabOrErr;
568 auto StrTabOrErr = EF.getSection(SymTableSec->sh_link);
569 if (!StrTabOrErr)
570 return StrTabOrErr.takeError();
571 const Elf_Shdr *StringTableSec = *StrTabOrErr;
572 auto SymStrTabOrErr = EF.getStringTable(*StringTableSec);
573 if (!SymStrTabOrErr)
574 return SymStrTabOrErr.takeError();
575 Expected<StringRef> Name = (*SymOrErr)->getName(*SymStrTabOrErr);
576 if (Name && !Name->empty())
577 return Name;
578
579 // If the symbol name is empty use the section name.
580 if ((*SymOrErr)->getType() == ELF::STT_SECTION) {
581 Expected<section_iterator> SecOrErr = getSymbolSection(Sym);
582 if (SecOrErr)
583 return (*SecOrErr)->getName();
584 return SecOrErr.takeError();
585 }
586 return Name;
587 }
588
589 template <class ELFT>
getSectionFlags(DataRefImpl Sec)590 uint64_t ELFObjectFile<ELFT>::getSectionFlags(DataRefImpl Sec) const {
591 return getSection(Sec)->sh_flags;
592 }
593
594 template <class ELFT>
getSectionType(DataRefImpl Sec)595 uint32_t ELFObjectFile<ELFT>::getSectionType(DataRefImpl Sec) const {
596 return getSection(Sec)->sh_type;
597 }
598
599 template <class ELFT>
getSectionOffset(DataRefImpl Sec)600 uint64_t ELFObjectFile<ELFT>::getSectionOffset(DataRefImpl Sec) const {
601 return getSection(Sec)->sh_offset;
602 }
603
604 template <class ELFT>
getSymbolValueImpl(DataRefImpl Symb)605 uint64_t ELFObjectFile<ELFT>::getSymbolValueImpl(DataRefImpl Symb) const {
606 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
607 if (!SymOrErr)
608 report_fatal_error(SymOrErr.takeError());
609
610 uint64_t Ret = (*SymOrErr)->st_value;
611 if ((*SymOrErr)->st_shndx == ELF::SHN_ABS)
612 return Ret;
613
614 const Elf_Ehdr &Header = EF.getHeader();
615 // Clear the ARM/Thumb or microMIPS indicator flag.
616 if ((Header.e_machine == ELF::EM_ARM || Header.e_machine == ELF::EM_MIPS) &&
617 (*SymOrErr)->getType() == ELF::STT_FUNC)
618 Ret &= ~1;
619
620 return Ret;
621 }
622
623 template <class ELFT>
624 Expected<uint64_t>
getSymbolAddress(DataRefImpl Symb)625 ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb) const {
626 Expected<uint64_t> SymbolValueOrErr = getSymbolValue(Symb);
627 if (!SymbolValueOrErr)
628 // TODO: Test this error.
629 return SymbolValueOrErr.takeError();
630
631 uint64_t Result = *SymbolValueOrErr;
632 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
633 if (!SymOrErr)
634 return SymOrErr.takeError();
635
636 switch ((*SymOrErr)->st_shndx) {
637 case ELF::SHN_COMMON:
638 case ELF::SHN_UNDEF:
639 case ELF::SHN_ABS:
640 return Result;
641 }
642
643 auto SymTabOrErr = EF.getSection(Symb.d.a);
644 if (!SymTabOrErr)
645 return SymTabOrErr.takeError();
646
647 if (EF.getHeader().e_type == ELF::ET_REL) {
648 ArrayRef<Elf_Word> ShndxTable;
649 if (DotSymtabShndxSec) {
650 // TODO: Test this error.
651 if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
652 EF.getSHNDXTable(*DotSymtabShndxSec))
653 ShndxTable = *ShndxTableOrErr;
654 else
655 return ShndxTableOrErr.takeError();
656 }
657
658 Expected<const Elf_Shdr *> SectionOrErr =
659 EF.getSection(**SymOrErr, *SymTabOrErr, ShndxTable);
660 if (!SectionOrErr)
661 return SectionOrErr.takeError();
662 const Elf_Shdr *Section = *SectionOrErr;
663 if (Section)
664 Result += Section->sh_addr;
665 }
666
667 return Result;
668 }
669
670 template <class ELFT>
getSymbolAlignment(DataRefImpl Symb)671 uint32_t ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb) const {
672 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
673 if (!SymOrErr)
674 report_fatal_error(SymOrErr.takeError());
675 if ((*SymOrErr)->st_shndx == ELF::SHN_COMMON)
676 return (*SymOrErr)->st_value;
677 return 0;
678 }
679
680 template <class ELFT>
getEMachine()681 uint16_t ELFObjectFile<ELFT>::getEMachine() const {
682 return EF.getHeader().e_machine;
683 }
684
getEType()685 template <class ELFT> uint16_t ELFObjectFile<ELFT>::getEType() const {
686 return EF.getHeader().e_type;
687 }
688
getEIdentABIVersion()689 template <class ELFT> uint8_t ELFObjectFile<ELFT>::getEIdentABIVersion() const {
690 return EF.getHeader().e_ident[ELF::EI_ABIVERSION];
691 }
692
693 template <class ELFT>
getSymbolSize(DataRefImpl Sym)694 uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Sym) const {
695 Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
696 if (!SymOrErr)
697 report_fatal_error(SymOrErr.takeError());
698 return (*SymOrErr)->st_size;
699 }
700
701 template <class ELFT>
getCommonSymbolSizeImpl(DataRefImpl Symb)702 uint64_t ELFObjectFile<ELFT>::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
703 return getSymbolSize(Symb);
704 }
705
706 template <class ELFT>
getSymbolBinding(DataRefImpl Symb)707 uint8_t ELFObjectFile<ELFT>::getSymbolBinding(DataRefImpl Symb) const {
708 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
709 if (!SymOrErr)
710 report_fatal_error(SymOrErr.takeError());
711 return (*SymOrErr)->getBinding();
712 }
713
714 template <class ELFT>
getSymbolOther(DataRefImpl Symb)715 uint8_t ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb) const {
716 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
717 if (!SymOrErr)
718 report_fatal_error(SymOrErr.takeError());
719 return (*SymOrErr)->st_other;
720 }
721
722 template <class ELFT>
getSymbolELFType(DataRefImpl Symb)723 uint8_t ELFObjectFile<ELFT>::getSymbolELFType(DataRefImpl Symb) const {
724 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
725 if (!SymOrErr)
726 report_fatal_error(SymOrErr.takeError());
727 return (*SymOrErr)->getType();
728 }
729
730 template <class ELFT>
731 Expected<SymbolRef::Type>
getSymbolType(DataRefImpl Symb)732 ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb) const {
733 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
734 if (!SymOrErr)
735 return SymOrErr.takeError();
736
737 switch ((*SymOrErr)->getType()) {
738 case ELF::STT_NOTYPE:
739 return SymbolRef::ST_Unknown;
740 case ELF::STT_SECTION:
741 return SymbolRef::ST_Debug;
742 case ELF::STT_FILE:
743 return SymbolRef::ST_File;
744 case ELF::STT_FUNC:
745 return SymbolRef::ST_Function;
746 case ELF::STT_OBJECT:
747 case ELF::STT_COMMON:
748 return SymbolRef::ST_Data;
749 case ELF::STT_TLS:
750 default:
751 return SymbolRef::ST_Other;
752 }
753 }
754
755 template <class ELFT>
getSymbolFlags(DataRefImpl Sym)756 Expected<uint32_t> ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Sym) const {
757 Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
758 if (!SymOrErr)
759 return SymOrErr.takeError();
760
761 const Elf_Sym *ESym = *SymOrErr;
762 uint32_t Result = SymbolRef::SF_None;
763
764 if (ESym->getBinding() != ELF::STB_LOCAL)
765 Result |= SymbolRef::SF_Global;
766
767 if (ESym->getBinding() == ELF::STB_WEAK)
768 Result |= SymbolRef::SF_Weak;
769
770 if (ESym->st_shndx == ELF::SHN_ABS)
771 Result |= SymbolRef::SF_Absolute;
772
773 if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION)
774 Result |= SymbolRef::SF_FormatSpecific;
775
776 if (Expected<typename ELFT::SymRange> SymbolsOrErr =
777 EF.symbols(DotSymtabSec)) {
778 // Set the SF_FormatSpecific flag for the 0-index null symbol.
779 if (ESym == SymbolsOrErr->begin())
780 Result |= SymbolRef::SF_FormatSpecific;
781 } else
782 // TODO: Test this error.
783 return SymbolsOrErr.takeError();
784
785 if (Expected<typename ELFT::SymRange> SymbolsOrErr =
786 EF.symbols(DotDynSymSec)) {
787 // Set the SF_FormatSpecific flag for the 0-index null symbol.
788 if (ESym == SymbolsOrErr->begin())
789 Result |= SymbolRef::SF_FormatSpecific;
790 } else
791 // TODO: Test this error.
792 return SymbolsOrErr.takeError();
793
794 if (EF.getHeader().e_machine == ELF::EM_AARCH64) {
795 if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
796 StringRef Name = *NameOrErr;
797 if (Name.starts_with("$d") || Name.starts_with("$x"))
798 Result |= SymbolRef::SF_FormatSpecific;
799 } else {
800 // TODO: Actually report errors helpfully.
801 consumeError(NameOrErr.takeError());
802 }
803 } else if (EF.getHeader().e_machine == ELF::EM_ARM) {
804 if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
805 StringRef Name = *NameOrErr;
806 // TODO Investigate why empty name symbols need to be marked.
807 if (Name.empty() || Name.starts_with("$d") || Name.starts_with("$t") ||
808 Name.starts_with("$a"))
809 Result |= SymbolRef::SF_FormatSpecific;
810 } else {
811 // TODO: Actually report errors helpfully.
812 consumeError(NameOrErr.takeError());
813 }
814 if (ESym->getType() == ELF::STT_FUNC && (ESym->st_value & 1) == 1)
815 Result |= SymbolRef::SF_Thumb;
816 } else if (EF.getHeader().e_machine == ELF::EM_CSKY) {
817 if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
818 StringRef Name = *NameOrErr;
819 if (Name.starts_with("$d") || Name.starts_with("$t"))
820 Result |= SymbolRef::SF_FormatSpecific;
821 } else {
822 // TODO: Actually report errors helpfully.
823 consumeError(NameOrErr.takeError());
824 }
825 } else if (EF.getHeader().e_machine == ELF::EM_RISCV) {
826 if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
827 StringRef Name = *NameOrErr;
828 // Mark fake labels (used for label differences) and mapping symbols.
829 if (Name == ".L0 " || Name.starts_with("$d") || Name.starts_with("$x"))
830 Result |= SymbolRef::SF_FormatSpecific;
831 } else {
832 // TODO: Actually report errors helpfully.
833 consumeError(NameOrErr.takeError());
834 }
835 }
836
837 if (ESym->st_shndx == ELF::SHN_UNDEF)
838 Result |= SymbolRef::SF_Undefined;
839
840 if (ESym->getType() == ELF::STT_COMMON || ESym->st_shndx == ELF::SHN_COMMON)
841 Result |= SymbolRef::SF_Common;
842
843 if (isExportedToOtherDSO(ESym))
844 Result |= SymbolRef::SF_Exported;
845
846 if (ESym->getType() == ELF::STT_GNU_IFUNC)
847 Result |= SymbolRef::SF_Indirect;
848
849 if (ESym->getVisibility() == ELF::STV_HIDDEN)
850 Result |= SymbolRef::SF_Hidden;
851
852 return Result;
853 }
854
855 template <class ELFT>
856 Expected<section_iterator>
getSymbolSection(const Elf_Sym * ESym,const Elf_Shdr * SymTab)857 ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym,
858 const Elf_Shdr *SymTab) const {
859 ArrayRef<Elf_Word> ShndxTable;
860 if (DotSymtabShndxSec) {
861 // TODO: Test this error.
862 Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
863 EF.getSHNDXTable(*DotSymtabShndxSec);
864 if (!ShndxTableOrErr)
865 return ShndxTableOrErr.takeError();
866 ShndxTable = *ShndxTableOrErr;
867 }
868
869 auto ESecOrErr = EF.getSection(*ESym, SymTab, ShndxTable);
870 if (!ESecOrErr)
871 return ESecOrErr.takeError();
872
873 const Elf_Shdr *ESec = *ESecOrErr;
874 if (!ESec)
875 return section_end();
876
877 DataRefImpl Sec;
878 Sec.p = reinterpret_cast<intptr_t>(ESec);
879 return section_iterator(SectionRef(Sec, this));
880 }
881
882 template <class ELFT>
883 Expected<section_iterator>
getSymbolSection(DataRefImpl Symb)884 ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb) const {
885 Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
886 if (!SymOrErr)
887 return SymOrErr.takeError();
888
889 auto SymTabOrErr = EF.getSection(Symb.d.a);
890 if (!SymTabOrErr)
891 return SymTabOrErr.takeError();
892 return getSymbolSection(*SymOrErr, *SymTabOrErr);
893 }
894
895 template <class ELFT>
moveSectionNext(DataRefImpl & Sec)896 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
897 const Elf_Shdr *ESec = getSection(Sec);
898 Sec = toDRI(++ESec);
899 }
900
901 template <class ELFT>
getSectionName(DataRefImpl Sec)902 Expected<StringRef> ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec) const {
903 return EF.getSectionName(*getSection(Sec));
904 }
905
906 template <class ELFT>
getSectionAddress(DataRefImpl Sec)907 uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
908 return getSection(Sec)->sh_addr;
909 }
910
911 template <class ELFT>
getSectionIndex(DataRefImpl Sec)912 uint64_t ELFObjectFile<ELFT>::getSectionIndex(DataRefImpl Sec) const {
913 auto SectionsOrErr = EF.sections();
914 handleAllErrors(std::move(SectionsOrErr.takeError()),
915 [](const ErrorInfoBase &) {
916 llvm_unreachable("unable to get section index");
917 });
918 const Elf_Shdr *First = SectionsOrErr->begin();
919 return getSection(Sec) - First;
920 }
921
922 template <class ELFT>
getSectionSize(DataRefImpl Sec)923 uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
924 return getSection(Sec)->sh_size;
925 }
926
927 template <class ELFT>
928 Expected<ArrayRef<uint8_t>>
getSectionContents(DataRefImpl Sec)929 ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec) const {
930 const Elf_Shdr *EShdr = getSection(Sec);
931 if (EShdr->sh_type == ELF::SHT_NOBITS)
932 return ArrayRef((const uint8_t *)base(), (size_t)0);
933 if (Error E =
934 checkOffset(getMemoryBufferRef(),
935 (uintptr_t)base() + EShdr->sh_offset, EShdr->sh_size))
936 return std::move(E);
937 return ArrayRef((const uint8_t *)base() + EShdr->sh_offset, EShdr->sh_size);
938 }
939
940 template <class ELFT>
getSectionAlignment(DataRefImpl Sec)941 uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
942 return getSection(Sec)->sh_addralign;
943 }
944
945 template <class ELFT>
isSectionCompressed(DataRefImpl Sec)946 bool ELFObjectFile<ELFT>::isSectionCompressed(DataRefImpl Sec) const {
947 return getSection(Sec)->sh_flags & ELF::SHF_COMPRESSED;
948 }
949
950 template <class ELFT>
isSectionText(DataRefImpl Sec)951 bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
952 return getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR;
953 }
954
955 template <class ELFT>
isSectionData(DataRefImpl Sec)956 bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
957 const Elf_Shdr *EShdr = getSection(Sec);
958 return (EShdr->sh_flags & ELF::SHF_ALLOC) &&
959 !(EShdr->sh_flags & ELF::SHF_EXECINSTR) &&
960 EShdr->sh_type != ELF::SHT_NOBITS;
961 }
962
963 template <class ELFT>
isSectionBSS(DataRefImpl Sec)964 bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
965 const Elf_Shdr *EShdr = getSection(Sec);
966 return EShdr->sh_flags & ELF::SHF_ALLOC && EShdr->sh_type == ELF::SHT_NOBITS;
967 }
968
969 template <class ELFT>
970 std::vector<SectionRef>
dynamic_relocation_sections()971 ELFObjectFile<ELFT>::dynamic_relocation_sections() const {
972 std::vector<SectionRef> Res;
973 std::vector<uintptr_t> Offsets;
974
975 auto SectionsOrErr = EF.sections();
976 if (!SectionsOrErr)
977 return Res;
978
979 for (const Elf_Shdr &Sec : *SectionsOrErr) {
980 if (Sec.sh_type != ELF::SHT_DYNAMIC)
981 continue;
982 Elf_Dyn *Dynamic =
983 reinterpret_cast<Elf_Dyn *>((uintptr_t)base() + Sec.sh_offset);
984 for (; Dynamic->d_tag != ELF::DT_NULL; Dynamic++) {
985 if (Dynamic->d_tag == ELF::DT_REL || Dynamic->d_tag == ELF::DT_RELA ||
986 Dynamic->d_tag == ELF::DT_JMPREL) {
987 Offsets.push_back(Dynamic->d_un.d_val);
988 }
989 }
990 }
991 for (const Elf_Shdr &Sec : *SectionsOrErr) {
992 if (is_contained(Offsets, Sec.sh_addr))
993 Res.emplace_back(toDRI(&Sec), this);
994 }
995 return Res;
996 }
997
998 template <class ELFT>
isSectionVirtual(DataRefImpl Sec)999 bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
1000 return getSection(Sec)->sh_type == ELF::SHT_NOBITS;
1001 }
1002
1003 template <class ELFT>
isBerkeleyText(DataRefImpl Sec)1004 bool ELFObjectFile<ELFT>::isBerkeleyText(DataRefImpl Sec) const {
1005 return getSection(Sec)->sh_flags & ELF::SHF_ALLOC &&
1006 (getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR ||
1007 !(getSection(Sec)->sh_flags & ELF::SHF_WRITE));
1008 }
1009
1010 template <class ELFT>
isBerkeleyData(DataRefImpl Sec)1011 bool ELFObjectFile<ELFT>::isBerkeleyData(DataRefImpl Sec) const {
1012 const Elf_Shdr *EShdr = getSection(Sec);
1013 return !isBerkeleyText(Sec) && EShdr->sh_type != ELF::SHT_NOBITS &&
1014 EShdr->sh_flags & ELF::SHF_ALLOC;
1015 }
1016
1017 template <class ELFT>
isDebugSection(DataRefImpl Sec)1018 bool ELFObjectFile<ELFT>::isDebugSection(DataRefImpl Sec) const {
1019 Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
1020 if (!SectionNameOrErr) {
1021 // TODO: Report the error message properly.
1022 consumeError(SectionNameOrErr.takeError());
1023 return false;
1024 }
1025 StringRef SectionName = SectionNameOrErr.get();
1026 return SectionName.starts_with(".debug") ||
1027 SectionName.starts_with(".zdebug") || SectionName == ".gdb_index";
1028 }
1029
1030 template <class ELFT>
1031 relocation_iterator
section_rel_begin(DataRefImpl Sec)1032 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
1033 DataRefImpl RelData;
1034 auto SectionsOrErr = EF.sections();
1035 if (!SectionsOrErr)
1036 return relocation_iterator(RelocationRef());
1037 uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
1038 RelData.d.a = (Sec.p - SHT) / EF.getHeader().e_shentsize;
1039 RelData.d.b = 0;
1040 if (reinterpret_cast<const Elf_Shdr *>(Sec.p)->sh_type == ELF::SHT_CREL) {
1041 if (RelData.d.a + 1 > Crels.size())
1042 Crels.resize(RelData.d.a + 1);
1043 auto &Crel = Crels[RelData.d.a];
1044 if (Crel.empty()) {
1045 ArrayRef<uint8_t> Content = cantFail(getSectionContents(Sec));
1046 size_t I = 0;
1047 Error Err = decodeCrel<ELFT::Is64Bits>(
1048 Content, [&](uint64_t Count, bool) { Crel.resize(Count); },
1049 [&](Elf_Crel Crel) { Crels[RelData.d.a][I++] = Crel; });
1050 if (Err) {
1051 Crel.assign(1, Elf_Crel{0, 0, 0, 0});
1052 if (RelData.d.a + 1 > CrelDecodeProblems.size())
1053 CrelDecodeProblems.resize(RelData.d.a + 1);
1054 CrelDecodeProblems[RelData.d.a] = toString(std::move(Err));
1055 }
1056 }
1057 }
1058 return relocation_iterator(RelocationRef(RelData, this));
1059 }
1060
1061 template <class ELFT>
1062 relocation_iterator
section_rel_end(DataRefImpl Sec)1063 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
1064 const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1065 relocation_iterator Begin = section_rel_begin(Sec);
1066 DataRefImpl RelData = Begin->getRawDataRefImpl();
1067 if (S->sh_type == ELF::SHT_CREL) {
1068 RelData.d.b = Crels[RelData.d.a].size();
1069 return relocation_iterator(RelocationRef(RelData, this));
1070 }
1071 if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
1072 return Begin;
1073 const Elf_Shdr *RelSec = getRelSection(RelData);
1074
1075 // Error check sh_link here so that getRelocationSymbol can just use it.
1076 auto SymSecOrErr = EF.getSection(RelSec->sh_link);
1077 if (!SymSecOrErr)
1078 report_fatal_error(
1079 Twine(errorToErrorCode(SymSecOrErr.takeError()).message()));
1080
1081 RelData.d.b += S->sh_size / S->sh_entsize;
1082 return relocation_iterator(RelocationRef(RelData, this));
1083 }
1084
1085 template <class ELFT>
1086 Expected<section_iterator>
getRelocatedSection(DataRefImpl Sec)1087 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
1088 const Elf_Shdr *EShdr = getSection(Sec);
1089 uintX_t Type = EShdr->sh_type;
1090 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA && Type != ELF::SHT_CREL)
1091 return section_end();
1092
1093 Expected<const Elf_Shdr *> SecOrErr = EF.getSection(EShdr->sh_info);
1094 if (!SecOrErr)
1095 return SecOrErr.takeError();
1096 return section_iterator(SectionRef(toDRI(*SecOrErr), this));
1097 }
1098
1099 // Relocations
1100 template <class ELFT>
moveRelocationNext(DataRefImpl & Rel)1101 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
1102 ++Rel.d.b;
1103 }
1104
1105 template <class ELFT>
1106 symbol_iterator
getRelocationSymbol(DataRefImpl Rel)1107 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
1108 uint32_t symbolIdx;
1109 const Elf_Shdr *sec = getRelSection(Rel);
1110 if (sec->sh_type == ELF::SHT_CREL)
1111 symbolIdx = getCrel(Rel).r_symidx;
1112 else if (sec->sh_type == ELF::SHT_REL)
1113 symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
1114 else
1115 symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
1116 if (!symbolIdx)
1117 return symbol_end();
1118
1119 // FIXME: error check symbolIdx
1120 DataRefImpl SymbolData;
1121 SymbolData.d.a = sec->sh_link;
1122 SymbolData.d.b = symbolIdx;
1123 return symbol_iterator(SymbolRef(SymbolData, this));
1124 }
1125
1126 template <class ELFT>
getRelocationOffset(DataRefImpl Rel)1127 uint64_t ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel) const {
1128 const Elf_Shdr *sec = getRelSection(Rel);
1129 if (sec->sh_type == ELF::SHT_CREL)
1130 return getCrel(Rel).r_offset;
1131 if (sec->sh_type == ELF::SHT_REL)
1132 return getRel(Rel)->r_offset;
1133
1134 return getRela(Rel)->r_offset;
1135 }
1136
1137 template <class ELFT>
getRelocationType(DataRefImpl Rel)1138 uint64_t ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel) const {
1139 const Elf_Shdr *sec = getRelSection(Rel);
1140 if (sec->sh_type == ELF::SHT_CREL)
1141 return getCrel(Rel).r_type;
1142 if (sec->sh_type == ELF::SHT_REL)
1143 return getRel(Rel)->getType(EF.isMips64EL());
1144 else
1145 return getRela(Rel)->getType(EF.isMips64EL());
1146 }
1147
1148 template <class ELFT>
getRelocationTypeName(uint32_t Type)1149 StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
1150 return getELFRelocationTypeName(EF.getHeader().e_machine, Type);
1151 }
1152
1153 template <class ELFT>
getRelocationTypeName(DataRefImpl Rel,SmallVectorImpl<char> & Result)1154 void ELFObjectFile<ELFT>::getRelocationTypeName(
1155 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1156 uint32_t type = getRelocationType(Rel);
1157 EF.getRelocationTypeName(type, Result);
1158 }
1159
1160 template <class ELFT>
1161 Expected<int64_t>
getRelocationAddend(DataRefImpl Rel)1162 ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel) const {
1163 if (getRelSection(Rel)->sh_type == ELF::SHT_RELA)
1164 return (int64_t)getRela(Rel)->r_addend;
1165 if (getRelSection(Rel)->sh_type == ELF::SHT_CREL)
1166 return (int64_t)getCrel(Rel).r_addend;
1167 return createError("Relocation section does not have addends");
1168 }
1169
1170 template <class ELFT>
1171 const typename ELFObjectFile<ELFT>::Elf_Rel *
getRel(DataRefImpl Rel)1172 ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
1173 assert(getRelSection(Rel)->sh_type == ELF::SHT_REL);
1174 auto Ret = EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
1175 if (!Ret)
1176 report_fatal_error(Twine(errorToErrorCode(Ret.takeError()).message()));
1177 return *Ret;
1178 }
1179
1180 template <class ELFT>
1181 const typename ELFObjectFile<ELFT>::Elf_Rela *
getRela(DataRefImpl Rela)1182 ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
1183 assert(getRelSection(Rela)->sh_type == ELF::SHT_RELA);
1184 auto Ret = EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
1185 if (!Ret)
1186 report_fatal_error(Twine(errorToErrorCode(Ret.takeError()).message()));
1187 return *Ret;
1188 }
1189
1190 template <class ELFT>
1191 typename ELFObjectFile<ELFT>::Elf_Crel
getCrel(DataRefImpl Crel)1192 ELFObjectFile<ELFT>::getCrel(DataRefImpl Crel) const {
1193 assert(getRelSection(Crel)->sh_type == ELF::SHT_CREL);
1194 assert(Crel.d.a < Crels.size());
1195 return Crels[Crel.d.a][Crel.d.b];
1196 }
1197
1198 template <class ELFT>
1199 Expected<ELFObjectFile<ELFT>>
create(MemoryBufferRef Object,bool InitContent)1200 ELFObjectFile<ELFT>::create(MemoryBufferRef Object, bool InitContent) {
1201 auto EFOrErr = ELFFile<ELFT>::create(Object.getBuffer());
1202 if (Error E = EFOrErr.takeError())
1203 return std::move(E);
1204
1205 ELFObjectFile<ELFT> Obj = {Object, std::move(*EFOrErr), nullptr, nullptr,
1206 nullptr};
1207 if (InitContent)
1208 if (Error E = Obj.initContent())
1209 return std::move(E);
1210 return std::move(Obj);
1211 }
1212
1213 template <class ELFT>
ELFObjectFile(MemoryBufferRef Object,ELFFile<ELFT> EF,const Elf_Shdr * DotDynSymSec,const Elf_Shdr * DotSymtabSec,const Elf_Shdr * DotSymtabShndx)1214 ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
1215 const Elf_Shdr *DotDynSymSec,
1216 const Elf_Shdr *DotSymtabSec,
1217 const Elf_Shdr *DotSymtabShndx)
1218 : ELFObjectFileBase(getELFType(ELFT::Endianness == llvm::endianness::little,
1219 ELFT::Is64Bits),
1220 Object),
1221 EF(EF), DotDynSymSec(DotDynSymSec), DotSymtabSec(DotSymtabSec),
1222 DotSymtabShndxSec(DotSymtabShndx) {}
1223
1224 template <class ELFT>
ELFObjectFile(ELFObjectFile<ELFT> && Other)1225 ELFObjectFile<ELFT>::ELFObjectFile(ELFObjectFile<ELFT> &&Other)
1226 : ELFObjectFile(Other.Data, Other.EF, Other.DotDynSymSec,
1227 Other.DotSymtabSec, Other.DotSymtabShndxSec) {}
1228
1229 template <class ELFT>
symbol_begin()1230 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin() const {
1231 DataRefImpl Sym =
1232 toDRI(DotSymtabSec,
1233 DotSymtabSec && DotSymtabSec->sh_size >= sizeof(Elf_Sym) ? 1 : 0);
1234 return basic_symbol_iterator(SymbolRef(Sym, this));
1235 }
1236
1237 template <class ELFT>
symbol_end()1238 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end() const {
1239 const Elf_Shdr *SymTab = DotSymtabSec;
1240 if (!SymTab)
1241 return symbol_begin();
1242 DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
1243 return basic_symbol_iterator(SymbolRef(Sym, this));
1244 }
1245
1246 template <class ELFT>
dynamic_symbol_begin()1247 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
1248 if (!DotDynSymSec || DotDynSymSec->sh_size < sizeof(Elf_Sym))
1249 // Ignore errors here where the dynsym is empty or sh_size less than the
1250 // size of one symbol. These should be handled elsewhere.
1251 return symbol_iterator(SymbolRef(toDRI(DotDynSymSec, 0), this));
1252 // Skip 0-index NULL symbol.
1253 return symbol_iterator(SymbolRef(toDRI(DotDynSymSec, 1), this));
1254 }
1255
1256 template <class ELFT>
dynamic_symbol_end()1257 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
1258 const Elf_Shdr *SymTab = DotDynSymSec;
1259 if (!SymTab)
1260 return dynamic_symbol_begin();
1261 DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
1262 return basic_symbol_iterator(SymbolRef(Sym, this));
1263 }
1264
1265 template <class ELFT>
section_begin()1266 section_iterator ELFObjectFile<ELFT>::section_begin() const {
1267 auto SectionsOrErr = EF.sections();
1268 if (!SectionsOrErr)
1269 return section_iterator(SectionRef());
1270 return section_iterator(SectionRef(toDRI((*SectionsOrErr).begin()), this));
1271 }
1272
1273 template <class ELFT>
section_end()1274 section_iterator ELFObjectFile<ELFT>::section_end() const {
1275 auto SectionsOrErr = EF.sections();
1276 if (!SectionsOrErr)
1277 return section_iterator(SectionRef());
1278 return section_iterator(SectionRef(toDRI((*SectionsOrErr).end()), this));
1279 }
1280
1281 template <class ELFT>
getBytesInAddress()1282 uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
1283 return ELFT::Is64Bits ? 8 : 4;
1284 }
1285
1286 template <class ELFT>
getFileFormatName()1287 StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
1288 constexpr bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
1289 switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1290 case ELF::ELFCLASS32:
1291 switch (EF.getHeader().e_machine) {
1292 case ELF::EM_68K:
1293 return "elf32-m68k";
1294 case ELF::EM_386:
1295 return "elf32-i386";
1296 case ELF::EM_IAMCU:
1297 return "elf32-iamcu";
1298 case ELF::EM_X86_64:
1299 return "elf32-x86-64";
1300 case ELF::EM_ARM:
1301 return (IsLittleEndian ? "elf32-littlearm" : "elf32-bigarm");
1302 case ELF::EM_AVR:
1303 return "elf32-avr";
1304 case ELF::EM_HEXAGON:
1305 return "elf32-hexagon";
1306 case ELF::EM_LANAI:
1307 return "elf32-lanai";
1308 case ELF::EM_MIPS:
1309 return "elf32-mips";
1310 case ELF::EM_MSP430:
1311 return "elf32-msp430";
1312 case ELF::EM_PPC:
1313 return (IsLittleEndian ? "elf32-powerpcle" : "elf32-powerpc");
1314 case ELF::EM_RISCV:
1315 return "elf32-littleriscv";
1316 case ELF::EM_CSKY:
1317 return "elf32-csky";
1318 case ELF::EM_SPARC:
1319 case ELF::EM_SPARC32PLUS:
1320 return "elf32-sparc";
1321 case ELF::EM_AMDGPU:
1322 return "elf32-amdgpu";
1323 case ELF::EM_LOONGARCH:
1324 return "elf32-loongarch";
1325 case ELF::EM_XTENSA:
1326 return "elf32-xtensa";
1327 default:
1328 return "elf32-unknown";
1329 }
1330 case ELF::ELFCLASS64:
1331 switch (EF.getHeader().e_machine) {
1332 case ELF::EM_386:
1333 return "elf64-i386";
1334 case ELF::EM_X86_64:
1335 return "elf64-x86-64";
1336 case ELF::EM_AARCH64:
1337 return (IsLittleEndian ? "elf64-littleaarch64" : "elf64-bigaarch64");
1338 case ELF::EM_PPC64:
1339 return (IsLittleEndian ? "elf64-powerpcle" : "elf64-powerpc");
1340 case ELF::EM_RISCV:
1341 return "elf64-littleriscv";
1342 case ELF::EM_S390:
1343 return "elf64-s390";
1344 case ELF::EM_SPARCV9:
1345 return "elf64-sparc";
1346 case ELF::EM_MIPS:
1347 return "elf64-mips";
1348 case ELF::EM_AMDGPU:
1349 return "elf64-amdgpu";
1350 case ELF::EM_BPF:
1351 return "elf64-bpf";
1352 case ELF::EM_VE:
1353 return "elf64-ve";
1354 case ELF::EM_LOONGARCH:
1355 return "elf64-loongarch";
1356 default:
1357 return "elf64-unknown";
1358 }
1359 default:
1360 // FIXME: Proper error handling.
1361 report_fatal_error("Invalid ELFCLASS!");
1362 }
1363 }
1364
getArch()1365 template <class ELFT> Triple::ArchType ELFObjectFile<ELFT>::getArch() const {
1366 bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
1367 switch (EF.getHeader().e_machine) {
1368 case ELF::EM_68K:
1369 return Triple::m68k;
1370 case ELF::EM_386:
1371 case ELF::EM_IAMCU:
1372 return Triple::x86;
1373 case ELF::EM_X86_64:
1374 return Triple::x86_64;
1375 case ELF::EM_AARCH64:
1376 return IsLittleEndian ? Triple::aarch64 : Triple::aarch64_be;
1377 case ELF::EM_ARM:
1378 return Triple::arm;
1379 case ELF::EM_AVR:
1380 return Triple::avr;
1381 case ELF::EM_HEXAGON:
1382 return Triple::hexagon;
1383 case ELF::EM_LANAI:
1384 return Triple::lanai;
1385 case ELF::EM_MIPS:
1386 switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1387 case ELF::ELFCLASS32:
1388 return IsLittleEndian ? Triple::mipsel : Triple::mips;
1389 case ELF::ELFCLASS64:
1390 return IsLittleEndian ? Triple::mips64el : Triple::mips64;
1391 default:
1392 report_fatal_error("Invalid ELFCLASS!");
1393 }
1394 case ELF::EM_MSP430:
1395 return Triple::msp430;
1396 case ELF::EM_PPC:
1397 return IsLittleEndian ? Triple::ppcle : Triple::ppc;
1398 case ELF::EM_PPC64:
1399 return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
1400 case ELF::EM_RISCV:
1401 switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1402 case ELF::ELFCLASS32:
1403 return Triple::riscv32;
1404 case ELF::ELFCLASS64:
1405 return Triple::riscv64;
1406 default:
1407 report_fatal_error("Invalid ELFCLASS!");
1408 }
1409 case ELF::EM_S390:
1410 return Triple::systemz;
1411
1412 case ELF::EM_SPARC:
1413 case ELF::EM_SPARC32PLUS:
1414 return IsLittleEndian ? Triple::sparcel : Triple::sparc;
1415 case ELF::EM_SPARCV9:
1416 return Triple::sparcv9;
1417
1418 case ELF::EM_AMDGPU: {
1419 if (!IsLittleEndian)
1420 return Triple::UnknownArch;
1421
1422 unsigned MACH = EF.getHeader().e_flags & ELF::EF_AMDGPU_MACH;
1423 if (MACH >= ELF::EF_AMDGPU_MACH_R600_FIRST &&
1424 MACH <= ELF::EF_AMDGPU_MACH_R600_LAST)
1425 return Triple::r600;
1426 if (MACH >= ELF::EF_AMDGPU_MACH_AMDGCN_FIRST &&
1427 MACH <= ELF::EF_AMDGPU_MACH_AMDGCN_LAST)
1428 return Triple::amdgcn;
1429
1430 return Triple::UnknownArch;
1431 }
1432
1433 case ELF::EM_CUDA: {
1434 if (EF.getHeader().e_ident[ELF::EI_CLASS] == ELF::ELFCLASS32)
1435 return Triple::nvptx;
1436 return Triple::nvptx64;
1437 }
1438
1439 case ELF::EM_BPF:
1440 return IsLittleEndian ? Triple::bpfel : Triple::bpfeb;
1441
1442 case ELF::EM_VE:
1443 return Triple::ve;
1444 case ELF::EM_CSKY:
1445 return Triple::csky;
1446
1447 case ELF::EM_LOONGARCH:
1448 switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1449 case ELF::ELFCLASS32:
1450 return Triple::loongarch32;
1451 case ELF::ELFCLASS64:
1452 return Triple::loongarch64;
1453 default:
1454 report_fatal_error("Invalid ELFCLASS!");
1455 }
1456
1457 case ELF::EM_XTENSA:
1458 return Triple::xtensa;
1459
1460 default:
1461 return Triple::UnknownArch;
1462 }
1463 }
1464
getOS()1465 template <class ELFT> Triple::OSType ELFObjectFile<ELFT>::getOS() const {
1466 switch (EF.getHeader().e_ident[ELF::EI_OSABI]) {
1467 case ELF::ELFOSABI_NETBSD:
1468 return Triple::NetBSD;
1469 case ELF::ELFOSABI_LINUX:
1470 return Triple::Linux;
1471 case ELF::ELFOSABI_HURD:
1472 return Triple::Hurd;
1473 case ELF::ELFOSABI_SOLARIS:
1474 return Triple::Solaris;
1475 case ELF::ELFOSABI_AIX:
1476 return Triple::AIX;
1477 case ELF::ELFOSABI_FREEBSD:
1478 return Triple::FreeBSD;
1479 case ELF::ELFOSABI_OPENBSD:
1480 return Triple::OpenBSD;
1481 case ELF::ELFOSABI_CUDA:
1482 case ELF::ELFOSABI_CUDA_V2:
1483 return Triple::CUDA;
1484 case ELF::ELFOSABI_AMDGPU_HSA:
1485 return Triple::AMDHSA;
1486 case ELF::ELFOSABI_AMDGPU_PAL:
1487 return Triple::AMDPAL;
1488 case ELF::ELFOSABI_AMDGPU_MESA3D:
1489 return Triple::Mesa3D;
1490 default:
1491 return Triple::UnknownOS;
1492 }
1493 }
1494
1495 template <class ELFT>
getStartAddress()1496 Expected<uint64_t> ELFObjectFile<ELFT>::getStartAddress() const {
1497 return EF.getHeader().e_entry;
1498 }
1499
1500 template <class ELFT>
1501 ELFObjectFileBase::elf_symbol_iterator_range
getDynamicSymbolIterators()1502 ELFObjectFile<ELFT>::getDynamicSymbolIterators() const {
1503 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
1504 }
1505
isRelocatableObject()1506 template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
1507 return EF.getHeader().e_type == ELF::ET_REL;
1508 }
1509
1510 template <class ELFT>
getCrelDecodeProblem(DataRefImpl Sec)1511 StringRef ELFObjectFile<ELFT>::getCrelDecodeProblem(DataRefImpl Sec) const {
1512 uintptr_t SHT = reinterpret_cast<uintptr_t>(cantFail(EF.sections()).begin());
1513 auto I = (Sec.p - SHT) / EF.getHeader().e_shentsize;
1514 if (I < CrelDecodeProblems.size())
1515 return CrelDecodeProblems[I];
1516 return "";
1517 }
1518
1519 } // end namespace object
1520 } // end namespace llvm
1521
1522 #endif // LLVM_OBJECT_ELFOBJECTFILE_H
1523