Fix various issues (or do cleanups) found by enabling certain MSVC warnings.
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldMachO.cpp
1 //===-- RuntimeDyldMachO.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/ADT/OwningPtr.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "RuntimeDyldMachO.h"
19 using namespace llvm;
20 using namespace llvm::object;
21
22 namespace llvm {
23
24 bool RuntimeDyldMachO::
25 resolveRelocation(uint8_t *Address, uint64_t Value, bool isPCRel,
26                   unsigned Type, unsigned Size, int64_t Addend) {
27   // This just dispatches to the proper target specific routine.
28   switch (CPUType) {
29   default: llvm_unreachable("Unsupported CPU type!");
30   case mach::CTM_x86_64:
31     return resolveX86_64Relocation((uintptr_t)Address, (uintptr_t)Value,
32                                    isPCRel, Type, Size, Addend);
33   case mach::CTM_ARM:
34     return resolveARMRelocation((uintptr_t)Address, (uintptr_t)Value,
35                                 isPCRel, Type, Size, Addend);
36   }
37   llvm_unreachable("");
38 }
39
40 bool RuntimeDyldMachO::
41 resolveX86_64Relocation(uintptr_t Address, uintptr_t Value, bool isPCRel,
42                         unsigned Type, unsigned Size, int64_t Addend) {
43   // If the relocation is PC-relative, the value to be encoded is the
44   // pointer difference.
45   if (isPCRel)
46     // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
47     // address. Is that expected? Only for branches, perhaps?
48     Value -= Address + 4;
49
50   switch(Type) {
51   default:
52     llvm_unreachable("Invalid relocation type!");
53   case macho::RIT_X86_64_Signed1:
54   case macho::RIT_X86_64_Signed2:
55   case macho::RIT_X86_64_Signed4:
56   case macho::RIT_X86_64_Signed:
57   case macho::RIT_X86_64_Unsigned:
58   case macho::RIT_X86_64_Branch: {
59     Value += Addend;
60     // Mask in the target value a byte at a time (we don't have an alignment
61     // guarantee for the target address, so this is safest).
62     uint8_t *p = (uint8_t*)Address;
63     for (unsigned i = 0; i < Size; ++i) {
64       *p++ = (uint8_t)Value;
65       Value >>= 8;
66     }
67     return false;
68   }
69   case macho::RIT_X86_64_GOTLoad:
70   case macho::RIT_X86_64_GOT:
71   case macho::RIT_X86_64_Subtractor:
72   case macho::RIT_X86_64_TLV:
73     return Error("Relocation type not implemented yet!");
74   }
75 }
76
77 bool RuntimeDyldMachO::
78 resolveARMRelocation(uintptr_t Address, uintptr_t Value, bool isPCRel,
79                      unsigned Type, unsigned Size, int64_t Addend) {
80   // If the relocation is PC-relative, the value to be encoded is the
81   // pointer difference.
82   if (isPCRel) {
83     Value -= Address;
84     // ARM PCRel relocations have an effective-PC offset of two instructions
85     // (four bytes in Thumb mode, 8 bytes in ARM mode).
86     // FIXME: For now, assume ARM mode.
87     Value -= 8;
88   }
89
90   switch(Type) {
91   default:
92     llvm_unreachable("Invalid relocation type!");
93   case macho::RIT_Vanilla: {
94     // Mask in the target value a byte at a time (we don't have an alignment
95     // guarantee for the target address, so this is safest).
96     uint8_t *p = (uint8_t*)Address;
97     for (unsigned i = 0; i < Size; ++i) {
98       *p++ = (uint8_t)Value;
99       Value >>= 8;
100     }
101     break;
102   }
103   case macho::RIT_ARM_Branch24Bit: {
104     // Mask the value into the target address. We know instructions are
105     // 32-bit aligned, so we can do it all at once.
106     uint32_t *p = (uint32_t*)Address;
107     // The low two bits of the value are not encoded.
108     Value >>= 2;
109     // Mask the value to 24 bits.
110     Value &= 0xffffff;
111     // FIXME: If the destination is a Thumb function (and the instruction
112     // is a non-predicated BL instruction), we need to change it to a BLX
113     // instruction instead.
114
115     // Insert the value into the instruction.
116     *p = (*p & ~0xffffff) | Value;
117     break;
118   }
119   case macho::RIT_ARM_ThumbBranch22Bit:
120   case macho::RIT_ARM_ThumbBranch32Bit:
121   case macho::RIT_ARM_Half:
122   case macho::RIT_ARM_HalfDifference:
123   case macho::RIT_Pair:
124   case macho::RIT_Difference:
125   case macho::RIT_ARM_LocalDifference:
126   case macho::RIT_ARM_PreboundLazyPointer:
127     return Error("Relocation type not implemented yet!");
128   }
129   return false;
130 }
131
132 bool RuntimeDyldMachO::
133 loadSegment32(const MachOObject *Obj,
134               const MachOObject::LoadCommandInfo *SegmentLCI,
135               const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
136   // FIXME: This should really be combined w/ loadSegment64. Templatized
137   // function on the 32/64 datatypes maybe?
138   InMemoryStruct<macho::SegmentLoadCommand> SegmentLC;
139   Obj->ReadSegmentLoadCommand(*SegmentLCI, SegmentLC);
140   if (!SegmentLC)
141     return Error("unable to load segment load command");
142
143
144   SmallVector<unsigned, 16> SectionMap;
145   for (unsigned SectNum = 0; SectNum != SegmentLC->NumSections; ++SectNum) {
146     InMemoryStruct<macho::Section> Sect;
147     Obj->ReadSection(*SegmentLCI, SectNum, Sect);
148     if (!Sect)
149       return Error("unable to load section: '" + Twine(SectNum) + "'");
150
151     // Allocate memory via the MM for the section.
152     uint8_t *Buffer;
153     uint32_t SectionID = Sections.size();
154     if (Sect->Flags != 0x80000400)
155       Buffer = MemMgr->allocateCodeSection(Sect->Size, Sect->Align, SectionID);
156     else
157       Buffer = MemMgr->allocateDataSection(Sect->Size, Sect->Align, SectionID);
158
159     DEBUG(dbgs() << "Loading "
160                  << ((Sect->Flags == 0x80000400) ? "text" : "data")
161                  << " (ID #" << SectionID << ")"
162                  << " '" << Sect->SegmentName << ","
163                  << Sect->Name << "' of size " << Sect->Size
164                  << " to address " << Buffer << ".\n");
165
166     // Copy the payload from the object file into the allocated buffer.
167     uint8_t *Base = (uint8_t*)Obj->getData(SegmentLC->FileOffset,
168                                            SegmentLC->FileSize).data();
169     memcpy(Buffer, Base + Sect->Address, Sect->Size);
170
171     // Remember what got allocated for this SectionID.
172     Sections.push_back(sys::MemoryBlock(Buffer, Sect->Size));
173     SectionLocalMemToID[Buffer] = SectionID;
174
175     // By default, the load address of a section is its memory buffer.
176     SectionLoadAddress.push_back((uint64_t)Buffer);
177
178     // Keep a map of object file section numbers to corresponding SectionIDs
179     // while processing the file.
180     SectionMap.push_back(SectionID);
181   }
182
183   // Process the symbol table.
184   SmallVector<StringRef, 64> SymbolNames;
185   processSymbols32(Obj, SectionMap, SymbolNames, SymtabLC);
186
187   // Process the relocations for each section we're loading.
188   Relocations.grow(Relocations.size() + SegmentLC->NumSections);
189   for (unsigned SectNum = 0; SectNum != SegmentLC->NumSections; ++SectNum) {
190     InMemoryStruct<macho::Section> Sect;
191     Obj->ReadSection(*SegmentLCI, SectNum, Sect);
192     if (!Sect)
193       return Error("unable to load section: '" + Twine(SectNum) + "'");
194     for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
195       InMemoryStruct<macho::RelocationEntry> RE;
196       Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
197       if (RE->Word0 & macho::RF_Scattered)
198         return Error("NOT YET IMPLEMENTED: scattered relocations.");
199       // Word0 of the relocation is the offset into the section where the
200       // relocation should be applied. We need to translate that into an
201       // offset into a function since that's our atom.
202       uint32_t Offset = RE->Word0;
203       bool isExtern = (RE->Word1 >> 27) & 1;
204
205       // FIXME: Get the relocation addend from the target address.
206       // FIXME: VERY imporant for internal relocations.
207
208       // Figure out the source symbol of the relocation. If isExtern is true,
209       // this relocation references the symbol table, otherwise it references
210       // a section in the same object, numbered from 1 through NumSections
211       // (SectionBases is [0, NumSections-1]).
212       uint32_t SourceNum = RE->Word1 & 0xffffff; // 24-bit value
213       if (!isExtern) {
214         assert(SourceNum > 0 && "Invalid relocation section number!");
215         unsigned SectionID = SectionMap[SourceNum - 1];
216         unsigned TargetID = SectionMap[SectNum];
217         DEBUG(dbgs() << "Internal relocation at Section #"
218                      << TargetID << " + " << Offset
219                      << " from Section #"
220                      << SectionID << " (Word1: "
221                      << format("0x%x", RE->Word1) << ")\n");
222
223         // Store the relocation information. It will get resolved when
224         // the section addresses are assigned.
225         Relocations[SectionID].push_back(RelocationEntry(TargetID,
226                                                          Offset,
227                                                          RE->Word1,
228                                                          0 /*Addend*/));
229       } else {
230         StringRef SourceName = SymbolNames[SourceNum];
231
232         // Now store the relocation information. Associate it with the source
233         // symbol. Just add it to the unresolved list and let the general
234         // path post-load resolve it if we know where the symbol is.
235         UnresolvedRelocations[SourceName].push_back(RelocationEntry(SectNum,
236                                                                     Offset,
237                                                                     RE->Word1,
238                                                                  0 /*Addend*/));
239         DEBUG(dbgs() << "Relocation at Section #" << SectNum << " + " << Offset
240               << " from '" << SourceName << "(Word1: "
241               << format("0x%x", RE->Word1) << ")\n");
242       }
243     }
244   }
245
246   // Resolve the addresses of any symbols that were defined in this segment.
247   for (int i = 0, e = SymbolNames.size(); i != e; ++i)
248     resolveSymbol(SymbolNames[i]);
249
250   return false;
251 }
252
253
254 bool RuntimeDyldMachO::
255 loadSegment64(const MachOObject *Obj,
256               const MachOObject::LoadCommandInfo *SegmentLCI,
257               const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
258   InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
259   Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
260   if (!Segment64LC)
261     return Error("unable to load segment load command");
262
263
264   SmallVector<unsigned, 16> SectionMap;
265   for (unsigned SectNum = 0; SectNum != Segment64LC->NumSections; ++SectNum) {
266     InMemoryStruct<macho::Section64> Sect;
267     Obj->ReadSection64(*SegmentLCI, SectNum, Sect);
268     if (!Sect)
269       return Error("unable to load section: '" + Twine(SectNum) + "'");
270
271     // Allocate memory via the MM for the section.
272     uint8_t *Buffer;
273     uint32_t SectionID = Sections.size();
274     unsigned Align = 1 << Sect->Align; // .o file has log2 alignment.
275     if (Sect->Flags == 0x80000400)
276       Buffer = MemMgr->allocateCodeSection(Sect->Size, Align, SectionID);
277     else
278       Buffer = MemMgr->allocateDataSection(Sect->Size, Align, SectionID);
279
280     DEBUG(dbgs() << "Loading "
281                  << ((Sect->Flags == 0x80000400) ? "text" : "data")
282                  << " (ID #" << SectionID << ")"
283                  << " '" << Sect->SegmentName << ","
284                  << Sect->Name << "' of size " << Sect->Size
285                  << " (align " << Align << ")"
286                  << " to address " << Buffer << ".\n");
287
288     // Copy the payload from the object file into the allocated buffer.
289     uint8_t *Base = (uint8_t*)Obj->getData(Segment64LC->FileOffset,
290                                            Segment64LC->FileSize).data();
291     memcpy(Buffer, Base + Sect->Address, Sect->Size);
292
293     // Remember what got allocated for this SectionID.
294     Sections.push_back(sys::MemoryBlock(Buffer, Sect->Size));
295     SectionLocalMemToID[Buffer] = SectionID;
296
297     // By default, the load address of a section is its memory buffer.
298     SectionLoadAddress.push_back((uint64_t)Buffer);
299
300     // Keep a map of object file section numbers to corresponding SectionIDs
301     // while processing the file.
302     SectionMap.push_back(SectionID);
303   }
304
305   // Process the symbol table.
306   SmallVector<StringRef, 64> SymbolNames;
307   processSymbols64(Obj, SectionMap, SymbolNames, SymtabLC);
308
309   // Process the relocations for each section we're loading.
310   Relocations.grow(Relocations.size() + Segment64LC->NumSections);
311   for (unsigned SectNum = 0; SectNum != Segment64LC->NumSections; ++SectNum) {
312     InMemoryStruct<macho::Section64> Sect;
313     Obj->ReadSection64(*SegmentLCI, SectNum, Sect);
314     if (!Sect)
315       return Error("unable to load section: '" + Twine(SectNum) + "'");
316     for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
317       InMemoryStruct<macho::RelocationEntry> RE;
318       Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
319       if (RE->Word0 & macho::RF_Scattered)
320         return Error("NOT YET IMPLEMENTED: scattered relocations.");
321       // Word0 of the relocation is the offset into the section where the
322       // relocation should be applied. We need to translate that into an
323       // offset into a function since that's our atom.
324       uint32_t Offset = RE->Word0;
325       bool isExtern = (RE->Word1 >> 27) & 1;
326
327       // FIXME: Get the relocation addend from the target address.
328       // FIXME: VERY imporant for internal relocations.
329
330       // Figure out the source symbol of the relocation. If isExtern is true,
331       // this relocation references the symbol table, otherwise it references
332       // a section in the same object, numbered from 1 through NumSections
333       // (SectionBases is [0, NumSections-1]).
334       uint32_t SourceNum = RE->Word1 & 0xffffff; // 24-bit value
335       if (!isExtern) {
336         assert(SourceNum > 0 && "Invalid relocation section number!");
337         unsigned SectionID = SectionMap[SourceNum - 1];
338         unsigned TargetID = SectionMap[SectNum];
339         DEBUG(dbgs() << "Internal relocation at Section #"
340                      << TargetID << " + " << Offset
341                      << " from Section #"
342                      << SectionID << " (Word1: "
343                      << format("0x%x", RE->Word1) << ")\n");
344
345         // Store the relocation information. It will get resolved when
346         // the section addresses are assigned.
347         Relocations[SectionID].push_back(RelocationEntry(TargetID,
348                                                          Offset,
349                                                          RE->Word1,
350                                                          0 /*Addend*/));
351       } else {
352         StringRef SourceName = SymbolNames[SourceNum];
353
354         // Now store the relocation information. Associate it with the source
355         // symbol. Just add it to the unresolved list and let the general
356         // path post-load resolve it if we know where the symbol is.
357         UnresolvedRelocations[SourceName].push_back(RelocationEntry(SectNum,
358                                                                     Offset,
359                                                                     RE->Word1,
360                                                                  0 /*Addend*/));
361         DEBUG(dbgs() << "Relocation at Section #" << SectNum << " + " << Offset
362               << " from '" << SourceName << "(Word1: "
363               << format("0x%x", RE->Word1) << ")\n");
364       }
365     }
366   }
367
368   // Resolve the addresses of any symbols that were defined in this segment.
369   for (int i = 0, e = SymbolNames.size(); i != e; ++i)
370     resolveSymbol(SymbolNames[i]);
371
372   return false;
373 }
374
375 bool RuntimeDyldMachO::
376 processSymbols32(const MachOObject *Obj,
377                  SmallVectorImpl<unsigned> &SectionMap,
378                  SmallVectorImpl<StringRef> &SymbolNames,
379                  const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
380   // FIXME: Combine w/ processSymbols64. Factor 64/32 datatype and such.
381   for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
382     InMemoryStruct<macho::SymbolTableEntry> STE;
383     Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
384     if (!STE)
385       return Error("unable to read symbol: '" + Twine(i) + "'");
386     // Get the symbol name.
387     StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
388     SymbolNames.push_back(Name);
389
390     // FIXME: Check the symbol type and flags.
391     if (STE->Type != 0xF)  // external, defined in this segment.
392       continue;
393     // Flags in the upper nibble we don't care about.
394     if ((STE->Flags & 0xf) != 0x0)
395       continue;
396
397     // Remember the symbol.
398     uint32_t SectionID = SectionMap[STE->SectionIndex - 1];
399     SymbolTable[Name] = SymbolLoc(SectionID, STE->Value);
400
401     DEBUG(dbgs() << "Symbol: '" << Name << "' @ "
402                  << (getSectionAddress(SectionID) + STE->Value)
403                  << "\n");
404   }
405   return false;
406 }
407
408 bool RuntimeDyldMachO::
409 processSymbols64(const MachOObject *Obj,
410                  SmallVectorImpl<unsigned> &SectionMap,
411                  SmallVectorImpl<StringRef> &SymbolNames,
412                  const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
413   for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
414     InMemoryStruct<macho::Symbol64TableEntry> STE;
415     Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
416     if (!STE)
417       return Error("unable to read symbol: '" + Twine(i) + "'");
418     // Get the symbol name.
419     StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
420     SymbolNames.push_back(Name);
421
422     // FIXME: Check the symbol type and flags.
423     if (STE->Type != 0xF)  // external, defined in this segment.
424       continue;
425     // Flags in the upper nibble we don't care about.
426     if ((STE->Flags & 0xf) != 0x0)
427       continue;
428
429     // Remember the symbol.
430     uint32_t SectionID = SectionMap[STE->SectionIndex - 1];
431     SymbolTable[Name] = SymbolLoc(SectionID, STE->Value);
432
433     DEBUG(dbgs() << "Symbol: '" << Name << "' @ "
434                  << (getSectionAddress(SectionID) + STE->Value)
435                  << "\n");
436   }
437   return false;
438 }
439
440 // resolveSymbol - Resolve any relocations to the specified symbol if
441 // we know where it lives.
442 void RuntimeDyldMachO::resolveSymbol(StringRef Name) {
443   StringMap<SymbolLoc>::const_iterator Loc = SymbolTable.find(Name);
444   if (Loc == SymbolTable.end())
445     return;
446
447   RelocationList &Relocs = UnresolvedRelocations[Name];
448   DEBUG(dbgs() << "Resolving symbol '" << Name << "'\n");
449   for (int i = 0, e = Relocs.size(); i != e; ++i) {
450     // Change the relocation to be section relative rather than symbol
451     // relative and move it to the resolved relocation list.
452     RelocationEntry Entry = Relocs[i];
453     Entry.Addend += Loc->second.second;
454     Relocations[Loc->second.first].push_back(Entry);
455   }
456   // FIXME: Keep a worklist of the relocations we've added so that we can
457   // resolve more selectively later.
458   Relocs.clear();
459 }
460
461 bool RuntimeDyldMachO::loadObject(MemoryBuffer *InputBuffer) {
462   // If the linker is in an error state, don't do anything.
463   if (hasError())
464     return true;
465   // Load the Mach-O wrapper object.
466   std::string ErrorStr;
467   OwningPtr<MachOObject> Obj(
468     MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
469   if (!Obj)
470     return Error("unable to load object: '" + ErrorStr + "'");
471
472   // Get the CPU type information from the header.
473   const macho::Header &Header = Obj->getHeader();
474
475   // FIXME: Error checking that the loaded object is compatible with
476   //        the system we're running on.
477   CPUType = Header.CPUType;
478   CPUSubtype = Header.CPUSubtype;
479
480   // Validate that the load commands match what we expect.
481   const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0,
482     *DysymtabLCI = 0;
483   for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
484     const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i);
485     switch (LCI.Command.Type) {
486     case macho::LCT_Segment:
487     case macho::LCT_Segment64:
488       if (SegmentLCI)
489         return Error("unexpected input object (multiple segments)");
490       SegmentLCI = &LCI;
491       break;
492     case macho::LCT_Symtab:
493       if (SymtabLCI)
494         return Error("unexpected input object (multiple symbol tables)");
495       SymtabLCI = &LCI;
496       break;
497     case macho::LCT_Dysymtab:
498       if (DysymtabLCI)
499         return Error("unexpected input object (multiple symbol tables)");
500       DysymtabLCI = &LCI;
501       break;
502     default:
503       return Error("unexpected input object (unexpected load command");
504     }
505   }
506
507   if (!SymtabLCI)
508     return Error("no symbol table found in object");
509   if (!SegmentLCI)
510     return Error("no segments found in object");
511
512   // Read and register the symbol table data.
513   InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
514   Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
515   if (!SymtabLC)
516     return Error("unable to load symbol table load command");
517   Obj->RegisterStringTable(*SymtabLC);
518
519   // Read the dynamic link-edit information, if present (not present in static
520   // objects).
521   if (DysymtabLCI) {
522     InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
523     Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
524     if (!DysymtabLC)
525       return Error("unable to load dynamic link-exit load command");
526
527     // FIXME: We don't support anything interesting yet.
528 //    if (DysymtabLC->LocalSymbolsIndex != 0)
529 //      return Error("NOT YET IMPLEMENTED: local symbol entries");
530 //    if (DysymtabLC->ExternalSymbolsIndex != 0)
531 //      return Error("NOT YET IMPLEMENTED: non-external symbol entries");
532 //    if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries)
533 //      return Error("NOT YET IMPLEMENTED: undefined symbol entries");
534   }
535
536   // Load the segment load command.
537   if (SegmentLCI->Command.Type == macho::LCT_Segment) {
538     if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
539       return true;
540   } else {
541     if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
542       return true;
543   }
544
545   // Assign the addresses of the sections from the object so that any
546   // relocations to them get set properly.
547   // FIXME: This is done directly from the client at the moment. We should
548   // default the values to the local storage, at least when the target arch
549   // is the same as the host arch.
550
551   return false;
552 }
553
554 // Assign an address to a symbol name and resolve all the relocations
555 // associated with it.
556 void RuntimeDyldMachO::reassignSectionAddress(unsigned SectionID,
557                                               uint64_t Addr) {
558   // The address to use for relocation resolution is not
559   // the address of the local section buffer. We must be doing
560   // a remote execution environment of some sort. Re-apply any
561   // relocations referencing this section with the given address.
562   //
563   // Addr is a uint64_t because we can't assume the pointer width
564   // of the target is the same as that of the host. Just use a generic
565   // "big enough" type.
566
567   SectionLoadAddress[SectionID] = Addr;
568
569   RelocationList &Relocs = Relocations[SectionID];
570   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
571     RelocationEntry &RE = Relocs[i];
572     uint8_t *Target = (uint8_t*)Sections[RE.SectionID].base() + RE.Offset;
573     bool isPCRel = (RE.Data >> 24) & 1;
574     unsigned Type = (RE.Data >> 28) & 0xf;
575     unsigned Size = 1 << ((RE.Data >> 25) & 3);
576
577     DEBUG(dbgs() << "Resolving relocation at Section #" << RE.SectionID
578           << " + " << RE.Offset << " (" << format("%p", Target) << ")"
579           << " from Section #" << SectionID << " (" << format("%p", Addr) << ")"
580           << "(" << (isPCRel ? "pcrel" : "absolute")
581           << ", type: " << Type << ", Size: " << Size << ", Addend: "
582           << RE.Addend << ").\n");
583
584     resolveRelocation(Target, Addr, isPCRel, Type, Size, RE.Addend);
585   }
586 }
587
588 bool RuntimeDyldMachO::isKnownFormat(const MemoryBuffer *InputBuffer) {
589   StringRef Magic = InputBuffer->getBuffer().slice(0, 4);
590   if (Magic == "\xFE\xED\xFA\xCE") return true;
591   if (Magic == "\xCE\xFA\xED\xFE") return true;
592   if (Magic == "\xFE\xED\xFA\xCF") return true;
593   if (Magic == "\xCF\xFA\xED\xFE") return true;
594   return false;
595 }
596
597 } // end namespace llvm