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