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/ExecutionEngine/JITMemoryManager.h"
22 #include "llvm/Object/MachOObject.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/Memory.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/system_error.h"
29 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm::object;
34 class RuntimeDyldImpl {
38 // The JITMemoryManager to load objects into.
39 JITMemoryManager *JMM;
41 // Master symbol table. As modules are loaded and external symbols are
42 // resolved, their addresses are stored here.
43 StringMap<void*> SymbolTable;
45 // FIXME: Should have multiple data blocks, one for each loaded chunk of
47 sys::MemoryBlock Data;
52 // Set the error state and record an error string.
53 bool Error(const Twine &Msg) {
59 bool resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
60 SmallVectorImpl<void *> &SectionBases,
61 SmallVectorImpl<StringRef> &SymbolNames);
62 bool resolveX86_64Relocation(intptr_t Address, intptr_t Value, bool isPCRel,
63 unsigned Type, unsigned Size);
64 bool resolveARMRelocation(intptr_t Address, intptr_t Value, bool isPCRel,
65 unsigned Type, unsigned Size);
67 bool loadSegment32(const MachOObject *Obj,
68 const MachOObject::LoadCommandInfo *SegmentLCI,
69 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
70 bool loadSegment64(const MachOObject *Obj,
71 const MachOObject::LoadCommandInfo *SegmentLCI,
72 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
75 RuntimeDyldImpl(JITMemoryManager *jmm) : JMM(jmm), HasError(false) {}
77 bool loadObject(MemoryBuffer *InputBuffer);
79 void *getSymbolAddress(StringRef Name) {
80 // Use lookup() rather than [] because we don't want to add an entry
81 // if there isn't one already, which the [] operator does.
82 return SymbolTable.lookup(Name);
85 sys::MemoryBlock getMemoryBlock() { return Data; }
87 // Is the linker in an error state?
88 bool hasError() { return HasError; }
90 // Mark the error condition as handled and continue.
91 void clearError() { HasError = false; }
93 // Get the error message.
94 StringRef getErrorString() { return ErrorStr; }
97 // FIXME: Relocations for targets other than x86_64.
98 bool RuntimeDyldImpl::
99 resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
100 SmallVectorImpl<void *> &SectionBases,
101 SmallVectorImpl<StringRef> &SymbolNames) {
102 // struct relocation_info {
103 // int32_t r_address;
104 // uint32_t r_symbolnum:24,
110 uint32_t SymbolNum = RE.Word1 & 0xffffff; // 24-bit value
111 bool isPCRel = (RE.Word1 >> 24) & 1;
112 unsigned Log2Size = (RE.Word1 >> 25) & 3;
113 bool isExtern = (RE.Word1 >> 27) & 1;
114 unsigned Type = (RE.Word1 >> 28) & 0xf;
115 if (RE.Word0 & macho::RF_Scattered)
116 return Error("NOT YET IMPLEMENTED: scattered relocations.");
118 // The address requiring a relocation.
119 intptr_t Address = (intptr_t)SectionBases[BaseSection] + RE.Word0;
121 // Figure out the target address of the relocation. If isExtern is true,
122 // this relocation references the symbol table, otherwise it references
123 // a section in the same object, numbered from 1 through NumSections
124 // (SectionBases is [0, NumSections-1]).
127 StringRef Name = SymbolNames[SymbolNum];
128 if (SymbolTable.lookup(Name)) {
129 // The symbol is in our symbol table, so we can resolve it directly.
130 Value = (intptr_t)SymbolTable[Name];
132 return Error("NOT YET IMPLEMENTED: relocations to pre-compiled code.");
134 DEBUG(dbgs() << "Resolve relocation(" << Type << ") from '" << Name
135 << "' to " << format("0x%x", Address) << ".\n");
137 // For non-external relocations, the SymbolNum is actual a section number
138 // as described above.
139 Value = (intptr_t)SectionBases[SymbolNum - 1];
142 unsigned Size = 1 << Log2Size;
144 default: assert(0 && "Unsupported CPU type!");
145 case mach::CTM_x86_64:
146 return resolveX86_64Relocation(Address, Value, isPCRel, Type, Size);
148 return resolveARMRelocation(Address, Value, isPCRel, Type, Size);
150 llvm_unreachable("");
153 bool RuntimeDyldImpl::resolveX86_64Relocation(intptr_t Address, intptr_t Value,
154 bool isPCRel, unsigned Type,
156 // If the relocation is PC-relative, the value to be encoded is the
157 // pointer difference.
159 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
160 // address. Is that expected? Only for branches, perhaps?
161 Value -= Address + 4;
165 llvm_unreachable("Invalid relocation type!");
166 case macho::RIT_X86_64_Unsigned:
167 case macho::RIT_X86_64_Branch: {
168 // Mask in the target value a byte at a time (we don't have an alignment
169 // guarantee for the target address, so this is safest).
170 uint8_t *p = (uint8_t*)Address;
171 for (unsigned i = 0; i < Size; ++i) {
172 *p++ = (uint8_t)Value;
177 case macho::RIT_X86_64_Signed:
178 case macho::RIT_X86_64_GOTLoad:
179 case macho::RIT_X86_64_GOT:
180 case macho::RIT_X86_64_Subtractor:
181 case macho::RIT_X86_64_Signed1:
182 case macho::RIT_X86_64_Signed2:
183 case macho::RIT_X86_64_Signed4:
184 case macho::RIT_X86_64_TLV:
185 return Error("Relocation type not implemented yet!");
190 bool RuntimeDyldImpl::resolveARMRelocation(intptr_t Address, intptr_t Value,
191 bool isPCRel, unsigned Type,
193 // If the relocation is PC-relative, the value to be encoded is the
194 // pointer difference.
197 // ARM PCRel relocations have an effective-PC offset of two instructions
198 // (four bytes in Thumb mode, 8 bytes in ARM mode).
199 // FIXME: For now, assume ARM mode.
205 case macho::RIT_Vanilla: {
206 llvm_unreachable("Invalid relocation type!");
207 // Mask in the target value a byte at a time (we don't have an alignment
208 // guarantee for the target address, so this is safest).
209 uint8_t *p = (uint8_t*)Address;
210 for (unsigned i = 0; i < Size; ++i) {
211 *p++ = (uint8_t)Value;
216 case macho::RIT_Pair:
217 case macho::RIT_Difference:
218 case macho::RIT_ARM_LocalDifference:
219 case macho::RIT_ARM_PreboundLazyPointer:
220 case macho::RIT_ARM_Branch24Bit: {
221 // Mask the value into the target address. We know instructions are
222 // 32-bit aligned, so we can do it all at once.
223 uint32_t *p = (uint32_t*)Address;
224 // The low two bits of the value are not encoded.
226 // Mask the value to 24 bits.
228 // FIXME: If the destination is a Thumb function (and the instruction
229 // is a non-predicated BL instruction), we need to change it to a BLX
230 // instruction instead.
232 // Insert the value into the instruction.
233 *p = (*p & ~0xffffff) | Value;
236 case macho::RIT_ARM_ThumbBranch22Bit:
237 case macho::RIT_ARM_ThumbBranch32Bit:
238 case macho::RIT_ARM_Half:
239 case macho::RIT_ARM_HalfDifference:
240 return Error("Relocation type not implemented yet!");
245 bool RuntimeDyldImpl::
246 loadSegment32(const MachOObject *Obj,
247 const MachOObject::LoadCommandInfo *SegmentLCI,
248 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
249 InMemoryStruct<macho::SegmentLoadCommand> Segment32LC;
250 Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC);
252 return Error("unable to load segment load command");
254 // Map the segment into memory.
255 std::string ErrorStr;
256 Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr);
258 return Error("unable to allocate memory block: '" + ErrorStr + "'");
259 memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset,
260 Segment32LC->FileSize).data(),
261 Segment32LC->FileSize);
262 memset((char*)Data.base() + Segment32LC->FileSize, 0,
263 Segment32LC->VMSize - Segment32LC->FileSize);
265 // Bind the section indices to addresses and record the relocations we
267 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
268 SmallVector<RelocationMap, 64> Relocations;
270 SmallVector<void *, 16> SectionBases;
271 for (unsigned i = 0; i != Segment32LC->NumSections; ++i) {
272 InMemoryStruct<macho::Section> Sect;
273 Obj->ReadSection(*SegmentLCI, i, Sect);
275 return Error("unable to load section: '" + Twine(i) + "'");
277 // Remember any relocations the section has so we can resolve them later.
278 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
279 InMemoryStruct<macho::RelocationEntry> RE;
280 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
281 Relocations.push_back(RelocationMap(j, *RE));
284 // FIXME: Improve check.
285 // if (Sect->Flags != 0x80000400)
286 // return Error("unsupported section type!");
288 SectionBases.push_back((char*) Data.base() + Sect->Address);
291 // Bind all the symbols to address. Keep a record of the names for use
292 // by relocation resolution.
293 SmallVector<StringRef, 64> SymbolNames;
294 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
295 InMemoryStruct<macho::SymbolTableEntry> STE;
296 Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
298 return Error("unable to read symbol: '" + Twine(i) + "'");
299 // Get the symbol name.
300 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
301 SymbolNames.push_back(Name);
303 // Just skip undefined symbols. They'll be loaded from whatever
304 // module they come from (or system dylib) when we resolve relocations
306 if (STE->SectionIndex == 0)
309 unsigned Index = STE->SectionIndex - 1;
310 if (Index >= Segment32LC->NumSections)
311 return Error("invalid section index for symbol: '" + Twine() + "'");
313 // Get the section base address.
314 void *SectionBase = SectionBases[Index];
316 // Get the symbol address.
317 void *Address = (char*) SectionBase + STE->Value;
319 // FIXME: Check the symbol type and flags.
320 if (STE->Type != 0xF)
321 return Error("unexpected symbol type!");
322 if (STE->Flags != 0x0)
323 return Error("unexpected symbol type!");
325 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
327 SymbolTable[Name] = Address;
330 // Now resolve any relocations.
331 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
332 if (resolveRelocation(Relocations[i].first, Relocations[i].second,
333 SectionBases, SymbolNames))
337 // We've loaded the section; now mark the functions in it as executable.
338 // FIXME: We really should use the JITMemoryManager for this.
339 sys::Memory::setRangeExecutable(Data.base(), Data.size());
345 bool RuntimeDyldImpl::
346 loadSegment64(const MachOObject *Obj,
347 const MachOObject::LoadCommandInfo *SegmentLCI,
348 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
349 InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
350 Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
352 return Error("unable to load segment load command");
354 // Map the segment into memory.
355 std::string ErrorStr;
356 Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr);
358 return Error("unable to allocate memory block: '" + ErrorStr + "'");
359 memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset,
360 Segment64LC->FileSize).data(),
361 Segment64LC->FileSize);
362 memset((char*)Data.base() + Segment64LC->FileSize, 0,
363 Segment64LC->VMSize - Segment64LC->FileSize);
365 // Bind the section indices to addresses and record the relocations we
367 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
368 SmallVector<RelocationMap, 64> Relocations;
370 SmallVector<void *, 16> SectionBases;
371 for (unsigned i = 0; i != Segment64LC->NumSections; ++i) {
372 InMemoryStruct<macho::Section64> Sect;
373 Obj->ReadSection64(*SegmentLCI, i, Sect);
375 return Error("unable to load section: '" + Twine(i) + "'");
377 // Remember any relocations the section has so we can resolve them later.
378 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
379 InMemoryStruct<macho::RelocationEntry> RE;
380 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
381 Relocations.push_back(RelocationMap(j, *RE));
384 // FIXME: Improve check.
385 if (Sect->Flags != 0x80000400)
386 return Error("unsupported section type!");
388 SectionBases.push_back((char*) Data.base() + Sect->Address);
391 // Bind all the symbols to address. Keep a record of the names for use
392 // by relocation resolution.
393 SmallVector<StringRef, 64> SymbolNames;
394 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
395 InMemoryStruct<macho::Symbol64TableEntry> STE;
396 Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
398 return Error("unable to read symbol: '" + Twine(i) + "'");
399 // Get the symbol name.
400 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
401 SymbolNames.push_back(Name);
403 // Just skip undefined symbols. They'll be loaded from whatever
404 // module they come from (or system dylib) when we resolve relocations
406 if (STE->SectionIndex == 0)
409 unsigned Index = STE->SectionIndex - 1;
410 if (Index >= Segment64LC->NumSections)
411 return Error("invalid section index for symbol: '" + Twine() + "'");
413 // Get the section base address.
414 void *SectionBase = SectionBases[Index];
416 // Get the symbol address.
417 void *Address = (char*) SectionBase + STE->Value;
419 // FIXME: Check the symbol type and flags.
420 if (STE->Type != 0xF)
421 return Error("unexpected symbol type!");
422 if (STE->Flags != 0x0)
423 return Error("unexpected symbol type!");
425 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
426 SymbolTable[Name] = Address;
429 // Now resolve any relocations.
430 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
431 if (resolveRelocation(Relocations[i].first, Relocations[i].second,
432 SectionBases, SymbolNames))
436 // We've loaded the section; now mark the functions in it as executable.
437 // FIXME: We really should use the JITMemoryManager for this.
438 sys::Memory::setRangeExecutable(Data.base(), Data.size());
443 bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) {
444 // If the linker is in an error state, don't do anything.
447 // Load the Mach-O wrapper object.
448 std::string ErrorStr;
449 OwningPtr<MachOObject> Obj(
450 MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
452 return Error("unable to load object: '" + ErrorStr + "'");
454 // Get the CPU type information from the header.
455 const macho::Header &Header = Obj->getHeader();
457 // FIXME: Error checking that the loaded object is compatible with
458 // the system we're running on.
459 CPUType = Header.CPUType;
460 CPUSubtype = Header.CPUSubtype;
462 // Validate that the load commands match what we expect.
463 const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0,
465 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
466 const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i);
467 switch (LCI.Command.Type) {
468 case macho::LCT_Segment:
469 case macho::LCT_Segment64:
471 return Error("unexpected input object (multiple segments)");
474 case macho::LCT_Symtab:
476 return Error("unexpected input object (multiple symbol tables)");
479 case macho::LCT_Dysymtab:
481 return Error("unexpected input object (multiple symbol tables)");
485 return Error("unexpected input object (unexpected load command");
490 return Error("no symbol table found in object");
492 return Error("no symbol table found in object");
494 // Read and register the symbol table data.
495 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
496 Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
498 return Error("unable to load symbol table load command");
499 Obj->RegisterStringTable(*SymtabLC);
501 // Read the dynamic link-edit information, if present (not present in static
504 InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
505 Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
507 return Error("unable to load dynamic link-exit load command");
509 // FIXME: We don't support anything interesting yet.
510 // if (DysymtabLC->LocalSymbolsIndex != 0)
511 // return Error("NOT YET IMPLEMENTED: local symbol entries");
512 // if (DysymtabLC->ExternalSymbolsIndex != 0)
513 // return Error("NOT YET IMPLEMENTED: non-external symbol entries");
514 // if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries)
515 // return Error("NOT YET IMPLEMENTED: undefined symbol entries");
518 // Load the segment load command.
519 if (SegmentLCI->Command.Type == macho::LCT_Segment) {
520 if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
523 if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
531 //===----------------------------------------------------------------------===//
532 // RuntimeDyld class implementation
533 RuntimeDyld::RuntimeDyld(JITMemoryManager *JMM) {
534 Dyld = new RuntimeDyldImpl(JMM);
537 RuntimeDyld::~RuntimeDyld() {
541 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
542 return Dyld->loadObject(InputBuffer);
545 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
546 return Dyld->getSymbolAddress(Name);
549 sys::MemoryBlock RuntimeDyld::getMemoryBlock() {
550 return Dyld->getMemoryBlock();
553 StringRef RuntimeDyld::getErrorString() {
554 return Dyld->getErrorString();
557 } // end namespace llvm