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 // Master symbol table. As modules are loaded and external symbols are
38 // resolved, their addresses are stored here.
39 StringMap<void*> SymbolTable;
41 // FIXME: Should have multiple data blocks, one for each loaded chunk of
43 sys::MemoryBlock Data;
48 // Set the error state and record an error string.
49 bool Error(const Twine &Msg) {
55 bool resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
56 SmallVectorImpl<void *> &SectionBases,
57 SmallVectorImpl<StringRef> &SymbolNames);
58 bool resolveX86_64Relocation(intptr_t Address, intptr_t Value, bool isPCRel,
59 unsigned Type, unsigned Size);
60 bool resolveARMRelocation(intptr_t Address, intptr_t Value, bool isPCRel,
61 unsigned Type, unsigned Size);
63 bool loadSegment32(const MachOObject *Obj,
64 const MachOObject::LoadCommandInfo *SegmentLCI,
65 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
66 bool loadSegment64(const MachOObject *Obj,
67 const MachOObject::LoadCommandInfo *SegmentLCI,
68 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
71 RuntimeDyldImpl() : HasError(false) {}
73 bool loadObject(MemoryBuffer *InputBuffer);
75 void *getSymbolAddress(StringRef Name) {
76 // Use lookup() rather than [] because we don't want to add an entry
77 // if there isn't one already, which the [] operator does.
78 return SymbolTable.lookup(Name);
81 sys::MemoryBlock getMemoryBlock() { return Data; }
83 // Is the linker in an error state?
84 bool hasError() { return HasError; }
86 // Mark the error condition as handled and continue.
87 void clearError() { HasError = false; }
89 // Get the error message.
90 StringRef getErrorString() { return ErrorStr; }
93 // FIXME: Relocations for targets other than x86_64.
94 bool RuntimeDyldImpl::
95 resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
96 SmallVectorImpl<void *> &SectionBases,
97 SmallVectorImpl<StringRef> &SymbolNames) {
98 // struct relocation_info {
100 // uint32_t r_symbolnum:24,
106 uint32_t SymbolNum = RE.Word1 & 0xffffff; // 24-bit value
107 bool isPCRel = (RE.Word1 >> 24) & 1;
108 unsigned Log2Size = (RE.Word1 >> 25) & 3;
109 bool isExtern = (RE.Word1 >> 27) & 1;
110 unsigned Type = (RE.Word1 >> 28) & 0xf;
111 if (RE.Word0 & macho::RF_Scattered)
112 return Error("NOT YET IMPLEMENTED: scattered relocations.");
114 // The address requiring a relocation.
115 intptr_t Address = (intptr_t)SectionBases[BaseSection] + RE.Word0;
117 // Figure out the target address of the relocation. If isExtern is true,
118 // this relocation references the symbol table, otherwise it references
119 // a section in the same object, numbered from 1 through NumSections
120 // (SectionBases is [0, NumSections-1]).
123 StringRef Name = SymbolNames[SymbolNum];
124 if (SymbolTable.lookup(Name)) {
125 // The symbol is in our symbol table, so we can resolve it directly.
126 Value = (intptr_t)SymbolTable[Name];
128 return Error("NOT YET IMPLEMENTED: relocations to pre-compiled code.");
130 DEBUG(dbgs() << "Resolve relocation(" << Type << ") from '" << Name
131 << "' to " << format("0x%x", Address) << ".\n");
133 // For non-external relocations, the SymbolNum is actual a section number
134 // as described above.
135 Value = (intptr_t)SectionBases[SymbolNum - 1];
138 unsigned Size = 1 << Log2Size;
140 default: assert(0 && "Unsupported CPU type!");
141 case mach::CTM_x86_64:
142 return resolveX86_64Relocation(Address, Value, isPCRel, Type, Size);
144 return resolveARMRelocation(Address, Value, isPCRel, Type, Size);
146 llvm_unreachable("");
149 bool RuntimeDyldImpl::resolveX86_64Relocation(intptr_t Address, intptr_t Value,
150 bool isPCRel, unsigned Type,
152 // If the relocation is PC-relative, the value to be encoded is the
153 // pointer difference.
155 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
156 // address. Is that expected? Only for branches, perhaps?
157 Value -= Address + 4;
161 llvm_unreachable("Invalid relocation type!");
162 case macho::RIT_X86_64_Unsigned:
163 case macho::RIT_X86_64_Branch: {
164 // Mask in the target value a byte at a time (we don't have an alignment
165 // guarantee for the target address, so this is safest).
166 uint8_t *p = (uint8_t*)Address;
167 for (unsigned i = 0; i < Size; ++i) {
168 *p++ = (uint8_t)Value;
173 case macho::RIT_X86_64_Signed:
174 case macho::RIT_X86_64_GOTLoad:
175 case macho::RIT_X86_64_GOT:
176 case macho::RIT_X86_64_Subtractor:
177 case macho::RIT_X86_64_Signed1:
178 case macho::RIT_X86_64_Signed2:
179 case macho::RIT_X86_64_Signed4:
180 case macho::RIT_X86_64_TLV:
181 return Error("Relocation type not implemented yet!");
186 bool RuntimeDyldImpl::resolveARMRelocation(intptr_t Address, intptr_t Value,
187 bool isPCRel, unsigned Type,
189 // If the relocation is PC-relative, the value to be encoded is the
190 // pointer difference.
193 // ARM PCRel relocations have an effective-PC offset of two instructions
194 // (four bytes in Thumb mode, 8 bytes in ARM mode).
195 // FIXME: For now, assume ARM mode.
201 case macho::RIT_Vanilla: {
202 llvm_unreachable("Invalid relocation type!");
203 // Mask in the target value a byte at a time (we don't have an alignment
204 // guarantee for the target address, so this is safest).
205 uint8_t *p = (uint8_t*)Address;
206 for (unsigned i = 0; i < Size; ++i) {
207 *p++ = (uint8_t)Value;
212 case macho::RIT_Pair:
213 case macho::RIT_Difference:
214 case macho::RIT_ARM_LocalDifference:
215 case macho::RIT_ARM_PreboundLazyPointer:
216 case macho::RIT_ARM_Branch24Bit: {
217 // Mask the value into the target address. We know instructions are
218 // 32-bit aligned, so we can do it all at once.
219 uint32_t *p = (uint32_t*)Address;
220 // The low two bits of the value are not encoded.
222 // Mask the value to 24 bits.
224 // FIXME: If the destination is a Thumb function (and the instruction
225 // is a non-predicated BL instruction), we need to change it to a BLX
226 // instruction instead.
228 // Insert the value into the instruction.
229 *p = (*p & ~0xffffff) | Value;
232 case macho::RIT_ARM_ThumbBranch22Bit:
233 case macho::RIT_ARM_ThumbBranch32Bit:
234 case macho::RIT_ARM_Half:
235 case macho::RIT_ARM_HalfDifference:
236 return Error("Relocation type not implemented yet!");
241 bool RuntimeDyldImpl::
242 loadSegment32(const MachOObject *Obj,
243 const MachOObject::LoadCommandInfo *SegmentLCI,
244 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
245 InMemoryStruct<macho::SegmentLoadCommand> Segment32LC;
246 Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC);
248 return Error("unable to load segment load command");
250 // Map the segment into memory.
251 std::string ErrorStr;
252 Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr);
254 return Error("unable to allocate memory block: '" + ErrorStr + "'");
255 memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset,
256 Segment32LC->FileSize).data(),
257 Segment32LC->FileSize);
258 memset((char*)Data.base() + Segment32LC->FileSize, 0,
259 Segment32LC->VMSize - Segment32LC->FileSize);
261 // Bind the section indices to addresses and record the relocations we
263 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
264 SmallVector<RelocationMap, 64> Relocations;
266 SmallVector<void *, 16> SectionBases;
267 for (unsigned i = 0; i != Segment32LC->NumSections; ++i) {
268 InMemoryStruct<macho::Section> Sect;
269 Obj->ReadSection(*SegmentLCI, i, Sect);
271 return Error("unable to load section: '" + Twine(i) + "'");
273 // Remember any relocations the section has so we can resolve them later.
274 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
275 InMemoryStruct<macho::RelocationEntry> RE;
276 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
277 Relocations.push_back(RelocationMap(j, *RE));
280 // FIXME: Improve check.
281 // if (Sect->Flags != 0x80000400)
282 // return Error("unsupported section type!");
284 SectionBases.push_back((char*) Data.base() + Sect->Address);
287 // Bind all the symbols to address. Keep a record of the names for use
288 // by relocation resolution.
289 SmallVector<StringRef, 64> SymbolNames;
290 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
291 InMemoryStruct<macho::SymbolTableEntry> STE;
292 Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
294 return Error("unable to read symbol: '" + Twine(i) + "'");
295 // Get the symbol name.
296 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
297 SymbolNames.push_back(Name);
299 // Just skip undefined symbols. They'll be loaded from whatever
300 // module they come from (or system dylib) when we resolve relocations
302 if (STE->SectionIndex == 0)
305 unsigned Index = STE->SectionIndex - 1;
306 if (Index >= Segment32LC->NumSections)
307 return Error("invalid section index for symbol: '" + Twine() + "'");
309 // Get the section base address.
310 void *SectionBase = SectionBases[Index];
312 // Get the symbol address.
313 void *Address = (char*) SectionBase + STE->Value;
315 // FIXME: Check the symbol type and flags.
316 if (STE->Type != 0xF)
317 return Error("unexpected symbol type!");
318 if (STE->Flags != 0x0)
319 return Error("unexpected symbol type!");
321 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
323 SymbolTable[Name] = Address;
326 // Now resolve any relocations.
327 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
328 if (resolveRelocation(Relocations[i].first, Relocations[i].second,
329 SectionBases, SymbolNames))
333 // We've loaded the section; now mark the functions in it as executable.
334 // FIXME: We really should use the JITMemoryManager for this.
335 sys::Memory::setRangeExecutable(Data.base(), Data.size());
341 bool RuntimeDyldImpl::
342 loadSegment64(const MachOObject *Obj,
343 const MachOObject::LoadCommandInfo *SegmentLCI,
344 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
345 InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
346 Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
348 return Error("unable to load segment load command");
350 // Map the segment into memory.
351 std::string ErrorStr;
352 Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr);
354 return Error("unable to allocate memory block: '" + ErrorStr + "'");
355 memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset,
356 Segment64LC->FileSize).data(),
357 Segment64LC->FileSize);
358 memset((char*)Data.base() + Segment64LC->FileSize, 0,
359 Segment64LC->VMSize - Segment64LC->FileSize);
361 // Bind the section indices to addresses and record the relocations we
363 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
364 SmallVector<RelocationMap, 64> Relocations;
366 SmallVector<void *, 16> SectionBases;
367 for (unsigned i = 0; i != Segment64LC->NumSections; ++i) {
368 InMemoryStruct<macho::Section64> Sect;
369 Obj->ReadSection64(*SegmentLCI, i, Sect);
371 return Error("unable to load section: '" + Twine(i) + "'");
373 // Remember any relocations the section has so we can resolve them later.
374 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
375 InMemoryStruct<macho::RelocationEntry> RE;
376 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
377 Relocations.push_back(RelocationMap(j, *RE));
380 // FIXME: Improve check.
381 if (Sect->Flags != 0x80000400)
382 return Error("unsupported section type!");
384 SectionBases.push_back((char*) Data.base() + Sect->Address);
387 // Bind all the symbols to address. Keep a record of the names for use
388 // by relocation resolution.
389 SmallVector<StringRef, 64> SymbolNames;
390 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
391 InMemoryStruct<macho::Symbol64TableEntry> STE;
392 Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
394 return Error("unable to read symbol: '" + Twine(i) + "'");
395 // Get the symbol name.
396 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
397 SymbolNames.push_back(Name);
399 // Just skip undefined symbols. They'll be loaded from whatever
400 // module they come from (or system dylib) when we resolve relocations
402 if (STE->SectionIndex == 0)
405 unsigned Index = STE->SectionIndex - 1;
406 if (Index >= Segment64LC->NumSections)
407 return Error("invalid section index for symbol: '" + Twine() + "'");
409 // Get the section base address.
410 void *SectionBase = SectionBases[Index];
412 // Get the symbol address.
413 void *Address = (char*) SectionBase + STE->Value;
415 // FIXME: Check the symbol type and flags.
416 if (STE->Type != 0xF)
417 return Error("unexpected symbol type!");
418 if (STE->Flags != 0x0)
419 return Error("unexpected symbol type!");
421 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
422 SymbolTable[Name] = Address;
425 // Now resolve any relocations.
426 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
427 if (resolveRelocation(Relocations[i].first, Relocations[i].second,
428 SectionBases, SymbolNames))
432 // We've loaded the section; now mark the functions in it as executable.
433 // FIXME: We really should use the JITMemoryManager for this.
434 sys::Memory::setRangeExecutable(Data.base(), Data.size());
439 bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) {
440 // If the linker is in an error state, don't do anything.
443 // Load the Mach-O wrapper object.
444 std::string ErrorStr;
445 OwningPtr<MachOObject> Obj(
446 MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
448 return Error("unable to load object: '" + ErrorStr + "'");
450 // Get the CPU type information from the header.
451 const macho::Header &Header = Obj->getHeader();
453 // FIXME: Error checking that the loaded object is compatible with
454 // the system we're running on.
455 CPUType = Header.CPUType;
456 CPUSubtype = Header.CPUSubtype;
458 // Validate that the load commands match what we expect.
459 const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0,
461 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
462 const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i);
463 switch (LCI.Command.Type) {
464 case macho::LCT_Segment:
465 case macho::LCT_Segment64:
467 return Error("unexpected input object (multiple segments)");
470 case macho::LCT_Symtab:
472 return Error("unexpected input object (multiple symbol tables)");
475 case macho::LCT_Dysymtab:
477 return Error("unexpected input object (multiple symbol tables)");
481 return Error("unexpected input object (unexpected load command");
486 return Error("no symbol table found in object");
488 return Error("no symbol table found in object");
490 // Read and register the symbol table data.
491 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
492 Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
494 return Error("unable to load symbol table load command");
495 Obj->RegisterStringTable(*SymtabLC);
497 // Read the dynamic link-edit information, if present (not present in static
500 InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
501 Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
503 return Error("unable to load dynamic link-exit load command");
505 // FIXME: We don't support anything interesting yet.
506 // if (DysymtabLC->LocalSymbolsIndex != 0)
507 // return Error("NOT YET IMPLEMENTED: local symbol entries");
508 // if (DysymtabLC->ExternalSymbolsIndex != 0)
509 // return Error("NOT YET IMPLEMENTED: non-external symbol entries");
510 // if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries)
511 // return Error("NOT YET IMPLEMENTED: undefined symbol entries");
514 // Load the segment load command.
515 if (SegmentLCI->Command.Type == macho::LCT_Segment) {
516 if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
519 if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
527 //===----------------------------------------------------------------------===//
528 // RuntimeDyld class implementation
529 RuntimeDyld::RuntimeDyld() {
530 Dyld = new RuntimeDyldImpl;
533 RuntimeDyld::~RuntimeDyld() {
537 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
538 return Dyld->loadObject(InputBuffer);
541 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
542 return Dyld->getSymbolAddress(Name);
545 sys::MemoryBlock RuntimeDyld::getMemoryBlock() {
546 return Dyld->getMemoryBlock();
549 StringRef RuntimeDyld::getErrorString() {
550 return Dyld->getErrorString();
553 } // end namespace llvm