Layer the memory manager between the JIT and the runtime Dyld.
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyld.cpp
1 //===-- RuntimeDyld.h - 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 #define DEBUG_TYPE "dyld"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/ExecutionEngine/RuntimeDyld.h"
21 #include "llvm/Object/MachOObject.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/Memory.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/system_error.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::object;
31
32 namespace llvm {
33 class RuntimeDyldImpl {
34   unsigned CPUType;
35   unsigned CPUSubtype;
36
37   // The MemoryManager to load objects into.
38   RTDyldMemoryManager *MemMgr;
39
40   // Master symbol table. As modules are loaded and external symbols are
41   // resolved, their addresses are stored here.
42   StringMap<uint64_t> SymbolTable;
43
44   // FIXME: Should have multiple data blocks, one for each loaded chunk of
45   //        compiled code.
46   sys::MemoryBlock Data;
47
48   bool HasError;
49   std::string ErrorStr;
50
51   // Set the error state and record an error string.
52   bool Error(const Twine &Msg) {
53     ErrorStr = Msg.str();
54     HasError = true;
55     return true;
56   }
57
58   bool resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
59                          SmallVectorImpl<void *> &SectionBases,
60                          SmallVectorImpl<StringRef> &SymbolNames);
61   bool resolveX86_64Relocation(intptr_t Address, intptr_t Value, bool isPCRel,
62                                unsigned Type, unsigned Size);
63   bool resolveARMRelocation(intptr_t Address, intptr_t Value, bool isPCRel,
64                             unsigned Type, unsigned Size);
65
66   bool loadSegment32(const MachOObject *Obj,
67                      const MachOObject::LoadCommandInfo *SegmentLCI,
68                      const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
69   bool loadSegment64(const MachOObject *Obj,
70                      const MachOObject::LoadCommandInfo *SegmentLCI,
71                      const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
72
73 public:
74   RuntimeDyldImpl(RTDyldMemoryManager *mm) : MemMgr(mm), HasError(false) {}
75
76   bool loadObject(MemoryBuffer *InputBuffer);
77
78   uint64_t getSymbolAddress(StringRef Name) {
79     // Use lookup() rather than [] because we don't want to add an entry
80     // if there isn't one already, which the [] operator does.
81     return SymbolTable.lookup(Name);
82   }
83
84   sys::MemoryBlock getMemoryBlock() { return Data; }
85
86   // Is the linker in an error state?
87   bool hasError() { return HasError; }
88
89   // Mark the error condition as handled and continue.
90   void clearError() { HasError = false; }
91
92   // Get the error message.
93   StringRef getErrorString() { return ErrorStr; }
94 };
95
96 // FIXME: Relocations for targets other than x86_64.
97 bool RuntimeDyldImpl::
98 resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
99                   SmallVectorImpl<void *> &SectionBases,
100                   SmallVectorImpl<StringRef> &SymbolNames) {
101   // struct relocation_info {
102   //   int32_t r_address;
103   //   uint32_t r_symbolnum:24,
104   //            r_pcrel:1,
105   //            r_length:2,
106   //            r_extern:1,
107   //            r_type:4;
108   // };
109   uint32_t SymbolNum = RE.Word1 & 0xffffff; // 24-bit value
110   bool isPCRel = (RE.Word1 >> 24) & 1;
111   unsigned Log2Size = (RE.Word1 >> 25) & 3;
112   bool isExtern = (RE.Word1 >> 27) & 1;
113   unsigned Type = (RE.Word1 >> 28) & 0xf;
114   if (RE.Word0 & macho::RF_Scattered)
115     return Error("NOT YET IMPLEMENTED: scattered relocations.");
116
117   // The address requiring a relocation.
118   intptr_t Address = (intptr_t)SectionBases[BaseSection] + RE.Word0;
119
120   // Figure out the target address of the relocation. If isExtern is true,
121   // this relocation references the symbol table, otherwise it references
122   // a section in the same object, numbered from 1 through NumSections
123   // (SectionBases is [0, NumSections-1]).
124   intptr_t Value;
125   if (isExtern) {
126     StringRef Name = SymbolNames[SymbolNum];
127     if (SymbolTable.lookup(Name)) {
128       // The symbol is in our symbol table, so we can resolve it directly.
129       Value = (intptr_t)SymbolTable[Name];
130     } else {
131       return Error("NOT YET IMPLEMENTED: relocations to pre-compiled code.");
132     }
133     DEBUG(dbgs() << "Resolve relocation(" << Type << ") from '" << Name
134                  << "' to " << format("0x%x", Address) << ".\n");
135   } else {
136     // For non-external relocations, the SymbolNum is actual a section number
137     // as described above.
138     Value = (intptr_t)SectionBases[SymbolNum - 1];
139   }
140
141   unsigned Size = 1 << Log2Size;
142   switch (CPUType) {
143   default: assert(0 && "Unsupported CPU type!");
144   case mach::CTM_x86_64:
145     return resolveX86_64Relocation(Address, Value, isPCRel, Type, Size);
146   case mach::CTM_ARM:
147     return resolveARMRelocation(Address, Value, isPCRel, Type, Size);
148   }
149   llvm_unreachable("");
150 }
151
152 bool RuntimeDyldImpl::resolveX86_64Relocation(intptr_t Address, intptr_t Value,
153                                               bool isPCRel, unsigned Type,
154                                               unsigned Size) {
155   // If the relocation is PC-relative, the value to be encoded is the
156   // pointer difference.
157   if (isPCRel)
158     // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
159     // address. Is that expected? Only for branches, perhaps?
160     Value -= Address + 4;
161
162   switch(Type) {
163   default:
164     llvm_unreachable("Invalid relocation type!");
165   case macho::RIT_X86_64_Unsigned:
166   case macho::RIT_X86_64_Branch: {
167     // Mask in the target value a byte at a time (we don't have an alignment
168     // guarantee for the target address, so this is safest).
169     uint8_t *p = (uint8_t*)Address;
170     for (unsigned i = 0; i < Size; ++i) {
171       *p++ = (uint8_t)Value;
172       Value >>= 8;
173     }
174     return false;
175   }
176   case macho::RIT_X86_64_Signed:
177   case macho::RIT_X86_64_GOTLoad:
178   case macho::RIT_X86_64_GOT:
179   case macho::RIT_X86_64_Subtractor:
180   case macho::RIT_X86_64_Signed1:
181   case macho::RIT_X86_64_Signed2:
182   case macho::RIT_X86_64_Signed4:
183   case macho::RIT_X86_64_TLV:
184     return Error("Relocation type not implemented yet!");
185   }
186   return false;
187 }
188
189 bool RuntimeDyldImpl::resolveARMRelocation(intptr_t Address, intptr_t Value,
190                                            bool isPCRel, unsigned Type,
191                                            unsigned Size) {
192   // If the relocation is PC-relative, the value to be encoded is the
193   // pointer difference.
194   if (isPCRel) {
195     Value -= Address;
196     // ARM PCRel relocations have an effective-PC offset of two instructions
197     // (four bytes in Thumb mode, 8 bytes in ARM mode).
198     // FIXME: For now, assume ARM mode.
199     Value -= 8;
200   }
201
202   switch(Type) {
203   default:
204   case macho::RIT_Vanilla: {
205     llvm_unreachable("Invalid relocation type!");
206     // Mask in the target value a byte at a time (we don't have an alignment
207     // guarantee for the target address, so this is safest).
208     uint8_t *p = (uint8_t*)Address;
209     for (unsigned i = 0; i < Size; ++i) {
210       *p++ = (uint8_t)Value;
211       Value >>= 8;
212     }
213     break;
214   }
215   case macho::RIT_Pair:
216   case macho::RIT_Difference:
217   case macho::RIT_ARM_LocalDifference:
218   case macho::RIT_ARM_PreboundLazyPointer:
219   case macho::RIT_ARM_Branch24Bit: {
220     // Mask the value into the target address. We know instructions are
221     // 32-bit aligned, so we can do it all at once.
222     uint32_t *p = (uint32_t*)Address;
223     // The low two bits of the value are not encoded.
224     Value >>= 2;
225     // Mask the value to 24 bits.
226     Value &= 0xffffff;
227     // FIXME: If the destination is a Thumb function (and the instruction
228     // is a non-predicated BL instruction), we need to change it to a BLX
229     // instruction instead.
230
231     // Insert the value into the instruction.
232     *p = (*p & ~0xffffff) | Value;
233     break;
234   }
235   case macho::RIT_ARM_ThumbBranch22Bit:
236   case macho::RIT_ARM_ThumbBranch32Bit:
237   case macho::RIT_ARM_Half:
238   case macho::RIT_ARM_HalfDifference:
239     return Error("Relocation type not implemented yet!");
240   }
241   return false;
242 }
243
244 bool RuntimeDyldImpl::
245 loadSegment32(const MachOObject *Obj,
246               const MachOObject::LoadCommandInfo *SegmentLCI,
247               const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
248   InMemoryStruct<macho::SegmentLoadCommand> Segment32LC;
249   Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC);
250   if (!Segment32LC)
251     return Error("unable to load segment load command");
252
253   // Map the segment into memory.
254   std::string ErrorStr;
255   Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr);
256   if (!Data.base())
257     return Error("unable to allocate memory block: '" + ErrorStr + "'");
258   memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset,
259                                    Segment32LC->FileSize).data(),
260          Segment32LC->FileSize);
261   memset((char*)Data.base() + Segment32LC->FileSize, 0,
262          Segment32LC->VMSize - Segment32LC->FileSize);
263
264   // Bind the section indices to addresses and record the relocations we
265   // need to resolve.
266   typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
267   SmallVector<RelocationMap, 64> Relocations;
268
269   SmallVector<void *, 16> SectionBases;
270   for (unsigned i = 0; i != Segment32LC->NumSections; ++i) {
271     InMemoryStruct<macho::Section> Sect;
272     Obj->ReadSection(*SegmentLCI, i, Sect);
273     if (!Sect)
274       return Error("unable to load section: '" + Twine(i) + "'");
275
276     // Remember any relocations the section has so we can resolve them later.
277     for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
278       InMemoryStruct<macho::RelocationEntry> RE;
279       Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
280       Relocations.push_back(RelocationMap(j, *RE));
281     }
282
283     // FIXME: Improve check.
284 //    if (Sect->Flags != 0x80000400)
285 //      return Error("unsupported section type!");
286
287     SectionBases.push_back((char*) Data.base() + Sect->Address);
288   }
289
290   // Bind all the symbols to address. Keep a record of the names for use
291   // by relocation resolution.
292   SmallVector<StringRef, 64> SymbolNames;
293   for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
294     InMemoryStruct<macho::SymbolTableEntry> STE;
295     Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
296     if (!STE)
297       return Error("unable to read symbol: '" + Twine(i) + "'");
298     // Get the symbol name.
299     StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
300     SymbolNames.push_back(Name);
301
302     // Just skip undefined symbols. They'll be loaded from whatever
303     // module they come from (or system dylib) when we resolve relocations
304     // involving them.
305     if (STE->SectionIndex == 0)
306       continue;
307
308     unsigned Index = STE->SectionIndex - 1;
309     if (Index >= Segment32LC->NumSections)
310       return Error("invalid section index for symbol: '" + Twine() + "'");
311
312     // Get the section base address.
313     void *SectionBase = SectionBases[Index];
314
315     // Get the symbol address.
316     uint64_t Address = (uint64_t)SectionBase + STE->Value;
317
318     // FIXME: Check the symbol type and flags.
319     if (STE->Type != 0xF)
320       return Error("unexpected symbol type!");
321     if (STE->Flags != 0x0)
322       return Error("unexpected symbol type!");
323
324     DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
325
326     SymbolTable[Name] = Address;
327   }
328
329   // Now resolve any relocations.
330   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
331     if (resolveRelocation(Relocations[i].first, Relocations[i].second,
332                           SectionBases, SymbolNames))
333       return true;
334   }
335
336   // We've loaded the section; now mark the functions in it as executable.
337   // FIXME: We really should use the MemoryManager for this.
338   sys::Memory::setRangeExecutable(Data.base(), Data.size());
339
340   return false;
341 }
342
343
344 bool RuntimeDyldImpl::
345 loadSegment64(const MachOObject *Obj,
346               const MachOObject::LoadCommandInfo *SegmentLCI,
347               const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
348   InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
349   Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
350   if (!Segment64LC)
351     return Error("unable to load segment load command");
352
353   // Map the segment into memory.
354   std::string ErrorStr;
355   Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr);
356   if (!Data.base())
357     return Error("unable to allocate memory block: '" + ErrorStr + "'");
358   memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset,
359                                    Segment64LC->FileSize).data(),
360          Segment64LC->FileSize);
361   memset((char*)Data.base() + Segment64LC->FileSize, 0,
362          Segment64LC->VMSize - Segment64LC->FileSize);
363
364   // Bind the section indices to addresses and record the relocations we
365   // need to resolve.
366   typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
367   SmallVector<RelocationMap, 64> Relocations;
368
369   SmallVector<void *, 16> SectionBases;
370   for (unsigned i = 0; i != Segment64LC->NumSections; ++i) {
371     InMemoryStruct<macho::Section64> Sect;
372     Obj->ReadSection64(*SegmentLCI, i, Sect);
373     if (!Sect)
374       return Error("unable to load section: '" + Twine(i) + "'");
375
376     // Remember any relocations the section has so we can resolve them later.
377     for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
378       InMemoryStruct<macho::RelocationEntry> RE;
379       Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
380       Relocations.push_back(RelocationMap(j, *RE));
381     }
382
383     // FIXME: Improve check.
384     if (Sect->Flags != 0x80000400)
385       return Error("unsupported section type!");
386
387     SectionBases.push_back((char*) Data.base() + Sect->Address);
388   }
389
390   // Bind all the symbols to address. Keep a record of the names for use
391   // by relocation resolution.
392   SmallVector<StringRef, 64> SymbolNames;
393   for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
394     InMemoryStruct<macho::Symbol64TableEntry> STE;
395     Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
396     if (!STE)
397       return Error("unable to read symbol: '" + Twine(i) + "'");
398     // Get the symbol name.
399     StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
400     SymbolNames.push_back(Name);
401
402     // Just skip undefined symbols. They'll be loaded from whatever
403     // module they come from (or system dylib) when we resolve relocations
404     // involving them.
405     if (STE->SectionIndex == 0)
406       continue;
407
408     unsigned Index = STE->SectionIndex - 1;
409     if (Index >= Segment64LC->NumSections)
410       return Error("invalid section index for symbol: '" + Twine() + "'");
411
412     // Get the section base address.
413     void *SectionBase = SectionBases[Index];
414
415     // Get the symbol address.
416     uint64_t Address = (uint64_t) SectionBase + STE->Value;
417
418     // FIXME: Check the symbol type and flags.
419     if (STE->Type != 0xF)
420       return Error("unexpected symbol type!");
421     if (STE->Flags != 0x0)
422       return Error("unexpected symbol type!");
423
424     DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
425     SymbolTable[Name] = Address;
426   }
427
428   // Now resolve any relocations.
429   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
430     if (resolveRelocation(Relocations[i].first, Relocations[i].second,
431                           SectionBases, SymbolNames))
432       return true;
433   }
434
435   // We've loaded the section; now mark the functions in it as executable.
436   // FIXME: We really should use the MemoryManager for this.
437   sys::Memory::setRangeExecutable(Data.base(), Data.size());
438
439   return false;
440 }
441
442 bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) {
443   // If the linker is in an error state, don't do anything.
444   if (hasError())
445     return true;
446   // Load the Mach-O wrapper object.
447   std::string ErrorStr;
448   OwningPtr<MachOObject> Obj(
449     MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
450   if (!Obj)
451     return Error("unable to load object: '" + ErrorStr + "'");
452
453   // Get the CPU type information from the header.
454   const macho::Header &Header = Obj->getHeader();
455
456   // FIXME: Error checking that the loaded object is compatible with
457   //        the system we're running on.
458   CPUType = Header.CPUType;
459   CPUSubtype = Header.CPUSubtype;
460
461   // Validate that the load commands match what we expect.
462   const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0,
463     *DysymtabLCI = 0;
464   for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
465     const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i);
466     switch (LCI.Command.Type) {
467     case macho::LCT_Segment:
468     case macho::LCT_Segment64:
469       if (SegmentLCI)
470         return Error("unexpected input object (multiple segments)");
471       SegmentLCI = &LCI;
472       break;
473     case macho::LCT_Symtab:
474       if (SymtabLCI)
475         return Error("unexpected input object (multiple symbol tables)");
476       SymtabLCI = &LCI;
477       break;
478     case macho::LCT_Dysymtab:
479       if (DysymtabLCI)
480         return Error("unexpected input object (multiple symbol tables)");
481       DysymtabLCI = &LCI;
482       break;
483     default:
484       return Error("unexpected input object (unexpected load command");
485     }
486   }
487
488   if (!SymtabLCI)
489     return Error("no symbol table found in object");
490   if (!SegmentLCI)
491     return Error("no symbol table found in object");
492
493   // Read and register the symbol table data.
494   InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
495   Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
496   if (!SymtabLC)
497     return Error("unable to load symbol table load command");
498   Obj->RegisterStringTable(*SymtabLC);
499
500   // Read the dynamic link-edit information, if present (not present in static
501   // objects).
502   if (DysymtabLCI) {
503     InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
504     Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
505     if (!DysymtabLC)
506       return Error("unable to load dynamic link-exit load command");
507
508     // FIXME: We don't support anything interesting yet.
509 //    if (DysymtabLC->LocalSymbolsIndex != 0)
510 //      return Error("NOT YET IMPLEMENTED: local symbol entries");
511 //    if (DysymtabLC->ExternalSymbolsIndex != 0)
512 //      return Error("NOT YET IMPLEMENTED: non-external symbol entries");
513 //    if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries)
514 //      return Error("NOT YET IMPLEMENTED: undefined symbol entries");
515   }
516
517   // Load the segment load command.
518   if (SegmentLCI->Command.Type == macho::LCT_Segment) {
519     if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
520       return true;
521   } else {
522     if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
523       return true;
524   }
525
526   return false;
527 }
528
529
530 //===----------------------------------------------------------------------===//
531 // RuntimeDyld class implementation
532 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *MM) {
533   Dyld = new RuntimeDyldImpl(MM);
534 }
535
536 RuntimeDyld::~RuntimeDyld() {
537   delete Dyld;
538 }
539
540 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
541   return Dyld->loadObject(InputBuffer);
542 }
543
544 uint64_t RuntimeDyld::getSymbolAddress(StringRef Name) {
545   return Dyld->getSymbolAddress(Name);
546 }
547
548 sys::MemoryBlock RuntimeDyld::getMemoryBlock() {
549   return Dyld->getMemoryBlock();
550 }
551
552 StringRef RuntimeDyld::getErrorString() {
553   return Dyld->getErrorString();
554 }
555
556 } // end namespace llvm