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