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