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