Add support for archives and object file caching under MCJIT.
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyld.cpp
1 //===-- RuntimeDyld.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 #define DEBUG_TYPE "dyld"
15 #include "llvm/ExecutionEngine/RuntimeDyld.h"
16 #include "JITRegistrar.h"
17 #include "ObjectImageCommon.h"
18 #include "RuntimeDyldELF.h"
19 #include "RuntimeDyldImpl.h"
20 #include "RuntimeDyldMachO.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MutexGuard.h"
24 #include "llvm/Object/ELF.h"
25
26 using namespace llvm;
27 using namespace llvm::object;
28
29 // Empty out-of-line virtual destructor as the key function.
30 RuntimeDyldImpl::~RuntimeDyldImpl() {}
31
32 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
33 void JITRegistrar::anchor() {}
34 void ObjectImage::anchor() {}
35 void ObjectImageCommon::anchor() {}
36
37 namespace llvm {
38
39 void RuntimeDyldImpl::registerEHFrames() {
40 }
41
42 void RuntimeDyldImpl::deregisterEHFrames() {
43 }
44
45 // Resolve the relocations for all symbols we currently know about.
46 void RuntimeDyldImpl::resolveRelocations() {
47   MutexGuard locked(lock);
48
49   // First, resolve relocations associated with external symbols.
50   resolveExternalSymbols();
51
52   // Just iterate over the sections we have and resolve all the relocations
53   // in them. Gross overkill, but it gets the job done.
54   for (int i = 0, e = Sections.size(); i != e; ++i) {
55     // The Section here (Sections[i]) refers to the section in which the
56     // symbol for the relocation is located.  The SectionID in the relocation
57     // entry provides the section to which the relocation will be applied.
58     uint64_t Addr = Sections[i].LoadAddress;
59     DEBUG(dbgs() << "Resolving relocations Section #" << i
60             << "\t" << format("%p", (uint8_t *)Addr)
61             << "\n");
62     resolveRelocationList(Relocations[i], Addr);
63     Relocations.erase(i);
64   }
65 }
66
67 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
68                                         uint64_t TargetAddress) {
69   MutexGuard locked(lock);
70   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
71     if (Sections[i].Address == LocalAddress) {
72       reassignSectionAddress(i, TargetAddress);
73       return;
74     }
75   }
76   llvm_unreachable("Attempting to remap address of unknown section!");
77 }
78
79 // Subclasses can implement this method to create specialized image instances.
80 // The caller owns the pointer that is returned.
81 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
82   return new ObjectImageCommon(InputBuffer);
83 }
84
85 ObjectImage *RuntimeDyldImpl::createObjectImageFromFile(ObjectFile *InputObject) {
86   return new ObjectImageCommon(InputObject);
87 }
88
89 ObjectImage *RuntimeDyldImpl::loadObject(ObjectFile *InputObject) {
90   return loadObject(createObjectImageFromFile(InputObject));
91 }
92
93 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
94   return loadObject(createObjectImage(InputBuffer));
95
96
97 ObjectImage *RuntimeDyldImpl::loadObject(ObjectImage *InputObject) {
98   MutexGuard locked(lock);
99
100   OwningPtr<ObjectImage> obj(InputObject);
101   if (!obj)
102     return NULL;
103
104   // Save information about our target
105   Arch = (Triple::ArchType)obj->getArch();
106   IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
107
108   // Symbols found in this object
109   StringMap<SymbolLoc> LocalSymbols;
110   // Used sections from the object file
111   ObjSectionToIDMap LocalSections;
112
113   // Common symbols requiring allocation, with their sizes and alignments
114   CommonSymbolMap CommonSymbols;
115   // Maximum required total memory to allocate all common symbols
116   uint64_t CommonSize = 0;
117
118   error_code err;
119   // Parse symbols
120   DEBUG(dbgs() << "Parse symbols:\n");
121   for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
122        i != e; i.increment(err)) {
123     Check(err);
124     object::SymbolRef::Type SymType;
125     StringRef Name;
126     Check(i->getType(SymType));
127     Check(i->getName(Name));
128
129     uint32_t flags;
130     Check(i->getFlags(flags));
131
132     bool isCommon = flags & SymbolRef::SF_Common;
133     if (isCommon) {
134       // Add the common symbols to a list.  We'll allocate them all below.
135       uint32_t Align;
136       Check(i->getAlignment(Align));
137       uint64_t Size = 0;
138       Check(i->getSize(Size));
139       CommonSize += Size + Align;
140       CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
141     } else {
142       if (SymType == object::SymbolRef::ST_Function ||
143           SymType == object::SymbolRef::ST_Data ||
144           SymType == object::SymbolRef::ST_Unknown) {
145         uint64_t FileOffset;
146         StringRef SectionData;
147         bool IsCode;
148         section_iterator si = obj->end_sections();
149         Check(i->getFileOffset(FileOffset));
150         Check(i->getSection(si));
151         if (si == obj->end_sections()) continue;
152         Check(si->getContents(SectionData));
153         Check(si->isText(IsCode));
154         const uint8_t* SymPtr = (const uint8_t*)InputObject->getData().data() +
155                                 (uintptr_t)FileOffset;
156         uintptr_t SectOffset = (uintptr_t)(SymPtr -
157                                            (const uint8_t*)SectionData.begin());
158         unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
159         LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
160         DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
161                      << " flags: " << flags
162                      << " SID: " << SectionID
163                      << " Offset: " << format("%p", SectOffset));
164         GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
165       }
166     }
167     DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
168   }
169
170   // Allocate common symbols
171   if (CommonSize != 0)
172     emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
173
174   // Parse and process relocations
175   DEBUG(dbgs() << "Parse relocations:\n");
176   for (section_iterator si = obj->begin_sections(),
177        se = obj->end_sections(); si != se; si.increment(err)) {
178     Check(err);
179     bool isFirstRelocation = true;
180     unsigned SectionID = 0;
181     StubMap Stubs;
182     section_iterator RelocatedSection = si->getRelocatedSection();
183
184     for (relocation_iterator i = si->begin_relocations(),
185          e = si->end_relocations(); i != e; i.increment(err)) {
186       Check(err);
187
188       // If it's the first relocation in this section, find its SectionID
189       if (isFirstRelocation) {
190         SectionID =
191             findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
192         DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
193         isFirstRelocation = false;
194       }
195
196       processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
197                            Stubs);
198     }
199   }
200
201   // Give the subclasses a chance to tie-up any loose ends.
202   finalizeLoad(LocalSections);
203
204   return obj.take();
205 }
206
207 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
208                                         const CommonSymbolMap &CommonSymbols,
209                                         uint64_t TotalSize,
210                                         SymbolTableMap &SymbolTable) {
211   // Allocate memory for the section
212   unsigned SectionID = Sections.size();
213   uint8_t *Addr = MemMgr->allocateDataSection(
214     TotalSize, sizeof(void*), SectionID, StringRef(), false);
215   if (!Addr)
216     report_fatal_error("Unable to allocate memory for common symbols!");
217   uint64_t Offset = 0;
218   Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
219   memset(Addr, 0, TotalSize);
220
221   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
222                << " new addr: " << format("%p", Addr)
223                << " DataSize: " << TotalSize
224                << "\n");
225
226   // Assign the address of each symbol
227   for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
228        itEnd = CommonSymbols.end(); it != itEnd; it++) {
229     uint64_t Size = it->second.first;
230     uint64_t Align = it->second.second;
231     StringRef Name;
232     it->first.getName(Name);
233     if (Align) {
234       // This symbol has an alignment requirement.
235       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
236       Addr += AlignOffset;
237       Offset += AlignOffset;
238       DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
239                       format("%p\n", Addr));
240     }
241     Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
242     SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
243     Offset += Size;
244     Addr += Size;
245   }
246 }
247
248 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
249                                       const SectionRef &Section,
250                                       bool IsCode) {
251
252   unsigned StubBufSize = 0,
253            StubSize = getMaxStubSize();
254   error_code err;
255   const ObjectFile *ObjFile = Obj.getObjectFile();
256   // FIXME: this is an inefficient way to handle this. We should computed the
257   // necessary section allocation size in loadObject by walking all the sections
258   // once.
259   if (StubSize > 0) {
260     for (section_iterator SI = ObjFile->begin_sections(),
261            SE = ObjFile->end_sections();
262          SI != SE; SI.increment(err), Check(err)) {
263       section_iterator RelSecI = SI->getRelocatedSection();
264       if (!(RelSecI == Section))
265         continue;
266
267       for (relocation_iterator I = SI->begin_relocations(),
268              E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
269         StubBufSize += StubSize;
270       }
271     }
272   }
273
274   StringRef data;
275   uint64_t Alignment64;
276   Check(Section.getContents(data));
277   Check(Section.getAlignment(Alignment64));
278
279   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
280   bool IsRequired;
281   bool IsVirtual;
282   bool IsZeroInit;
283   bool IsReadOnly;
284   uint64_t DataSize;
285   unsigned PaddingSize = 0;
286   StringRef Name;
287   Check(Section.isRequiredForExecution(IsRequired));
288   Check(Section.isVirtual(IsVirtual));
289   Check(Section.isZeroInit(IsZeroInit));
290   Check(Section.isReadOnlyData(IsReadOnly));
291   Check(Section.getSize(DataSize));
292   Check(Section.getName(Name));
293   if (StubSize > 0) {
294     unsigned StubAlignment = getStubAlignment();
295     unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
296     if (StubAlignment > EndAlignment)
297       StubBufSize += StubAlignment - EndAlignment;
298   }
299
300   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
301   // with zeroes added at the end.  For MachO objects, this section has a
302   // slightly different name, so this won't have any effect for MachO objects.
303   if (Name == ".eh_frame")
304     PaddingSize = 4;
305
306   unsigned Allocate;
307   unsigned SectionID = Sections.size();
308   uint8_t *Addr;
309   const char *pData = 0;
310
311   // Some sections, such as debug info, don't need to be loaded for execution.
312   // Leave those where they are.
313   if (IsRequired) {
314     Allocate = DataSize + PaddingSize + StubBufSize;
315     Addr = IsCode
316       ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
317       : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
318                                     IsReadOnly);
319     if (!Addr)
320       report_fatal_error("Unable to allocate section memory!");
321
322     // Virtual sections have no data in the object image, so leave pData = 0
323     if (!IsVirtual)
324       pData = data.data();
325
326     // Zero-initialize or copy the data from the image
327     if (IsZeroInit || IsVirtual)
328       memset(Addr, 0, DataSize);
329     else
330       memcpy(Addr, pData, DataSize);
331
332     // Fill in any extra bytes we allocated for padding
333     if (PaddingSize != 0) {
334       memset(Addr + DataSize, 0, PaddingSize);
335       // Update the DataSize variable so that the stub offset is set correctly.
336       DataSize += PaddingSize;
337     }
338
339     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
340                  << " Name: " << Name
341                  << " obj addr: " << format("%p", pData)
342                  << " new addr: " << format("%p", Addr)
343                  << " DataSize: " << DataSize
344                  << " StubBufSize: " << StubBufSize
345                  << " Allocate: " << Allocate
346                  << "\n");
347     Obj.updateSectionAddress(Section, (uint64_t)Addr);
348   }
349   else {
350     // Even if we didn't load the section, we need to record an entry for it
351     // to handle later processing (and by 'handle' I mean don't do anything
352     // with these sections).
353     Allocate = 0;
354     Addr = 0;
355     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
356                  << " Name: " << Name
357                  << " obj addr: " << format("%p", data.data())
358                  << " new addr: 0"
359                  << " DataSize: " << DataSize
360                  << " StubBufSize: " << StubBufSize
361                  << " Allocate: " << Allocate
362                  << "\n");
363   }
364
365   Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
366   return SectionID;
367 }
368
369 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
370                                             const SectionRef &Section,
371                                             bool IsCode,
372                                             ObjSectionToIDMap &LocalSections) {
373
374   unsigned SectionID = 0;
375   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
376   if (i != LocalSections.end())
377     SectionID = i->second;
378   else {
379     SectionID = emitSection(Obj, Section, IsCode);
380     LocalSections[Section] = SectionID;
381   }
382   return SectionID;
383 }
384
385 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
386                                               unsigned SectionID) {
387   Relocations[SectionID].push_back(RE);
388 }
389
390 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
391                                              StringRef SymbolName) {
392   // Relocation by symbol.  If the symbol is found in the global symbol table,
393   // create an appropriate section relocation.  Otherwise, add it to
394   // ExternalSymbolRelocations.
395   SymbolTableMap::const_iterator Loc =
396       GlobalSymbolTable.find(SymbolName);
397   if (Loc == GlobalSymbolTable.end()) {
398     ExternalSymbolRelocations[SymbolName].push_back(RE);
399   } else {
400     // Copy the RE since we want to modify its addend.
401     RelocationEntry RECopy = RE;
402     RECopy.Addend += Loc->second.second;
403     Relocations[Loc->second.first].push_back(RECopy);
404   }
405 }
406
407 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
408   if (Arch == Triple::aarch64) {
409     // This stub has to be able to access the full address space,
410     // since symbol lookup won't necessarily find a handy, in-range,
411     // PLT stub for functions which could be anywhere.
412     uint32_t *StubAddr = (uint32_t*)Addr;
413
414     // Stub can use ip0 (== x16) to calculate address
415     *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
416     StubAddr++;
417     *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
418     StubAddr++;
419     *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
420     StubAddr++;
421     *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
422     StubAddr++;
423     *StubAddr = 0xd61f0200; // br ip0
424
425     return Addr;
426   } else if (Arch == Triple::arm) {
427     // TODO: There is only ARM far stub now. We should add the Thumb stub,
428     // and stubs for branches Thumb - ARM and ARM - Thumb.
429     uint32_t *StubAddr = (uint32_t*)Addr;
430     *StubAddr = 0xe51ff004; // ldr pc,<label>
431     return (uint8_t*)++StubAddr;
432   } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
433     uint32_t *StubAddr = (uint32_t*)Addr;
434     // 0:   3c190000        lui     t9,%hi(addr).
435     // 4:   27390000        addiu   t9,t9,%lo(addr).
436     // 8:   03200008        jr      t9.
437     // c:   00000000        nop.
438     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
439     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
440
441     *StubAddr = LuiT9Instr;
442     StubAddr++;
443     *StubAddr = AdduiT9Instr;
444     StubAddr++;
445     *StubAddr = JrT9Instr;
446     StubAddr++;
447     *StubAddr = NopInstr;
448     return Addr;
449   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
450     // PowerPC64 stub: the address points to a function descriptor
451     // instead of the function itself. Load the function address
452     // on r11 and sets it to control register. Also loads the function
453     // TOC in r2 and environment pointer to r11.
454     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
455     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
456     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
457     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
458     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
459     writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
460     writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
461     writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
462     writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
463     writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
464     writeInt32BE(Addr+40, 0x4E800420); // bctr
465
466     return Addr;
467   } else if (Arch == Triple::systemz) {
468     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
469     writeInt16BE(Addr+2,  0x0000);
470     writeInt16BE(Addr+4,  0x0004);
471     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
472     // 8-byte address stored at Addr + 8
473     return Addr;
474   } else if (Arch == Triple::x86_64) {
475     *Addr      = 0xFF; // jmp
476     *(Addr+1)  = 0x25; // rip
477     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
478   }
479   return Addr;
480 }
481
482 // Assign an address to a symbol name and resolve all the relocations
483 // associated with it.
484 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
485                                              uint64_t Addr) {
486   // The address to use for relocation resolution is not
487   // the address of the local section buffer. We must be doing
488   // a remote execution environment of some sort. Relocations can't
489   // be applied until all the sections have been moved.  The client must
490   // trigger this with a call to MCJIT::finalize() or
491   // RuntimeDyld::resolveRelocations().
492   //
493   // Addr is a uint64_t because we can't assume the pointer width
494   // of the target is the same as that of the host. Just use a generic
495   // "big enough" type.
496   Sections[SectionID].LoadAddress = Addr;
497 }
498
499 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
500                                             uint64_t Value) {
501   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
502     const RelocationEntry &RE = Relocs[i];
503     // Ignore relocations for sections that were not loaded
504     if (Sections[RE.SectionID].Address == 0)
505       continue;
506     resolveRelocation(RE, Value);
507   }
508 }
509
510 void RuntimeDyldImpl::resolveExternalSymbols() {
511   while(!ExternalSymbolRelocations.empty()) {
512     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
513
514     StringRef Name = i->first();
515     if (Name.size() == 0) {
516       // This is an absolute symbol, use an address of zero.
517       DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
518       RelocationList &Relocs = i->second;
519       resolveRelocationList(Relocs, 0);
520     } else {
521       uint64_t Addr = 0;
522       SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
523       if (Loc == GlobalSymbolTable.end()) {
524           // This is an external symbol, try to get its address from
525           // MemoryManager.
526           Addr = MemMgr->getSymbolAddress(Name.data());
527           // The call to getSymbolAddress may have caused additional modules to
528           // be loaded, which may have added new entries to the
529           // ExternalSymbolRelocations map.  Consquently, we need to update our
530           // iterator.  This is also why retrieval of the relocation list
531           // associated with this symbol is deferred until below this point.
532           // New entries may have been added to the relocation list.
533           i = ExternalSymbolRelocations.find(Name);
534       } else {
535         // We found the symbol in our global table.  It was probably in a
536         // Module that we loaded previously.
537         SymbolLoc SymLoc = Loc->second;
538         Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
539       }
540
541       // FIXME: Implement error handling that doesn't kill the host program!
542       if (!Addr)
543         report_fatal_error("Program used external function '" + Name +
544                           "' which could not be resolved!");
545
546       updateGOTEntries(Name, Addr);
547       DEBUG(dbgs() << "Resolving relocations Name: " << Name
548               << "\t" << format("0x%lx", Addr)
549               << "\n");
550       // This list may have been updated when we called getSymbolAddress, so
551       // don't change this code to get the list earlier.
552       RelocationList &Relocs = i->second;
553       resolveRelocationList(Relocs, Addr);
554     }
555
556     ExternalSymbolRelocations.erase(i);
557   }
558 }
559
560
561 //===----------------------------------------------------------------------===//
562 // RuntimeDyld class implementation
563 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
564   // FIXME: There's a potential issue lurking here if a single instance of
565   // RuntimeDyld is used to load multiple objects.  The current implementation
566   // associates a single memory manager with a RuntimeDyld instance.  Even
567   // though the public class spawns a new 'impl' instance for each load,
568   // they share a single memory manager.  This can become a problem when page
569   // permissions are applied.
570   Dyld = 0;
571   MM = mm;
572 }
573
574 RuntimeDyld::~RuntimeDyld() {
575   delete Dyld;
576 }
577
578 ObjectImage *RuntimeDyld::loadObject(ObjectFile *InputObject) {
579   if (!Dyld) {
580     if (InputObject->isELF())
581       Dyld = new RuntimeDyldELF(MM);
582     else if (InputObject->isMachO())
583       Dyld = new RuntimeDyldMachO(MM);
584     else
585       report_fatal_error("Incompatible object format!");
586   } else {
587     if (!Dyld->isCompatibleFile(InputObject))
588       report_fatal_error("Incompatible object format!");
589   }
590
591   return Dyld->loadObject(InputObject);
592 }
593
594 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
595   if (!Dyld) {
596     sys::fs::file_magic Type =
597         sys::fs::identify_magic(InputBuffer->getBuffer());
598     switch (Type) {
599     case sys::fs::file_magic::elf_relocatable:
600     case sys::fs::file_magic::elf_executable:
601     case sys::fs::file_magic::elf_shared_object:
602     case sys::fs::file_magic::elf_core:
603       Dyld = new RuntimeDyldELF(MM);
604       break;
605     case sys::fs::file_magic::macho_object:
606     case sys::fs::file_magic::macho_executable:
607     case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
608     case sys::fs::file_magic::macho_core:
609     case sys::fs::file_magic::macho_preload_executable:
610     case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
611     case sys::fs::file_magic::macho_dynamic_linker:
612     case sys::fs::file_magic::macho_bundle:
613     case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
614     case sys::fs::file_magic::macho_dsym_companion:
615       Dyld = new RuntimeDyldMachO(MM);
616       break;
617     case sys::fs::file_magic::unknown:
618     case sys::fs::file_magic::bitcode:
619     case sys::fs::file_magic::archive:
620     case sys::fs::file_magic::coff_object:
621     case sys::fs::file_magic::coff_import_library:
622     case sys::fs::file_magic::pecoff_executable:
623     case sys::fs::file_magic::macho_universal_binary:
624     case sys::fs::file_magic::windows_resource:
625       report_fatal_error("Incompatible object format!");
626     }
627   } else {
628     if (!Dyld->isCompatibleFormat(InputBuffer))
629       report_fatal_error("Incompatible object format!");
630   }
631
632   return Dyld->loadObject(InputBuffer);
633 }
634
635 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
636   if (!Dyld)
637     return NULL;
638   return Dyld->getSymbolAddress(Name);
639 }
640
641 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
642   if (!Dyld)
643     return 0;
644   return Dyld->getSymbolLoadAddress(Name);
645 }
646
647 void RuntimeDyld::resolveRelocations() {
648   Dyld->resolveRelocations();
649 }
650
651 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
652                                          uint64_t Addr) {
653   Dyld->reassignSectionAddress(SectionID, Addr);
654 }
655
656 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
657                                     uint64_t TargetAddress) {
658   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
659 }
660
661 StringRef RuntimeDyld::getErrorString() {
662   return Dyld->getErrorString();
663 }
664
665 void RuntimeDyld::registerEHFrames() {
666   if (Dyld)
667     Dyld->registerEHFrames();
668 }
669
670 void RuntimeDyld::deregisterEHFrames() {
671   if (Dyld)
672     Dyld->deregisterEHFrames();
673 }
674
675 } // end namespace llvm