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