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