1 //===-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RuntimeDyldMachO.h"
15 #include "Targets/RuntimeDyldMachOAArch64.h"
16 #include "Targets/RuntimeDyldMachOARM.h"
17 #include "Targets/RuntimeDyldMachOI386.h"
18 #include "Targets/RuntimeDyldMachOX86_64.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 
22 using namespace llvm;
23 using namespace llvm::object;
24 
25 #define DEBUG_TYPE "dyld"
26 
27 namespace {
28 
29 class LoadedMachOObjectInfo : public RuntimeDyld::LoadedObjectInfo {
30 public:
LoadedMachOObjectInfo(RuntimeDyldImpl & RTDyld,unsigned BeginIdx,unsigned EndIdx)31   LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
32                         unsigned EndIdx)
33     : RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
34 
35   OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile & Obj) const36   getObjectForDebug(const ObjectFile &Obj) const override {
37     return OwningBinary<ObjectFile>();
38   }
39 };
40 
41 }
42 
43 namespace llvm {
44 
memcpyAddend(const RelocationEntry & RE) const45 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
46   unsigned NumBytes = 1 << RE.Size;
47   uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
48 
49   return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
50 }
51 
getRelocationValueRef(const ObjectFile & BaseTObj,const relocation_iterator & RI,const RelocationEntry & RE,ObjSectionToIDMap & ObjSectionToID)52 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
53     const ObjectFile &BaseTObj, const relocation_iterator &RI,
54     const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
55 
56   const MachOObjectFile &Obj =
57       static_cast<const MachOObjectFile &>(BaseTObj);
58   MachO::any_relocation_info RelInfo =
59       Obj.getRelocation(RI->getRawDataRefImpl());
60   RelocationValueRef Value;
61 
62   bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
63   if (IsExternal) {
64     symbol_iterator Symbol = RI->getSymbol();
65     StringRef TargetName;
66     Symbol->getName(TargetName);
67     SymbolTableMap::const_iterator SI =
68       GlobalSymbolTable.find(TargetName.data());
69     if (SI != GlobalSymbolTable.end()) {
70       Value.SectionID = SI->second.first;
71       Value.Offset = SI->second.second + RE.Addend;
72     } else {
73       Value.SymbolName = TargetName.data();
74       Value.Offset = RE.Addend;
75     }
76   } else {
77     SectionRef Sec = Obj.getRelocationSection(RelInfo);
78     bool IsCode = Sec.isText();
79     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
80     uint64_t Addr = Sec.getAddress();
81     Value.Offset = RE.Addend - Addr;
82   }
83 
84   return Value;
85 }
86 
makeValueAddendPCRel(RelocationValueRef & Value,const ObjectFile & BaseTObj,const relocation_iterator & RI,unsigned OffsetToNextPC)87 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
88                                             const ObjectFile &BaseTObj,
89                                             const relocation_iterator &RI,
90                                             unsigned OffsetToNextPC) {
91   const MachOObjectFile &Obj =
92       static_cast<const MachOObjectFile &>(BaseTObj);
93   MachO::any_relocation_info RelInfo =
94       Obj.getRelocation(RI->getRawDataRefImpl());
95 
96   bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
97   if (IsPCRel) {
98     uint64_t RelocAddr = 0;
99     RI->getAddress(RelocAddr);
100     Value.Offset += RelocAddr + OffsetToNextPC;
101   }
102 }
103 
dumpRelocationToResolve(const RelocationEntry & RE,uint64_t Value) const104 void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
105                                                uint64_t Value) const {
106   const SectionEntry &Section = Sections[RE.SectionID];
107   uint8_t *LocalAddress = Section.Address + RE.Offset;
108   uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
109 
110   dbgs() << "resolveRelocation Section: " << RE.SectionID
111          << " LocalAddress: " << format("%p", LocalAddress)
112          << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
113          << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
114          << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
115          << " Size: " << (1 << RE.Size) << "\n";
116 }
117 
118 section_iterator
getSectionByAddress(const MachOObjectFile & Obj,uint64_t Addr)119 RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
120                                       uint64_t Addr) {
121   section_iterator SI = Obj.section_begin();
122   section_iterator SE = Obj.section_end();
123 
124   for (; SI != SE; ++SI) {
125     uint64_t SAddr = SI->getAddress();
126     uint64_t SSize = SI->getSize();
127     if ((Addr >= SAddr) && (Addr < SAddr + SSize))
128       return SI;
129   }
130 
131   return SE;
132 }
133 
134 
135 // Populate __pointers section.
populateIndirectSymbolPointersSection(const MachOObjectFile & Obj,const SectionRef & PTSection,unsigned PTSectionID)136 void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
137                                                     const MachOObjectFile &Obj,
138                                                     const SectionRef &PTSection,
139                                                     unsigned PTSectionID) {
140   assert(!Obj.is64Bit() &&
141          "Pointer table section not supported in 64-bit MachO.");
142 
143   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
144   MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
145   uint32_t PTSectionSize = Sec32.size;
146   unsigned FirstIndirectSymbol = Sec32.reserved1;
147   const unsigned PTEntrySize = 4;
148   unsigned NumPTEntries = PTSectionSize / PTEntrySize;
149   unsigned PTEntryOffset = 0;
150 
151   assert((PTSectionSize % PTEntrySize) == 0 &&
152          "Pointers section does not contain a whole number of stubs?");
153 
154   DEBUG(dbgs() << "Populating pointer table section "
155                << Sections[PTSectionID].Name
156                << ", Section ID " << PTSectionID << ", "
157                << NumPTEntries << " entries, " << PTEntrySize
158                << " bytes each:\n");
159 
160   for (unsigned i = 0; i < NumPTEntries; ++i) {
161     unsigned SymbolIndex =
162       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
163     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
164     StringRef IndirectSymbolName;
165     SI->getName(IndirectSymbolName);
166     DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
167           << ", PT offset: " << PTEntryOffset << "\n");
168     RelocationEntry RE(PTSectionID, PTEntryOffset,
169                        MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
170     addRelocationForSymbol(RE, IndirectSymbolName);
171     PTEntryOffset += PTEntrySize;
172   }
173 }
174 
isCompatibleFile(const object::ObjectFile & Obj) const175 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
176   return Obj.isMachO();
177 }
178 
179 template <typename Impl>
finalizeLoad(const ObjectFile & Obj,ObjSectionToIDMap & SectionMap)180 void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
181                                                   ObjSectionToIDMap &SectionMap) {
182   unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
183   unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
184   unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
185 
186   for (const auto &Section : Obj.sections()) {
187     StringRef Name;
188     Section.getName(Name);
189 
190     // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
191     // if they're present. Otherwise call down to the impl to handle other
192     // sections that have already been emitted.
193     if (Name == "__text")
194       TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
195     else if (Name == "__eh_frame")
196       EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
197     else if (Name == "__gcc_except_tab")
198       ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
199     else {
200       auto I = SectionMap.find(Section);
201       if (I != SectionMap.end())
202         impl().finalizeSection(Obj, I->second, Section);
203     }
204   }
205   UnregisteredEHFrameSections.push_back(
206     EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
207 }
208 
209 template <typename Impl>
processFDE(unsigned char * P,int64_t DeltaForText,int64_t DeltaForEH)210 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
211                                                           int64_t DeltaForText,
212                                                           int64_t DeltaForEH) {
213   typedef typename Impl::TargetPtrT TargetPtrT;
214 
215   DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
216                << ", Delta for EH: " << DeltaForEH << "\n");
217   uint32_t Length = readBytesUnaligned(P, 4);
218   P += 4;
219   unsigned char *Ret = P + Length;
220   uint32_t Offset = readBytesUnaligned(P, 4);
221   if (Offset == 0) // is a CIE
222     return Ret;
223 
224   P += 4;
225   TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
226   TargetPtrT NewLocation = FDELocation - DeltaForText;
227   writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
228 
229   P += sizeof(TargetPtrT);
230 
231   // Skip the FDE address range
232   P += sizeof(TargetPtrT);
233 
234   uint8_t Augmentationsize = *P;
235   P += 1;
236   if (Augmentationsize != 0) {
237     TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
238     TargetPtrT NewLSDA = LSDA - DeltaForEH;
239     writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
240   }
241 
242   return Ret;
243 }
244 
computeDelta(SectionEntry * A,SectionEntry * B)245 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
246   int64_t ObjDistance =
247     static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
248   int64_t MemDistance = A->LoadAddress - B->LoadAddress;
249   return ObjDistance - MemDistance;
250 }
251 
252 template <typename Impl>
registerEHFrames()253 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
254 
255   if (!MemMgr)
256     return;
257   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
258     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
259     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
260         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
261       continue;
262     SectionEntry *Text = &Sections[SectionInfo.TextSID];
263     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
264     SectionEntry *ExceptTab = nullptr;
265     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
266       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
267 
268     int64_t DeltaForText = computeDelta(Text, EHFrame);
269     int64_t DeltaForEH = 0;
270     if (ExceptTab)
271       DeltaForEH = computeDelta(ExceptTab, EHFrame);
272 
273     unsigned char *P = EHFrame->Address;
274     unsigned char *End = P + EHFrame->Size;
275     do {
276       P = processFDE(P, DeltaForText, DeltaForEH);
277     } while (P != End);
278 
279     MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
280                              EHFrame->Size);
281   }
282   UnregisteredEHFrameSections.clear();
283 }
284 
285 std::unique_ptr<RuntimeDyldMachO>
create(Triple::ArchType Arch,RTDyldMemoryManager * MM)286 RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
287   switch (Arch) {
288   default:
289     llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
290     break;
291   case Triple::arm: return make_unique<RuntimeDyldMachOARM>(MM);
292   case Triple::aarch64: return make_unique<RuntimeDyldMachOAArch64>(MM);
293   case Triple::x86: return make_unique<RuntimeDyldMachOI386>(MM);
294   case Triple::x86_64: return make_unique<RuntimeDyldMachOX86_64>(MM);
295   }
296 }
297 
298 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
loadObject(const object::ObjectFile & O)299 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
300   unsigned SectionStartIdx, SectionEndIdx;
301   std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
302   return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
303                                                   SectionEndIdx);
304 }
305 
306 } // end namespace llvm
307