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