xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/ExecutionEngine/JITLink/MachO_arm64.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===---- MachO_arm64.cpp - JIT linker implementation for MachO/arm64 -----===//
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 // MachO/arm64 jit-link implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ExecutionEngine/JITLink/MachO_arm64.h"
14 
15 #include "MachOLinkGraphBuilder.h"
16 #include "PerGraphGOTAndPLTStubsBuilder.h"
17 
18 #define DEBUG_TYPE "jitlink"
19 
20 using namespace llvm;
21 using namespace llvm::jitlink;
22 using namespace llvm::jitlink::MachO_arm64_Edges;
23 
24 namespace {
25 
26 class MachOLinkGraphBuilder_arm64 : public MachOLinkGraphBuilder {
27 public:
MachOLinkGraphBuilder_arm64(const object::MachOObjectFile & Obj)28   MachOLinkGraphBuilder_arm64(const object::MachOObjectFile &Obj)
29       : MachOLinkGraphBuilder(Obj, Triple("arm64-apple-darwin"),
30                               getMachOARM64RelocationKindName),
31         NumSymbols(Obj.getSymtabLoadCommand().nsyms) {}
32 
33 private:
34   static Expected<MachOARM64RelocationKind>
getRelocationKind(const MachO::relocation_info & RI)35   getRelocationKind(const MachO::relocation_info &RI) {
36     switch (RI.r_type) {
37     case MachO::ARM64_RELOC_UNSIGNED:
38       if (!RI.r_pcrel) {
39         if (RI.r_length == 3)
40           return RI.r_extern ? Pointer64 : Pointer64Anon;
41         else if (RI.r_length == 2)
42           return Pointer32;
43       }
44       break;
45     case MachO::ARM64_RELOC_SUBTRACTOR:
46       // SUBTRACTOR must be non-pc-rel, extern, with length 2 or 3.
47       // Initially represent SUBTRACTOR relocations with 'Delta<W>'.
48       // They may be turned into NegDelta<W> by parsePairRelocation.
49       if (!RI.r_pcrel && RI.r_extern) {
50         if (RI.r_length == 2)
51           return Delta32;
52         else if (RI.r_length == 3)
53           return Delta64;
54       }
55       break;
56     case MachO::ARM64_RELOC_BRANCH26:
57       if (RI.r_pcrel && RI.r_extern && RI.r_length == 2)
58         return Branch26;
59       break;
60     case MachO::ARM64_RELOC_PAGE21:
61       if (RI.r_pcrel && RI.r_extern && RI.r_length == 2)
62         return Page21;
63       break;
64     case MachO::ARM64_RELOC_PAGEOFF12:
65       if (!RI.r_pcrel && RI.r_extern && RI.r_length == 2)
66         return PageOffset12;
67       break;
68     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
69       if (RI.r_pcrel && RI.r_extern && RI.r_length == 2)
70         return GOTPage21;
71       break;
72     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
73       if (!RI.r_pcrel && RI.r_extern && RI.r_length == 2)
74         return GOTPageOffset12;
75       break;
76     case MachO::ARM64_RELOC_POINTER_TO_GOT:
77       if (RI.r_pcrel && RI.r_extern && RI.r_length == 2)
78         return PointerToGOT;
79       break;
80     case MachO::ARM64_RELOC_ADDEND:
81       if (!RI.r_pcrel && !RI.r_extern && RI.r_length == 2)
82         return PairedAddend;
83       break;
84     }
85 
86     return make_error<JITLinkError>(
87         "Unsupported arm64 relocation: address=" +
88         formatv("{0:x8}", RI.r_address) +
89         ", symbolnum=" + formatv("{0:x6}", RI.r_symbolnum) +
90         ", kind=" + formatv("{0:x1}", RI.r_type) +
91         ", pc_rel=" + (RI.r_pcrel ? "true" : "false") +
92         ", extern=" + (RI.r_extern ? "true" : "false") +
93         ", length=" + formatv("{0:d}", RI.r_length));
94   }
95 
96   using PairRelocInfo =
97       std::tuple<MachOARM64RelocationKind, Symbol *, uint64_t>;
98 
99   // Parses paired SUBTRACTOR/UNSIGNED relocations and, on success,
100   // returns the edge kind and addend to be used.
101   Expected<PairRelocInfo>
parsePairRelocation(Block & BlockToFix,Edge::Kind SubtractorKind,const MachO::relocation_info & SubRI,JITTargetAddress FixupAddress,const char * FixupContent,object::relocation_iterator & UnsignedRelItr,object::relocation_iterator & RelEnd)102   parsePairRelocation(Block &BlockToFix, Edge::Kind SubtractorKind,
103                       const MachO::relocation_info &SubRI,
104                       JITTargetAddress FixupAddress, const char *FixupContent,
105                       object::relocation_iterator &UnsignedRelItr,
106                       object::relocation_iterator &RelEnd) {
107     using namespace support;
108 
109     assert(((SubtractorKind == Delta32 && SubRI.r_length == 2) ||
110             (SubtractorKind == Delta64 && SubRI.r_length == 3)) &&
111            "Subtractor kind should match length");
112     assert(SubRI.r_extern && "SUBTRACTOR reloc symbol should be extern");
113     assert(!SubRI.r_pcrel && "SUBTRACTOR reloc should not be PCRel");
114 
115     if (UnsignedRelItr == RelEnd)
116       return make_error<JITLinkError>("arm64 SUBTRACTOR without paired "
117                                       "UNSIGNED relocation");
118 
119     auto UnsignedRI = getRelocationInfo(UnsignedRelItr);
120 
121     if (SubRI.r_address != UnsignedRI.r_address)
122       return make_error<JITLinkError>("arm64 SUBTRACTOR and paired UNSIGNED "
123                                       "point to different addresses");
124 
125     if (SubRI.r_length != UnsignedRI.r_length)
126       return make_error<JITLinkError>("length of arm64 SUBTRACTOR and paired "
127                                       "UNSIGNED reloc must match");
128 
129     Symbol *FromSymbol;
130     if (auto FromSymbolOrErr = findSymbolByIndex(SubRI.r_symbolnum))
131       FromSymbol = FromSymbolOrErr->GraphSymbol;
132     else
133       return FromSymbolOrErr.takeError();
134 
135     // Read the current fixup value.
136     uint64_t FixupValue = 0;
137     if (SubRI.r_length == 3)
138       FixupValue = *(const little64_t *)FixupContent;
139     else
140       FixupValue = *(const little32_t *)FixupContent;
141 
142     // Find 'ToSymbol' using symbol number or address, depending on whether the
143     // paired UNSIGNED relocation is extern.
144     Symbol *ToSymbol = nullptr;
145     if (UnsignedRI.r_extern) {
146       // Find target symbol by symbol index.
147       if (auto ToSymbolOrErr = findSymbolByIndex(UnsignedRI.r_symbolnum))
148         ToSymbol = ToSymbolOrErr->GraphSymbol;
149       else
150         return ToSymbolOrErr.takeError();
151     } else {
152       auto ToSymbolSec = findSectionByIndex(UnsignedRI.r_symbolnum - 1);
153       if (!ToSymbolSec)
154         return ToSymbolSec.takeError();
155       ToSymbol = getSymbolByAddress(ToSymbolSec->Address);
156       assert(ToSymbol && "No symbol for section");
157       FixupValue -= ToSymbol->getAddress();
158     }
159 
160     MachOARM64RelocationKind DeltaKind;
161     Symbol *TargetSymbol;
162     uint64_t Addend;
163     if (&BlockToFix == &FromSymbol->getAddressable()) {
164       TargetSymbol = ToSymbol;
165       DeltaKind = (SubRI.r_length == 3) ? Delta64 : Delta32;
166       Addend = FixupValue + (FixupAddress - FromSymbol->getAddress());
167       // FIXME: handle extern 'from'.
168     } else if (&BlockToFix == &ToSymbol->getAddressable()) {
169       TargetSymbol = &*FromSymbol;
170       DeltaKind = (SubRI.r_length == 3) ? NegDelta64 : NegDelta32;
171       Addend = FixupValue - (FixupAddress - ToSymbol->getAddress());
172     } else {
173       // BlockToFix was neither FromSymbol nor ToSymbol.
174       return make_error<JITLinkError>("SUBTRACTOR relocation must fix up "
175                                       "either 'A' or 'B' (or a symbol in one "
176                                       "of their alt-entry groups)");
177     }
178 
179     return PairRelocInfo(DeltaKind, TargetSymbol, Addend);
180   }
181 
addRelocations()182   Error addRelocations() override {
183     using namespace support;
184     auto &Obj = getObject();
185 
186     LLVM_DEBUG(dbgs() << "Processing relocations:\n");
187 
188     for (auto &S : Obj.sections()) {
189 
190       JITTargetAddress SectionAddress = S.getAddress();
191 
192       // Skip relocations virtual sections.
193       if (S.isVirtual()) {
194         if (S.relocation_begin() != S.relocation_end())
195           return make_error<JITLinkError>("Virtual section contains "
196                                           "relocations");
197         continue;
198       }
199 
200       // Skip relocations for debug symbols.
201       {
202         auto &NSec =
203             getSectionByIndex(Obj.getSectionIndex(S.getRawDataRefImpl()));
204         if (!NSec.GraphSection) {
205           LLVM_DEBUG({
206             dbgs() << "  Skipping relocations for MachO section "
207                    << NSec.SegName << "/" << NSec.SectName
208                    << " which has no associated graph section\n";
209           });
210           continue;
211         }
212       }
213 
214       for (auto RelItr = S.relocation_begin(), RelEnd = S.relocation_end();
215            RelItr != RelEnd; ++RelItr) {
216 
217         MachO::relocation_info RI = getRelocationInfo(RelItr);
218 
219         // Sanity check the relocation kind.
220         auto Kind = getRelocationKind(RI);
221         if (!Kind)
222           return Kind.takeError();
223 
224         // Find the address of the value to fix up.
225         JITTargetAddress FixupAddress = SectionAddress + (uint32_t)RI.r_address;
226 
227         LLVM_DEBUG({
228           auto &NSec =
229               getSectionByIndex(Obj.getSectionIndex(S.getRawDataRefImpl()));
230           dbgs() << "  " << NSec.SectName << " + "
231                  << formatv("{0:x8}", RI.r_address) << ":\n";
232         });
233 
234         // Find the block that the fixup points to.
235         Block *BlockToFix = nullptr;
236         {
237           auto SymbolToFixOrErr = findSymbolByAddress(FixupAddress);
238           if (!SymbolToFixOrErr)
239             return SymbolToFixOrErr.takeError();
240           BlockToFix = &SymbolToFixOrErr->getBlock();
241         }
242 
243         if (FixupAddress + static_cast<JITTargetAddress>(1ULL << RI.r_length) >
244             BlockToFix->getAddress() + BlockToFix->getContent().size())
245           return make_error<JITLinkError>(
246               "Relocation content extends past end of fixup block");
247 
248         // Get a pointer to the fixup content.
249         const char *FixupContent = BlockToFix->getContent().data() +
250                                    (FixupAddress - BlockToFix->getAddress());
251 
252         // The target symbol and addend will be populated by the switch below.
253         Symbol *TargetSymbol = nullptr;
254         uint64_t Addend = 0;
255 
256         if (*Kind == PairedAddend) {
257           // If this is an Addend relocation then process it and move to the
258           // paired reloc.
259 
260           Addend = SignExtend64(RI.r_symbolnum, 24);
261 
262           if (RelItr == RelEnd)
263             return make_error<JITLinkError>("Unpaired Addend reloc at " +
264                                             formatv("{0:x16}", FixupAddress));
265           ++RelItr;
266           RI = getRelocationInfo(RelItr);
267 
268           Kind = getRelocationKind(RI);
269           if (!Kind)
270             return Kind.takeError();
271 
272           if (*Kind != Branch26 && *Kind != Page21 && *Kind != PageOffset12)
273             return make_error<JITLinkError>(
274                 "Invalid relocation pair: Addend + " +
275                 StringRef(getMachOARM64RelocationKindName(*Kind)));
276 
277           LLVM_DEBUG({
278             dbgs() << "    Addend: value = " << formatv("{0:x6}", Addend)
279                    << ", pair is " << getMachOARM64RelocationKindName(*Kind)
280                    << "\n";
281           });
282 
283           // Find the address of the value to fix up.
284           JITTargetAddress PairedFixupAddress =
285               SectionAddress + (uint32_t)RI.r_address;
286           if (PairedFixupAddress != FixupAddress)
287             return make_error<JITLinkError>("Paired relocation points at "
288                                             "different target");
289         }
290 
291         switch (*Kind) {
292         case Branch26: {
293           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
294             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
295           else
296             return TargetSymbolOrErr.takeError();
297           uint32_t Instr = *(const ulittle32_t *)FixupContent;
298           if ((Instr & 0x7fffffff) != 0x14000000)
299             return make_error<JITLinkError>("BRANCH26 target is not a B or BL "
300                                             "instruction with a zero addend");
301           break;
302         }
303         case Pointer32:
304           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
305             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
306           else
307             return TargetSymbolOrErr.takeError();
308           Addend = *(const ulittle32_t *)FixupContent;
309           break;
310         case Pointer64:
311           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
312             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
313           else
314             return TargetSymbolOrErr.takeError();
315           Addend = *(const ulittle64_t *)FixupContent;
316           break;
317         case Pointer64Anon: {
318           JITTargetAddress TargetAddress = *(const ulittle64_t *)FixupContent;
319           if (auto TargetSymbolOrErr = findSymbolByAddress(TargetAddress))
320             TargetSymbol = &*TargetSymbolOrErr;
321           else
322             return TargetSymbolOrErr.takeError();
323           Addend = TargetAddress - TargetSymbol->getAddress();
324           break;
325         }
326         case Page21:
327         case GOTPage21: {
328           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
329             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
330           else
331             return TargetSymbolOrErr.takeError();
332           uint32_t Instr = *(const ulittle32_t *)FixupContent;
333           if ((Instr & 0xffffffe0) != 0x90000000)
334             return make_error<JITLinkError>("PAGE21/GOTPAGE21 target is not an "
335                                             "ADRP instruction with a zero "
336                                             "addend");
337           break;
338         }
339         case PageOffset12: {
340           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
341             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
342           else
343             return TargetSymbolOrErr.takeError();
344           uint32_t Instr = *(const ulittle32_t *)FixupContent;
345           uint32_t EncodedAddend = (Instr & 0x003FFC00) >> 10;
346           if (EncodedAddend != 0)
347             return make_error<JITLinkError>("GOTPAGEOFF12 target has non-zero "
348                                             "encoded addend");
349           break;
350         }
351         case GOTPageOffset12: {
352           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
353             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
354           else
355             return TargetSymbolOrErr.takeError();
356           uint32_t Instr = *(const ulittle32_t *)FixupContent;
357           if ((Instr & 0xfffffc00) != 0xf9400000)
358             return make_error<JITLinkError>("GOTPAGEOFF12 target is not an LDR "
359                                             "immediate instruction with a zero "
360                                             "addend");
361           break;
362         }
363         case PointerToGOT:
364           if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum))
365             TargetSymbol = TargetSymbolOrErr->GraphSymbol;
366           else
367             return TargetSymbolOrErr.takeError();
368           break;
369         case Delta32:
370         case Delta64: {
371           // We use Delta32/Delta64 to represent SUBTRACTOR relocations.
372           // parsePairRelocation handles the paired reloc, and returns the
373           // edge kind to be used (either Delta32/Delta64, or
374           // NegDelta32/NegDelta64, depending on the direction of the
375           // subtraction) along with the addend.
376           auto PairInfo =
377               parsePairRelocation(*BlockToFix, *Kind, RI, FixupAddress,
378                                   FixupContent, ++RelItr, RelEnd);
379           if (!PairInfo)
380             return PairInfo.takeError();
381           std::tie(*Kind, TargetSymbol, Addend) = *PairInfo;
382           assert(TargetSymbol && "No target symbol from parsePairRelocation?");
383           break;
384         }
385         default:
386           llvm_unreachable("Special relocation kind should not appear in "
387                            "mach-o file");
388         }
389 
390         LLVM_DEBUG({
391           dbgs() << "    ";
392           Edge GE(*Kind, FixupAddress - BlockToFix->getAddress(), *TargetSymbol,
393                   Addend);
394           printEdge(dbgs(), *BlockToFix, GE,
395                     getMachOARM64RelocationKindName(*Kind));
396           dbgs() << "\n";
397         });
398         BlockToFix->addEdge(*Kind, FixupAddress - BlockToFix->getAddress(),
399                             *TargetSymbol, Addend);
400       }
401     }
402     return Error::success();
403   }
404 
405   unsigned NumSymbols = 0;
406 };
407 
408 class PerGraphGOTAndPLTStubsBuilder_MachO_arm64
409     : public PerGraphGOTAndPLTStubsBuilder<
410           PerGraphGOTAndPLTStubsBuilder_MachO_arm64> {
411 public:
412   using PerGraphGOTAndPLTStubsBuilder<
413       PerGraphGOTAndPLTStubsBuilder_MachO_arm64>::PerGraphGOTAndPLTStubsBuilder;
414 
isGOTEdgeToFix(Edge & E) const415   bool isGOTEdgeToFix(Edge &E) const {
416     return (E.getKind() == GOTPage21 || E.getKind() == GOTPageOffset12 ||
417             E.getKind() == PointerToGOT) &&
418            E.getTarget().isExternal();
419   }
420 
createGOTEntry(Symbol & Target)421   Symbol &createGOTEntry(Symbol &Target) {
422     auto &GOTEntryBlock = G.createContentBlock(
423         getGOTSection(), getGOTEntryBlockContent(), 0, 8, 0);
424     GOTEntryBlock.addEdge(Pointer64, 0, Target, 0);
425     return G.addAnonymousSymbol(GOTEntryBlock, 0, 8, false, false);
426   }
427 
fixGOTEdge(Edge & E,Symbol & GOTEntry)428   void fixGOTEdge(Edge &E, Symbol &GOTEntry) {
429     if (E.getKind() == GOTPage21 || E.getKind() == GOTPageOffset12) {
430       // Update the target, but leave the edge addend as-is.
431       E.setTarget(GOTEntry);
432     } else if (E.getKind() == PointerToGOT) {
433       E.setTarget(GOTEntry);
434       E.setKind(Delta32);
435     } else
436       llvm_unreachable("Not a GOT edge?");
437   }
438 
isExternalBranchEdge(Edge & E)439   bool isExternalBranchEdge(Edge &E) {
440     return E.getKind() == Branch26 && !E.getTarget().isDefined();
441   }
442 
createPLTStub(Symbol & Target)443   Symbol &createPLTStub(Symbol &Target) {
444     auto &StubContentBlock =
445         G.createContentBlock(getStubsSection(), getStubBlockContent(), 0, 1, 0);
446     // Re-use GOT entries for stub targets.
447     auto &GOTEntrySymbol = getGOTEntry(Target);
448     StubContentBlock.addEdge(LDRLiteral19, 0, GOTEntrySymbol, 0);
449     return G.addAnonymousSymbol(StubContentBlock, 0, 8, true, false);
450   }
451 
fixPLTEdge(Edge & E,Symbol & Stub)452   void fixPLTEdge(Edge &E, Symbol &Stub) {
453     assert(E.getKind() == Branch26 && "Not a Branch32 edge?");
454     assert(E.getAddend() == 0 && "Branch32 edge has non-zero addend?");
455     E.setTarget(Stub);
456   }
457 
458 private:
getGOTSection()459   Section &getGOTSection() {
460     if (!GOTSection)
461       GOTSection = &G.createSection("$__GOT", sys::Memory::MF_READ);
462     return *GOTSection;
463   }
464 
getStubsSection()465   Section &getStubsSection() {
466     if (!StubsSection) {
467       auto StubsProt = static_cast<sys::Memory::ProtectionFlags>(
468           sys::Memory::MF_READ | sys::Memory::MF_EXEC);
469       StubsSection = &G.createSection("$__STUBS", StubsProt);
470     }
471     return *StubsSection;
472   }
473 
getGOTEntryBlockContent()474   ArrayRef<char> getGOTEntryBlockContent() {
475     return {reinterpret_cast<const char *>(NullGOTEntryContent),
476             sizeof(NullGOTEntryContent)};
477   }
478 
getStubBlockContent()479   ArrayRef<char> getStubBlockContent() {
480     return {reinterpret_cast<const char *>(StubContent), sizeof(StubContent)};
481   }
482 
483   static const uint8_t NullGOTEntryContent[8];
484   static const uint8_t StubContent[8];
485   Section *GOTSection = nullptr;
486   Section *StubsSection = nullptr;
487 };
488 
489 const uint8_t
490     PerGraphGOTAndPLTStubsBuilder_MachO_arm64::NullGOTEntryContent[8] = {
491         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
492 const uint8_t PerGraphGOTAndPLTStubsBuilder_MachO_arm64::StubContent[8] = {
493     0x10, 0x00, 0x00, 0x58, // LDR x16, <literal>
494     0x00, 0x02, 0x1f, 0xd6  // BR  x16
495 };
496 
497 } // namespace
498 
499 namespace llvm {
500 namespace jitlink {
501 
502 class MachOJITLinker_arm64 : public JITLinker<MachOJITLinker_arm64> {
503   friend class JITLinker<MachOJITLinker_arm64>;
504 
505 public:
MachOJITLinker_arm64(std::unique_ptr<JITLinkContext> Ctx,std::unique_ptr<LinkGraph> G,PassConfiguration PassConfig)506   MachOJITLinker_arm64(std::unique_ptr<JITLinkContext> Ctx,
507                        std::unique_ptr<LinkGraph> G,
508                        PassConfiguration PassConfig)
509       : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {}
510 
511 private:
512 
getPageOffset12Shift(uint32_t Instr)513   static unsigned getPageOffset12Shift(uint32_t Instr) {
514     constexpr uint32_t LoadStoreImm12Mask = 0x3b000000;
515     constexpr uint32_t Vec128Mask = 0x04800000;
516 
517     if ((Instr & LoadStoreImm12Mask) == 0x39000000) {
518       uint32_t ImplicitShift = Instr >> 30;
519       if (ImplicitShift == 0)
520         if ((Instr & Vec128Mask) == Vec128Mask)
521           ImplicitShift = 4;
522 
523       return ImplicitShift;
524     }
525 
526     return 0;
527   }
528 
applyFixup(LinkGraph & G,Block & B,const Edge & E,char * BlockWorkingMem) const529   Error applyFixup(LinkGraph &G, Block &B, const Edge &E,
530                    char *BlockWorkingMem) const {
531     using namespace support;
532 
533     char *FixupPtr = BlockWorkingMem + E.getOffset();
534     JITTargetAddress FixupAddress = B.getAddress() + E.getOffset();
535 
536     switch (E.getKind()) {
537     case Branch26: {
538       assert((FixupAddress & 0x3) == 0 && "Branch-inst is not 32-bit aligned");
539 
540       int64_t Value = E.getTarget().getAddress() - FixupAddress + E.getAddend();
541 
542       if (static_cast<uint64_t>(Value) & 0x3)
543         return make_error<JITLinkError>("Branch26 target is not 32-bit "
544                                         "aligned");
545 
546       if (Value < -(1 << 27) || Value > ((1 << 27) - 1))
547         return makeTargetOutOfRangeError(G, B, E);
548 
549       uint32_t RawInstr = *(little32_t *)FixupPtr;
550       assert((RawInstr & 0x7fffffff) == 0x14000000 &&
551              "RawInstr isn't a B or BR immediate instruction");
552       uint32_t Imm = (static_cast<uint32_t>(Value) & ((1 << 28) - 1)) >> 2;
553       uint32_t FixedInstr = RawInstr | Imm;
554       *(little32_t *)FixupPtr = FixedInstr;
555       break;
556     }
557     case Pointer32: {
558       uint64_t Value = E.getTarget().getAddress() + E.getAddend();
559       if (Value > std::numeric_limits<uint32_t>::max())
560         return makeTargetOutOfRangeError(G, B, E);
561       *(ulittle32_t *)FixupPtr = Value;
562       break;
563     }
564     case Pointer64:
565     case Pointer64Anon: {
566       uint64_t Value = E.getTarget().getAddress() + E.getAddend();
567       *(ulittle64_t *)FixupPtr = Value;
568       break;
569     }
570     case Page21:
571     case GOTPage21: {
572       assert((E.getKind() != GOTPage21 || E.getAddend() == 0) &&
573              "GOTPAGE21 with non-zero addend");
574       uint64_t TargetPage =
575           (E.getTarget().getAddress() + E.getAddend()) &
576             ~static_cast<uint64_t>(4096 - 1);
577       uint64_t PCPage = FixupAddress & ~static_cast<uint64_t>(4096 - 1);
578 
579       int64_t PageDelta = TargetPage - PCPage;
580       if (PageDelta < -(1 << 30) || PageDelta > ((1 << 30) - 1))
581         return makeTargetOutOfRangeError(G, B, E);
582 
583       uint32_t RawInstr = *(ulittle32_t *)FixupPtr;
584       assert((RawInstr & 0xffffffe0) == 0x90000000 &&
585              "RawInstr isn't an ADRP instruction");
586       uint32_t ImmLo = (static_cast<uint64_t>(PageDelta) >> 12) & 0x3;
587       uint32_t ImmHi = (static_cast<uint64_t>(PageDelta) >> 14) & 0x7ffff;
588       uint32_t FixedInstr = RawInstr | (ImmLo << 29) | (ImmHi << 5);
589       *(ulittle32_t *)FixupPtr = FixedInstr;
590       break;
591     }
592     case PageOffset12: {
593       uint64_t TargetOffset =
594         (E.getTarget().getAddress() + E.getAddend()) & 0xfff;
595 
596       uint32_t RawInstr = *(ulittle32_t *)FixupPtr;
597       unsigned ImmShift = getPageOffset12Shift(RawInstr);
598 
599       if (TargetOffset & ((1 << ImmShift) - 1))
600         return make_error<JITLinkError>("PAGEOFF12 target is not aligned");
601 
602       uint32_t EncodedImm = (TargetOffset >> ImmShift) << 10;
603       uint32_t FixedInstr = RawInstr | EncodedImm;
604       *(ulittle32_t *)FixupPtr = FixedInstr;
605       break;
606     }
607     case GOTPageOffset12: {
608       assert(E.getAddend() == 0 && "GOTPAGEOF12 with non-zero addend");
609 
610       uint32_t RawInstr = *(ulittle32_t *)FixupPtr;
611       assert((RawInstr & 0xfffffc00) == 0xf9400000 &&
612              "RawInstr isn't a 64-bit LDR immediate");
613 
614       uint32_t TargetOffset = E.getTarget().getAddress() & 0xfff;
615       assert((TargetOffset & 0x7) == 0 && "GOT entry is not 8-byte aligned");
616       uint32_t EncodedImm = (TargetOffset >> 3) << 10;
617       uint32_t FixedInstr = RawInstr | EncodedImm;
618       *(ulittle32_t *)FixupPtr = FixedInstr;
619       break;
620     }
621     case LDRLiteral19: {
622       assert((FixupAddress & 0x3) == 0 && "LDR is not 32-bit aligned");
623       assert(E.getAddend() == 0 && "LDRLiteral19 with non-zero addend");
624       uint32_t RawInstr = *(ulittle32_t *)FixupPtr;
625       assert(RawInstr == 0x58000010 && "RawInstr isn't a 64-bit LDR literal");
626       int64_t Delta = E.getTarget().getAddress() - FixupAddress;
627       if (Delta & 0x3)
628         return make_error<JITLinkError>("LDR literal target is not 32-bit "
629                                         "aligned");
630       if (Delta < -(1 << 20) || Delta > ((1 << 20) - 1))
631         return makeTargetOutOfRangeError(G, B, E);
632 
633       uint32_t EncodedImm = (static_cast<uint32_t>(Delta) >> 2) << 5;
634       uint32_t FixedInstr = RawInstr | EncodedImm;
635       *(ulittle32_t *)FixupPtr = FixedInstr;
636       break;
637     }
638     case Delta32:
639     case Delta64:
640     case NegDelta32:
641     case NegDelta64: {
642       int64_t Value;
643       if (E.getKind() == Delta32 || E.getKind() == Delta64)
644         Value = E.getTarget().getAddress() - FixupAddress + E.getAddend();
645       else
646         Value = FixupAddress - E.getTarget().getAddress() + E.getAddend();
647 
648       if (E.getKind() == Delta32 || E.getKind() == NegDelta32) {
649         if (Value < std::numeric_limits<int32_t>::min() ||
650             Value > std::numeric_limits<int32_t>::max())
651           return makeTargetOutOfRangeError(G, B, E);
652         *(little32_t *)FixupPtr = Value;
653       } else
654         *(little64_t *)FixupPtr = Value;
655       break;
656     }
657     default:
658       llvm_unreachable("Unrecognized edge kind");
659     }
660 
661     return Error::success();
662   }
663 
664   uint64_t NullValue = 0;
665 };
666 
667 Expected<std::unique_ptr<LinkGraph>>
createLinkGraphFromMachOObject_arm64(MemoryBufferRef ObjectBuffer)668 createLinkGraphFromMachOObject_arm64(MemoryBufferRef ObjectBuffer) {
669   auto MachOObj = object::ObjectFile::createMachOObjectFile(ObjectBuffer);
670   if (!MachOObj)
671     return MachOObj.takeError();
672   return MachOLinkGraphBuilder_arm64(**MachOObj).buildGraph();
673 }
674 
link_MachO_arm64(std::unique_ptr<LinkGraph> G,std::unique_ptr<JITLinkContext> Ctx)675 void link_MachO_arm64(std::unique_ptr<LinkGraph> G,
676                       std::unique_ptr<JITLinkContext> Ctx) {
677 
678   PassConfiguration Config;
679 
680   if (Ctx->shouldAddDefaultTargetPasses(G->getTargetTriple())) {
681     // Add a mark-live pass.
682     if (auto MarkLive = Ctx->getMarkLivePass(G->getTargetTriple()))
683       Config.PrePrunePasses.push_back(std::move(MarkLive));
684     else
685       Config.PrePrunePasses.push_back(markAllSymbolsLive);
686 
687     // Add an in-place GOT/Stubs pass.
688     Config.PostPrunePasses.push_back(
689         PerGraphGOTAndPLTStubsBuilder_MachO_arm64::asPass);
690   }
691 
692   if (auto Err = Ctx->modifyPassConfig(*G, Config))
693     return Ctx->notifyFailed(std::move(Err));
694 
695   // Construct a JITLinker and run the link function.
696   MachOJITLinker_arm64::link(std::move(Ctx), std::move(G), std::move(Config));
697 }
698 
getMachOARM64RelocationKindName(Edge::Kind R)699 const char *getMachOARM64RelocationKindName(Edge::Kind R) {
700   switch (R) {
701   case Branch26:
702     return "Branch26";
703   case Pointer64:
704     return "Pointer64";
705   case Pointer64Anon:
706     return "Pointer64Anon";
707   case Page21:
708     return "Page21";
709   case PageOffset12:
710     return "PageOffset12";
711   case GOTPage21:
712     return "GOTPage21";
713   case GOTPageOffset12:
714     return "GOTPageOffset12";
715   case PointerToGOT:
716     return "PointerToGOT";
717   case PairedAddend:
718     return "PairedAddend";
719   case LDRLiteral19:
720     return "LDRLiteral19";
721   case Delta32:
722     return "Delta32";
723   case Delta64:
724     return "Delta64";
725   case NegDelta32:
726     return "NegDelta32";
727   case NegDelta64:
728     return "NegDelta64";
729   default:
730     return getGenericEdgeKindName(static_cast<Edge::Kind>(R));
731   }
732 }
733 
734 } // end namespace jitlink
735 } // end namespace llvm
736