1 //===---- ELF_x86_64.cpp -JIT linker implementation for ELF/x86-64 ----===//
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 // ELF/x86-64 jit-link implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ExecutionEngine/JITLink/ELF_x86_64.h"
14 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
15 #include "llvm/Object/ELFObjectFile.h"
16 #include "llvm/Support/Endian.h"
17 
18 #include "BasicGOTAndStubsBuilder.h"
19 #include "EHFrameSupportImpl.h"
20 #include "JITLinkGeneric.h"
21 
22 #define DEBUG_TYPE "jitlink"
23 
24 using namespace llvm;
25 using namespace llvm::jitlink;
26 using namespace llvm::jitlink::ELF_x86_64_Edges;
27 
28 namespace {
29 
30 class ELF_x86_64_GOTAndStubsBuilder
31     : public BasicGOTAndStubsBuilder<ELF_x86_64_GOTAndStubsBuilder> {
32 public:
33   static const uint8_t NullGOTEntryContent[8];
34   static const uint8_t StubContent[6];
35 
36   ELF_x86_64_GOTAndStubsBuilder(LinkGraph &G)
37       : BasicGOTAndStubsBuilder<ELF_x86_64_GOTAndStubsBuilder>(G) {}
38 
39   bool isGOTEdge(Edge &E) const {
40     return E.getKind() == PCRel32GOT || E.getKind() == PCRel32GOTLoad;
41   }
42 
43   Symbol &createGOTEntry(Symbol &Target) {
44     auto &GOTEntryBlock = G.createContentBlock(
45         getGOTSection(), getGOTEntryBlockContent(), 0, 8, 0);
46     GOTEntryBlock.addEdge(Pointer64, 0, Target, 0);
47     return G.addAnonymousSymbol(GOTEntryBlock, 0, 8, false, false);
48   }
49 
50   void fixGOTEdge(Edge &E, Symbol &GOTEntry) {
51     assert((E.getKind() == PCRel32GOT || E.getKind() == PCRel32GOTLoad) &&
52            "Not a GOT edge?");
53     // If this is a PCRel32GOT then change it to an ordinary PCRel32. If it is
54     // a PCRel32GOTLoad then leave it as-is for now. We will use the kind to
55     // check for GOT optimization opportunities in the
56     // optimizeMachO_x86_64_GOTAndStubs pass below.
57     if (E.getKind() == PCRel32GOT)
58       E.setKind(PCRel32);
59 
60     E.setTarget(GOTEntry);
61     // Leave the edge addend as-is.
62   }
63 
64   bool isExternalBranchEdge(Edge &E) {
65     return E.getKind() == Branch32 && !E.getTarget().isDefined();
66   }
67 
68   Symbol &createStub(Symbol &Target) {
69     auto &StubContentBlock =
70         G.createContentBlock(getStubsSection(), getStubBlockContent(), 0, 1, 0);
71     // Re-use GOT entries for stub targets.
72     auto &GOTEntrySymbol = getGOTEntrySymbol(Target);
73     StubContentBlock.addEdge(PCRel32, 2, GOTEntrySymbol, -4);
74     return G.addAnonymousSymbol(StubContentBlock, 0, 6, true, false);
75   }
76 
77   void fixExternalBranchEdge(Edge &E, Symbol &Stub) {
78     assert(E.getKind() == Branch32 && "Not a Branch32 edge?");
79 
80     // Set the edge kind to Branch32ToStub. We will use this to check for stub
81     // optimization opportunities in the optimize ELF_x86_64_GOTAndStubs pass
82     // below.
83     E.setKind(Branch32ToStub);
84     E.setTarget(Stub);
85   }
86 
87 private:
88   Section &getGOTSection() {
89     if (!GOTSection)
90       GOTSection = &G.createSection("$__GOT", sys::Memory::MF_READ);
91     return *GOTSection;
92   }
93 
94   Section &getStubsSection() {
95     if (!StubsSection) {
96       auto StubsProt = static_cast<sys::Memory::ProtectionFlags>(
97           sys::Memory::MF_READ | sys::Memory::MF_EXEC);
98       StubsSection = &G.createSection("$__STUBS", StubsProt);
99     }
100     return *StubsSection;
101   }
102 
103   StringRef getGOTEntryBlockContent() {
104     return StringRef(reinterpret_cast<const char *>(NullGOTEntryContent),
105                      sizeof(NullGOTEntryContent));
106   }
107 
108   StringRef getStubBlockContent() {
109     return StringRef(reinterpret_cast<const char *>(StubContent),
110                      sizeof(StubContent));
111   }
112 
113   Section *GOTSection = nullptr;
114   Section *StubsSection = nullptr;
115 };
116 
117 const char *const DwarfSectionNames[] = {
118 #define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME, OPTION)        \
119   ELF_NAME,
120 #include "llvm/BinaryFormat/Dwarf.def"
121 #undef HANDLE_DWARF_SECTION
122 };
123 
124 } // namespace
125 
126 const uint8_t ELF_x86_64_GOTAndStubsBuilder::NullGOTEntryContent[8] = {
127     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
128 const uint8_t ELF_x86_64_GOTAndStubsBuilder::StubContent[6] = {
129     0xFF, 0x25, 0x00, 0x00, 0x00, 0x00};
130 
131 static const char *CommonSectionName = "__common";
132 static Error optimizeELF_x86_64_GOTAndStubs(LinkGraph &G) {
133   LLVM_DEBUG(dbgs() << "Optimizing GOT entries and stubs:\n");
134 
135   for (auto *B : G.blocks())
136     for (auto &E : B->edges())
137       if (E.getKind() == PCRel32GOTLoad) {
138         // Replace GOT load with LEA only for MOVQ instructions.
139         constexpr uint8_t MOVQRIPRel[] = {0x48, 0x8b};
140         if (E.getOffset() < 3 ||
141             strncmp(B->getContent().data() + E.getOffset() - 3,
142                     reinterpret_cast<const char *>(MOVQRIPRel), 2) != 0)
143           continue;
144 
145         auto &GOTBlock = E.getTarget().getBlock();
146         assert(GOTBlock.getSize() == G.getPointerSize() &&
147                "GOT entry block should be pointer sized");
148         assert(GOTBlock.edges_size() == 1 &&
149                "GOT entry should only have one outgoing edge");
150 
151         auto &GOTTarget = GOTBlock.edges().begin()->getTarget();
152         JITTargetAddress EdgeAddr = B->getAddress() + E.getOffset();
153         JITTargetAddress TargetAddr = GOTTarget.getAddress();
154 
155         int64_t Displacement = TargetAddr - EdgeAddr + 4;
156         if (Displacement >= std::numeric_limits<int32_t>::min() &&
157             Displacement <= std::numeric_limits<int32_t>::max()) {
158           // Change the edge kind as we don't go through GOT anymore. This is
159           // for formal correctness only. Technically, the two relocation kinds
160           // are resolved the same way.
161           E.setKind(PCRel32);
162           E.setTarget(GOTTarget);
163           auto *BlockData = reinterpret_cast<uint8_t *>(
164               const_cast<char *>(B->getContent().data()));
165           BlockData[E.getOffset() - 2] = 0x8d;
166           LLVM_DEBUG({
167             dbgs() << "  Replaced GOT load wih LEA:\n    ";
168             printEdge(dbgs(), *B, E, getELFX86RelocationKindName(E.getKind()));
169             dbgs() << "\n";
170           });
171         }
172       } else if (E.getKind() == Branch32ToStub) {
173         auto &StubBlock = E.getTarget().getBlock();
174         assert(StubBlock.getSize() ==
175                    sizeof(ELF_x86_64_GOTAndStubsBuilder::StubContent) &&
176                "Stub block should be stub sized");
177         assert(StubBlock.edges_size() == 1 &&
178                "Stub block should only have one outgoing edge");
179 
180         auto &GOTBlock = StubBlock.edges().begin()->getTarget().getBlock();
181         assert(GOTBlock.getSize() == G.getPointerSize() &&
182                "GOT block should be pointer sized");
183         assert(GOTBlock.edges_size() == 1 &&
184                "GOT block should only have one outgoing edge");
185 
186         auto &GOTTarget = GOTBlock.edges().begin()->getTarget();
187         JITTargetAddress EdgeAddr = B->getAddress() + E.getOffset();
188         JITTargetAddress TargetAddr = GOTTarget.getAddress();
189 
190         int64_t Displacement = TargetAddr - EdgeAddr + 4;
191         if (Displacement >= std::numeric_limits<int32_t>::min() &&
192             Displacement <= std::numeric_limits<int32_t>::max()) {
193           E.setKind(Branch32);
194           E.setTarget(GOTTarget);
195           LLVM_DEBUG({
196             dbgs() << "  Replaced stub branch with direct branch:\n    ";
197             printEdge(dbgs(), *B, E, getELFX86RelocationKindName(E.getKind()));
198             dbgs() << "\n";
199           });
200         }
201       }
202 
203   return Error::success();
204 }
205 
206 static bool isDwarfSection(StringRef SectionName) {
207   return llvm::is_contained(DwarfSectionNames, SectionName);
208 }
209 
210 namespace llvm {
211 namespace jitlink {
212 
213 // This should become a template as the ELFFile is so a lot of this could become
214 // generic
215 class ELFLinkGraphBuilder_x86_64 {
216 
217 private:
218   Section *CommonSection = nullptr;
219   // TODO hack to get this working
220   // Find a better way
221   using SymbolTable = object::ELFFile<object::ELF64LE>::Elf_Shdr;
222   // For now we just assume
223   using SymbolMap = std::map<int32_t, Symbol *>;
224   SymbolMap JITSymbolTable;
225 
226   Section &getCommonSection() {
227     if (!CommonSection) {
228       auto Prot = static_cast<sys::Memory::ProtectionFlags>(
229           sys::Memory::MF_READ | sys::Memory::MF_WRITE);
230       CommonSection = &G->createSection(CommonSectionName, Prot);
231     }
232     return *CommonSection;
233   }
234 
235   static Expected<ELF_x86_64_Edges::ELFX86RelocationKind>
236   getRelocationKind(const uint32_t Type) {
237     switch (Type) {
238     case ELF::R_X86_64_PC32:
239       return ELF_x86_64_Edges::ELFX86RelocationKind::PCRel32;
240     case ELF::R_X86_64_PC64:
241       return ELF_x86_64_Edges::ELFX86RelocationKind::Delta64;
242     case ELF::R_X86_64_64:
243       return ELF_x86_64_Edges::ELFX86RelocationKind::Pointer64;
244     case ELF::R_X86_64_GOTPCREL:
245     case ELF::R_X86_64_GOTPCRELX:
246     case ELF::R_X86_64_REX_GOTPCRELX:
247       return ELF_x86_64_Edges::ELFX86RelocationKind::PCRel32GOTLoad;
248     case ELF::R_X86_64_PLT32:
249       return ELF_x86_64_Edges::ELFX86RelocationKind::Branch32;
250     }
251     return make_error<JITLinkError>("Unsupported x86-64 relocation:" +
252                                     formatv("{0:d}", Type));
253   }
254 
255   std::unique_ptr<LinkGraph> G;
256   // This could be a template
257   const object::ELFFile<object::ELF64LE> &Obj;
258   object::ELFFile<object::ELF64LE>::Elf_Shdr_Range sections;
259   SymbolTable SymTab;
260 
261   bool isRelocatable() { return Obj.getHeader().e_type == llvm::ELF::ET_REL; }
262 
263   support::endianness
264   getEndianness(const object::ELFFile<object::ELF64LE> &Obj) {
265     return Obj.isLE() ? support::little : support::big;
266   }
267 
268   // This could also just become part of a template
269   unsigned getPointerSize(const object::ELFFile<object::ELF64LE> &Obj) {
270     return Obj.getHeader().getFileClass() == ELF::ELFCLASS64 ? 8 : 4;
271   }
272 
273   // We don't technically need this right now
274   // But for now going to keep it as it helps me to debug things
275 
276   Error createNormalizedSymbols() {
277     LLVM_DEBUG(dbgs() << "Creating normalized symbols...\n");
278 
279     for (auto SecRef : sections) {
280       if (SecRef.sh_type != ELF::SHT_SYMTAB &&
281           SecRef.sh_type != ELF::SHT_DYNSYM)
282         continue;
283 
284       auto Symbols = Obj.symbols(&SecRef);
285       // TODO: Currently I use this function to test things
286       // I also want to leave it to see if its common between MACH and elf
287       // so for now I just want to continue even if there is an error
288       if (errorToBool(Symbols.takeError()))
289         continue;
290 
291       auto StrTabSec = Obj.getSection(SecRef.sh_link);
292       if (!StrTabSec)
293         return StrTabSec.takeError();
294       auto StringTable = Obj.getStringTable(**StrTabSec);
295       if (!StringTable)
296         return StringTable.takeError();
297 
298       for (auto SymRef : *Symbols) {
299         Optional<StringRef> Name;
300 
301         if (auto NameOrErr = SymRef.getName(*StringTable))
302           Name = *NameOrErr;
303         else
304           return NameOrErr.takeError();
305 
306         LLVM_DEBUG({
307           dbgs() << "  value = " << formatv("{0:x16}", SymRef.getValue())
308                  << ", type = " << formatv("{0:x2}", SymRef.getType())
309                  << ", binding = " << formatv("{0:x2}", SymRef.getBinding())
310                  << ", size = "
311                  << formatv("{0:x16}", static_cast<uint64_t>(SymRef.st_size))
312                  << ", info = " << formatv("{0:x2}", SymRef.st_info)
313                  << " :" << (Name ? *Name : "<anonymous symbol>") << "\n";
314         });
315       }
316     }
317     return Error::success();
318   }
319 
320   Error createNormalizedSections() {
321     LLVM_DEBUG(dbgs() << "Creating normalized sections...\n");
322     for (auto &SecRef : sections) {
323       auto Name = Obj.getSectionName(SecRef);
324       if (!Name)
325         return Name.takeError();
326 
327       // Skip Dwarf sections.
328       if (isDwarfSection(*Name)) {
329         LLVM_DEBUG({
330           dbgs() << *Name
331                  << " is a debug section: No graph section will be created.\n";
332         });
333         continue;
334       }
335 
336       sys::Memory::ProtectionFlags Prot;
337       if (SecRef.sh_flags & ELF::SHF_EXECINSTR) {
338         Prot = static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
339                                                          sys::Memory::MF_EXEC);
340       } else {
341         Prot = static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
342                                                          sys::Memory::MF_WRITE);
343       }
344       uint64_t Address = SecRef.sh_addr;
345       uint64_t Size = SecRef.sh_size;
346       uint64_t Flags = SecRef.sh_flags;
347       uint64_t Alignment = SecRef.sh_addralign;
348       const char *Data = nullptr;
349       // for now we just use this to skip the "undefined" section, probably need
350       // to revist
351       if (Size == 0)
352         continue;
353 
354       // FIXME: Use flags.
355       (void)Flags;
356 
357       LLVM_DEBUG({
358         dbgs() << "  " << *Name << ": " << formatv("{0:x16}", Address) << " -- "
359                << formatv("{0:x16}", Address + Size) << ", align: " << Alignment
360                << " Flags: " << formatv("{0:x}", Flags) << "\n";
361       });
362 
363       if (SecRef.sh_type != ELF::SHT_NOBITS) {
364         // .sections() already checks that the data is not beyond the end of
365         // file
366         auto contents = Obj.getSectionContentsAsArray<char>(SecRef);
367         if (!contents)
368           return contents.takeError();
369 
370         Data = contents->data();
371         // TODO protection flags.
372         // for now everything is
373         auto &section = G->createSection(*Name, Prot);
374         // Do this here because we have it, but move it into graphify later
375         G->createContentBlock(section, StringRef(Data, Size), Address,
376                               Alignment, 0);
377         if (SecRef.sh_type == ELF::SHT_SYMTAB)
378           // TODO: Dynamic?
379           SymTab = SecRef;
380       } else {
381         auto &Section = G->createSection(*Name, Prot);
382         G->createZeroFillBlock(Section, Size, Address, Alignment, 0);
383       }
384     }
385 
386     return Error::success();
387   }
388 
389   Error addRelocations() {
390     LLVM_DEBUG(dbgs() << "Adding relocations\n");
391     // TODO a partern is forming of iterate some sections but only give me
392     // ones I am interested, i should abstract that concept some where
393     for (auto &SecRef : sections) {
394       if (SecRef.sh_type != ELF::SHT_RELA && SecRef.sh_type != ELF::SHT_REL)
395         continue;
396       // TODO can the elf obj file do this for me?
397       if (SecRef.sh_type == ELF::SHT_REL)
398         return make_error<llvm::StringError>("Shouldn't have REL in x64",
399                                              llvm::inconvertibleErrorCode());
400 
401       auto RelSectName = Obj.getSectionName(SecRef);
402       if (!RelSectName)
403         return RelSectName.takeError();
404 
405       LLVM_DEBUG({
406         dbgs() << "Adding relocations from section " << *RelSectName << "\n";
407       });
408 
409       auto UpdateSection = Obj.getSection(SecRef.sh_info);
410       if (!UpdateSection)
411         return UpdateSection.takeError();
412 
413       auto UpdateSectionName = Obj.getSectionName(**UpdateSection);
414       if (!UpdateSectionName)
415         return UpdateSectionName.takeError();
416 
417       // Don't process relocations for debug sections.
418       if (isDwarfSection(*UpdateSectionName)) {
419         LLVM_DEBUG({
420           dbgs() << "  Target is dwarf section " << *UpdateSectionName
421                  << ". Skipping.\n";
422         });
423         continue;
424       } else
425         LLVM_DEBUG({
426           dbgs() << "  For target section " << *UpdateSectionName << "\n";
427         });
428 
429       auto JITSection = G->findSectionByName(*UpdateSectionName);
430       if (!JITSection)
431         return make_error<llvm::StringError>(
432             "Refencing a a section that wasn't added to graph" +
433                 *UpdateSectionName,
434             llvm::inconvertibleErrorCode());
435 
436       auto Relocations = Obj.relas(SecRef);
437       if (!Relocations)
438         return Relocations.takeError();
439 
440       for (const auto &Rela : *Relocations) {
441         auto Type = Rela.getType(false);
442 
443         LLVM_DEBUG({
444           dbgs() << "Relocation Type: " << Type << "\n"
445                  << "Name: " << Obj.getRelocationTypeName(Type) << "\n";
446         });
447         auto SymbolIndex = Rela.getSymbol(false);
448         auto Symbol = Obj.getRelocationSymbol(Rela, &SymTab);
449         if (!Symbol)
450           return Symbol.takeError();
451 
452         auto BlockToFix = *(JITSection->blocks().begin());
453         auto *TargetSymbol = JITSymbolTable[SymbolIndex];
454 
455         if (!TargetSymbol) {
456           return make_error<llvm::StringError>(
457               "Could not find symbol at given index, did you add it to "
458               "JITSymbolTable? index: " + std::to_string(SymbolIndex)
459               + ", shndx: " + std::to_string((*Symbol)->st_shndx) +
460                   " Size of table: " + std::to_string(JITSymbolTable.size()),
461               llvm::inconvertibleErrorCode());
462         }
463         uint64_t Addend = Rela.r_addend;
464         JITTargetAddress FixupAddress =
465             (*UpdateSection)->sh_addr + Rela.r_offset;
466 
467         LLVM_DEBUG({
468           dbgs() << "Processing relocation at "
469                  << format("0x%016" PRIx64, FixupAddress) << "\n";
470         });
471         auto Kind = getRelocationKind(Type);
472         if (!Kind)
473           return Kind.takeError();
474 
475         LLVM_DEBUG({
476           Edge GE(*Kind, FixupAddress - BlockToFix->getAddress(), *TargetSymbol,
477                   Addend);
478           printEdge(dbgs(), *BlockToFix, GE,
479                     getELFX86RelocationKindName(*Kind));
480           dbgs() << "\n";
481         });
482         BlockToFix->addEdge(*Kind, FixupAddress - BlockToFix->getAddress(),
483                             *TargetSymbol, Addend);
484       }
485     }
486     return Error::success();
487   }
488 
489   Error graphifyRegularSymbols() {
490 
491     // TODO: ELF supports beyond SHN_LORESERVE,
492     // need to perf test how a vector vs map handles those cases
493 
494     std::vector<std::vector<object::ELFFile<object::ELF64LE>::Elf_Shdr_Range *>>
495         SecIndexToSymbols;
496 
497     LLVM_DEBUG(dbgs() << "Creating graph symbols...\n");
498 
499     for (auto SecRef : sections) {
500 
501       if (SecRef.sh_type != ELF::SHT_SYMTAB &&
502           SecRef.sh_type != ELF::SHT_DYNSYM)
503         continue;
504       auto Symbols = Obj.symbols(&SecRef);
505       if (!Symbols)
506         return Symbols.takeError();
507 
508       auto StrTabSec = Obj.getSection(SecRef.sh_link);
509       if (!StrTabSec)
510         return StrTabSec.takeError();
511       auto StringTable = Obj.getStringTable(**StrTabSec);
512       if (!StringTable)
513         return StringTable.takeError();
514       auto Name = Obj.getSectionName(SecRef);
515       if (!Name)
516         return Name.takeError();
517 
518       LLVM_DEBUG(dbgs() << "Processing symbol section " << *Name << ":\n");
519 
520       auto Section = G->findSectionByName(*Name);
521       if (!Section)
522         return make_error<llvm::StringError>("Could not find a section " +
523                                              *Name,
524                                              llvm::inconvertibleErrorCode());
525       // we only have one for now
526       auto blocks = Section->blocks();
527       if (blocks.empty())
528         return make_error<llvm::StringError>("Section has no block",
529                                              llvm::inconvertibleErrorCode());
530       int SymbolIndex = -1;
531       for (auto SymRef : *Symbols) {
532         ++SymbolIndex;
533         auto Type = SymRef.getType();
534 
535         if (Type == ELF::STT_FILE || SymbolIndex == 0)
536           continue;
537         // these should do it for now
538         // if(Type != ELF::STT_NOTYPE &&
539         //   Type != ELF::STT_OBJECT &&
540         //   Type != ELF::STT_FUNC    &&
541         //   Type != ELF::STT_SECTION &&
542         //   Type != ELF::STT_COMMON) {
543         //     continue;
544         //   }
545         auto Name = SymRef.getName(*StringTable);
546         // I am not sure on If this is going to hold as an invariant. Revisit.
547         if (!Name)
548           return Name.takeError();
549 
550         if (SymRef.isCommon()) {
551           // Symbols in SHN_COMMON refer to uninitialized data. The st_value
552           // field holds alignment constraints.
553           Symbol &S =
554               G->addCommonSymbol(*Name, Scope::Default, getCommonSection(), 0,
555                                  SymRef.st_size, SymRef.getValue(), false);
556           JITSymbolTable[SymbolIndex] = &S;
557           continue;
558         }
559 
560         // Map Visibility and Binding to Scope and Linkage:
561         Linkage L = Linkage::Strong;
562         Scope S = Scope::Default;
563 
564         switch (SymRef.getBinding()) {
565         case ELF::STB_LOCAL:
566           S = Scope::Local;
567           break;
568         case ELF::STB_GLOBAL:
569           // Nothing to do here.
570           break;
571         case ELF::STB_WEAK:
572           L = Linkage::Weak;
573           break;
574         default:
575           return make_error<StringError>("Unrecognized symbol binding for " +
576                                              *Name,
577                                          inconvertibleErrorCode());
578         }
579 
580         switch (SymRef.getVisibility()) {
581         case ELF::STV_DEFAULT:
582         case ELF::STV_PROTECTED:
583           // FIXME: Make STV_DEFAULT symbols pre-emptible? This probably needs
584           // Orc support.
585           // Otherwise nothing to do here.
586           break;
587         case ELF::STV_HIDDEN:
588           // Default scope -> Hidden scope. No effect on local scope.
589           if (S == Scope::Default)
590             S = Scope::Hidden;
591           break;
592         case ELF::STV_INTERNAL:
593           return make_error<StringError>("Unrecognized symbol visibility for " +
594                                              *Name,
595                                          inconvertibleErrorCode());
596         }
597 
598         if (SymRef.isDefined() &&
599             (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
600              Type == ELF::STT_SECTION)) {
601 
602           auto DefinedSection = Obj.getSection(SymRef.st_shndx);
603           if (!DefinedSection)
604             return DefinedSection.takeError();
605           auto sectName = Obj.getSectionName(**DefinedSection);
606           if (!sectName)
607             return Name.takeError();
608 
609           // Skip debug section symbols.
610           if (isDwarfSection(*sectName))
611             continue;
612 
613           auto JitSection = G->findSectionByName(*sectName);
614           if (!JitSection)
615             return make_error<llvm::StringError>(
616                 "Could not find the JitSection " + *sectName,
617                 llvm::inconvertibleErrorCode());
618           auto bs = JitSection->blocks();
619           if (bs.empty())
620             return make_error<llvm::StringError>(
621                 "Section has no block", llvm::inconvertibleErrorCode());
622 
623           auto *B = *bs.begin();
624           LLVM_DEBUG({ dbgs() << "  " << *Name << " at index " << SymbolIndex << "\n"; });
625           if (SymRef.getType() == ELF::STT_SECTION)
626             *Name = *sectName;
627           auto &Sym = G->addDefinedSymbol(
628               *B, SymRef.getValue(), *Name, SymRef.st_size, L, S,
629               SymRef.getType() == ELF::STT_FUNC, false);
630           JITSymbolTable[SymbolIndex] = &Sym;
631         } else if (SymRef.isUndefined() && SymRef.isExternal()) {
632           auto &Sym = G->addExternalSymbol(*Name, SymRef.st_size, L);
633           JITSymbolTable[SymbolIndex] = &Sym;
634         } else
635           LLVM_DEBUG({
636               dbgs()
637                 << "Not creating graph symbol for normalized symbol at index "
638                 << SymbolIndex << ", \"" << *Name << "\"\n";
639             });
640 
641         // TODO: The following has to be implmented.
642         // leaving commented out to save time for future patchs
643         /*
644           G->addAbsoluteSymbol(*Name, SymRef.getValue(), SymRef.st_size,
645           Linkage::Strong, Scope::Default, false);
646         */
647       }
648     }
649     return Error::success();
650   }
651 
652 public:
653   ELFLinkGraphBuilder_x86_64(StringRef FileName,
654                              const object::ELFFile<object::ELF64LE> &Obj)
655       : G(std::make_unique<LinkGraph>(FileName.str(),
656                                       Triple("x86_64-unknown-linux"),
657                                       getPointerSize(Obj), getEndianness(Obj))),
658         Obj(Obj) {}
659 
660   Expected<std::unique_ptr<LinkGraph>> buildGraph() {
661     // Sanity check: we only operate on relocatable objects.
662     if (!isRelocatable())
663       return make_error<JITLinkError>("Object is not a relocatable ELF");
664 
665     auto Secs = Obj.sections();
666 
667     if (!Secs) {
668       return Secs.takeError();
669     }
670     sections = *Secs;
671 
672     if (auto Err = createNormalizedSections())
673       return std::move(Err);
674 
675     if (auto Err = createNormalizedSymbols())
676       return std::move(Err);
677 
678     if (auto Err = graphifyRegularSymbols())
679       return std::move(Err);
680 
681     if (auto Err = addRelocations())
682       return std::move(Err);
683 
684     return std::move(G);
685   }
686 };
687 
688 class ELFJITLinker_x86_64 : public JITLinker<ELFJITLinker_x86_64> {
689   friend class JITLinker<ELFJITLinker_x86_64>;
690 
691 public:
692   ELFJITLinker_x86_64(std::unique_ptr<JITLinkContext> Ctx,
693                       std::unique_ptr<LinkGraph> G,
694                       PassConfiguration PassConfig)
695       : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {}
696 
697 private:
698   StringRef getEdgeKindName(Edge::Kind R) const override {
699     return getELFX86RelocationKindName(R);
700   }
701 
702   static Error targetOutOfRangeError(const Block &B, const Edge &E) {
703     std::string ErrMsg;
704     {
705       raw_string_ostream ErrStream(ErrMsg);
706       ErrStream << "Relocation target out of range: ";
707       printEdge(ErrStream, B, E, getELFX86RelocationKindName(E.getKind()));
708       ErrStream << "\n";
709     }
710     return make_error<JITLinkError>(std::move(ErrMsg));
711   }
712 
713   Error applyFixup(Block &B, const Edge &E, char *BlockWorkingMem) const {
714     using namespace ELF_x86_64_Edges;
715     using namespace llvm::support;
716     char *FixupPtr = BlockWorkingMem + E.getOffset();
717     JITTargetAddress FixupAddress = B.getAddress() + E.getOffset();
718     switch (E.getKind()) {
719     case ELFX86RelocationKind::Branch32:
720     case ELFX86RelocationKind::Branch32ToStub:
721     case ELFX86RelocationKind::PCRel32:
722     case ELFX86RelocationKind::PCRel32GOTLoad: {
723       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
724       if (Value < std::numeric_limits<int32_t>::min() ||
725           Value > std::numeric_limits<int32_t>::max())
726         return targetOutOfRangeError(B, E);
727       *(little32_t *)FixupPtr = Value;
728       break;
729     }
730     case ELFX86RelocationKind::Pointer64: {
731       int64_t Value = E.getTarget().getAddress() + E.getAddend();
732       *(ulittle64_t *)FixupPtr = Value;
733       break;
734     }
735     case ELFX86RelocationKind::Delta64: {
736       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
737       *(little64_t *)FixupPtr = Value;
738       break;
739     }
740     }
741     return Error::success();
742   }
743 };
744 
745 Expected<std::unique_ptr<LinkGraph>>
746 createLinkGraphFromELFObject_x86_64(MemoryBufferRef ObjectBuffer) {
747   LLVM_DEBUG({
748     dbgs() << "Building jitlink graph for new input "
749            << ObjectBuffer.getBufferIdentifier() << "...\n";
750   });
751 
752   auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
753   if (!ELFObj)
754     return ELFObj.takeError();
755 
756   auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF64LE>>(**ELFObj);
757   return ELFLinkGraphBuilder_x86_64((*ELFObj)->getFileName(),
758                                     ELFObjFile.getELFFile())
759       .buildGraph();
760 }
761 
762 void link_ELF_x86_64(std::unique_ptr<LinkGraph> G,
763                      std::unique_ptr<JITLinkContext> Ctx) {
764   PassConfiguration Config;
765 
766   if (Ctx->shouldAddDefaultTargetPasses(G->getTargetTriple())) {
767 
768     Config.PrePrunePasses.push_back(EHFrameSplitter(".eh_frame"));
769     Config.PrePrunePasses.push_back(EHFrameEdgeFixer(
770         ".eh_frame", G->getPointerSize(), Delta64, Delta32, NegDelta32));
771 
772     // Construct a JITLinker and run the link function.
773     // Add a mark-live pass.
774     if (auto MarkLive = Ctx->getMarkLivePass(G->getTargetTriple()))
775       Config.PrePrunePasses.push_back(std::move(MarkLive));
776     else
777       Config.PrePrunePasses.push_back(markAllSymbolsLive);
778 
779     // Add an in-place GOT/Stubs pass.
780     Config.PostPrunePasses.push_back([](LinkGraph &G) -> Error {
781       ELF_x86_64_GOTAndStubsBuilder(G).run();
782       return Error::success();
783     });
784 
785     // Add GOT/Stubs optimizer pass.
786     Config.PreFixupPasses.push_back(optimizeELF_x86_64_GOTAndStubs);
787   }
788 
789   if (auto Err = Ctx->modifyPassConfig(G->getTargetTriple(), Config))
790     return Ctx->notifyFailed(std::move(Err));
791 
792   ELFJITLinker_x86_64::link(std::move(Ctx), std::move(G), std::move(Config));
793 }
794 StringRef getELFX86RelocationKindName(Edge::Kind R) {
795   switch (R) {
796   case PCRel32:
797     return "PCRel32";
798   case Pointer64:
799     return "Pointer64";
800   case PCRel32GOTLoad:
801     return "PCRel32GOTLoad";
802   case Branch32:
803     return "Branch32";
804   case Branch32ToStub:
805     return "Branch32ToStub";
806   }
807   return getGenericEdgeKindName(static_cast<Edge::Kind>(R));
808 }
809 } // end namespace jitlink
810 } // end namespace llvm
811