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