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.
10//
11//===----------------------------------------------------------------------===//
12
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/HexagonAttributeParser.h"
24#include "llvm/Support/RISCVAttributeParser.h"
25#include "llvm/Support/RISCVAttributes.h"
26#include "llvm/TargetParser/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>
36
37using namespace llvm;
38using namespace object;
39
40const 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}
57};
58
59ELFObjectFileBase::ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source)
60 : ObjectFile(Type, Source) {}
61
62template <class ELFT>
63static Expected<std::unique_ptr<ELFObjectFile<ELFT>>>
64createPtr(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));
69}
70
71Expected<std::unique_ptr<ObjectFile>>
72ObjectFile::createELFObjectFile(MemoryBufferRef Obj, bool InitContent) {
73 std::pair<unsigned char, unsigned char> Ident =
74 getElfArchType(Object: Obj.getBuffer());
75 std::size_t MaxAlignment =
76 1ULL << llvm::countr_zero(
77 Val: reinterpret_cast<uintptr_t>(Obj.getBufferStart()));
78
79 if (MaxAlignment < 2)
80 return createError(Err: "Insufficient alignment");
81
82 if (Ident.first == ELF::ELFCLASS32) {
83 if (Ident.second == ELF::ELFDATA2LSB)
84 return createPtr<ELF32LE>(Object: Obj, InitContent);
85 else if (Ident.second == ELF::ELFDATA2MSB)
86 return createPtr<ELF32BE>(Object: Obj, InitContent);
87 else
88 return createError(Err: "Invalid ELF data");
89 } else if (Ident.first == ELF::ELFCLASS64) {
90 if (Ident.second == ELF::ELFDATA2LSB)
91 return createPtr<ELF64LE>(Object: Obj, InitContent);
92 else if (Ident.second == ELF::ELFDATA2MSB)
93 return createPtr<ELF64BE>(Object: Obj, InitContent);
94 else
95 return createError(Err: "Invalid ELF data");
96 }
97 return createError(Err: "Invalid ELF class");
98}
99
100SubtargetFeatures ELFObjectFileBase::getMIPSFeatures() const {
101 SubtargetFeatures Features;
102 unsigned PlatformFlags = getPlatformFlags();
103
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(String: "mips2");
109 break;
110 case ELF::EF_MIPS_ARCH_3:
111 Features.AddFeature(String: "mips3");
112 break;
113 case ELF::EF_MIPS_ARCH_4:
114 Features.AddFeature(String: "mips4");
115 break;
116 case ELF::EF_MIPS_ARCH_5:
117 Features.AddFeature(String: "mips5");
118 break;
119 case ELF::EF_MIPS_ARCH_32:
120 Features.AddFeature(String: "mips32");
121 break;
122 case ELF::EF_MIPS_ARCH_64:
123 Features.AddFeature(String: "mips64");
124 break;
125 case ELF::EF_MIPS_ARCH_32R2:
126 Features.AddFeature(String: "mips32r2");
127 break;
128 case ELF::EF_MIPS_ARCH_64R2:
129 Features.AddFeature(String: "mips64r2");
130 break;
131 case ELF::EF_MIPS_ARCH_32R6:
132 Features.AddFeature(String: "mips32r6");
133 break;
134 case ELF::EF_MIPS_ARCH_64R6:
135 Features.AddFeature(String: "mips64r6");
136 break;
137 default:
138 llvm_unreachable("Unknown EF_MIPS_ARCH value");
139 }
140
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(String: "cnmips");
147 break;
148 default:
149 llvm_unreachable("Unknown EF_MIPS_ARCH value");
150 }
151
152 if (PlatformFlags & ELF::EF_MIPS_ARCH_ASE_M16)
153 Features.AddFeature(String: "mips16");
154 if (PlatformFlags & ELF::EF_MIPS_MICROMIPS)
155 Features.AddFeature(String: "micromips");
156
157 return Features;
158}
159
160SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
161 SubtargetFeatures Features;
162 ARMAttributeParser Attributes;
163 if (Error E = getBuildAttributes(Attributes)) {
164 consumeError(Err: std::move(E));
165 return SubtargetFeatures();
166 }
167
168 // both ARMv7-M and R have to support thumb hardware div
169 bool isV7 = false;
170 std::optional<unsigned> Attr =
171 Attributes.getAttributeValue(tag: ARMBuildAttrs::CPU_arch);
172 if (Attr)
173 isV7 = *Attr == ARMBuildAttrs::v7;
174
175 Attr = Attributes.getAttributeValue(tag: ARMBuildAttrs::CPU_arch_profile);
176 if (Attr) {
177 switch (*Attr) {
178 case ARMBuildAttrs::ApplicationProfile:
179 Features.AddFeature(String: "aclass");
180 break;
181 case ARMBuildAttrs::RealTimeProfile:
182 Features.AddFeature(String: "rclass");
183 if (isV7)
184 Features.AddFeature(String: "hwdiv");
185 break;
186 case ARMBuildAttrs::MicroControllerProfile:
187 Features.AddFeature(String: "mclass");
188 if (isV7)
189 Features.AddFeature(String: "hwdiv");
190 break;
191 }
192 }
193
194 Attr = Attributes.getAttributeValue(tag: ARMBuildAttrs::THUMB_ISA_use);
195 if (Attr) {
196 switch (*Attr) {
197 default:
198 break;
199 case ARMBuildAttrs::Not_Allowed:
200 Features.AddFeature(String: "thumb", Enable: false);
201 Features.AddFeature(String: "thumb2", Enable: false);
202 break;
203 case ARMBuildAttrs::AllowThumb32:
204 Features.AddFeature(String: "thumb2");
205 break;
206 }
207 }
208
209 Attr = Attributes.getAttributeValue(tag: ARMBuildAttrs::FP_arch);
210 if (Attr) {
211 switch (*Attr) {
212 default:
213 break;
214 case ARMBuildAttrs::Not_Allowed:
215 Features.AddFeature(String: "vfp2sp", Enable: false);
216 Features.AddFeature(String: "vfp3d16sp", Enable: false);
217 Features.AddFeature(String: "vfp4d16sp", Enable: false);
218 break;
219 case ARMBuildAttrs::AllowFPv2:
220 Features.AddFeature(String: "vfp2");
221 break;
222 case ARMBuildAttrs::AllowFPv3A:
223 case ARMBuildAttrs::AllowFPv3B:
224 Features.AddFeature(String: "vfp3");
225 break;
226 case ARMBuildAttrs::AllowFPv4A:
227 case ARMBuildAttrs::AllowFPv4B:
228 Features.AddFeature(String: "vfp4");
229 break;
230 }
231 }
232
233 Attr = Attributes.getAttributeValue(tag: ARMBuildAttrs::Advanced_SIMD_arch);
234 if (Attr) {
235 switch (*Attr) {
236 default:
237 break;
238 case ARMBuildAttrs::Not_Allowed:
239 Features.AddFeature(String: "neon", Enable: false);
240 Features.AddFeature(String: "fp16", Enable: false);
241 break;
242 case ARMBuildAttrs::AllowNeon:
243 Features.AddFeature(String: "neon");
244 break;
245 case ARMBuildAttrs::AllowNeon2:
246 Features.AddFeature(String: "neon");
247 Features.AddFeature(String: "fp16");
248 break;
249 }
250 }
251
252 Attr = Attributes.getAttributeValue(tag: ARMBuildAttrs::MVE_arch);
253 if (Attr) {
254 switch (*Attr) {
255 default:
256 break;
257 case ARMBuildAttrs::Not_Allowed:
258 Features.AddFeature(String: "mve", Enable: false);
259 Features.AddFeature(String: "mve.fp", Enable: false);
260 break;
261 case ARMBuildAttrs::AllowMVEInteger:
262 Features.AddFeature(String: "mve.fp", Enable: false);
263 Features.AddFeature(String: "mve");
264 break;
265 case ARMBuildAttrs::AllowMVEIntegerAndFloat:
266 Features.AddFeature(String: "mve.fp");
267 break;
268 }
269 }
270
271 Attr = Attributes.getAttributeValue(tag: ARMBuildAttrs::DIV_use);
272 if (Attr) {
273 switch (*Attr) {
274 default:
275 break;
276 case ARMBuildAttrs::DisallowDIV:
277 Features.AddFeature(String: "hwdiv", Enable: false);
278 Features.AddFeature(String: "hwdiv-arm", Enable: false);
279 break;
280 case ARMBuildAttrs::AllowDIVExt:
281 Features.AddFeature(String: "hwdiv");
282 Features.AddFeature(String: "hwdiv-arm");
283 break;
284 }
285 }
286
287 return Features;
288}
289
290static std::optional<std::string> hexagonAttrToFeatureString(unsigned Attr) {
291 switch (Attr) {
292 case 5:
293 return "v5";
294 case 55:
295 return "v55";
296 case 60:
297 return "v60";
298 case 62:
299 return "v62";
300 case 65:
301 return "v65";
302 case 67:
303 return "v67";
304 case 68:
305 return "v68";
306 case 69:
307 return "v69";
308 case 71:
309 return "v71";
310 case 73:
311 return "v73";
312 case 75:
313 return "v75";
314 case 79:
315 return "v79";
316 case 81:
317 return "v81";
318 default:
319 return {};
320 }
321}
322
323SubtargetFeatures ELFObjectFileBase::getHexagonFeatures() const {
324 SubtargetFeatures Features;
325 HexagonAttributeParser Parser;
326 if (Error E = getBuildAttributes(Attributes&: Parser)) {
327 // Return no attributes if none can be read.
328 // This behavior is important for backwards compatibility.
329 consumeError(Err: std::move(E));
330 return Features;
331 }
332 std::optional<unsigned> Attr;
333
334 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::ARCH))) {
335 if (std::optional<std::string> FeatureString =
336 hexagonAttrToFeatureString(Attr: *Attr))
337 Features.AddFeature(String: *FeatureString);
338 }
339
340 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::HVXARCH))) {
341 std::optional<std::string> FeatureString =
342 hexagonAttrToFeatureString(Attr: *Attr);
343 // There is no corresponding hvx arch for v5 and v55.
344 if (FeatureString && *Attr >= 60)
345 Features.AddFeature(String: "hvx" + *FeatureString);
346 }
347
348 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::HVXIEEEFP)))
349 if (*Attr)
350 Features.AddFeature(String: "hvx-ieee-fp");
351
352 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::HVXQFLOAT)))
353 if (*Attr)
354 Features.AddFeature(String: "hvx-qfloat");
355
356 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::ZREG)))
357 if (*Attr)
358 Features.AddFeature(String: "zreg");
359
360 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::AUDIO)))
361 if (*Attr)
362 Features.AddFeature(String: "audio");
363
364 if ((Attr = Parser.getAttributeValue(tag: HexagonAttrs::CABAC)))
365 if (*Attr)
366 Features.AddFeature(String: "cabac");
367
368 return Features;
369}
370
371Expected<SubtargetFeatures> ELFObjectFileBase::getRISCVFeatures() const {
372 SubtargetFeatures Features;
373 unsigned PlatformFlags = getPlatformFlags();
374
375 if (PlatformFlags & ELF::EF_RISCV_RVC) {
376 Features.AddFeature(String: "zca");
377 }
378
379 RISCVAttributeParser Attributes;
380 if (Error E = getBuildAttributes(Attributes)) {
381 return std::move(E);
382 }
383
384 std::optional<StringRef> Attr =
385 Attributes.getAttributeString(tag: RISCVAttrs::ARCH);
386 if (Attr) {
387 auto ParseResult = RISCVISAInfo::parseNormalizedArchString(Arch: *Attr);
388 if (!ParseResult)
389 return ParseResult.takeError();
390 auto &ISAInfo = *ParseResult;
391
392 if (ISAInfo->getXLen() == 32)
393 Features.AddFeature(String: "64bit", Enable: false);
394 else if (ISAInfo->getXLen() == 64)
395 Features.AddFeature(String: "64bit");
396 else
397 llvm_unreachable("XLEN should be 32 or 64.");
398
399 Features.addFeaturesVector(OtherFeatures: ISAInfo->toFeatures());
400 }
401
402 return Features;
403}
404
405SubtargetFeatures ELFObjectFileBase::getLoongArchFeatures() const {
406 SubtargetFeatures Features;
407
408 switch (getPlatformFlags() & ELF::EF_LOONGARCH_ABI_MODIFIER_MASK) {
409 case ELF::EF_LOONGARCH_ABI_SOFT_FLOAT:
410 break;
411 case ELF::EF_LOONGARCH_ABI_DOUBLE_FLOAT:
412 Features.AddFeature(String: "d");
413 // D implies F according to LoongArch ISA spec.
414 [[fallthrough]];
415 case ELF::EF_LOONGARCH_ABI_SINGLE_FLOAT:
416 Features.AddFeature(String: "f");
417 break;
418 }
419
420 return Features;
421}
422
423Expected<SubtargetFeatures> ELFObjectFileBase::getFeatures() const {
424 switch (getEMachine()) {
425 case ELF::EM_MIPS:
426 return getMIPSFeatures();
427 case ELF::EM_ARM:
428 return getARMFeatures();
429 case ELF::EM_RISCV:
430 return getRISCVFeatures();
431 case ELF::EM_LOONGARCH:
432 return getLoongArchFeatures();
433 case ELF::EM_HEXAGON:
434 return getHexagonFeatures();
435 default:
436 return SubtargetFeatures();
437 }
438}
439
440std::optional<StringRef> ELFObjectFileBase::tryGetCPUName() const {
441 switch (getEMachine()) {
442 case ELF::EM_AMDGPU:
443 return getAMDGPUCPUName();
444 case ELF::EM_CUDA:
445 return getNVPTXCPUName();
446 case ELF::EM_PPC:
447 case ELF::EM_PPC64:
448 return StringRef("future");
449 case ELF::EM_BPF:
450 return StringRef("v4");
451 default:
452 return std::nullopt;
453 }
454}
455
456StringRef ELFObjectFileBase::getAMDGPUCPUName() const {
457 assert(getEMachine() == ELF::EM_AMDGPU);
458 unsigned CPU = getPlatformFlags() & ELF::EF_AMDGPU_MACH;
459
460 switch (CPU) {
461#define X(NUM, ENUM, NAME) \
462 case ELF::ENUM: \
463 return NAME;
464 AMDGPU_MACH_LIST(X)
465#undef X
466
467 default:
468 llvm_unreachable("Unknown EF_AMDGPU_MACH value");
469 }
470}
471
472StringRef ELFObjectFileBase::getNVPTXCPUName() const {
473 assert(getEMachine() == ELF::EM_CUDA);
474 unsigned SM = getEIdentABIVersion() == ELF::ELFABIVERSION_CUDA_V1
475 ? getPlatformFlags() & ELF::EF_CUDA_SM
476 : (getPlatformFlags() & ELF::EF_CUDA_SM_MASK) >>
477 ELF::EF_CUDA_SM_OFFSET;
478
479 switch (SM) {
480 // Fermi architecture.
481 case ELF::EF_CUDA_SM20:
482 return "sm_20";
483 case ELF::EF_CUDA_SM21:
484 return "sm_21";
485
486 // Kepler architecture.
487 case ELF::EF_CUDA_SM30:
488 return "sm_30";
489 case ELF::EF_CUDA_SM32:
490 return "sm_32";
491 case ELF::EF_CUDA_SM35:
492 return "sm_35";
493 case ELF::EF_CUDA_SM37:
494 return "sm_37";
495
496 // Maxwell architecture.
497 case ELF::EF_CUDA_SM50:
498 return "sm_50";
499 case ELF::EF_CUDA_SM52:
500 return "sm_52";
501 case ELF::EF_CUDA_SM53:
502 return "sm_53";
503
504 // Pascal architecture.
505 case ELF::EF_CUDA_SM60:
506 return "sm_60";
507 case ELF::EF_CUDA_SM61:
508 return "sm_61";
509 case ELF::EF_CUDA_SM62:
510 return "sm_62";
511
512 // Volta architecture.
513 case ELF::EF_CUDA_SM70:
514 return "sm_70";
515 case ELF::EF_CUDA_SM72:
516 return "sm_72";
517
518 // Turing architecture.
519 case ELF::EF_CUDA_SM75:
520 return "sm_75";
521
522 // Ampere architecture.
523 case ELF::EF_CUDA_SM80:
524 return "sm_80";
525 case ELF::EF_CUDA_SM86:
526 return "sm_86";
527 case ELF::EF_CUDA_SM87:
528 return "sm_87";
529 case ELF::EF_CUDA_SM88:
530 return "sm_88";
531
532 // Ada architecture.
533 case ELF::EF_CUDA_SM89:
534 return "sm_89";
535
536 // Hopper architecture.
537 case ELF::EF_CUDA_SM90:
538 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS_V1 ? "sm_90a"
539 : "sm_90";
540
541 // Blackwell architecture.
542 case ELF::EF_CUDA_SM100:
543 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS ? "sm_100a"
544 : "sm_100";
545 case ELF::EF_CUDA_SM101:
546 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS ? "sm_101a"
547 : "sm_101";
548 case ELF::EF_CUDA_SM103:
549 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS ? "sm_103a"
550 : "sm_103";
551 case ELF::EF_CUDA_SM110:
552 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS ? "sm_110a"
553 : "sm_110";
554
555 // Rubin architecture.
556 case ELF::EF_CUDA_SM120:
557 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS ? "sm_120a"
558 : "sm_120";
559 case ELF::EF_CUDA_SM121:
560 return getPlatformFlags() & ELF::EF_CUDA_ACCELERATORS ? "sm_121a"
561 : "sm_121";
562 default:
563 llvm_unreachable("Unknown EF_CUDA_SM value");
564 }
565}
566
567// FIXME Encode from a tablegen description or target parser.
568void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const {
569 if (TheTriple.getSubArch() != Triple::NoSubArch)
570 return;
571
572 ARMAttributeParser Attributes;
573 if (Error E = getBuildAttributes(Attributes)) {
574 // TODO Propagate Error.
575 consumeError(Err: std::move(E));
576 return;
577 }
578
579 std::string Triple;
580 // Default to ARM, but use the triple if it's been set.
581 if (TheTriple.isThumb())
582 Triple = "thumb";
583 else
584 Triple = "arm";
585
586 std::optional<unsigned> Attr =
587 Attributes.getAttributeValue(tag: ARMBuildAttrs::CPU_arch);
588 if (Attr) {
589 switch (*Attr) {
590 case ARMBuildAttrs::v4:
591 Triple += "v4";
592 break;
593 case ARMBuildAttrs::v4T:
594 Triple += "v4t";
595 break;
596 case ARMBuildAttrs::v5T:
597 Triple += "v5t";
598 break;
599 case ARMBuildAttrs::v5TE:
600 Triple += "v5te";
601 break;
602 case ARMBuildAttrs::v5TEJ:
603 Triple += "v5tej";
604 break;
605 case ARMBuildAttrs::v6:
606 Triple += "v6";
607 break;
608 case ARMBuildAttrs::v6KZ:
609 Triple += "v6kz";
610 break;
611 case ARMBuildAttrs::v6T2:
612 Triple += "v6t2";
613 break;
614 case ARMBuildAttrs::v6K:
615 Triple += "v6k";
616 break;
617 case ARMBuildAttrs::v7: {
618 std::optional<unsigned> ArchProfileAttr =
619 Attributes.getAttributeValue(tag: ARMBuildAttrs::CPU_arch_profile);
620 if (ArchProfileAttr == ARMBuildAttrs::MicroControllerProfile)
621 Triple += "v7m";
622 else
623 Triple += "v7";
624 break;
625 }
626 case ARMBuildAttrs::v6_M:
627 Triple += "v6m";
628 break;
629 case ARMBuildAttrs::v6S_M:
630 Triple += "v6sm";
631 break;
632 case ARMBuildAttrs::v7E_M:
633 Triple += "v7em";
634 break;
635 case ARMBuildAttrs::v8_A:
636 Triple += "v8a";
637 break;
638 case ARMBuildAttrs::v8_R:
639 Triple += "v8r";
640 break;
641 case ARMBuildAttrs::v8_M_Base:
642 Triple += "v8m.base";
643 break;
644 case ARMBuildAttrs::v8_M_Main:
645 Triple += "v8m.main";
646 break;
647 case ARMBuildAttrs::v8_1_M_Main:
648 Triple += "v8.1m.main";
649 break;
650 case ARMBuildAttrs::v9_A:
651 Triple += "v9a";
652 break;
653 }
654 }
655 if (!isLittleEndian())
656 Triple += "eb";
657
658 TheTriple.setArchName(Triple);
659}
660
661std::vector<ELFPltEntry>
662ELFObjectFileBase::getPltEntries(const MCSubtargetInfo &STI) const {
663 std::string Err;
664 const auto Triple = makeTriple();
665 const auto *T = TargetRegistry::lookupTarget(TheTriple: Triple, Error&: Err);
666 if (!T)
667 return {};
668 uint32_t JumpSlotReloc = 0, GlobDatReloc = 0;
669 switch (Triple.getArch()) {
670 case Triple::x86:
671 JumpSlotReloc = ELF::R_386_JUMP_SLOT;
672 GlobDatReloc = ELF::R_386_GLOB_DAT;
673 break;
674 case Triple::x86_64:
675 JumpSlotReloc = ELF::R_X86_64_JUMP_SLOT;
676 GlobDatReloc = ELF::R_X86_64_GLOB_DAT;
677 break;
678 case Triple::aarch64:
679 case Triple::aarch64_be:
680 JumpSlotReloc = ELF::R_AARCH64_JUMP_SLOT;
681 break;
682 case Triple::arm:
683 case Triple::armeb:
684 case Triple::thumb:
685 case Triple::thumbeb:
686 JumpSlotReloc = ELF::R_ARM_JUMP_SLOT;
687 break;
688 case Triple::hexagon:
689 JumpSlotReloc = ELF::R_HEX_JMP_SLOT;
690 GlobDatReloc = ELF::R_HEX_GLOB_DAT;
691 break;
692 case Triple::riscv32:
693 case Triple::riscv64:
694 JumpSlotReloc = ELF::R_RISCV_JUMP_SLOT;
695 break;
696 default:
697 return {};
698 }
699 std::unique_ptr<const MCInstrInfo> MII(T->createMCInstrInfo());
700 std::unique_ptr<const MCInstrAnalysis> MIA(
701 T->createMCInstrAnalysis(Info: MII.get()));
702 if (!MIA)
703 return {};
704 std::vector<std::pair<uint64_t, uint64_t>> PltEntries;
705 std::optional<SectionRef> RelaPlt, RelaDyn;
706 uint64_t GotBaseVA = 0;
707 for (const SectionRef &Section : sections()) {
708 Expected<StringRef> NameOrErr = Section.getName();
709 if (!NameOrErr) {
710 consumeError(Err: NameOrErr.takeError());
711 continue;
712 }
713 StringRef Name = *NameOrErr;
714
715 if (Name == ".rela.plt" || Name == ".rel.plt") {
716 RelaPlt = Section;
717 } else if (Name == ".rela.dyn" || Name == ".rel.dyn") {
718 RelaDyn = Section;
719 } else if (Name == ".got.plt") {
720 GotBaseVA = Section.getAddress();
721 } else if (Name == ".plt" || Name == ".plt.got") {
722 Expected<StringRef> PltContents = Section.getContents();
723 if (!PltContents) {
724 consumeError(Err: PltContents.takeError());
725 return {};
726 }
727 llvm::append_range(
728 C&: PltEntries,
729 R: MIA->findPltEntries(PltSectionVA: Section.getAddress(),
730 PltContents: arrayRefFromStringRef(Input: *PltContents), STI));
731 }
732 }
733
734 // Build a map from GOT entry virtual address to PLT entry virtual address.
735 DenseMap<uint64_t, uint64_t> GotToPlt;
736 for (auto [Plt, GotPlt] : PltEntries) {
737 uint64_t GotPltEntry = GotPlt;
738 // An x86-32 PIC PLT uses jmp DWORD PTR [ebx-offset]. Add
739 // _GLOBAL_OFFSET_TABLE_ (EBX) to get the .got.plt (or .got) entry address.
740 // See X86MCTargetDesc.cpp:findPltEntries for the 1 << 32 bit.
741 if (GotPltEntry & (uint64_t(1) << 32) && getEMachine() == ELF::EM_386)
742 GotPltEntry = static_cast<int32_t>(GotPltEntry) + GotBaseVA;
743 GotToPlt.insert(KV: std::make_pair(x&: GotPltEntry, y&: Plt));
744 }
745
746 // Find the relocations in the dynamic relocation table that point to
747 // locations in the GOT for which we know the corresponding PLT entry.
748 std::vector<ELFPltEntry> Result;
749 auto handleRels = [&](iterator_range<relocation_iterator> Rels,
750 uint32_t RelType, StringRef PltSec) {
751 for (const auto &R : Rels) {
752 if (R.getType() != RelType)
753 continue;
754 auto PltEntryIter = GotToPlt.find(Val: R.getOffset());
755 if (PltEntryIter != GotToPlt.end()) {
756 symbol_iterator Sym = R.getSymbol();
757 if (Sym == symbol_end())
758 Result.push_back(
759 x: ELFPltEntry{.Section: PltSec, .Symbol: std::nullopt, .Address: PltEntryIter->second});
760 else
761 Result.push_back(x: ELFPltEntry{.Section: PltSec, .Symbol: Sym->getRawDataRefImpl(),
762 .Address: PltEntryIter->second});
763 }
764 }
765 };
766
767 if (RelaPlt)
768 handleRels(RelaPlt->relocations(), JumpSlotReloc, ".plt");
769
770 // If a symbol needing a PLT entry also needs a GLOB_DAT relocation, GNU ld's
771 // x86 port places the PLT entry in the .plt.got section.
772 if (RelaDyn)
773 handleRels(RelaDyn->relocations(), GlobDatReloc, ".plt.got");
774
775 return Result;
776}
777
778template <class ELFT>
779Expected<std::vector<BBAddrMap>> static readBBAddrMapImpl(
780 const ELFFile<ELFT> &EF, std::optional<unsigned> TextSectionIndex,
781 std::vector<PGOAnalysisMap> *PGOAnalyses) {
782 using Elf_Shdr = typename ELFT::Shdr;
783 bool IsRelocatable = EF.getHeader().e_type == ELF::ET_REL;
784 std::vector<BBAddrMap> BBAddrMaps;
785 if (PGOAnalyses)
786 PGOAnalyses->clear();
787
788 const auto &Sections = cantFail(EF.sections());
789 auto IsMatch = [&](const Elf_Shdr &Sec) -> Expected<bool> {
790 if (Sec.sh_type != ELF::SHT_LLVM_BB_ADDR_MAP)
791 return false;
792 if (!TextSectionIndex)
793 return true;
794 Expected<const Elf_Shdr *> TextSecOrErr = EF.getSection(Sec.sh_link);
795 if (!TextSecOrErr)
796 return createError("unable to get the linked-to section for " +
797 describe(EF, Sec) + ": " +
798 toString(TextSecOrErr.takeError()));
799 assert(*TextSecOrErr >= Sections.begin() &&
800 "Text section pointer outside of bounds");
801 if (*TextSectionIndex !=
802 (unsigned)std::distance(Sections.begin(), *TextSecOrErr))
803 return false;
804 return true;
805 };
806
807 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SectionRelocMapOrErr =
808 EF.getSectionAndRelocations(IsMatch);
809 if (!SectionRelocMapOrErr)
810 return SectionRelocMapOrErr.takeError();
811
812 for (auto const &[Sec, RelocSec] : *SectionRelocMapOrErr) {
813 if (IsRelocatable && !RelocSec)
814 return createError("unable to get relocation section for " +
815 describe(EF, *Sec));
816 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
817 EF.decodeBBAddrMap(*Sec, RelocSec, PGOAnalyses);
818 if (!BBAddrMapOrErr) {
819 if (PGOAnalyses)
820 PGOAnalyses->clear();
821 return createError("unable to read " + describe(EF, *Sec) + ": " +
822 toString(E: BBAddrMapOrErr.takeError()));
823 }
824 std::move(first: BBAddrMapOrErr->begin(), last: BBAddrMapOrErr->end(),
825 result: std::back_inserter(x&: BBAddrMaps));
826 }
827 if (PGOAnalyses)
828 assert(PGOAnalyses->size() == BBAddrMaps.size() &&
829 "The same number of BBAddrMaps and PGOAnalysisMaps should be "
830 "returned when PGO information is requested");
831 return BBAddrMaps;
832}
833
834template <class ELFT>
835static Expected<std::vector<VersionEntry>>
836readDynsymVersionsImpl(const ELFFile<ELFT> &EF,
837 ELFObjectFileBase::elf_symbol_iterator_range Symbols) {
838 using Elf_Shdr = typename ELFT::Shdr;
839 const Elf_Shdr *VerSec = nullptr;
840 const Elf_Shdr *VerNeedSec = nullptr;
841 const Elf_Shdr *VerDefSec = nullptr;
842 // The user should ensure sections() can't fail here.
843 for (const Elf_Shdr &Sec : cantFail(EF.sections())) {
844 if (Sec.sh_type == ELF::SHT_GNU_versym)
845 VerSec = &Sec;
846 else if (Sec.sh_type == ELF::SHT_GNU_verdef)
847 VerDefSec = &Sec;
848 else if (Sec.sh_type == ELF::SHT_GNU_verneed)
849 VerNeedSec = &Sec;
850 }
851 if (!VerSec)
852 return std::vector<VersionEntry>();
853
854 Expected<SmallVector<std::optional<VersionEntry>, 0>> MapOrErr =
855 EF.loadVersionMap(VerNeedSec, VerDefSec);
856 if (!MapOrErr)
857 return MapOrErr.takeError();
858
859 std::vector<VersionEntry> Ret;
860 size_t I = 0;
861 for (const ELFSymbolRef &Sym : Symbols) {
862 ++I;
863 Expected<const typename ELFT::Versym *> VerEntryOrErr =
864 EF.template getEntry<typename ELFT::Versym>(*VerSec, I);
865 if (!VerEntryOrErr)
866 return createError("unable to read an entry with index " + Twine(I) +
867 " from " + describe(EF, *VerSec) + ": " +
868 toString(VerEntryOrErr.takeError()));
869
870 Expected<uint32_t> FlagsOrErr = Sym.getFlags();
871 if (!FlagsOrErr)
872 return createError(Err: "unable to read flags for symbol with index " +
873 Twine(I) + ": " + toString(E: FlagsOrErr.takeError()));
874
875 bool IsDefault;
876 Expected<StringRef> VerOrErr = EF.getSymbolVersionByIndex(
877 (*VerEntryOrErr)->vs_index, IsDefault, *MapOrErr,
878 (*FlagsOrErr) & SymbolRef::SF_Undefined);
879 if (!VerOrErr)
880 return createError("unable to get a version for entry " + Twine(I) +
881 " of " + describe(EF, *VerSec) + ": " +
882 toString(E: VerOrErr.takeError()));
883
884 Ret.push_back(x: {.Name: (*VerOrErr).str(), .IsVerDef: IsDefault});
885 }
886
887 return Ret;
888}
889
890Expected<std::vector<VersionEntry>>
891ELFObjectFileBase::readDynsymVersions() const {
892 elf_symbol_iterator_range Symbols = getDynamicSymbolIterators();
893 if (const auto *Obj = dyn_cast<ELF32LEObjectFile>(Val: this))
894 return readDynsymVersionsImpl(EF: Obj->getELFFile(), Symbols);
895 if (const auto *Obj = dyn_cast<ELF32BEObjectFile>(Val: this))
896 return readDynsymVersionsImpl(EF: Obj->getELFFile(), Symbols);
897 if (const auto *Obj = dyn_cast<ELF64LEObjectFile>(Val: this))
898 return readDynsymVersionsImpl(EF: Obj->getELFFile(), Symbols);
899 return readDynsymVersionsImpl(EF: cast<ELF64BEObjectFile>(Val: this)->getELFFile(),
900 Symbols);
901}
902
903Expected<std::vector<BBAddrMap>> ELFObjectFileBase::readBBAddrMap(
904 std::optional<unsigned> TextSectionIndex,
905 std::vector<PGOAnalysisMap> *PGOAnalyses) const {
906 if (const auto *Obj = dyn_cast<ELF32LEObjectFile>(Val: this))
907 return readBBAddrMapImpl(EF: Obj->getELFFile(), TextSectionIndex, PGOAnalyses);
908 if (const auto *Obj = dyn_cast<ELF64LEObjectFile>(Val: this))
909 return readBBAddrMapImpl(EF: Obj->getELFFile(), TextSectionIndex, PGOAnalyses);
910 if (const auto *Obj = dyn_cast<ELF32BEObjectFile>(Val: this))
911 return readBBAddrMapImpl(EF: Obj->getELFFile(), TextSectionIndex, PGOAnalyses);
912 return readBBAddrMapImpl(EF: cast<ELF64BEObjectFile>(Val: this)->getELFFile(),
913 TextSectionIndex, PGOAnalyses);
914}
915
916StringRef ELFObjectFileBase::getCrelDecodeProblem(SectionRef Sec) const {
917 auto Data = Sec.getRawDataRefImpl();
918 if (const auto *Obj = dyn_cast<ELF32LEObjectFile>(Val: this))
919 return Obj->getCrelDecodeProblem(Sec: Data);
920 if (const auto *Obj = dyn_cast<ELF32BEObjectFile>(Val: this))
921 return Obj->getCrelDecodeProblem(Sec: Data);
922 if (const auto *Obj = dyn_cast<ELF64LEObjectFile>(Val: this))
923 return Obj->getCrelDecodeProblem(Sec: Data);
924 return cast<ELF64BEObjectFile>(Val: this)->getCrelDecodeProblem(Sec: Data);
925}
926