xref: /llvm-project-15.0.7/llvm/lib/Object/ELF.cpp (revision e32ff096)
1 //===- ELF.cpp - ELF object file implementation ---------------------------===//
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 #include "llvm/Object/ELF.h"
10 #include "llvm/BinaryFormat/ELF.h"
11 #include "llvm/Support/LEB128.h"
12 
13 using namespace llvm;
14 using namespace object;
15 
16 #define STRINGIFY_ENUM_CASE(ns, name)                                          \
17   case ns::name:                                                               \
18     return #name;
19 
20 #define ELF_RELOC(name, value) STRINGIFY_ENUM_CASE(ELF, name)
21 
22 StringRef llvm::object::getELFRelocationTypeName(uint32_t Machine,
23                                                  uint32_t Type) {
24   switch (Machine) {
25   case ELF::EM_X86_64:
26     switch (Type) {
27 #include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
28     default:
29       break;
30     }
31     break;
32   case ELF::EM_386:
33   case ELF::EM_IAMCU:
34     switch (Type) {
35 #include "llvm/BinaryFormat/ELFRelocs/i386.def"
36     default:
37       break;
38     }
39     break;
40   case ELF::EM_MIPS:
41     switch (Type) {
42 #include "llvm/BinaryFormat/ELFRelocs/Mips.def"
43     default:
44       break;
45     }
46     break;
47   case ELF::EM_AARCH64:
48     switch (Type) {
49 #include "llvm/BinaryFormat/ELFRelocs/AArch64.def"
50     default:
51       break;
52     }
53     break;
54   case ELF::EM_ARM:
55     switch (Type) {
56 #include "llvm/BinaryFormat/ELFRelocs/ARM.def"
57     default:
58       break;
59     }
60     break;
61   case ELF::EM_ARC_COMPACT:
62   case ELF::EM_ARC_COMPACT2:
63     switch (Type) {
64 #include "llvm/BinaryFormat/ELFRelocs/ARC.def"
65     default:
66       break;
67     }
68     break;
69   case ELF::EM_AVR:
70     switch (Type) {
71 #include "llvm/BinaryFormat/ELFRelocs/AVR.def"
72     default:
73       break;
74     }
75     break;
76   case ELF::EM_HEXAGON:
77     switch (Type) {
78 #include "llvm/BinaryFormat/ELFRelocs/Hexagon.def"
79     default:
80       break;
81     }
82     break;
83   case ELF::EM_LANAI:
84     switch (Type) {
85 #include "llvm/BinaryFormat/ELFRelocs/Lanai.def"
86     default:
87       break;
88     }
89     break;
90   case ELF::EM_PPC:
91     switch (Type) {
92 #include "llvm/BinaryFormat/ELFRelocs/PowerPC.def"
93     default:
94       break;
95     }
96     break;
97   case ELF::EM_PPC64:
98     switch (Type) {
99 #include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def"
100     default:
101       break;
102     }
103     break;
104   case ELF::EM_RISCV:
105     switch (Type) {
106 #include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
107     default:
108       break;
109     }
110     break;
111   case ELF::EM_S390:
112     switch (Type) {
113 #include "llvm/BinaryFormat/ELFRelocs/SystemZ.def"
114     default:
115       break;
116     }
117     break;
118   case ELF::EM_SPARC:
119   case ELF::EM_SPARC32PLUS:
120   case ELF::EM_SPARCV9:
121     switch (Type) {
122 #include "llvm/BinaryFormat/ELFRelocs/Sparc.def"
123     default:
124       break;
125     }
126     break;
127   case ELF::EM_AMDGPU:
128     switch (Type) {
129 #include "llvm/BinaryFormat/ELFRelocs/AMDGPU.def"
130     default:
131       break;
132     }
133     break;
134   case ELF::EM_BPF:
135     switch (Type) {
136 #include "llvm/BinaryFormat/ELFRelocs/BPF.def"
137     default:
138       break;
139     }
140     break;
141   case ELF::EM_MSP430:
142     switch (Type) {
143 #include "llvm/BinaryFormat/ELFRelocs/MSP430.def"
144     default:
145       break;
146     }
147     break;
148   default:
149     break;
150   }
151   return "Unknown";
152 }
153 
154 #undef ELF_RELOC
155 
156 uint32_t llvm::object::getELFRelativeRelocationType(uint32_t Machine) {
157   switch (Machine) {
158   case ELF::EM_X86_64:
159     return ELF::R_X86_64_RELATIVE;
160   case ELF::EM_386:
161   case ELF::EM_IAMCU:
162     return ELF::R_386_RELATIVE;
163   case ELF::EM_MIPS:
164     break;
165   case ELF::EM_AARCH64:
166     return ELF::R_AARCH64_RELATIVE;
167   case ELF::EM_ARM:
168     return ELF::R_ARM_RELATIVE;
169   case ELF::EM_ARC_COMPACT:
170   case ELF::EM_ARC_COMPACT2:
171     return ELF::R_ARC_RELATIVE;
172   case ELF::EM_AVR:
173     break;
174   case ELF::EM_HEXAGON:
175     return ELF::R_HEX_RELATIVE;
176   case ELF::EM_LANAI:
177     break;
178   case ELF::EM_PPC:
179     break;
180   case ELF::EM_PPC64:
181     return ELF::R_PPC64_RELATIVE;
182   case ELF::EM_RISCV:
183     return ELF::R_RISCV_RELATIVE;
184   case ELF::EM_S390:
185     return ELF::R_390_RELATIVE;
186   case ELF::EM_SPARC:
187   case ELF::EM_SPARC32PLUS:
188   case ELF::EM_SPARCV9:
189     return ELF::R_SPARC_RELATIVE;
190   case ELF::EM_AMDGPU:
191     break;
192   case ELF::EM_BPF:
193     break;
194   default:
195     break;
196   }
197   return 0;
198 }
199 
200 StringRef llvm::object::getELFSectionTypeName(uint32_t Machine, unsigned Type) {
201   switch (Machine) {
202   case ELF::EM_ARM:
203     switch (Type) {
204       STRINGIFY_ENUM_CASE(ELF, SHT_ARM_EXIDX);
205       STRINGIFY_ENUM_CASE(ELF, SHT_ARM_PREEMPTMAP);
206       STRINGIFY_ENUM_CASE(ELF, SHT_ARM_ATTRIBUTES);
207       STRINGIFY_ENUM_CASE(ELF, SHT_ARM_DEBUGOVERLAY);
208       STRINGIFY_ENUM_CASE(ELF, SHT_ARM_OVERLAYSECTION);
209     }
210     break;
211   case ELF::EM_HEXAGON:
212     switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_HEX_ORDERED); }
213     break;
214   case ELF::EM_X86_64:
215     switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_X86_64_UNWIND); }
216     break;
217   case ELF::EM_MIPS:
218   case ELF::EM_MIPS_RS3_LE:
219     switch (Type) {
220       STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_REGINFO);
221       STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_OPTIONS);
222       STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_DWARF);
223       STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_ABIFLAGS);
224     }
225     break;
226   default:
227     break;
228   }
229 
230   switch (Type) {
231     STRINGIFY_ENUM_CASE(ELF, SHT_NULL);
232     STRINGIFY_ENUM_CASE(ELF, SHT_PROGBITS);
233     STRINGIFY_ENUM_CASE(ELF, SHT_SYMTAB);
234     STRINGIFY_ENUM_CASE(ELF, SHT_STRTAB);
235     STRINGIFY_ENUM_CASE(ELF, SHT_RELA);
236     STRINGIFY_ENUM_CASE(ELF, SHT_HASH);
237     STRINGIFY_ENUM_CASE(ELF, SHT_DYNAMIC);
238     STRINGIFY_ENUM_CASE(ELF, SHT_NOTE);
239     STRINGIFY_ENUM_CASE(ELF, SHT_NOBITS);
240     STRINGIFY_ENUM_CASE(ELF, SHT_REL);
241     STRINGIFY_ENUM_CASE(ELF, SHT_SHLIB);
242     STRINGIFY_ENUM_CASE(ELF, SHT_DYNSYM);
243     STRINGIFY_ENUM_CASE(ELF, SHT_INIT_ARRAY);
244     STRINGIFY_ENUM_CASE(ELF, SHT_FINI_ARRAY);
245     STRINGIFY_ENUM_CASE(ELF, SHT_PREINIT_ARRAY);
246     STRINGIFY_ENUM_CASE(ELF, SHT_GROUP);
247     STRINGIFY_ENUM_CASE(ELF, SHT_SYMTAB_SHNDX);
248     STRINGIFY_ENUM_CASE(ELF, SHT_RELR);
249     STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_REL);
250     STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_RELA);
251     STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_RELR);
252     STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_ODRTAB);
253     STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_LINKER_OPTIONS);
254     STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_CALL_GRAPH_PROFILE);
255     STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_ADDRSIG);
256     STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_DEPENDENT_LIBRARIES);
257     STRINGIFY_ENUM_CASE(ELF, SHT_GNU_ATTRIBUTES);
258     STRINGIFY_ENUM_CASE(ELF, SHT_GNU_HASH);
259     STRINGIFY_ENUM_CASE(ELF, SHT_GNU_verdef);
260     STRINGIFY_ENUM_CASE(ELF, SHT_GNU_verneed);
261     STRINGIFY_ENUM_CASE(ELF, SHT_GNU_versym);
262   default:
263     return "Unknown";
264   }
265 }
266 
267 template <class ELFT>
268 Expected<std::vector<typename ELFT::Rela>>
269 ELFFile<ELFT>::decode_relrs(Elf_Relr_Range relrs) const {
270   // This function decodes the contents of an SHT_RELR packed relocation
271   // section.
272   //
273   // Proposal for adding SHT_RELR sections to generic-abi is here:
274   //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
275   //
276   // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
277   // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
278   //
279   // i.e. start with an address, followed by any number of bitmaps. The address
280   // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
281   // relocations each, at subsequent offsets following the last address entry.
282   //
283   // The bitmap entries must have 1 in the least significant bit. The assumption
284   // here is that an address cannot have 1 in lsb. Odd addresses are not
285   // supported.
286   //
287   // Excluding the least significant bit in the bitmap, each non-zero bit in
288   // the bitmap represents a relocation to be applied to a corresponding machine
289   // word that follows the base address word. The second least significant bit
290   // represents the machine word immediately following the initial address, and
291   // each bit that follows represents the next word, in linear order. As such,
292   // a single bitmap can encode up to 31 relocations in a 32-bit object, and
293   // 63 relocations in a 64-bit object.
294   //
295   // This encoding has a couple of interesting properties:
296   // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
297   //    even means address, odd means bitmap.
298   // 2. Just a simple list of addresses is a valid encoding.
299 
300   Elf_Rela Rela;
301   Rela.r_info = 0;
302   Rela.r_addend = 0;
303   Rela.setType(getRelativeRelocationType(), false);
304   std::vector<Elf_Rela> Relocs;
305 
306   // Word type: uint32_t for Elf32, and uint64_t for Elf64.
307   typedef typename ELFT::uint Word;
308 
309   // Word size in number of bytes.
310   const size_t WordSize = sizeof(Word);
311 
312   // Number of bits used for the relocation offsets bitmap.
313   // These many relative relocations can be encoded in a single entry.
314   const size_t NBits = 8*WordSize - 1;
315 
316   Word Base = 0;
317   for (const Elf_Relr &R : relrs) {
318     Word Entry = R;
319     if ((Entry&1) == 0) {
320       // Even entry: encodes the offset for next relocation.
321       Rela.r_offset = Entry;
322       Relocs.push_back(Rela);
323       // Set base offset for subsequent bitmap entries.
324       Base = Entry + WordSize;
325       continue;
326     }
327 
328     // Odd entry: encodes bitmap for relocations starting at base.
329     Word Offset = Base;
330     while (Entry != 0) {
331       Entry >>= 1;
332       if ((Entry&1) != 0) {
333         Rela.r_offset = Offset;
334         Relocs.push_back(Rela);
335       }
336       Offset += WordSize;
337     }
338 
339     // Advance base offset by NBits words.
340     Base += NBits * WordSize;
341   }
342 
343   return Relocs;
344 }
345 
346 template <class ELFT>
347 Expected<std::vector<typename ELFT::Rela>>
348 ELFFile<ELFT>::android_relas(const Elf_Shdr *Sec) const {
349   // This function reads relocations in Android's packed relocation format,
350   // which is based on SLEB128 and delta encoding.
351   Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
352   if (!ContentsOrErr)
353     return ContentsOrErr.takeError();
354   const uint8_t *Cur = ContentsOrErr->begin();
355   const uint8_t *End = ContentsOrErr->end();
356   if (ContentsOrErr->size() < 4 || Cur[0] != 'A' || Cur[1] != 'P' ||
357       Cur[2] != 'S' || Cur[3] != '2')
358     return createError("invalid packed relocation header");
359   Cur += 4;
360 
361   const char *ErrStr = nullptr;
362   auto ReadSLEB = [&]() -> int64_t {
363     if (ErrStr)
364       return 0;
365     unsigned Len;
366     int64_t Result = decodeSLEB128(Cur, &Len, End, &ErrStr);
367     Cur += Len;
368     return Result;
369   };
370 
371   uint64_t NumRelocs = ReadSLEB();
372   uint64_t Offset = ReadSLEB();
373   uint64_t Addend = 0;
374 
375   if (ErrStr)
376     return createError(ErrStr);
377 
378   std::vector<Elf_Rela> Relocs;
379   Relocs.reserve(NumRelocs);
380   while (NumRelocs) {
381     uint64_t NumRelocsInGroup = ReadSLEB();
382     if (NumRelocsInGroup > NumRelocs)
383       return createError("relocation group unexpectedly large");
384     NumRelocs -= NumRelocsInGroup;
385 
386     uint64_t GroupFlags = ReadSLEB();
387     bool GroupedByInfo = GroupFlags & ELF::RELOCATION_GROUPED_BY_INFO_FLAG;
388     bool GroupedByOffsetDelta = GroupFlags & ELF::RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG;
389     bool GroupedByAddend = GroupFlags & ELF::RELOCATION_GROUPED_BY_ADDEND_FLAG;
390     bool GroupHasAddend = GroupFlags & ELF::RELOCATION_GROUP_HAS_ADDEND_FLAG;
391 
392     uint64_t GroupOffsetDelta;
393     if (GroupedByOffsetDelta)
394       GroupOffsetDelta = ReadSLEB();
395 
396     uint64_t GroupRInfo;
397     if (GroupedByInfo)
398       GroupRInfo = ReadSLEB();
399 
400     if (GroupedByAddend && GroupHasAddend)
401       Addend += ReadSLEB();
402 
403     if (!GroupHasAddend)
404       Addend = 0;
405 
406     for (uint64_t I = 0; I != NumRelocsInGroup; ++I) {
407       Elf_Rela R;
408       Offset += GroupedByOffsetDelta ? GroupOffsetDelta : ReadSLEB();
409       R.r_offset = Offset;
410       R.r_info = GroupedByInfo ? GroupRInfo : ReadSLEB();
411       if (GroupHasAddend && !GroupedByAddend)
412         Addend += ReadSLEB();
413       R.r_addend = Addend;
414       Relocs.push_back(R);
415 
416       if (ErrStr)
417         return createError(ErrStr);
418     }
419 
420     if (ErrStr)
421       return createError(ErrStr);
422   }
423 
424   return Relocs;
425 }
426 
427 template <class ELFT>
428 std::string ELFFile<ELFT>::getDynamicTagAsString(unsigned Arch,
429                                                  uint64_t Type) const {
430 #define DYNAMIC_STRINGIFY_ENUM(tag, value)                                     \
431   case value:                                                                  \
432     return #tag;
433 
434 #define DYNAMIC_TAG(n, v)
435   switch (Arch) {
436   case ELF::EM_HEXAGON:
437     switch (Type) {
438 #define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
439 #include "llvm/BinaryFormat/DynamicTags.def"
440 #undef HEXAGON_DYNAMIC_TAG
441     }
442     break;
443 
444   case ELF::EM_MIPS:
445     switch (Type) {
446 #define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
447 #include "llvm/BinaryFormat/DynamicTags.def"
448 #undef MIPS_DYNAMIC_TAG
449     }
450     break;
451 
452   case ELF::EM_PPC64:
453     switch (Type) {
454 #define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
455 #include "llvm/BinaryFormat/DynamicTags.def"
456 #undef PPC64_DYNAMIC_TAG
457     }
458     break;
459   }
460 #undef DYNAMIC_TAG
461   switch (Type) {
462 // Now handle all dynamic tags except the architecture specific ones
463 #define MIPS_DYNAMIC_TAG(name, value)
464 #define HEXAGON_DYNAMIC_TAG(name, value)
465 #define PPC64_DYNAMIC_TAG(name, value)
466 // Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc.
467 #define DYNAMIC_TAG_MARKER(name, value)
468 #define DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
469 #include "llvm/BinaryFormat/DynamicTags.def"
470 #undef DYNAMIC_TAG
471 #undef MIPS_DYNAMIC_TAG
472 #undef HEXAGON_DYNAMIC_TAG
473 #undef PPC64_DYNAMIC_TAG
474 #undef DYNAMIC_TAG_MARKER
475 #undef DYNAMIC_STRINGIFY_ENUM
476   default:
477     return "<unknown:>0x" + utohexstr(Type, true);
478   }
479 }
480 
481 template <class ELFT>
482 std::string ELFFile<ELFT>::getDynamicTagAsString(uint64_t Type) const {
483   return getDynamicTagAsString(getHeader()->e_machine, Type);
484 }
485 
486 template <class ELFT>
487 Expected<typename ELFT::DynRange> ELFFile<ELFT>::dynamicEntries() const {
488   ArrayRef<Elf_Dyn> Dyn;
489   size_t DynSecSize = 0;
490 
491   auto ProgramHeadersOrError = program_headers();
492   if (!ProgramHeadersOrError)
493     return ProgramHeadersOrError.takeError();
494 
495   for (const Elf_Phdr &Phdr : *ProgramHeadersOrError) {
496     if (Phdr.p_type == ELF::PT_DYNAMIC) {
497       Dyn = makeArrayRef(
498           reinterpret_cast<const Elf_Dyn *>(base() + Phdr.p_offset),
499           Phdr.p_filesz / sizeof(Elf_Dyn));
500       DynSecSize = Phdr.p_filesz;
501       break;
502     }
503   }
504 
505   // If we can't find the dynamic section in the program headers, we just fall
506   // back on the sections.
507   if (Dyn.empty()) {
508     auto SectionsOrError = sections();
509     if (!SectionsOrError)
510       return SectionsOrError.takeError();
511 
512     for (const Elf_Shdr &Sec : *SectionsOrError) {
513       if (Sec.sh_type == ELF::SHT_DYNAMIC) {
514         Expected<ArrayRef<Elf_Dyn>> DynOrError =
515             getSectionContentsAsArray<Elf_Dyn>(&Sec);
516         if (!DynOrError)
517           return DynOrError.takeError();
518         Dyn = *DynOrError;
519         DynSecSize = Sec.sh_size;
520         break;
521       }
522     }
523 
524     if (!Dyn.data())
525       return ArrayRef<Elf_Dyn>();
526   }
527 
528   if (Dyn.empty())
529     return createError("invalid empty dynamic section");
530 
531   if (DynSecSize % sizeof(Elf_Dyn) != 0)
532     return createError("malformed dynamic section");
533 
534   if (Dyn.back().d_tag != ELF::DT_NULL)
535     return createError("dynamic sections must be DT_NULL terminated");
536 
537   return Dyn;
538 }
539 
540 template <class ELFT>
541 Expected<const uint8_t *> ELFFile<ELFT>::toMappedAddr(uint64_t VAddr) const {
542   auto ProgramHeadersOrError = program_headers();
543   if (!ProgramHeadersOrError)
544     return ProgramHeadersOrError.takeError();
545 
546   llvm::SmallVector<Elf_Phdr *, 4> LoadSegments;
547 
548   for (const Elf_Phdr &Phdr : *ProgramHeadersOrError)
549     if (Phdr.p_type == ELF::PT_LOAD)
550       LoadSegments.push_back(const_cast<Elf_Phdr *>(&Phdr));
551 
552   const Elf_Phdr *const *I =
553       std::upper_bound(LoadSegments.begin(), LoadSegments.end(), VAddr,
554                        [](uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
555                          return VAddr < Phdr->p_vaddr;
556                        });
557 
558   if (I == LoadSegments.begin())
559     return createError("Virtual address is not in any segment");
560   --I;
561   const Elf_Phdr &Phdr = **I;
562   uint64_t Delta = VAddr - Phdr.p_vaddr;
563   if (Delta >= Phdr.p_filesz)
564     return createError("Virtual address is not in any segment");
565   return base() + Phdr.p_offset + Delta;
566 }
567 
568 template class llvm::object::ELFFile<ELF32LE>;
569 template class llvm::object::ELFFile<ELF32BE>;
570 template class llvm::object::ELFFile<ELF64LE>;
571 template class llvm::object::ELFFile<ELF64BE>;
572