Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / Object / ELFObjectFile.cpp
blob143f9d37849d238c5ec4004cb88bab7147b2fcb2
1 //===- ELFObjectFile.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 // Part of the ELFObjectFile class implementation.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Object/ELFObjectFile.h"
14 #include "llvm/BinaryFormat/ELF.h"
15 #include "llvm/MC/MCInstrAnalysis.h"
16 #include "llvm/MC/TargetRegistry.h"
17 #include "llvm/Object/ELF.h"
18 #include "llvm/Object/ELFTypes.h"
19 #include "llvm/Object/Error.h"
20 #include "llvm/Support/ARMAttributeParser.h"
21 #include "llvm/Support/ARMBuildAttributes.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/RISCVAttributeParser.h"
25 #include "llvm/Support/RISCVAttributes.h"
26 #include "llvm/Support/RISCVISAInfo.h"
27 #include "llvm/TargetParser/SubtargetFeature.h"
28 #include "llvm/TargetParser/Triple.h"
29 #include <algorithm>
30 #include <cstddef>
31 #include <cstdint>
32 #include <memory>
33 #include <optional>
34 #include <string>
35 #include <utility>
37 using namespace llvm;
38 using namespace object;
40 const EnumEntry<unsigned> llvm::object::ElfSymbolTypes[NumElfSymbolTypes] = {
41 {"None", "NOTYPE", ELF::STT_NOTYPE},
42 {"Object", "OBJECT", ELF::STT_OBJECT},
43 {"Function", "FUNC", ELF::STT_FUNC},
44 {"Section", "SECTION", ELF::STT_SECTION},
45 {"File", "FILE", ELF::STT_FILE},
46 {"Common", "COMMON", ELF::STT_COMMON},
47 {"TLS", "TLS", ELF::STT_TLS},
48 {"Unknown", "<unknown>: 7", 7},
49 {"Unknown", "<unknown>: 8", 8},
50 {"Unknown", "<unknown>: 9", 9},
51 {"GNU_IFunc", "IFUNC", ELF::STT_GNU_IFUNC},
52 {"OS Specific", "<OS specific>: 11", 11},
53 {"OS Specific", "<OS specific>: 12", 12},
54 {"Proc Specific", "<processor specific>: 13", 13},
55 {"Proc Specific", "<processor specific>: 14", 14},
56 {"Proc Specific", "<processor specific>: 15", 15}
59 ELFObjectFileBase::ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source)
60 : ObjectFile(Type, Source) {}
62 template <class ELFT>
63 static Expected<std::unique_ptr<ELFObjectFile<ELFT>>>
64 createPtr(MemoryBufferRef Object, bool InitContent) {
65 auto Ret = ELFObjectFile<ELFT>::create(Object, InitContent);
66 if (Error E = Ret.takeError())
67 return std::move(E);
68 return std::make_unique<ELFObjectFile<ELFT>>(std::move(*Ret));
71 Expected<std::unique_ptr<ObjectFile>>
72 ObjectFile::createELFObjectFile(MemoryBufferRef Obj, bool InitContent) {
73 std::pair<unsigned char, unsigned char> Ident =
74 getElfArchType(Obj.getBuffer());
75 std::size_t MaxAlignment =
76 1ULL << llvm::countr_zero(
77 reinterpret_cast<uintptr_t>(Obj.getBufferStart()));
79 if (MaxAlignment < 2)
80 return createError("Insufficient alignment");
82 if (Ident.first == ELF::ELFCLASS32) {
83 if (Ident.second == ELF::ELFDATA2LSB)
84 return createPtr<ELF32LE>(Obj, InitContent);
85 else if (Ident.second == ELF::ELFDATA2MSB)
86 return createPtr<ELF32BE>(Obj, InitContent);
87 else
88 return createError("Invalid ELF data");
89 } else if (Ident.first == ELF::ELFCLASS64) {
90 if (Ident.second == ELF::ELFDATA2LSB)
91 return createPtr<ELF64LE>(Obj, InitContent);
92 else if (Ident.second == ELF::ELFDATA2MSB)
93 return createPtr<ELF64BE>(Obj, InitContent);
94 else
95 return createError("Invalid ELF data");
97 return createError("Invalid ELF class");
100 SubtargetFeatures ELFObjectFileBase::getMIPSFeatures() const {
101 SubtargetFeatures Features;
102 unsigned PlatformFlags = getPlatformFlags();
104 switch (PlatformFlags & ELF::EF_MIPS_ARCH) {
105 case ELF::EF_MIPS_ARCH_1:
106 break;
107 case ELF::EF_MIPS_ARCH_2:
108 Features.AddFeature("mips2");
109 break;
110 case ELF::EF_MIPS_ARCH_3:
111 Features.AddFeature("mips3");
112 break;
113 case ELF::EF_MIPS_ARCH_4:
114 Features.AddFeature("mips4");
115 break;
116 case ELF::EF_MIPS_ARCH_5:
117 Features.AddFeature("mips5");
118 break;
119 case ELF::EF_MIPS_ARCH_32:
120 Features.AddFeature("mips32");
121 break;
122 case ELF::EF_MIPS_ARCH_64:
123 Features.AddFeature("mips64");
124 break;
125 case ELF::EF_MIPS_ARCH_32R2:
126 Features.AddFeature("mips32r2");
127 break;
128 case ELF::EF_MIPS_ARCH_64R2:
129 Features.AddFeature("mips64r2");
130 break;
131 case ELF::EF_MIPS_ARCH_32R6:
132 Features.AddFeature("mips32r6");
133 break;
134 case ELF::EF_MIPS_ARCH_64R6:
135 Features.AddFeature("mips64r6");
136 break;
137 default:
138 llvm_unreachable("Unknown EF_MIPS_ARCH value");
141 switch (PlatformFlags & ELF::EF_MIPS_MACH) {
142 case ELF::EF_MIPS_MACH_NONE:
143 // No feature associated with this value.
144 break;
145 case ELF::EF_MIPS_MACH_OCTEON:
146 Features.AddFeature("cnmips");
147 break;
148 default:
149 llvm_unreachable("Unknown EF_MIPS_ARCH value");
152 if (PlatformFlags & ELF::EF_MIPS_ARCH_ASE_M16)
153 Features.AddFeature("mips16");
154 if (PlatformFlags & ELF::EF_MIPS_MICROMIPS)
155 Features.AddFeature("micromips");
157 return Features;
160 SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
161 SubtargetFeatures Features;
162 ARMAttributeParser Attributes;
163 if (Error E = getBuildAttributes(Attributes)) {
164 consumeError(std::move(E));
165 return SubtargetFeatures();
168 // both ARMv7-M and R have to support thumb hardware div
169 bool isV7 = false;
170 std::optional<unsigned> Attr =
171 Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
172 if (Attr)
173 isV7 = *Attr == ARMBuildAttrs::v7;
175 Attr = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
176 if (Attr) {
177 switch (*Attr) {
178 case ARMBuildAttrs::ApplicationProfile:
179 Features.AddFeature("aclass");
180 break;
181 case ARMBuildAttrs::RealTimeProfile:
182 Features.AddFeature("rclass");
183 if (isV7)
184 Features.AddFeature("hwdiv");
185 break;
186 case ARMBuildAttrs::MicroControllerProfile:
187 Features.AddFeature("mclass");
188 if (isV7)
189 Features.AddFeature("hwdiv");
190 break;
194 Attr = Attributes.getAttributeValue(ARMBuildAttrs::THUMB_ISA_use);
195 if (Attr) {
196 switch (*Attr) {
197 default:
198 break;
199 case ARMBuildAttrs::Not_Allowed:
200 Features.AddFeature("thumb", false);
201 Features.AddFeature("thumb2", false);
202 break;
203 case ARMBuildAttrs::AllowThumb32:
204 Features.AddFeature("thumb2");
205 break;
209 Attr = Attributes.getAttributeValue(ARMBuildAttrs::FP_arch);
210 if (Attr) {
211 switch (*Attr) {
212 default:
213 break;
214 case ARMBuildAttrs::Not_Allowed:
215 Features.AddFeature("vfp2sp", false);
216 Features.AddFeature("vfp3d16sp", false);
217 Features.AddFeature("vfp4d16sp", false);
218 break;
219 case ARMBuildAttrs::AllowFPv2:
220 Features.AddFeature("vfp2");
221 break;
222 case ARMBuildAttrs::AllowFPv3A:
223 case ARMBuildAttrs::AllowFPv3B:
224 Features.AddFeature("vfp3");
225 break;
226 case ARMBuildAttrs::AllowFPv4A:
227 case ARMBuildAttrs::AllowFPv4B:
228 Features.AddFeature("vfp4");
229 break;
233 Attr = Attributes.getAttributeValue(ARMBuildAttrs::Advanced_SIMD_arch);
234 if (Attr) {
235 switch (*Attr) {
236 default:
237 break;
238 case ARMBuildAttrs::Not_Allowed:
239 Features.AddFeature("neon", false);
240 Features.AddFeature("fp16", false);
241 break;
242 case ARMBuildAttrs::AllowNeon:
243 Features.AddFeature("neon");
244 break;
245 case ARMBuildAttrs::AllowNeon2:
246 Features.AddFeature("neon");
247 Features.AddFeature("fp16");
248 break;
252 Attr = Attributes.getAttributeValue(ARMBuildAttrs::MVE_arch);
253 if (Attr) {
254 switch (*Attr) {
255 default:
256 break;
257 case ARMBuildAttrs::Not_Allowed:
258 Features.AddFeature("mve", false);
259 Features.AddFeature("mve.fp", false);
260 break;
261 case ARMBuildAttrs::AllowMVEInteger:
262 Features.AddFeature("mve.fp", false);
263 Features.AddFeature("mve");
264 break;
265 case ARMBuildAttrs::AllowMVEIntegerAndFloat:
266 Features.AddFeature("mve.fp");
267 break;
271 Attr = Attributes.getAttributeValue(ARMBuildAttrs::DIV_use);
272 if (Attr) {
273 switch (*Attr) {
274 default:
275 break;
276 case ARMBuildAttrs::DisallowDIV:
277 Features.AddFeature("hwdiv", false);
278 Features.AddFeature("hwdiv-arm", false);
279 break;
280 case ARMBuildAttrs::AllowDIVExt:
281 Features.AddFeature("hwdiv");
282 Features.AddFeature("hwdiv-arm");
283 break;
287 return Features;
290 Expected<SubtargetFeatures> ELFObjectFileBase::getRISCVFeatures() const {
291 SubtargetFeatures Features;
292 unsigned PlatformFlags = getPlatformFlags();
294 if (PlatformFlags & ELF::EF_RISCV_RVC) {
295 Features.AddFeature("c");
298 RISCVAttributeParser Attributes;
299 if (Error E = getBuildAttributes(Attributes)) {
300 return std::move(E);
303 std::optional<StringRef> Attr =
304 Attributes.getAttributeString(RISCVAttrs::ARCH);
305 if (Attr) {
306 auto ParseResult = RISCVISAInfo::parseNormalizedArchString(*Attr);
307 if (!ParseResult)
308 return ParseResult.takeError();
309 auto &ISAInfo = *ParseResult;
311 if (ISAInfo->getXLen() == 32)
312 Features.AddFeature("64bit", false);
313 else if (ISAInfo->getXLen() == 64)
314 Features.AddFeature("64bit");
315 else
316 llvm_unreachable("XLEN should be 32 or 64.");
318 Features.addFeaturesVector(ISAInfo->toFeatureVector());
321 return Features;
324 SubtargetFeatures ELFObjectFileBase::getLoongArchFeatures() const {
325 SubtargetFeatures Features;
327 switch (getPlatformFlags() & ELF::EF_LOONGARCH_ABI_MODIFIER_MASK) {
328 case ELF::EF_LOONGARCH_ABI_SOFT_FLOAT:
329 break;
330 case ELF::EF_LOONGARCH_ABI_DOUBLE_FLOAT:
331 Features.AddFeature("d");
332 // D implies F according to LoongArch ISA spec.
333 [[fallthrough]];
334 case ELF::EF_LOONGARCH_ABI_SINGLE_FLOAT:
335 Features.AddFeature("f");
336 break;
339 return Features;
342 Expected<SubtargetFeatures> ELFObjectFileBase::getFeatures() const {
343 switch (getEMachine()) {
344 case ELF::EM_MIPS:
345 return getMIPSFeatures();
346 case ELF::EM_ARM:
347 return getARMFeatures();
348 case ELF::EM_RISCV:
349 return getRISCVFeatures();
350 case ELF::EM_LOONGARCH:
351 return getLoongArchFeatures();
352 default:
353 return SubtargetFeatures();
357 std::optional<StringRef> ELFObjectFileBase::tryGetCPUName() const {
358 switch (getEMachine()) {
359 case ELF::EM_AMDGPU:
360 return getAMDGPUCPUName();
361 case ELF::EM_PPC:
362 case ELF::EM_PPC64:
363 return StringRef("future");
364 default:
365 return std::nullopt;
369 StringRef ELFObjectFileBase::getAMDGPUCPUName() const {
370 assert(getEMachine() == ELF::EM_AMDGPU);
371 unsigned CPU = getPlatformFlags() & ELF::EF_AMDGPU_MACH;
373 switch (CPU) {
374 // Radeon HD 2000/3000 Series (R600).
375 case ELF::EF_AMDGPU_MACH_R600_R600:
376 return "r600";
377 case ELF::EF_AMDGPU_MACH_R600_R630:
378 return "r630";
379 case ELF::EF_AMDGPU_MACH_R600_RS880:
380 return "rs880";
381 case ELF::EF_AMDGPU_MACH_R600_RV670:
382 return "rv670";
384 // Radeon HD 4000 Series (R700).
385 case ELF::EF_AMDGPU_MACH_R600_RV710:
386 return "rv710";
387 case ELF::EF_AMDGPU_MACH_R600_RV730:
388 return "rv730";
389 case ELF::EF_AMDGPU_MACH_R600_RV770:
390 return "rv770";
392 // Radeon HD 5000 Series (Evergreen).
393 case ELF::EF_AMDGPU_MACH_R600_CEDAR:
394 return "cedar";
395 case ELF::EF_AMDGPU_MACH_R600_CYPRESS:
396 return "cypress";
397 case ELF::EF_AMDGPU_MACH_R600_JUNIPER:
398 return "juniper";
399 case ELF::EF_AMDGPU_MACH_R600_REDWOOD:
400 return "redwood";
401 case ELF::EF_AMDGPU_MACH_R600_SUMO:
402 return "sumo";
404 // Radeon HD 6000 Series (Northern Islands).
405 case ELF::EF_AMDGPU_MACH_R600_BARTS:
406 return "barts";
407 case ELF::EF_AMDGPU_MACH_R600_CAICOS:
408 return "caicos";
409 case ELF::EF_AMDGPU_MACH_R600_CAYMAN:
410 return "cayman";
411 case ELF::EF_AMDGPU_MACH_R600_TURKS:
412 return "turks";
414 // AMDGCN GFX6.
415 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX600:
416 return "gfx600";
417 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX601:
418 return "gfx601";
419 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX602:
420 return "gfx602";
422 // AMDGCN GFX7.
423 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX700:
424 return "gfx700";
425 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX701:
426 return "gfx701";
427 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX702:
428 return "gfx702";
429 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX703:
430 return "gfx703";
431 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX704:
432 return "gfx704";
433 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX705:
434 return "gfx705";
436 // AMDGCN GFX8.
437 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX801:
438 return "gfx801";
439 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX802:
440 return "gfx802";
441 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX803:
442 return "gfx803";
443 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX805:
444 return "gfx805";
445 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX810:
446 return "gfx810";
448 // AMDGCN GFX9.
449 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX900:
450 return "gfx900";
451 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX902:
452 return "gfx902";
453 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX904:
454 return "gfx904";
455 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX906:
456 return "gfx906";
457 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX908:
458 return "gfx908";
459 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX909:
460 return "gfx909";
461 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX90A:
462 return "gfx90a";
463 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX90C:
464 return "gfx90c";
465 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX940:
466 return "gfx940";
467 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX941:
468 return "gfx941";
469 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX942:
470 return "gfx942";
472 // AMDGCN GFX10.
473 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1010:
474 return "gfx1010";
475 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1011:
476 return "gfx1011";
477 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1012:
478 return "gfx1012";
479 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1013:
480 return "gfx1013";
481 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1030:
482 return "gfx1030";
483 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1031:
484 return "gfx1031";
485 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1032:
486 return "gfx1032";
487 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1033:
488 return "gfx1033";
489 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1034:
490 return "gfx1034";
491 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1035:
492 return "gfx1035";
493 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1036:
494 return "gfx1036";
496 // AMDGCN GFX11.
497 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1100:
498 return "gfx1100";
499 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1101:
500 return "gfx1101";
501 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1102:
502 return "gfx1102";
503 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1103:
504 return "gfx1103";
505 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1150:
506 return "gfx1150";
507 case ELF::EF_AMDGPU_MACH_AMDGCN_GFX1151:
508 return "gfx1151";
509 default:
510 llvm_unreachable("Unknown EF_AMDGPU_MACH value");
514 // FIXME Encode from a tablegen description or target parser.
515 void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const {
516 if (TheTriple.getSubArch() != Triple::NoSubArch)
517 return;
519 ARMAttributeParser Attributes;
520 if (Error E = getBuildAttributes(Attributes)) {
521 // TODO Propagate Error.
522 consumeError(std::move(E));
523 return;
526 std::string Triple;
527 // Default to ARM, but use the triple if it's been set.
528 if (TheTriple.isThumb())
529 Triple = "thumb";
530 else
531 Triple = "arm";
533 std::optional<unsigned> Attr =
534 Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
535 if (Attr) {
536 switch (*Attr) {
537 case ARMBuildAttrs::v4:
538 Triple += "v4";
539 break;
540 case ARMBuildAttrs::v4T:
541 Triple += "v4t";
542 break;
543 case ARMBuildAttrs::v5T:
544 Triple += "v5t";
545 break;
546 case ARMBuildAttrs::v5TE:
547 Triple += "v5te";
548 break;
549 case ARMBuildAttrs::v5TEJ:
550 Triple += "v5tej";
551 break;
552 case ARMBuildAttrs::v6:
553 Triple += "v6";
554 break;
555 case ARMBuildAttrs::v6KZ:
556 Triple += "v6kz";
557 break;
558 case ARMBuildAttrs::v6T2:
559 Triple += "v6t2";
560 break;
561 case ARMBuildAttrs::v6K:
562 Triple += "v6k";
563 break;
564 case ARMBuildAttrs::v7: {
565 std::optional<unsigned> ArchProfileAttr =
566 Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
567 if (ArchProfileAttr &&
568 *ArchProfileAttr == ARMBuildAttrs::MicroControllerProfile)
569 Triple += "v7m";
570 else
571 Triple += "v7";
572 break;
574 case ARMBuildAttrs::v6_M:
575 Triple += "v6m";
576 break;
577 case ARMBuildAttrs::v6S_M:
578 Triple += "v6sm";
579 break;
580 case ARMBuildAttrs::v7E_M:
581 Triple += "v7em";
582 break;
583 case ARMBuildAttrs::v8_A:
584 Triple += "v8a";
585 break;
586 case ARMBuildAttrs::v8_R:
587 Triple += "v8r";
588 break;
589 case ARMBuildAttrs::v8_M_Base:
590 Triple += "v8m.base";
591 break;
592 case ARMBuildAttrs::v8_M_Main:
593 Triple += "v8m.main";
594 break;
595 case ARMBuildAttrs::v8_1_M_Main:
596 Triple += "v8.1m.main";
597 break;
598 case ARMBuildAttrs::v9_A:
599 Triple += "v9a";
600 break;
603 if (!isLittleEndian())
604 Triple += "eb";
606 TheTriple.setArchName(Triple);
609 std::vector<ELFPltEntry> ELFObjectFileBase::getPltEntries() const {
610 std::string Err;
611 const auto Triple = makeTriple();
612 const auto *T = TargetRegistry::lookupTarget(Triple.str(), Err);
613 if (!T)
614 return {};
615 uint32_t JumpSlotReloc = 0, GlobDatReloc = 0;
616 switch (Triple.getArch()) {
617 case Triple::x86:
618 JumpSlotReloc = ELF::R_386_JUMP_SLOT;
619 GlobDatReloc = ELF::R_386_GLOB_DAT;
620 break;
621 case Triple::x86_64:
622 JumpSlotReloc = ELF::R_X86_64_JUMP_SLOT;
623 GlobDatReloc = ELF::R_X86_64_GLOB_DAT;
624 break;
625 case Triple::aarch64:
626 case Triple::aarch64_be:
627 JumpSlotReloc = ELF::R_AARCH64_JUMP_SLOT;
628 break;
629 default:
630 return {};
632 std::unique_ptr<const MCInstrInfo> MII(T->createMCInstrInfo());
633 std::unique_ptr<const MCInstrAnalysis> MIA(
634 T->createMCInstrAnalysis(MII.get()));
635 if (!MIA)
636 return {};
637 std::vector<std::pair<uint64_t, uint64_t>> PltEntries;
638 std::optional<SectionRef> RelaPlt, RelaDyn;
639 uint64_t GotBaseVA = 0;
640 for (const SectionRef &Section : sections()) {
641 Expected<StringRef> NameOrErr = Section.getName();
642 if (!NameOrErr) {
643 consumeError(NameOrErr.takeError());
644 continue;
646 StringRef Name = *NameOrErr;
648 if (Name == ".rela.plt" || Name == ".rel.plt") {
649 RelaPlt = Section;
650 } else if (Name == ".rela.dyn" || Name == ".rel.dyn") {
651 RelaDyn = Section;
652 } else if (Name == ".got.plt") {
653 GotBaseVA = Section.getAddress();
654 } else if (Name == ".plt" || Name == ".plt.got") {
655 Expected<StringRef> PltContents = Section.getContents();
656 if (!PltContents) {
657 consumeError(PltContents.takeError());
658 return {};
660 llvm::append_range(
661 PltEntries,
662 MIA->findPltEntries(Section.getAddress(),
663 arrayRefFromStringRef(*PltContents), Triple));
667 // Build a map from GOT entry virtual address to PLT entry virtual address.
668 DenseMap<uint64_t, uint64_t> GotToPlt;
669 for (auto [Plt, GotPlt] : PltEntries) {
670 uint64_t GotPltEntry = GotPlt;
671 // An x86-32 PIC PLT uses jmp DWORD PTR [ebx-offset]. Add
672 // _GLOBAL_OFFSET_TABLE_ (EBX) to get the .got.plt (or .got) entry address.
673 // See X86MCTargetDesc.cpp:findPltEntries for the 1 << 32 bit.
674 if (GotPltEntry & (uint64_t(1) << 32) && getEMachine() == ELF::EM_386)
675 GotPltEntry = static_cast<int32_t>(GotPltEntry) + GotBaseVA;
676 GotToPlt.insert(std::make_pair(GotPltEntry, Plt));
679 // Find the relocations in the dynamic relocation table that point to
680 // locations in the GOT for which we know the corresponding PLT entry.
681 std::vector<ELFPltEntry> Result;
682 auto handleRels = [&](iterator_range<relocation_iterator> Rels,
683 uint32_t RelType, StringRef PltSec) {
684 for (const auto &R : Rels) {
685 if (R.getType() != RelType)
686 continue;
687 auto PltEntryIter = GotToPlt.find(R.getOffset());
688 if (PltEntryIter != GotToPlt.end()) {
689 symbol_iterator Sym = R.getSymbol();
690 if (Sym == symbol_end())
691 Result.push_back(
692 ELFPltEntry{PltSec, std::nullopt, PltEntryIter->second});
693 else
694 Result.push_back(ELFPltEntry{PltSec, Sym->getRawDataRefImpl(),
695 PltEntryIter->second});
700 if (RelaPlt)
701 handleRels(RelaPlt->relocations(), JumpSlotReloc, ".plt");
703 // If a symbol needing a PLT entry also needs a GLOB_DAT relocation, GNU ld's
704 // x86 port places the PLT entry in the .plt.got section.
705 if (RelaDyn)
706 handleRels(RelaDyn->relocations(), GlobDatReloc, ".plt.got");
708 return Result;
711 template <class ELFT>
712 Expected<std::vector<BBAddrMap>> static readBBAddrMapImpl(
713 const ELFFile<ELFT> &EF, std::optional<unsigned> TextSectionIndex) {
714 using Elf_Shdr = typename ELFT::Shdr;
715 bool IsRelocatable = EF.getHeader().e_type == ELF::ET_REL;
716 std::vector<BBAddrMap> BBAddrMaps;
718 const auto &Sections = cantFail(EF.sections());
719 auto IsMatch = [&](const Elf_Shdr &Sec) -> Expected<bool> {
720 if (Sec.sh_type != ELF::SHT_LLVM_BB_ADDR_MAP &&
721 Sec.sh_type != ELF::SHT_LLVM_BB_ADDR_MAP_V0)
722 return false;
723 if (!TextSectionIndex)
724 return true;
725 Expected<const Elf_Shdr *> TextSecOrErr = EF.getSection(Sec.sh_link);
726 if (!TextSecOrErr)
727 return createError("unable to get the linked-to section for " +
728 describe(EF, Sec) + ": " +
729 toString(TextSecOrErr.takeError()));
730 if (*TextSectionIndex != std::distance(Sections.begin(), *TextSecOrErr))
731 return false;
732 return true;
735 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SectionRelocMapOrErr =
736 EF.getSectionAndRelocations(IsMatch);
737 if (!SectionRelocMapOrErr)
738 return SectionRelocMapOrErr.takeError();
740 for (auto const &[Sec, RelocSec] : *SectionRelocMapOrErr) {
741 if (IsRelocatable && !RelocSec)
742 return createError("unable to get relocation section for " +
743 describe(EF, *Sec));
744 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
745 EF.decodeBBAddrMap(*Sec, RelocSec);
746 if (!BBAddrMapOrErr)
747 return createError("unable to read " + describe(EF, *Sec) + ": " +
748 toString(BBAddrMapOrErr.takeError()));
749 std::move(BBAddrMapOrErr->begin(), BBAddrMapOrErr->end(),
750 std::back_inserter(BBAddrMaps));
752 return BBAddrMaps;
755 template <class ELFT>
756 static Expected<std::vector<VersionEntry>>
757 readDynsymVersionsImpl(const ELFFile<ELFT> &EF,
758 ELFObjectFileBase::elf_symbol_iterator_range Symbols) {
759 using Elf_Shdr = typename ELFT::Shdr;
760 const Elf_Shdr *VerSec = nullptr;
761 const Elf_Shdr *VerNeedSec = nullptr;
762 const Elf_Shdr *VerDefSec = nullptr;
763 // The user should ensure sections() can't fail here.
764 for (const Elf_Shdr &Sec : cantFail(EF.sections())) {
765 if (Sec.sh_type == ELF::SHT_GNU_versym)
766 VerSec = &Sec;
767 else if (Sec.sh_type == ELF::SHT_GNU_verdef)
768 VerDefSec = &Sec;
769 else if (Sec.sh_type == ELF::SHT_GNU_verneed)
770 VerNeedSec = &Sec;
772 if (!VerSec)
773 return std::vector<VersionEntry>();
775 Expected<SmallVector<std::optional<VersionEntry>, 0>> MapOrErr =
776 EF.loadVersionMap(VerNeedSec, VerDefSec);
777 if (!MapOrErr)
778 return MapOrErr.takeError();
780 std::vector<VersionEntry> Ret;
781 size_t I = 0;
782 for (const ELFSymbolRef &Sym : Symbols) {
783 ++I;
784 Expected<const typename ELFT::Versym *> VerEntryOrErr =
785 EF.template getEntry<typename ELFT::Versym>(*VerSec, I);
786 if (!VerEntryOrErr)
787 return createError("unable to read an entry with index " + Twine(I) +
788 " from " + describe(EF, *VerSec) + ": " +
789 toString(VerEntryOrErr.takeError()));
791 Expected<uint32_t> FlagsOrErr = Sym.getFlags();
792 if (!FlagsOrErr)
793 return createError("unable to read flags for symbol with index " +
794 Twine(I) + ": " + toString(FlagsOrErr.takeError()));
796 bool IsDefault;
797 Expected<StringRef> VerOrErr = EF.getSymbolVersionByIndex(
798 (*VerEntryOrErr)->vs_index, IsDefault, *MapOrErr,
799 (*FlagsOrErr) & SymbolRef::SF_Undefined);
800 if (!VerOrErr)
801 return createError("unable to get a version for entry " + Twine(I) +
802 " of " + describe(EF, *VerSec) + ": " +
803 toString(VerOrErr.takeError()));
805 Ret.push_back({(*VerOrErr).str(), IsDefault});
808 return Ret;
811 Expected<std::vector<VersionEntry>>
812 ELFObjectFileBase::readDynsymVersions() const {
813 elf_symbol_iterator_range Symbols = getDynamicSymbolIterators();
814 if (const auto *Obj = dyn_cast<ELF32LEObjectFile>(this))
815 return readDynsymVersionsImpl(Obj->getELFFile(), Symbols);
816 if (const auto *Obj = dyn_cast<ELF32BEObjectFile>(this))
817 return readDynsymVersionsImpl(Obj->getELFFile(), Symbols);
818 if (const auto *Obj = dyn_cast<ELF64LEObjectFile>(this))
819 return readDynsymVersionsImpl(Obj->getELFFile(), Symbols);
820 return readDynsymVersionsImpl(cast<ELF64BEObjectFile>(this)->getELFFile(),
821 Symbols);
824 Expected<std::vector<BBAddrMap>> ELFObjectFileBase::readBBAddrMap(
825 std::optional<unsigned> TextSectionIndex) const {
826 if (const auto *Obj = dyn_cast<ELF32LEObjectFile>(this))
827 return readBBAddrMapImpl(Obj->getELFFile(), TextSectionIndex);
828 if (const auto *Obj = dyn_cast<ELF64LEObjectFile>(this))
829 return readBBAddrMapImpl(Obj->getELFFile(), TextSectionIndex);
830 if (const auto *Obj = dyn_cast<ELF32BEObjectFile>(this))
831 return readBBAddrMapImpl(Obj->getELFFile(), TextSectionIndex);
832 return readBBAddrMapImpl(cast<ELF64BEObjectFile>(this)->getELFFile(),
833 TextSectionIndex);