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 {
34 // Master symbol table. As modules are loaded and external symbols are
35 // resolved, their addresses are stored here.
36 StringMap<void*> SymbolTable;
38 // FIXME: Should have multiple data blocks, one for each loaded chunk of
40 sys::MemoryBlock Data;
45 // Set the error state and record an error string.
46 bool Error(const Twine &Msg) {
52 bool resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
53 SmallVectorImpl<void *> &SectionBases,
54 SmallVectorImpl<StringRef> &SymbolNames);
56 bool loadSegment32(const MachOObject *Obj,
57 const MachOObject::LoadCommandInfo *SegmentLCI,
58 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
59 bool loadSegment64(const MachOObject *Obj,
60 const MachOObject::LoadCommandInfo *SegmentLCI,
61 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC);
64 RuntimeDyldImpl() : HasError(false) {}
66 bool loadObject(MemoryBuffer *InputBuffer);
68 void *getSymbolAddress(StringRef Name) {
69 // Use lookup() rather than [] because we don't want to add an entry
70 // if there isn't one already, which the [] operator does.
71 return SymbolTable.lookup(Name);
74 sys::MemoryBlock getMemoryBlock() { return Data; }
76 // Is the linker in an error state?
77 bool hasError() { return HasError; }
79 // Mark the error condition as handled and continue.
80 void clearError() { HasError = false; }
82 // Get the error message.
83 StringRef getErrorString() { return ErrorStr; }
86 // FIXME: Relocations for targets other than x86_64.
87 bool RuntimeDyldImpl::
88 resolveRelocation(uint32_t BaseSection, macho::RelocationEntry RE,
89 SmallVectorImpl<void *> &SectionBases,
90 SmallVectorImpl<StringRef> &SymbolNames) {
91 // struct relocation_info {
93 // uint32_t r_symbolnum:24,
99 uint32_t SymbolNum = RE.Word1 & 0xffffff; // 24-bit value
100 bool isPCRel = (RE.Word1 >> 24) & 1;
101 unsigned Log2Size = (RE.Word1 >> 25) & 3;
102 bool isExtern = (RE.Word1 >> 27) & 1;
103 unsigned Type = (RE.Word1 >> 28) & 0xf;
104 if (RE.Word0 & macho::RF_Scattered)
105 return Error("NOT YET IMPLEMENTED: scattered relocations.");
107 // The address requiring a relocation.
108 intptr_t Address = (intptr_t)SectionBases[BaseSection] + RE.Word0;
110 // Figure out the target address of the relocation. If isExtern is true,
111 // this relocation references the symbol table, otherwise it references
112 // a section in the same object, numbered from 1 through NumSections
113 // (SectionBases is [0, NumSections-1]).
116 StringRef Name = SymbolNames[SymbolNum];
117 if (SymbolTable.lookup(Name)) {
118 // The symbol is in our symbol table, so we can resolve it directly.
119 Value = (intptr_t)SymbolTable[Name];
121 return Error("NOT YET IMPLEMENTED: relocations to pre-compiled code.");
123 DEBUG(dbgs() << "Resolve relocation(" << Type << ") from '" << Name
124 << "' to " << format("0x%x", Address) << ".\n");
126 // For non-external relocations, the SymbolNum is actual a section number
127 // as described above.
128 Value = (intptr_t)SectionBases[SymbolNum - 1];
131 // If the relocation is PC-relative, the value to be encoded is the
132 // pointer difference.
134 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
135 // address. Is that expected? Only for branches, perhaps?
136 Value -= Address + 4;
140 llvm_unreachable("Invalid relocation type!");
141 case macho::RIT_X86_64_Unsigned:
142 case macho::RIT_X86_64_Branch: {
143 // Mask in the target value a byte at a time (we don't have an alignment
144 // guarantee for the target address, so this is safest).
145 unsigned Len = 1 << Log2Size;
146 uint8_t *p = (uint8_t*)Address;
147 for (unsigned i = 0; i < Len; ++i) {
148 *p++ = (uint8_t)Value;
153 case macho::RIT_X86_64_Signed:
154 case macho::RIT_X86_64_GOTLoad:
155 case macho::RIT_X86_64_GOT:
156 case macho::RIT_X86_64_Subtractor:
157 case macho::RIT_X86_64_Signed1:
158 case macho::RIT_X86_64_Signed2:
159 case macho::RIT_X86_64_Signed4:
160 case macho::RIT_X86_64_TLV:
161 return Error("Relocation type not implemented yet!");
166 bool RuntimeDyldImpl::
167 loadSegment32(const MachOObject *Obj,
168 const MachOObject::LoadCommandInfo *SegmentLCI,
169 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
170 InMemoryStruct<macho::SegmentLoadCommand> Segment32LC;
171 Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC);
173 return Error("unable to load segment load command");
175 // Map the segment into memory.
176 std::string ErrorStr;
177 Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr);
179 return Error("unable to allocate memory block: '" + ErrorStr + "'");
180 memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset,
181 Segment32LC->FileSize).data(),
182 Segment32LC->FileSize);
183 memset((char*)Data.base() + Segment32LC->FileSize, 0,
184 Segment32LC->VMSize - Segment32LC->FileSize);
186 // Bind the section indices to address.
187 SmallVector<void *, 16> SectionBases;
188 for (unsigned i = 0; i != Segment32LC->NumSections; ++i) {
189 InMemoryStruct<macho::Section> Sect;
190 Obj->ReadSection(*SegmentLCI, i, Sect);
192 return Error("unable to load section: '" + Twine(i) + "'");
194 // FIXME: We don't support relocations yet.
195 if (Sect->NumRelocationTableEntries != 0)
196 return Error("not yet implemented: relocations!");
198 // FIXME: Improve check.
199 if (Sect->Flags != 0x80000400)
200 return Error("unsupported section type!");
202 SectionBases.push_back((char*) Data.base() + Sect->Address);
205 // Bind all the symbols to address.
206 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
207 InMemoryStruct<macho::SymbolTableEntry> STE;
208 Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
210 return Error("unable to read symbol: '" + Twine(i) + "'");
211 if (STE->SectionIndex == 0)
212 return Error("unexpected undefined symbol!");
214 unsigned Index = STE->SectionIndex - 1;
215 if (Index >= Segment32LC->NumSections)
216 return Error("invalid section index for symbol: '" + Twine() + "'");
218 // Get the symbol name.
219 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
221 // Get the section base address.
222 void *SectionBase = SectionBases[Index];
224 // Get the symbol address.
225 void *Address = (char*) SectionBase + STE->Value;
227 // FIXME: Check the symbol type and flags.
228 if (STE->Type != 0xF)
229 return Error("unexpected symbol type!");
230 if (STE->Flags != 0x0)
231 return Error("unexpected symbol type!");
233 DEBUG(dbgs() << "Symbol: '" << Name << "' @ " << Address << "\n");
235 SymbolTable[Name] = Address;
238 // We've loaded the section; now mark the functions in it as executable.
239 // FIXME: We really should use the JITMemoryManager for this.
240 sys::Memory::setRangeExecutable(Data.base(), Data.size());
246 bool RuntimeDyldImpl::
247 loadSegment64(const MachOObject *Obj,
248 const MachOObject::LoadCommandInfo *SegmentLCI,
249 const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
250 InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
251 Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
253 return Error("unable to load segment load command");
255 // Map the segment into memory.
256 std::string ErrorStr;
257 Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr);
259 return Error("unable to allocate memory block: '" + ErrorStr + "'");
260 memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset,
261 Segment64LC->FileSize).data(),
262 Segment64LC->FileSize);
263 memset((char*)Data.base() + Segment64LC->FileSize, 0,
264 Segment64LC->VMSize - Segment64LC->FileSize);
266 // Bind the section indices to addresses and record the relocations we
268 typedef std::pair<uint32_t, macho::RelocationEntry> RelocationMap;
269 SmallVector<RelocationMap, 64> Relocations;
271 SmallVector<void *, 16> SectionBases;
272 for (unsigned i = 0; i != Segment64LC->NumSections; ++i) {
273 InMemoryStruct<macho::Section64> Sect;
274 Obj->ReadSection64(*SegmentLCI, i, Sect);
276 return Error("unable to load section: '" + Twine(i) + "'");
278 // Resolve any relocations the section has.
279 for (unsigned j = 0; j != Sect->NumRelocationTableEntries; ++j) {
280 InMemoryStruct<macho::RelocationEntry> RE;
281 Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
282 Relocations.push_back(RelocationMap(j, *RE));
285 // FIXME: Improve check.
286 if (Sect->Flags != 0x80000400)
287 return Error("unsupported section type!");
289 SectionBases.push_back((char*) Data.base() + Sect->Address);
292 // Bind all the symbols to address. Keep a record of the names for use
293 // by relocation resolution.
294 SmallVector<StringRef, 64> SymbolNames;
295 for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) {
296 InMemoryStruct<macho::Symbol64TableEntry> STE;
297 Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
299 return Error("unable to read symbol: '" + Twine(i) + "'");
300 // Get the symbol name.
301 StringRef Name = Obj->getStringAtIndex(STE->StringIndex);
302 SymbolNames.push_back(Name);
304 // Just skip undefined symbols. They'll be loaded from whatever
305 // module they come from (or system dylib) when we resolve relocations
307 if (STE->SectionIndex == 0)
310 unsigned Index = STE->SectionIndex - 1;
311 if (Index >= Segment64LC->NumSections)
312 return Error("invalid section index for symbol: '" + Twine() + "'");
314 // Get the section base address.
315 void *SectionBase = SectionBases[Index];
317 // Get the symbol address.
318 void *Address = (char*) SectionBase + STE->Value;
320 // FIXME: Check the symbol type and flags.
321 if (STE->Type != 0xF)
322 return Error("unexpected symbol type!");
323 if (STE->Flags != 0x0)
324 return Error("unexpected symbol type!");
326 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());
344 bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) {
345 // If the linker is in an error state, don't do anything.
348 // Load the Mach-O wrapper object.
349 std::string ErrorStr;
350 OwningPtr<MachOObject> Obj(
351 MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
353 return Error("unable to load object: '" + ErrorStr + "'");
355 // Validate that the load commands match what we expect.
356 const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0,
358 for (unsigned i = 0; i != Obj->getHeader().NumLoadCommands; ++i) {
359 const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i);
360 switch (LCI.Command.Type) {
361 case macho::LCT_Segment:
362 case macho::LCT_Segment64:
364 return Error("unexpected input object (multiple segments)");
367 case macho::LCT_Symtab:
369 return Error("unexpected input object (multiple symbol tables)");
372 case macho::LCT_Dysymtab:
374 return Error("unexpected input object (multiple symbol tables)");
378 return Error("unexpected input object (unexpected load command");
383 return Error("no symbol table found in object");
385 return Error("no symbol table found in object");
387 // Read and register the symbol table data.
388 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
389 Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
391 return Error("unable to load symbol table load command");
392 Obj->RegisterStringTable(*SymtabLC);
394 // Read the dynamic link-edit information, if present (not present in static
397 InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
398 Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
400 return Error("unable to load dynamic link-exit load command");
402 // FIXME: We don't support anything interesting yet.
403 // if (DysymtabLC->LocalSymbolsIndex != 0)
404 // return Error("NOT YET IMPLEMENTED: local symbol entries");
405 // if (DysymtabLC->ExternalSymbolsIndex != 0)
406 // return Error("NOT YET IMPLEMENTED: non-external symbol entries");
407 // if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries)
408 // return Error("NOT YET IMPLEMENTED: undefined symbol entries");
411 // Load the segment load command.
412 if (SegmentLCI->Command.Type == macho::LCT_Segment) {
413 if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
416 if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
424 //===----------------------------------------------------------------------===//
425 // RuntimeDyld class implementation
426 RuntimeDyld::RuntimeDyld() {
427 Dyld = new RuntimeDyldImpl;
430 RuntimeDyld::~RuntimeDyld() {
434 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
435 return Dyld->loadObject(InputBuffer);
438 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
439 return Dyld->getSymbolAddress(Name);
442 sys::MemoryBlock RuntimeDyld::getMemoryBlock() {
443 return Dyld->getMemoryBlock();
446 StringRef RuntimeDyld::getErrorString() {
447 return Dyld->getErrorString();
450 } // end namespace llvm