1 //===-- RuntimeDyld.h - Run-time dynamic linker for MC-JIT ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
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"
30 using namespace llvm::object;
33 class RuntimeDyldImpl {
37 // The MemoryManager to load objects into.
38 RTDyldMemoryManager *MemMgr;
40 // Master symbol table. As modules are loaded and external symbols are
41 // resolved, their addresses are stored here.
42 StringMap<uint64_t> SymbolTable;
44 // FIXME: Should have multiple data blocks, one for each loaded chunk of
46 sys::MemoryBlock Data;
51 // Set the error state and record an error string.
52 bool Error(const Twine &Msg) {
58 bool resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
59 SmallVectorImpl<void *> &SectionBases,
60 SmallVectorImpl<StringRef> &SymbolNames);
61 bool resolveX86_64Relocation(intptr_t Address, intptr_t Value, bool isPCRel,
62 unsigned Type, unsigned Size);
63 bool resolveARMRelocation(intptr_t Address, intptr_t Value, bool isPCRel,
64 unsigned Type, unsigned Size);
66 bool loadSegment32(const MachOObject *Obj,
67 const MachOObject::LoadCommandInfo *SegmentLCI,
68 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
69 bool loadSegment64(const MachOObject *Obj,
70 const MachOObject::LoadCommandInfo *SegmentLCI,
71 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
74 RuntimeDyldImpl(RTDyldMemoryManager *mm) : MemMgr(mm), HasError(false) {}
76 bool loadObject(MemoryBuffer *InputBuffer);
78 uint64_t getSymbolAddress(StringRef Name) {
79 // Use lookup() rather than [] because we don't want to add an entry
80 // if there isn't one already, which the [] operator does.
81 return SymbolTable.lookup(Name);
84 sys::MemoryBlock getMemoryBlock() { return Data; }
86 // Is the linker in an error state?
87 bool hasError() { return HasError; }
89 // Mark the error condition as handled and continue.
90 void clearError() { HasError = false; }
92 // Get the error message.
93 StringRef getErrorString() { return ErrorStr; }
96 // FIXME: Relocations for targets other than x86_64.
97 bool RuntimeDyldImpl::
98 resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
99 SmallVectorImpl<void *> &SectionBases,
100 SmallVectorImpl<StringRef> &SymbolNames) {
101 // struct relocation_info {
102 // int32_t r_address;
103 // uint32_t r_symbolnum:24,
109 uint32_t SymbolNum = RE.Word1 & 0xffffff; // 24-bit value
110 bool isPCRel = (RE.Word1 >> 24) & 1;
111 unsigned Log2Size = (RE.Word1 >> 25) & 3;
112 bool isExtern = (RE.Word1 >> 27) & 1;
113 unsigned Type = (RE.Word1 >> 28) & 0xf;
114 if (RE.Word0 & macho::RF_Scattered)
115 return Error("NOT YET IMPLEMENTED: scattered relocations.");
117 // The address requiring a relocation.
118 intptr_t Address = (intptr_t)SectionBases[BaseSection] + RE.Word0;
120 // Figure out the target address of the relocation. If isExtern is true,
121 // this relocation references the symbol table, otherwise it references
122 // a section in the same object, numbered from 1 through NumSections
123 // (SectionBases is [0, NumSections-1]).
126 StringRef Name = SymbolNames[SymbolNum];
127 if (SymbolTable.lookup(Name)) {
128 // The symbol is in our symbol table, so we can resolve it directly.
129 Value = (intptr_t)SymbolTable[Name];
131 return Error("NOT YET IMPLEMENTED: relocations to pre-compiled code.");
133 DEBUG(dbgs() << "Resolve relocation(" << Type << ") from '" << Name
134 << "' to " << format("0x%x", Address) << ".\n");
136 // For non-external relocations, the SymbolNum is actual a section number
137 // as described above.
138 Value = (intptr_t)SectionBases[SymbolNum - 1];
141 unsigned Size = 1 << Log2Size;
143 default: assert(0 && "Unsupported CPU type!");
144 case mach::CTM_x86_64:
145 return resolveX86_64Relocation(Address, Value, isPCRel, Type, Size);
147 return resolveARMRelocation(Address, Value, isPCRel, Type, Size);
149 llvm_unreachable("");
152 bool RuntimeDyldImpl::resolveX86_64Relocation(intptr_t Address, intptr_t Value,
153 bool isPCRel, unsigned Type,
155 // If the relocation is PC-relative, the value to be encoded is the
156 // pointer difference.
158 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
159 // address. Is that expected? Only for branches, perhaps?
160 Value -= Address + 4;
164 llvm_unreachable("Invalid relocation type!");
165 case macho::RIT_X86_64_Unsigned:
166 case macho::RIT_X86_64_Branch: {
167 // Mask in the target value a byte at a time (we don't have an alignment
168 // guarantee for the target address, so this is safest).
169 uint8_t *p = (uint8_t*)Address;
170 for (unsigned i = 0; i < Size; ++i) {
171 *p++ = (uint8_t)Value;
176 case macho::RIT_X86_64_Signed:
177 case macho::RIT_X86_64_GOTLoad:
178 case macho::RIT_X86_64_GOT:
179 case macho::RIT_X86_64_Subtractor:
180 case macho::RIT_X86_64_Signed1:
181 case macho::RIT_X86_64_Signed2:
182 case macho::RIT_X86_64_Signed4:
183 case macho::RIT_X86_64_TLV:
184 return Error("Relocation type not implemented yet!");
189 bool RuntimeDyldImpl::resolveARMRelocation(intptr_t Address, intptr_t Value,
190 bool isPCRel, unsigned Type,
192 // If the relocation is PC-relative, the value to be encoded is the
193 // pointer difference.
196 // ARM PCRel relocations have an effective-PC offset of two instructions
197 // (four bytes in Thumb mode, 8 bytes in ARM mode).
198 // FIXME: For now, assume ARM mode.
204 case macho::RIT_Vanilla: {
205 llvm_unreachable("Invalid relocation type!");
206 // Mask in the target value a byte at a time (we don't have an alignment
207 // guarantee for the target address, so this is safest).
208 uint8_t *p = (uint8_t*)Address;
209 for (unsigned i = 0; i < Size; ++i) {
210 *p++ = (uint8_t)Value;
215 case macho::RIT_Pair:
216 case macho::RIT_Difference:
217 case macho::RIT_ARM_LocalDifference:
218 case macho::RIT_ARM_PreboundLazyPointer:
219 case macho::RIT_ARM_Branch24Bit: {
220 // Mask the value into the target address. We know instructions are
221 // 32-bit aligned, so we can do it all at once.
222 uint32_t *p = (uint32_t*)Address;
223 // The low two bits of the value are not encoded.
225 // Mask the value to 24 bits.
227 // FIXME: If the destination is a Thumb function (and the instruction
228 // is a non-predicated BL instruction), we need to change it to a BLX
229 // instruction instead.
231 // Insert the value into the instruction.
232 *p = (*p & ~0xffffff) | Value;
235 case macho::RIT_ARM_ThumbBranch22Bit:
236 case macho::RIT_ARM_ThumbBranch32Bit:
237 case macho::RIT_ARM_Half:
238 case macho::RIT_ARM_HalfDifference:
239 return Error("Relocation type not implemented yet!");
244 bool RuntimeDyldImpl::
245 loadSegment32(const MachOObject *Obj,
246 const MachOObject::LoadCommandInfo *SegmentLCI,
247 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
248 InMemoryStruct<macho::SegmentLoadCommand> Segment32LC;
249 Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC);
251 return Error("unable to load segment load command");
253 // Map the segment into memory.
254 std::string ErrorStr;
255 Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr);
257 return Error("unable to allocate memory block: '" + ErrorStr + "'");
258 memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset,
259 Segment32LC->FileSize).data(),
260 Segment32LC->FileSize);
261 memset((char*)Data.base() + Segment32LC->FileSize, 0,
262 Segment32LC->VMSize - Segment32LC->FileSize);
264 // Bind the section indices to addresses and record the relocations we
266 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
267 SmallVector<RelocationMap, 64> Relocations;
269 SmallVector<void *, 16> SectionBases;
270 for (unsigned i = 0; i != Segment32LC->NumSections; ++i) {
271 InMemoryStruct<macho::Section> Sect;
272 Obj->ReadSection(*SegmentLCI, i, Sect);
274 return Error("unable to load section: '" + Twine(i) + "'");
276 // Remember any relocations the section has so we can resolve them later.
277 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
278 InMemoryStruct<macho::RelocationEntry> RE;
279 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
280 Relocations.push_back(RelocationMap(j, *RE));
283 // FIXME: Improve check.
284 // if (Sect->Flags != 0x80000400)
285 // return Error("unsupported section type!");
287 SectionBases.push_back((char*) Data.base() + Sect->Address);
290 // Bind all the symbols to address. Keep a record of the names for use
291 // by relocation resolution.
292 SmallVector<StringRef, 64> SymbolNames;
293 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
294 InMemoryStruct<macho::SymbolTableEntry> STE;
295 Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
297 return Error("unable to read symbol: '" + Twine(i) + "'");
298 // Get the symbol name.
299 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
300 SymbolNames.push_back(Name);
302 // Just skip undefined symbols. They'll be loaded from whatever
303 // module they come from (or system dylib) when we resolve relocations
305 if (STE->SectionIndex == 0)
308 unsigned Index = STE->SectionIndex - 1;
309 if (Index >= Segment32LC->NumSections)
310 return Error("invalid section index for symbol: '" + Twine() + "'");
312 // Get the section base address.
313 void *SectionBase = SectionBases[Index];
315 // Get the symbol address.
316 uint64_t Address = (uint64_t)SectionBase + STE->Value;
318 // FIXME: Check the symbol type and flags.
319 if (STE->Type != 0xF)
320 return Error("unexpected symbol type!");
321 if (STE->Flags != 0x0)
322 return Error("unexpected symbol type!");
324 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
326 SymbolTable[Name] = Address;
329 // Now resolve any relocations.
330 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
331 if (resolveRelocation(Relocations[i].first, Relocations[i].second,
332 SectionBases, SymbolNames))
336 // We've loaded the section; now mark the functions in it as executable.
337 // FIXME: We really should use the MemoryManager for this.
338 sys::Memory::setRangeExecutable(Data.base(), Data.size());
344 bool RuntimeDyldImpl::
345 loadSegment64(const MachOObject *Obj,
346 const MachOObject::LoadCommandInfo *SegmentLCI,
347 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
348 InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
349 Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
351 return Error("unable to load segment load command");
353 // Map the segment into memory.
354 std::string ErrorStr;
355 Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr);
357 return Error("unable to allocate memory block: '" + ErrorStr + "'");
358 memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset,
359 Segment64LC->FileSize).data(),
360 Segment64LC->FileSize);
361 memset((char*)Data.base() + Segment64LC->FileSize, 0,
362 Segment64LC->VMSize - Segment64LC->FileSize);
364 // Bind the section indices to addresses and record the relocations we
366 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
367 SmallVector<RelocationMap, 64> Relocations;
369 SmallVector<void *, 16> SectionBases;
370 for (unsigned i = 0; i != Segment64LC->NumSections; ++i) {
371 InMemoryStruct<macho::Section64> Sect;
372 Obj->ReadSection64(*SegmentLCI, i, Sect);
374 return Error("unable to load section: '" + Twine(i) + "'");
376 // Remember any relocations the section has so we can resolve them later.
377 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
378 InMemoryStruct<macho::RelocationEntry> RE;
379 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
380 Relocations.push_back(RelocationMap(j, *RE));
383 // FIXME: Improve check.
384 if (Sect->Flags != 0x80000400)
385 return Error("unsupported section type!");
387 SectionBases.push_back((char*) Data.base() + Sect->Address);
390 // Bind all the symbols to address. Keep a record of the names for use
391 // by relocation resolution.
392 SmallVector<StringRef, 64> SymbolNames;
393 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
394 InMemoryStruct<macho::Symbol64TableEntry> STE;
395 Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
397 return Error("unable to read symbol: '" + Twine(i) + "'");
398 // Get the symbol name.
399 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
400 SymbolNames.push_back(Name);
402 // Just skip undefined symbols. They'll be loaded from whatever
403 // module they come from (or system dylib) when we resolve relocations
405 if (STE->SectionIndex == 0)
408 unsigned Index = STE->SectionIndex - 1;
409 if (Index >= Segment64LC->NumSections)
410 return Error("invalid section index for symbol: '" + Twine() + "'");
412 // Get the section base address.
413 void *SectionBase = SectionBases[Index];
415 // Get the symbol address.
416 uint64_t Address = (uint64_t) SectionBase + STE->Value;
418 // FIXME: Check the symbol type and flags.
419 if (STE->Type != 0xF)
420 return Error("unexpected symbol type!");
421 if (STE->Flags != 0x0)
422 return Error("unexpected symbol type!");
424 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
425 SymbolTable[Name] = Address;
428 // Now resolve any relocations.
429 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
430 if (resolveRelocation(Relocations[i].first, Relocations[i].second,
431 SectionBases, SymbolNames))
435 // We've loaded the section; now mark the functions in it as executable.
436 // FIXME: We really should use the MemoryManager for this.
437 sys::Memory::setRangeExecutable(Data.base(), Data.size());
442 bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) {
443 // If the linker is in an error state, don't do anything.
446 // Load the Mach-O wrapper object.
447 std::string ErrorStr;
448 OwningPtr<MachOObject> Obj(
449 MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
451 return Error("unable to load object: '" + ErrorStr + "'");
453 // Get the CPU type information from the header.
454 const macho::Header &Header = Obj->getHeader();
456 // FIXME: Error checking that the loaded object is compatible with
457 // the system we're running on.
458 CPUType = Header.CPUType;
459 CPUSubtype = Header.CPUSubtype;
461 // Validate that the load commands match what we expect.
462 const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0,
464 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
465 const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i);
466 switch (LCI.Command.Type) {
467 case macho::LCT_Segment:
468 case macho::LCT_Segment64:
470 return Error("unexpected input object (multiple segments)");
473 case macho::LCT_Symtab:
475 return Error("unexpected input object (multiple symbol tables)");
478 case macho::LCT_Dysymtab:
480 return Error("unexpected input object (multiple symbol tables)");
484 return Error("unexpected input object (unexpected load command");
489 return Error("no symbol table found in object");
491 return Error("no symbol table found in object");
493 // Read and register the symbol table data.
494 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
495 Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
497 return Error("unable to load symbol table load command");
498 Obj->RegisterStringTable(*SymtabLC);
500 // Read the dynamic link-edit information, if present (not present in static
503 InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
504 Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
506 return Error("unable to load dynamic link-exit load command");
508 // FIXME: We don't support anything interesting yet.
509 // if (DysymtabLC->LocalSymbolsIndex != 0)
510 // return Error("NOT YET IMPLEMENTED: local symbol entries");
511 // if (DysymtabLC->ExternalSymbolsIndex != 0)
512 // return Error("NOT YET IMPLEMENTED: non-external symbol entries");
513 // if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries)
514 // return Error("NOT YET IMPLEMENTED: undefined symbol entries");
517 // Load the segment load command.
518 if (SegmentLCI->Command.Type == macho::LCT_Segment) {
519 if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
522 if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
530 //===----------------------------------------------------------------------===//
531 // RuntimeDyld class implementation
532 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *MM) {
533 Dyld = new RuntimeDyldImpl(MM);
536 RuntimeDyld::~RuntimeDyld() {
540 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
541 return Dyld->loadObject(InputBuffer);
544 uint64_t RuntimeDyld::getSymbolAddress(StringRef Name) {
545 return Dyld->getSymbolAddress(Name);
548 sys::MemoryBlock RuntimeDyld::getMemoryBlock() {
549 return Dyld->getMemoryBlock();
552 StringRef RuntimeDyld::getErrorString() {
553 return Dyld->getErrorString();
556 } // end namespace llvm