LLVM 24.0.0git
ELF.cpp
Go to the documentation of this file.
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"
15
16using namespace llvm;
17using namespace object;
18
19#define STRINGIFY_ENUM_CASE(ns, name) \
20 case ns::name: \
21 return #name;
22
23#define ELF_RELOC(name, value) STRINGIFY_ENUM_CASE(ELF, name)
24
26 uint32_t Type) {
27 switch (Machine) {
28 case ELF::EM_68K:
29 switch (Type) {
30#include "llvm/BinaryFormat/ELFRelocs/M68k.def"
31 default:
32 break;
33 }
34 break;
35 case ELF::EM_X86_64:
36 switch (Type) {
37#include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
38 default:
39 break;
40 }
41 break;
42 case ELF::EM_386:
43 case ELF::EM_IAMCU:
44 switch (Type) {
45#include "llvm/BinaryFormat/ELFRelocs/i386.def"
46 default:
47 break;
48 }
49 break;
50 case ELF::EM_MIPS:
51 switch (Type) {
52#include "llvm/BinaryFormat/ELFRelocs/Mips.def"
53 default:
54 break;
55 }
56 break;
57 case ELF::EM_AARCH64:
58 switch (Type) {
59#include "llvm/BinaryFormat/ELFRelocs/AArch64.def"
60 default:
61 break;
62 }
63 break;
64 case ELF::EM_ARM:
65 switch (Type) {
66#include "llvm/BinaryFormat/ELFRelocs/ARM.def"
67 default:
68 break;
69 }
70 break;
71 case ELF::EM_ARC_COMPACT:
72 case ELF::EM_ARC_COMPACT2:
73 switch (Type) {
74#include "llvm/BinaryFormat/ELFRelocs/ARC.def"
75 default:
76 break;
77 }
78 break;
79 case ELF::EM_AVR:
80 switch (Type) {
81#include "llvm/BinaryFormat/ELFRelocs/AVR.def"
82 default:
83 break;
84 }
85 break;
86 case ELF::EM_HEXAGON:
87 switch (Type) {
88#include "llvm/BinaryFormat/ELFRelocs/Hexagon.def"
89 default:
90 break;
91 }
92 break;
93 case ELF::EM_LANAI:
94 switch (Type) {
95#include "llvm/BinaryFormat/ELFRelocs/Lanai.def"
96 default:
97 break;
98 }
99 break;
100 case ELF::EM_PPC:
101 switch (Type) {
102#include "llvm/BinaryFormat/ELFRelocs/PowerPC.def"
103 default:
104 break;
105 }
106 break;
107 case ELF::EM_PPC64:
108 switch (Type) {
109#include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def"
110 default:
111 break;
112 }
113 break;
114 case ELF::EM_RISCV:
115 switch (Type) {
116#include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
117 default:
118 break;
119 }
120 break;
121 case ELF::EM_S390:
122 switch (Type) {
123#include "llvm/BinaryFormat/ELFRelocs/SystemZ.def"
124 default:
125 break;
126 }
127 break;
128 case ELF::EM_SPARC:
129 case ELF::EM_SPARC32PLUS:
130 case ELF::EM_SPARCV9:
131 switch (Type) {
132#include "llvm/BinaryFormat/ELFRelocs/Sparc.def"
133 default:
134 break;
135 }
136 break;
137 case ELF::EM_AMDGPU:
138 switch (Type) {
139#include "llvm/BinaryFormat/ELFRelocs/AMDGPU.def"
140 default:
141 break;
142 }
143 break;
144 case ELF::EM_BPF:
145 switch (Type) {
146#include "llvm/BinaryFormat/ELFRelocs/BPF.def"
147 default:
148 break;
149 }
150 break;
151 case ELF::EM_MSP430:
152 switch (Type) {
153#include "llvm/BinaryFormat/ELFRelocs/MSP430.def"
154 default:
155 break;
156 }
157 break;
158 case ELF::EM_VE:
159 switch (Type) {
160#include "llvm/BinaryFormat/ELFRelocs/VE.def"
161 default:
162 break;
163 }
164 break;
165 case ELF::EM_CSKY:
166 switch (Type) {
167#include "llvm/BinaryFormat/ELFRelocs/CSKY.def"
168 default:
169 break;
170 }
171 break;
172 case ELF::EM_LOONGARCH:
173 switch (Type) {
174#include "llvm/BinaryFormat/ELFRelocs/LoongArch.def"
175 default:
176 break;
177 }
178 break;
179 case ELF::EM_XTENSA:
180 switch (Type) {
181#include "llvm/BinaryFormat/ELFRelocs/Xtensa.def"
182 default:
183 break;
184 }
185 break;
186 case ELF::EM_NANOMIPS:
187 switch (Type) {
188#include "llvm/BinaryFormat/ELFRelocs/NanoMips.def"
189 default:
190 break;
191 }
192 break;
193 default:
194 break;
195 }
196 return "Unknown";
197}
198
199#undef ELF_RELOC
200
202 StringRef Vendor) {
203#define ELF_RISCV_NONSTANDARD_RELOC(vendor, name, number) \
204 if (Vendor == #vendor && Type == number) \
205 return #name;
206
207#include "llvm/BinaryFormat/ELFRelocs/RISCV_nonstandard.def"
208
209#undef ELF_RISCV_NONSTANDARD_RELOC
210
211 return "Unknown";
212}
213
215 switch (Machine) {
216 case ELF::EM_X86_64:
217 return ELF::R_X86_64_RELATIVE;
218 case ELF::EM_386:
219 case ELF::EM_IAMCU:
220 return ELF::R_386_RELATIVE;
221 case ELF::EM_MIPS:
222 break;
223 case ELF::EM_AARCH64:
224 return ELF::R_AARCH64_RELATIVE;
225 case ELF::EM_ARM:
226 return ELF::R_ARM_RELATIVE;
227 case ELF::EM_ARC_COMPACT:
228 case ELF::EM_ARC_COMPACT2:
229 return ELF::R_ARC_RELATIVE;
230 case ELF::EM_AVR:
231 break;
232 case ELF::EM_HEXAGON:
233 return ELF::R_HEX_RELATIVE;
234 case ELF::EM_LANAI:
235 break;
236 case ELF::EM_PPC:
237 break;
238 case ELF::EM_PPC64:
239 return ELF::R_PPC64_RELATIVE;
240 case ELF::EM_RISCV:
241 return ELF::R_RISCV_RELATIVE;
242 case ELF::EM_S390:
243 return ELF::R_390_RELATIVE;
244 case ELF::EM_SPARC:
245 case ELF::EM_SPARC32PLUS:
246 case ELF::EM_SPARCV9:
247 return ELF::R_SPARC_RELATIVE;
248 case ELF::EM_CSKY:
249 return ELF::R_CKCORE_RELATIVE;
250 case ELF::EM_VE:
251 return ELF::R_VE_RELATIVE;
252 case ELF::EM_AMDGPU:
253 break;
254 case ELF::EM_BPF:
255 break;
256 case ELF::EM_LOONGARCH:
257 return ELF::R_LARCH_RELATIVE;
258 case ELF::EM_NANOMIPS:
259 return ELF::R_NANOMIPS_RELATIVE;
260 default:
261 break;
262 }
263 return 0;
264}
265
267 switch (Machine) {
268 case ELF::EM_ARM:
269 switch (Type) {
270 STRINGIFY_ENUM_CASE(ELF, SHT_ARM_EXIDX);
271 STRINGIFY_ENUM_CASE(ELF, SHT_ARM_PREEMPTMAP);
272 STRINGIFY_ENUM_CASE(ELF, SHT_ARM_ATTRIBUTES);
273 STRINGIFY_ENUM_CASE(ELF, SHT_ARM_DEBUGOVERLAY);
274 STRINGIFY_ENUM_CASE(ELF, SHT_ARM_OVERLAYSECTION);
275 }
276 break;
277 case ELF::EM_HEXAGON:
278 switch (Type) {
279 STRINGIFY_ENUM_CASE(ELF, SHT_HEX_ORDERED);
280 STRINGIFY_ENUM_CASE(ELF, SHT_HEXAGON_ATTRIBUTES);
281 }
282 break;
283 case ELF::EM_X86_64:
284 switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_X86_64_UNWIND); }
285 break;
286 case ELF::EM_MIPS:
287 case ELF::EM_MIPS_RS3_LE:
288 switch (Type) {
289 STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_REGINFO);
290 STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_OPTIONS);
291 STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_DWARF);
292 STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_ABIFLAGS);
293 }
294 break;
295 case ELF::EM_MSP430:
296 switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_MSP430_ATTRIBUTES); }
297 break;
298 case ELF::EM_RISCV:
299 switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_RISCV_ATTRIBUTES); }
300 break;
301 case ELF::EM_AARCH64:
302 switch (Type) {
303 STRINGIFY_ENUM_CASE(ELF, SHT_AARCH64_AUTH_RELR);
304 STRINGIFY_ENUM_CASE(ELF, SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC);
305 STRINGIFY_ENUM_CASE(ELF, SHT_AARCH64_MEMTAG_GLOBALS_STATIC);
306 }
307 default:
308 break;
309 }
310
311 switch (Type) {
312 STRINGIFY_ENUM_CASE(ELF, SHT_NULL);
313 STRINGIFY_ENUM_CASE(ELF, SHT_PROGBITS);
314 STRINGIFY_ENUM_CASE(ELF, SHT_SYMTAB);
315 STRINGIFY_ENUM_CASE(ELF, SHT_STRTAB);
316 STRINGIFY_ENUM_CASE(ELF, SHT_RELA);
317 STRINGIFY_ENUM_CASE(ELF, SHT_HASH);
318 STRINGIFY_ENUM_CASE(ELF, SHT_DYNAMIC);
319 STRINGIFY_ENUM_CASE(ELF, SHT_NOTE);
320 STRINGIFY_ENUM_CASE(ELF, SHT_NOBITS);
321 STRINGIFY_ENUM_CASE(ELF, SHT_REL);
322 STRINGIFY_ENUM_CASE(ELF, SHT_SHLIB);
323 STRINGIFY_ENUM_CASE(ELF, SHT_DYNSYM);
324 STRINGIFY_ENUM_CASE(ELF, SHT_INIT_ARRAY);
325 STRINGIFY_ENUM_CASE(ELF, SHT_FINI_ARRAY);
326 STRINGIFY_ENUM_CASE(ELF, SHT_PREINIT_ARRAY);
327 STRINGIFY_ENUM_CASE(ELF, SHT_GROUP);
328 STRINGIFY_ENUM_CASE(ELF, SHT_SYMTAB_SHNDX);
329 STRINGIFY_ENUM_CASE(ELF, SHT_RELR);
330 STRINGIFY_ENUM_CASE(ELF, SHT_CREL);
331 STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_REL);
332 STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_RELA);
333 STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_RELR);
334 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_ODRTAB);
335 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_LINKER_OPTIONS);
336 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_CALL_GRAPH_PROFILE);
337 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_ADDRSIG);
338 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_DEPENDENT_LIBRARIES);
339 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_SYMPART);
340 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_PART_EHDR);
341 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_PART_PHDR);
342 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_BB_ADDR_MAP);
343 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_OFFLOADING);
344 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_LTO);
345 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_JT_SIZES)
346 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_CFI_JUMP_TABLE)
347 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_CALL_GRAPH);
348 STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_DYNDBG_ELF);
349 STRINGIFY_ENUM_CASE(ELF, SHT_GNU_SFRAME);
350 STRINGIFY_ENUM_CASE(ELF, SHT_GNU_ATTRIBUTES);
351 STRINGIFY_ENUM_CASE(ELF, SHT_GNU_HASH);
352 STRINGIFY_ENUM_CASE(ELF, SHT_GNU_verdef);
353 STRINGIFY_ENUM_CASE(ELF, SHT_GNU_verneed);
354 STRINGIFY_ENUM_CASE(ELF, SHT_GNU_versym);
355 default:
356 return "Unknown";
357 }
358}
359
360template <class ELFT>
361std::vector<typename ELFT::Rel>
362ELFFile<ELFT>::decode_relrs(Elf_Relr_Range relrs) const {
363 // This function decodes the contents of an SHT_RELR packed relocation
364 // section.
365 //
366 // Proposal for adding SHT_RELR sections to generic-abi is here:
367 // https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
368 //
369 // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks
370 // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ]
371 //
372 // i.e. start with an address, followed by any number of bitmaps. The address
373 // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63
374 // relocations each, at subsequent offsets following the last address entry.
375 //
376 // The bitmap entries must have 1 in the least significant bit. The assumption
377 // here is that an address cannot have 1 in lsb. Odd addresses are not
378 // supported.
379 //
380 // Excluding the least significant bit in the bitmap, each non-zero bit in
381 // the bitmap represents a relocation to be applied to a corresponding machine
382 // word that follows the base address word. The second least significant bit
383 // represents the machine word immediately following the initial address, and
384 // each bit that follows represents the next word, in linear order. As such,
385 // a single bitmap can encode up to 31 relocations in a 32-bit object, and
386 // 63 relocations in a 64-bit object.
387 //
388 // This encoding has a couple of interesting properties:
389 // 1. Looking at any entry, it is clear whether it's an address or a bitmap:
390 // even means address, odd means bitmap.
391 // 2. Just a simple list of addresses is a valid encoding.
392
393 Elf_Rel Rel;
394 Rel.r_info = 0;
395 Rel.setType(getRelativeRelocationType(), false);
396 std::vector<Elf_Rel> Relocs;
397
398 // Word type: uint32_t for Elf32, and uint64_t for Elf64.
399 using Addr = typename ELFT::uint;
400
401 Addr Base = 0;
402 for (Elf_Relr R : relrs) {
403 typename ELFT::uint Entry = R;
404 if ((Entry & 1) == 0) {
405 // Even entry: encodes the offset for next relocation.
406 Rel.r_offset = Entry;
407 Relocs.push_back(Rel);
408 // Set base offset for subsequent bitmap entries.
409 Base = Entry + sizeof(Addr);
410 } else {
411 // Odd entry: encodes bitmap for relocations starting at base.
412 for (Addr Offset = Base; (Entry >>= 1) != 0; Offset += sizeof(Addr))
413 if ((Entry & 1) != 0) {
414 Rel.r_offset = Offset;
415 Relocs.push_back(Rel);
416 }
417 Base += (CHAR_BIT * sizeof(Entry) - 1) * sizeof(Addr);
418 }
419 }
420
421 return Relocs;
422}
423
424template <class ELFT>
427 DataExtractor Data(Content, isLE());
428 Error Err = Error::success();
429 uint64_t Hdr = 0;
430 Hdr = Data.getULEB128(&Hdr, &Err);
431 if (Err)
432 return Err;
433 return Hdr;
434}
436template <class ELFT>
439 std::vector<Elf_Rel> Rels;
440 std::vector<Elf_Rela> Relas;
441 size_t I = 0;
442 bool HasAddend;
444 Content,
445 [&](uint64_t Count, bool HasA) {
446 HasAddend = HasA;
447 if (HasAddend)
448 Relas.resize(Count);
449 else
450 Rels.resize(Count);
451 },
452 [&](Elf_Crel Crel) {
453 if (HasAddend) {
454 Relas[I].r_offset = Crel.r_offset;
455 Relas[I].setSymbolAndType(Crel.r_symidx, Crel.r_type, false);
456 Relas[I++].r_addend = Crel.r_addend;
457 } else {
458 Rels[I].r_offset = Crel.r_offset;
459 Rels[I++].setSymbolAndType(Crel.r_symidx, Crel.r_type, false);
460 }
461 });
462 if (Err)
463 return std::move(Err);
464 return std::make_pair(std::move(Rels), std::move(Relas));
465}
466
467template <class ELFT>
469ELFFile<ELFT>::crels(const Elf_Shdr &Sec) const {
471 if (!ContentsOrErr)
472 return ContentsOrErr.takeError();
473 return decodeCrel(*ContentsOrErr);
474}
475
476template <class ELFT>
478ELFFile<ELFT>::android_relas(const Elf_Shdr &Sec) const {
479 // This function reads relocations in Android's packed relocation format,
480 // which is based on SLEB128 and delta encoding.
482 if (!ContentsOrErr)
483 return ContentsOrErr.takeError();
484 ArrayRef<uint8_t> Content = *ContentsOrErr;
485 if (Content.size() < 4 || Content[0] != 'A' || Content[1] != 'P' ||
486 Content[2] != 'S' || Content[3] != '2')
487 return createError("invalid packed relocation header");
488 DataExtractor Data(Content, isLE());
489 DataExtractor::Cursor Cur(/*Offset=*/4);
490
491 uint64_t NumRelocs = Data.getSLEB128(Cur);
492 uint64_t Offset = Data.getSLEB128(Cur);
493 uint64_t Addend = 0;
494
495 if (!Cur)
496 return std::move(Cur.takeError());
497
498 std::vector<Elf_Rela> Relocs;
499 Relocs.reserve(NumRelocs);
500 while (NumRelocs) {
501 uint64_t NumRelocsInGroup = Data.getSLEB128(Cur);
502 if (!Cur)
503 return std::move(Cur.takeError());
504 if (NumRelocsInGroup > NumRelocs)
505 return createError("relocation group unexpectedly large");
506 NumRelocs -= NumRelocsInGroup;
507
508 uint64_t GroupFlags = Data.getSLEB128(Cur);
509 bool GroupedByInfo = GroupFlags & ELF::RELOCATION_GROUPED_BY_INFO_FLAG;
510 bool GroupedByOffsetDelta = GroupFlags & ELF::RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG;
511 bool GroupedByAddend = GroupFlags & ELF::RELOCATION_GROUPED_BY_ADDEND_FLAG;
512 bool GroupHasAddend = GroupFlags & ELF::RELOCATION_GROUP_HAS_ADDEND_FLAG;
513
514 uint64_t GroupOffsetDelta;
515 if (GroupedByOffsetDelta)
516 GroupOffsetDelta = Data.getSLEB128(Cur);
517
518 uint64_t GroupRInfo;
519 if (GroupedByInfo)
520 GroupRInfo = Data.getSLEB128(Cur);
521
522 if (GroupedByAddend && GroupHasAddend)
523 Addend += Data.getSLEB128(Cur);
524
525 if (!GroupHasAddend)
526 Addend = 0;
527
528 for (uint64_t I = 0; Cur && I != NumRelocsInGroup; ++I) {
529 Elf_Rela R;
530 Offset += GroupedByOffsetDelta ? GroupOffsetDelta : Data.getSLEB128(Cur);
531 R.r_offset = Offset;
532 R.r_info = GroupedByInfo ? GroupRInfo : Data.getSLEB128(Cur);
533 if (GroupHasAddend && !GroupedByAddend)
534 Addend += Data.getSLEB128(Cur);
535 R.r_addend = Addend;
536 Relocs.push_back(R);
537 }
538 if (!Cur)
539 return std::move(Cur.takeError());
540 }
541
542 return Relocs;
543}
544
545template <class ELFT>
546std::string ELFFile<ELFT>::getDynamicTagAsString(unsigned Arch,
547 uint64_t Type) const {
548#define DYNAMIC_STRINGIFY_ENUM(tag, value) \
549 case value: \
550 return #tag;
551
552#define DYNAMIC_TAG(n, v)
553 switch (Arch) {
554 case ELF::EM_AARCH64:
555 switch (Type) {
556#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
557#include "llvm/BinaryFormat/DynamicTags.def"
558#undef AARCH64_DYNAMIC_TAG
559 }
560 break;
561
562 case ELF::EM_HEXAGON:
563 switch (Type) {
564#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
565#include "llvm/BinaryFormat/DynamicTags.def"
566#undef HEXAGON_DYNAMIC_TAG
567 }
568 break;
569
570 case ELF::EM_MIPS:
571 switch (Type) {
572#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
573#include "llvm/BinaryFormat/DynamicTags.def"
574#undef MIPS_DYNAMIC_TAG
575 }
576 break;
577
578 case ELF::EM_PPC:
579 switch (Type) {
580#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
581#include "llvm/BinaryFormat/DynamicTags.def"
582#undef PPC_DYNAMIC_TAG
583 }
584 break;
585
586 case ELF::EM_PPC64:
587 switch (Type) {
588#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
589#include "llvm/BinaryFormat/DynamicTags.def"
590#undef PPC64_DYNAMIC_TAG
591 }
592 break;
593
594 case ELF::EM_RISCV:
595 switch (Type) {
596#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
597#include "llvm/BinaryFormat/DynamicTags.def"
598#undef RISCV_DYNAMIC_TAG
599 }
600 break;
601
602 case ELF::EM_SPARC:
603 case ELF::EM_SPARC32PLUS:
604 case ELF::EM_SPARCV9:
605 switch (Type) {
606#define SPARC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
607#include "llvm/BinaryFormat/DynamicTags.def"
608#undef SPARC_DYNAMIC_TAG
609 }
610 break;
611
612 case ELF::EM_X86_64:
613 switch (Type) {
614#define X86_64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
615#include "llvm/BinaryFormat/DynamicTags.def"
616#undef X86_64_DYNAMIC_TAG
617 }
618 break;
619 }
620#undef DYNAMIC_TAG
621 switch (Type) {
622// Now handle all dynamic tags except the architecture specific ones
623#define AARCH64_DYNAMIC_TAG(name, value)
624#define MIPS_DYNAMIC_TAG(name, value)
625#define HEXAGON_DYNAMIC_TAG(name, value)
626#define PPC_DYNAMIC_TAG(name, value)
627#define PPC64_DYNAMIC_TAG(name, value)
628#define RISCV_DYNAMIC_TAG(name, value)
629#define SPARC_DYNAMIC_TAG(name, value)
630#define X86_64_DYNAMIC_TAG(name, value)
631// Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc.
632#define DYNAMIC_TAG_MARKER(name, value)
633#define DYNAMIC_TAG(name, value) case value: return #name;
634#include "llvm/BinaryFormat/DynamicTags.def"
635#undef DYNAMIC_TAG
636#undef AARCH64_DYNAMIC_TAG
637#undef MIPS_DYNAMIC_TAG
638#undef HEXAGON_DYNAMIC_TAG
639#undef PPC_DYNAMIC_TAG
640#undef PPC64_DYNAMIC_TAG
641#undef RISCV_DYNAMIC_TAG
642#undef SPARC_DYNAMIC_TAG
643#undef X86_64_DYNAMIC_TAG
644#undef DYNAMIC_TAG_MARKER
645#undef DYNAMIC_STRINGIFY_ENUM
646 default:
647 return "<unknown:>0x" + utohexstr(Type, true);
648 }
649}
650
651template <class ELFT>
652std::string ELFFile<ELFT>::getDynamicTagAsString(uint64_t Type) const {
653 return getDynamicTagAsString(getHeader().e_machine, Type);
654}
655
656template <class ELFT>
659
660 auto ProgramHeadersOrError = program_headers();
661 if (!ProgramHeadersOrError)
662 return ProgramHeadersOrError.takeError();
663
664 for (const Elf_Phdr &Phdr : *ProgramHeadersOrError) {
665 if (Phdr.p_type == ELF::PT_DYNAMIC) {
666 const uint8_t *DynOffset = base() + Phdr.p_offset;
667 if (DynOffset > end())
668 return createError(
669 "dynamic section offset past file size: corrupted ELF");
670 Dyn = ArrayRef(reinterpret_cast<const Elf_Dyn *>(DynOffset),
671 Phdr.p_filesz / sizeof(Elf_Dyn));
672 break;
673 }
674 }
675
676 // If we can't find the dynamic section in the program headers, we just fall
677 // back on the sections.
678 if (Dyn.empty()) {
679 auto SectionsOrError = sections();
680 if (!SectionsOrError)
681 return SectionsOrError.takeError();
682
683 for (const Elf_Shdr &Sec : *SectionsOrError) {
684 if (Sec.sh_type == ELF::SHT_DYNAMIC) {
685 Expected<ArrayRef<Elf_Dyn>> DynOrError =
687 if (!DynOrError)
688 return DynOrError.takeError();
689 Dyn = *DynOrError;
690 break;
691 }
692 }
693
694 if (!Dyn.data())
695 return ArrayRef<Elf_Dyn>();
696 }
697
698 if (Dyn.empty())
699 return createError("invalid empty dynamic section");
700
701 if (Dyn.back().d_tag != ELF::DT_NULL)
702 return createError("dynamic sections must be DT_NULL terminated");
703
704 return Dyn;
705}
706
707template <class ELFT>
709ELFFile<ELFT>::toMappedAddr(uint64_t VAddr, WarningHandler WarnHandler) const {
710 auto ProgramHeadersOrError = program_headers();
711 if (!ProgramHeadersOrError)
712 return ProgramHeadersOrError.takeError();
713
715
716 for (const Elf_Phdr &Phdr : *ProgramHeadersOrError)
717 if (Phdr.p_type == ELF::PT_LOAD)
718 LoadSegments.push_back(const_cast<Elf_Phdr *>(&Phdr));
719
720 auto SortPred = [](const Elf_Phdr_Impl<ELFT> *A,
721 const Elf_Phdr_Impl<ELFT> *B) {
722 return A->p_vaddr < B->p_vaddr;
723 };
724 if (!llvm::is_sorted(LoadSegments, SortPred)) {
725 if (Error E =
726 WarnHandler("loadable segments are unsorted by virtual address"))
727 return std::move(E);
728 llvm::stable_sort(LoadSegments, SortPred);
729 }
730
731 const Elf_Phdr *const *I = llvm::upper_bound(
732 LoadSegments, VAddr, [](uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
733 return VAddr < Phdr->p_vaddr;
734 });
735
736 if (I == LoadSegments.begin())
737 return createError("virtual address is not in any segment: 0x" +
738 Twine::utohexstr(VAddr));
739 --I;
740 const Elf_Phdr &Phdr = **I;
741 uint64_t Delta = VAddr - Phdr.p_vaddr;
742 if (Delta >= Phdr.p_filesz)
743 return createError("virtual address is not in any segment: 0x" +
744 Twine::utohexstr(VAddr));
745
746 uint64_t Offset = Phdr.p_offset + Delta;
747 if (Offset >= getBufSize())
748 return createError("can't map virtual address 0x" +
749 Twine::utohexstr(VAddr) + " to the segment with index " +
750 Twine(&Phdr - (*ProgramHeadersOrError).data() + 1) +
751 ": the segment ends at 0x" +
752 Twine::utohexstr(Phdr.p_offset + Phdr.p_filesz) +
753 ", which is greater than the file size (0x" +
755
756 return base() + Offset;
757}
758
759/// Address extractor for ELF BB address map sections.
760class ELFBBAddrMapAddressExtractor : public AddressExtractor {
761 bool IsRelocatable;
762 // Maps the offset of each address field in the BB addr map section to the
763 // resolved function address (the relocation addend).
764 DenseMap<uint64_t, uint64_t> FunctionOffsetTranslations;
765
766 ELFBBAddrMapAddressExtractor(
767 const DataExtractor &Data, unsigned AddressSize, bool IsRelocatable,
768 DenseMap<uint64_t, uint64_t> FunctionOffsetTranslations)
769 : AddressExtractor(Data, AddressSize), IsRelocatable(IsRelocatable),
770 FunctionOffsetTranslations(std::move(FunctionOffsetTranslations)) {}
771
772public:
773 template <typename ELFT>
775 create(const DataExtractor &Data, const ELFFile<ELFT> &EF,
776 const typename ELFFile<ELFT>::Elf_Shdr &Sec,
777 const typename ELFFile<ELFT>::Elf_Shdr *RelaSec) {
778 bool IsRelocatable = EF.getHeader().e_type == ELF::ET_REL;
779
780 // Build relocation offset-to-addend map.
781 DenseMap<uint64_t, uint64_t> FunctionOffsetTranslations;
782 if (IsRelocatable && RelaSec) {
783 assert(RelaSec &&
784 "Can't read a SHT_LLVM_BB_ADDR_MAP section in a relocatable "
785 "object file without providing a relocation section.");
786 if (RelaSec->sh_type == ELF::SHT_CREL) {
788 EF.crels(*RelaSec);
789 if (!Relas)
790 return createError("unable to read CREL relocations for section " +
791 describe(EF, Sec) + ": " +
792 toString(Relas.takeError()));
793 for (typename ELFFile<ELFT>::Elf_Rela Rela : std::get<1>(*Relas))
794 FunctionOffsetTranslations[Rela.r_offset] = Rela.r_addend;
795 } else {
797 EF.relas(*RelaSec);
798 if (!Relas)
799 return createError("unable to read relocations for section " +
800 describe(EF, Sec) + ": " +
801 toString(Relas.takeError()));
802 for (typename ELFFile<ELFT>::Elf_Rela Rela : *Relas)
803 FunctionOffsetTranslations[Rela.r_offset] = Rela.r_addend;
804 }
805 }
806
807 unsigned AddressSize = sizeof(typename ELFFile<ELFT>::uintX_t);
808 return ELFBBAddrMapAddressExtractor(Data, AddressSize, IsRelocatable,
809 std::move(FunctionOffsetTranslations));
810 }
811
813 uint64_t Offset = Cur.tell();
815 if (!AddressOrErr)
816 return AddressOrErr.takeError();
817 if (!IsRelocatable)
818 return *AddressOrErr;
819 auto FOTIterator = FunctionOffsetTranslations.find(Offset);
820 if (FOTIterator == FunctionOffsetTranslations.end())
821 return createError("failed to get relocation data for offset: " +
823 return FOTIterator->second;
824 }
825};
826
827template <typename ELFT>
830 const typename ELFFile<ELFT>::Elf_Shdr &Sec,
831 const typename ELFFile<ELFT>::Elf_Shdr *RelaSec,
832 std::vector<PGOAnalysisMap> *PGOAnalyses) {
833 // Read and optionally decompress section contents.
834 Expected<ArrayRef<uint8_t>> ContentsOrErr = EF.getSectionContents(Sec);
835 if (!ContentsOrErr)
836 return ContentsOrErr.takeError();
837 ArrayRef<uint8_t> Content = *ContentsOrErr;
838
839 std::unique_ptr<uint8_t[]> DecompressedContent;
840 if (Sec.sh_flags & llvm::ELF::SHF_COMPRESSED) {
841 Expected<StringRef> SectionNameOrErr = EF.getSectionName(Sec);
842 if (!SectionNameOrErr)
843 return SectionNameOrErr.takeError();
844 auto DecompressorOrErr =
845 Decompressor::create(*SectionNameOrErr, toStringRef(*ContentsOrErr),
846 EF.isLE(), ELFT::Is64Bits);
847 if (!DecompressorOrErr)
848 return DecompressorOrErr.takeError();
849 size_t DecompressedSize = DecompressorOrErr->getDecompressedSize();
850 DecompressedContent = std::make_unique<uint8_t[]>(DecompressedSize);
851 MutableArrayRef<uint8_t> DecompressedContentRef(DecompressedContent.get(),
852 DecompressedSize);
853 if (Error Err = DecompressorOrErr->decompress(DecompressedContentRef))
854 return std::move(Err);
855 Content = DecompressedContentRef;
856 }
857
858 DataExtractor Data(Content, EF.isLE());
859 auto ExtractorOrErr =
861 if (!ExtractorOrErr)
862 return ExtractorOrErr.takeError();
863 auto BBAddrMapsOrErr = decodeBBAddrMapPayload(*ExtractorOrErr, PGOAnalyses);
864 if (!BBAddrMapsOrErr)
865 return createError(toString(BBAddrMapsOrErr.takeError()) + " in " +
866 describe(EF, Sec));
867 return BBAddrMapsOrErr;
868}
869
870template <class ELFT>
872ELFFile<ELFT>::decodeBBAddrMap(const Elf_Shdr &Sec, const Elf_Shdr *RelaSec,
873 std::vector<PGOAnalysisMap> *PGOAnalyses) const {
874 size_t OriginalPGOSize = PGOAnalyses ? PGOAnalyses->size() : 0;
875 auto AddrMapsOrErr = decodeBBAddrMapImpl(*this, Sec, RelaSec, PGOAnalyses);
876 // remove new analyses when an error occurs
877 if (!AddrMapsOrErr && PGOAnalyses)
878 PGOAnalyses->resize(OriginalPGOSize);
879 return std::move(AddrMapsOrErr);
880}
881
882template <class ELFT>
886 std::function<Expected<bool>(const Elf_Shdr &)> IsMatch) const {
888 Error Errors = Error::success();
889 for (const Elf_Shdr &Sec : cantFail(this->sections())) {
890 Expected<bool> DoesSectionMatch = IsMatch(Sec);
891 if (!DoesSectionMatch) {
892 Errors = joinErrors(std::move(Errors), DoesSectionMatch.takeError());
893 continue;
894 }
895 if (*DoesSectionMatch) {
896 if (SecToRelocMap.try_emplace(&Sec).second)
897 continue;
898 }
899
900 if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL &&
901 Sec.sh_type != ELF::SHT_CREL)
902 continue;
903
904 Expected<const Elf_Shdr *> RelSecOrErr = this->getSection(Sec.sh_info);
905 if (!RelSecOrErr) {
906 Errors = joinErrors(std::move(Errors),
907 createError(describe(*this, Sec) +
908 ": failed to get a relocated section: " +
909 toString(RelSecOrErr.takeError())));
910 continue;
911 }
912 const Elf_Shdr *ContentsSec = *RelSecOrErr;
913 Expected<bool> DoesRelTargetMatch = IsMatch(*ContentsSec);
914 if (!DoesRelTargetMatch) {
915 Errors = joinErrors(std::move(Errors), DoesRelTargetMatch.takeError());
916 continue;
917 }
918 if (*DoesRelTargetMatch)
919 SecToRelocMap[ContentsSec] = &Sec;
920 }
921 if(Errors)
922 return std::move(Errors);
923 return SecToRelocMap;
924}
925
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares common types and utilities for basic-block address maps.
bbsections Prepares for basic block sections
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
#define I(x, y, z)
Definition MD5.cpp:57
#define STRINGIFY_ENUM_CASE(ns, name)
Definition ELF.cpp:19
static Expected< std::vector< BBAddrMap > > decodeBBAddrMapImpl(const ELFFile< ELFT > &EF, const typename ELFFile< ELFT >::Elf_Shdr &Sec, const typename ELFFile< ELFT >::Elf_Shdr *RelaSec, std::vector< PGOAnalysisMap > *PGOAnalyses)
Definition ELF.cpp:829
Function const char TargetMachine * Machine
This file contains some functions that are useful when dealing with strings.
Expected< uint64_t > extractAddress(DataExtractor::Cursor &Cur) override
Extract and resolve an address at the current Cur position.
Definition ELF.cpp:812
static Expected< ELFBBAddrMapAddressExtractor > create(const DataExtractor &Data, const ELFFile< ELFT > &EF, const typename ELFFile< ELFT >::Elf_Shdr &Sec, const typename ELFFile< ELFT >::Elf_Shdr *RelaSec)
Definition ELF.cpp:775
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
const T * data() const
Definition ArrayRef.h:138
A class representing a position in a DataExtractor, as well as any error encountered during extractio...
uint64_t tell() const
Return the current position of this Cursor.
Error takeError()
Return error contained inside this Cursor, if any.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
virtual Expected< uint64_t > extractAddress(DataExtractor::Cursor &Cur)
Extract and resolve an address at the current Cur position.
Definition BBAddrMap.h:273
AddressExtractor(const DataExtractor &Data, unsigned AddressSize)
Definition BBAddrMap.h:265
static LLVM_ABI Expected< Decompressor > create(StringRef Name, StringRef Data, bool IsLE, bool Is64Bit)
Create decompressor object.
const Elf_Ehdr & getHeader() const
Definition ELF.h:346
Expected< std::vector< Elf_Rela > > android_relas(const Elf_Shdr &Sec) const
Definition ELF.cpp:478
std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const
Definition ELF.cpp:546
Expected< std::vector< BBAddrMap > > decodeBBAddrMap(const Elf_Shdr &Sec, const Elf_Shdr *RelaSec=nullptr, std::vector< PGOAnalysisMap > *PGOAnalyses=nullptr) const
Returns a vector of BBAddrMap structs corresponding to each function within the text section that the...
Definition ELF.cpp:872
uint32_t getRelativeRelocationType() const
Expected< ArrayRef< uint8_t > > getSectionContents(const Elf_Shdr &Sec) const
Definition ELF.h:745
Expected< Elf_Rela_Range > relas(const Elf_Shdr &Sec) const
Definition ELF.h:421
Expected< Elf_Phdr_Range > program_headers() const
Iterate over program header table.
Definition ELF.h:443
size_t getBufSize() const
Definition ELF.h:277
Expected< RelsOrRelas > decodeCrel(ArrayRef< uint8_t > Content) const
Definition ELF.cpp:438
const uint8_t * end() const
Definition ELF.h:275
Expected< uint64_t > getCrelHeader(ArrayRef< uint8_t > Content) const
Definition ELF.cpp:426
Expected< Elf_Dyn_Range > dynamicEntries() const
Definition ELF.cpp:657
const uint8_t * base() const
Definition ELF.h:274
Expected< const uint8_t * > toMappedAddr(uint64_t VAddr, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition ELF.cpp:709
Expected< Elf_Relr_Range > relrs(const Elf_Shdr &Sec) const
Definition ELF.h:429
Expected< MapVector< const Elf_Shdr *, const Elf_Shdr * > > getSectionAndRelocations(std::function< Expected< bool >(const Elf_Shdr &)> IsMatch) const
Returns a map from every section matching IsMatch to its relocation section, or nullptr if it has no ...
Definition ELF.cpp:885
bool isLE() const
Definition ELF.h:396
Expected< StringRef > getSectionName(const Elf_Shdr &Section, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition ELF.h:1437
llvm::function_ref< Error(const Twine &Msg)> WarningHandler
Definition ELF.h:272
Expected< ArrayRef< T > > getSectionContentsAsArray(const Elf_Shdr &Sec) const
Definition ELF.h:689
Expected< RelsOrRelas > crels(const Elf_Shdr &Sec) const
Definition ELF.cpp:469
std::vector< Elf_Rel > decode_relrs(Elf_Relr_Range relrs) const
Definition ELF.cpp:362
@ RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG
Definition ELF.h:1868
@ RELOCATION_GROUPED_BY_INFO_FLAG
Definition ELF.h:1867
@ RELOCATION_GROUPED_BY_ADDEND_FLAG
Definition ELF.h:1869
@ RELOCATION_GROUP_HAS_ADDEND_FLAG
Definition ELF.h:1870
@ SHF_COMPRESSED
Definition ELF.h:1126
@ ET_REL
Definition ELF.h:119
@ PT_LOAD
Definition ELF.h:1414
@ PT_DYNAMIC
Definition ELF.h:1415
@ SHT_REL
Definition ELF.h:1004
@ SHT_CREL
Definition ELF.h:1017
@ SHT_DYNAMIC
Definition ELF.h:1001
@ SHT_RELA
Definition ELF.h:999
Error decodeCrel(ArrayRef< uint8_t > Content, function_ref< void(uint64_t, bool)> HdrHandler, function_ref< void(Elf_Crel_Impl< Is64 >)> EntryHandler)
Definition ELF.h:217
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition ELF.h:607
Error createError(const Twine &Err)
Definition Error.h:86
LLVM_ABI StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type)
Definition ELF.cpp:25
LLVM_ABI uint32_t getELFRelativeRelocationType(uint32_t Machine)
Definition ELF.cpp:214
LLVM_ABI StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type)
LLVM_ABI StringRef getRISCVVendorRelocationTypeName(uint32_t Type, StringRef Vendor)
Definition ELF.cpp:201
LLVM_ABI Expected< std::vector< BBAddrMap > > decodeBBAddrMapPayload(AddressExtractor &Extractor, std::vector< PGOAnalysisMap > *PGOAnalyses=nullptr)
Decodes one BB address map section payload.
Definition BBAddrMap.cpp:47
std::string describe(const ELFFile< ELFT > &Obj, const typename ELFT::Shdr &Sec)
Definition ELF.h:147
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2081
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
StringRef toStringRef(bool B)
Construct a string ref from a boolean.