1 //===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
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 // This is a testing tool for use with the MC-JIT LLVM components.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/DebugInfo/DIContext.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
18 #include "llvm/ExecutionEngine/RuntimeDyld.h"
19 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/Object/SymbolSize.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DynamicLibrary.h"
30 #include "llvm/Support/InitLLVM.h"
31 #include "llvm/Support/Memory.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <list>
37
38 using namespace llvm;
39 using namespace llvm::object;
40
41 static cl::list<std::string>
42 InputFileList(cl::Positional, cl::ZeroOrMore,
43 cl::desc("<input files>"));
44
45 enum ActionType {
46 AC_Execute,
47 AC_PrintObjectLineInfo,
48 AC_PrintLineInfo,
49 AC_PrintDebugLineInfo,
50 AC_Verify
51 };
52
53 static cl::opt<ActionType>
54 Action(cl::desc("Action to perform:"),
55 cl::init(AC_Execute),
56 cl::values(clEnumValN(AC_Execute, "execute",
57 "Load, link, and execute the inputs."),
58 clEnumValN(AC_PrintLineInfo, "printline",
59 "Load, link, and print line information for each function."),
60 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
61 "Load, link, and print line information for each function using the debug object"),
62 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
63 "Like -printlineinfo but does not load the object first"),
64 clEnumValN(AC_Verify, "verify",
65 "Load, link and verify the resulting memory image.")));
66
67 static cl::opt<std::string>
68 EntryPoint("entry",
69 cl::desc("Function to call as entry point."),
70 cl::init("_main"));
71
72 static cl::list<std::string>
73 Dylibs("dylib",
74 cl::desc("Add library."),
75 cl::ZeroOrMore);
76
77 static cl::opt<std::string>
78 TripleName("triple", cl::desc("Target triple for disassembler"));
79
80 static cl::opt<std::string>
81 MCPU("mcpu",
82 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
83 cl::value_desc("cpu-name"),
84 cl::init(""));
85
86 static cl::list<std::string>
87 CheckFiles("check",
88 cl::desc("File containing RuntimeDyld verifier checks."),
89 cl::ZeroOrMore);
90
91 static cl::opt<uint64_t>
92 PreallocMemory("preallocate",
93 cl::desc("Allocate memory upfront rather than on-demand"),
94 cl::init(0));
95
96 static cl::opt<uint64_t>
97 TargetAddrStart("target-addr-start",
98 cl::desc("For -verify only: start of phony target address "
99 "range."),
100 cl::init(4096), // Start at "page 1" - no allocating at "null".
101 cl::Hidden);
102
103 static cl::opt<uint64_t>
104 TargetAddrEnd("target-addr-end",
105 cl::desc("For -verify only: end of phony target address range."),
106 cl::init(~0ULL),
107 cl::Hidden);
108
109 static cl::opt<uint64_t>
110 TargetSectionSep("target-section-sep",
111 cl::desc("For -verify only: Separation between sections in "
112 "phony target address space."),
113 cl::init(0),
114 cl::Hidden);
115
116 static cl::list<std::string>
117 SpecificSectionMappings("map-section",
118 cl::desc("For -verify only: Map a section to a "
119 "specific address."),
120 cl::ZeroOrMore,
121 cl::Hidden);
122
123 static cl::list<std::string>
124 DummySymbolMappings("dummy-extern",
125 cl::desc("For -verify only: Inject a symbol into the extern "
126 "symbol table."),
127 cl::ZeroOrMore,
128 cl::Hidden);
129
130 static cl::opt<bool>
131 PrintAllocationRequests("print-alloc-requests",
132 cl::desc("Print allocation requests made to the memory "
133 "manager by RuntimeDyld"),
134 cl::Hidden);
135
136 /* *** */
137
138 // A trivial memory manager that doesn't do anything fancy, just uses the
139 // support library allocation routines directly.
140 class TrivialMemoryManager : public RTDyldMemoryManager {
141 public:
142 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
143 SmallVector<sys::MemoryBlock, 16> DataMemory;
144
145 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
146 unsigned SectionID,
147 StringRef SectionName) override;
148 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
149 unsigned SectionID, StringRef SectionName,
150 bool IsReadOnly) override;
151
getPointerToNamedFunction(const std::string & Name,bool AbortOnFailure=true)152 void *getPointerToNamedFunction(const std::string &Name,
153 bool AbortOnFailure = true) override {
154 return nullptr;
155 }
156
finalizeMemory(std::string * ErrMsg)157 bool finalizeMemory(std::string *ErrMsg) override { return false; }
158
addDummySymbol(const std::string & Name,uint64_t Addr)159 void addDummySymbol(const std::string &Name, uint64_t Addr) {
160 DummyExterns[Name] = Addr;
161 }
162
findSymbol(const std::string & Name)163 JITSymbol findSymbol(const std::string &Name) override {
164 auto I = DummyExterns.find(Name);
165
166 if (I != DummyExterns.end())
167 return JITSymbol(I->second, JITSymbolFlags::Exported);
168
169 return RTDyldMemoryManager::findSymbol(Name);
170 }
171
registerEHFrames(uint8_t * Addr,uint64_t LoadAddr,size_t Size)172 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
173 size_t Size) override {}
deregisterEHFrames()174 void deregisterEHFrames() override {}
175
preallocateSlab(uint64_t Size)176 void preallocateSlab(uint64_t Size) {
177 std::error_code EC;
178 sys::MemoryBlock MB =
179 sys::Memory::allocateMappedMemory(Size, nullptr,
180 sys::Memory::MF_READ |
181 sys::Memory::MF_WRITE,
182 EC);
183 if (!MB.base())
184 report_fatal_error("Can't allocate enough memory: " + EC.message());
185
186 PreallocSlab = MB;
187 UsePreallocation = true;
188 SlabSize = Size;
189 }
190
allocateFromSlab(uintptr_t Size,unsigned Alignment,bool isCode)191 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode) {
192 Size = alignTo(Size, Alignment);
193 if (CurrentSlabOffset + Size > SlabSize)
194 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
195
196 uintptr_t OldSlabOffset = CurrentSlabOffset;
197 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
198 if (isCode)
199 FunctionMemory.push_back(MB);
200 else
201 DataMemory.push_back(MB);
202 CurrentSlabOffset += Size;
203 return (uint8_t*)OldSlabOffset;
204 }
205
206 private:
207 std::map<std::string, uint64_t> DummyExterns;
208 sys::MemoryBlock PreallocSlab;
209 bool UsePreallocation = false;
210 uintptr_t SlabSize = 0;
211 uintptr_t CurrentSlabOffset = 0;
212 };
213
allocateCodeSection(uintptr_t Size,unsigned Alignment,unsigned SectionID,StringRef SectionName)214 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
215 unsigned Alignment,
216 unsigned SectionID,
217 StringRef SectionName) {
218 if (PrintAllocationRequests)
219 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
220 << Alignment << ", SectionName = " << SectionName << ")\n";
221
222 if (UsePreallocation)
223 return allocateFromSlab(Size, Alignment, true /* isCode */);
224
225 std::error_code EC;
226 sys::MemoryBlock MB =
227 sys::Memory::allocateMappedMemory(Size, nullptr,
228 sys::Memory::MF_READ |
229 sys::Memory::MF_WRITE,
230 EC);
231 if (!MB.base())
232 report_fatal_error("MemoryManager allocation failed: " + EC.message());
233 FunctionMemory.push_back(MB);
234 return (uint8_t*)MB.base();
235 }
236
allocateDataSection(uintptr_t Size,unsigned Alignment,unsigned SectionID,StringRef SectionName,bool IsReadOnly)237 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
238 unsigned Alignment,
239 unsigned SectionID,
240 StringRef SectionName,
241 bool IsReadOnly) {
242 if (PrintAllocationRequests)
243 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
244 << Alignment << ", SectionName = " << SectionName << ")\n";
245
246 if (UsePreallocation)
247 return allocateFromSlab(Size, Alignment, false /* isCode */);
248
249 std::error_code EC;
250 sys::MemoryBlock MB =
251 sys::Memory::allocateMappedMemory(Size, nullptr,
252 sys::Memory::MF_READ |
253 sys::Memory::MF_WRITE,
254 EC);
255 if (!MB.base())
256 report_fatal_error("MemoryManager allocation failed: " + EC.message());
257 DataMemory.push_back(MB);
258 return (uint8_t*)MB.base();
259 }
260
261 static const char *ProgramName;
262
ErrorAndExit(const Twine & Msg)263 static void ErrorAndExit(const Twine &Msg) {
264 errs() << ProgramName << ": error: " << Msg << "\n";
265 exit(1);
266 }
267
loadDylibs()268 static void loadDylibs() {
269 for (const std::string &Dylib : Dylibs) {
270 if (!sys::fs::is_regular_file(Dylib))
271 report_fatal_error("Dylib not found: '" + Dylib + "'.");
272 std::string ErrMsg;
273 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
274 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
275 }
276 }
277
278 /* *** */
279
printLineInfoForInput(bool LoadObjects,bool UseDebugObj)280 static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
281 assert(LoadObjects || !UseDebugObj);
282
283 // Load any dylibs requested on the command line.
284 loadDylibs();
285
286 // If we don't have any input files, read from stdin.
287 if (!InputFileList.size())
288 InputFileList.push_back("-");
289 for (auto &File : InputFileList) {
290 // Instantiate a dynamic linker.
291 TrivialMemoryManager MemMgr;
292 RuntimeDyld Dyld(MemMgr, MemMgr);
293
294 // Load the input memory buffer.
295
296 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
297 MemoryBuffer::getFileOrSTDIN(File);
298 if (std::error_code EC = InputBuffer.getError())
299 ErrorAndExit("unable to read input: '" + EC.message() + "'");
300
301 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
302 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
303
304 if (!MaybeObj) {
305 std::string Buf;
306 raw_string_ostream OS(Buf);
307 logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
308 OS.flush();
309 ErrorAndExit("unable to create object file: '" + Buf + "'");
310 }
311
312 ObjectFile &Obj = **MaybeObj;
313
314 OwningBinary<ObjectFile> DebugObj;
315 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
316 ObjectFile *SymbolObj = &Obj;
317 if (LoadObjects) {
318 // Load the object file
319 LoadedObjInfo =
320 Dyld.loadObject(Obj);
321
322 if (Dyld.hasError())
323 ErrorAndExit(Dyld.getErrorString());
324
325 // Resolve all the relocations we can.
326 Dyld.resolveRelocations();
327
328 if (UseDebugObj) {
329 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
330 SymbolObj = DebugObj.getBinary();
331 LoadedObjInfo.reset();
332 }
333 }
334
335 std::unique_ptr<DIContext> Context =
336 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
337
338 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
339 object::computeSymbolSizes(*SymbolObj);
340
341 // Use symbol info to iterate functions in the object.
342 for (const auto &P : SymAddr) {
343 object::SymbolRef Sym = P.first;
344 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
345 if (!TypeOrErr) {
346 // TODO: Actually report errors helpfully.
347 consumeError(TypeOrErr.takeError());
348 continue;
349 }
350 SymbolRef::Type Type = *TypeOrErr;
351 if (Type == object::SymbolRef::ST_Function) {
352 Expected<StringRef> Name = Sym.getName();
353 if (!Name) {
354 // TODO: Actually report errors helpfully.
355 consumeError(Name.takeError());
356 continue;
357 }
358 Expected<uint64_t> AddrOrErr = Sym.getAddress();
359 if (!AddrOrErr) {
360 // TODO: Actually report errors helpfully.
361 consumeError(AddrOrErr.takeError());
362 continue;
363 }
364 uint64_t Addr = *AddrOrErr;
365
366 uint64_t Size = P.second;
367 // If we're not using the debug object, compute the address of the
368 // symbol in memory (rather than that in the unrelocated object file)
369 // and use that to query the DWARFContext.
370 if (!UseDebugObj && LoadObjects) {
371 auto SecOrErr = Sym.getSection();
372 if (!SecOrErr) {
373 // TODO: Actually report errors helpfully.
374 consumeError(SecOrErr.takeError());
375 continue;
376 }
377 object::section_iterator Sec = *SecOrErr;
378 StringRef SecName;
379 Sec->getName(SecName);
380 uint64_t SectionLoadAddress =
381 LoadedObjInfo->getSectionLoadAddress(*Sec);
382 if (SectionLoadAddress != 0)
383 Addr += SectionLoadAddress - Sec->getAddress();
384 }
385
386 outs() << "Function: " << *Name << ", Size = " << Size
387 << ", Addr = " << Addr << "\n";
388
389 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
390 for (auto &D : Lines) {
391 outs() << " Line info @ " << D.first - Addr << ": "
392 << D.second.FileName << ", line:" << D.second.Line << "\n";
393 }
394 }
395 }
396 }
397
398 return 0;
399 }
400
doPreallocation(TrivialMemoryManager & MemMgr)401 static void doPreallocation(TrivialMemoryManager &MemMgr) {
402 // Allocate a slab of memory upfront, if required. This is used if
403 // we want to test small code models.
404 if (static_cast<intptr_t>(PreallocMemory) < 0)
405 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
406
407 // FIXME: Limit the amount of memory that can be preallocated?
408 if (PreallocMemory != 0)
409 MemMgr.preallocateSlab(PreallocMemory);
410 }
411
executeInput()412 static int executeInput() {
413 // Load any dylibs requested on the command line.
414 loadDylibs();
415
416 // Instantiate a dynamic linker.
417 TrivialMemoryManager MemMgr;
418 doPreallocation(MemMgr);
419 RuntimeDyld Dyld(MemMgr, MemMgr);
420
421 // If we don't have any input files, read from stdin.
422 if (!InputFileList.size())
423 InputFileList.push_back("-");
424 for (auto &File : InputFileList) {
425 // Load the input memory buffer.
426 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
427 MemoryBuffer::getFileOrSTDIN(File);
428 if (std::error_code EC = InputBuffer.getError())
429 ErrorAndExit("unable to read input: '" + EC.message() + "'");
430 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
431 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
432
433 if (!MaybeObj) {
434 std::string Buf;
435 raw_string_ostream OS(Buf);
436 logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
437 OS.flush();
438 ErrorAndExit("unable to create object file: '" + Buf + "'");
439 }
440
441 ObjectFile &Obj = **MaybeObj;
442
443 // Load the object file
444 Dyld.loadObject(Obj);
445 if (Dyld.hasError()) {
446 ErrorAndExit(Dyld.getErrorString());
447 }
448 }
449
450 // Resove all the relocations we can.
451 // FIXME: Error out if there are unresolved relocations.
452 Dyld.resolveRelocations();
453
454 // Get the address of the entry point (_main by default).
455 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
456 if (!MainAddress)
457 ErrorAndExit("no definition for '" + EntryPoint + "'");
458
459 // Invalidate the instruction cache for each loaded function.
460 for (auto &FM : MemMgr.FunctionMemory) {
461
462 // Make sure the memory is executable.
463 // setExecutable will call InvalidateInstructionCache.
464 if (auto EC = sys::Memory::protectMappedMemory(FM,
465 sys::Memory::MF_READ |
466 sys::Memory::MF_EXEC))
467 ErrorAndExit("unable to mark function executable: '" + EC.message() +
468 "'");
469 }
470
471 // Dispatch to _main().
472 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
473
474 int (*Main)(int, const char**) =
475 (int(*)(int,const char**)) uintptr_t(MainAddress);
476 const char **Argv = new const char*[2];
477 // Use the name of the first input object module as argv[0] for the target.
478 Argv[0] = InputFileList[0].c_str();
479 Argv[1] = nullptr;
480 return Main(1, Argv);
481 }
482
checkAllExpressions(RuntimeDyldChecker & Checker)483 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
484 for (const auto& CheckerFileName : CheckFiles) {
485 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
486 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
487 if (std::error_code EC = CheckerFileBuf.getError())
488 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
489 EC.message());
490
491 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
492 CheckerFileBuf.get().get()))
493 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
494 }
495 return 0;
496 }
497
applySpecificSectionMappings(RuntimeDyldChecker & Checker)498 void applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
499
500 for (StringRef Mapping : SpecificSectionMappings) {
501
502 size_t EqualsIdx = Mapping.find_first_of("=");
503 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
504 size_t ComaIdx = Mapping.find_first_of(",");
505
506 if (ComaIdx == StringRef::npos)
507 report_fatal_error("Invalid section specification '" + Mapping +
508 "'. Should be '<file name>,<section name>=<addr>'");
509
510 std::string FileName = SectionIDStr.substr(0, ComaIdx);
511 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
512
513 uint64_t OldAddrInt;
514 std::string ErrorMsg;
515 std::tie(OldAddrInt, ErrorMsg) =
516 Checker.getSectionAddr(FileName, SectionName, true);
517
518 if (ErrorMsg != "")
519 report_fatal_error(ErrorMsg);
520
521 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
522
523 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
524 uint64_t NewAddr;
525
526 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
527 report_fatal_error("Invalid section address in mapping '" + Mapping +
528 "'.");
529
530 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
531 }
532 }
533
534 // Scatter sections in all directions!
535 // Remaps section addresses for -verify mode. The following command line options
536 // can be used to customize the layout of the memory within the phony target's
537 // address space:
538 // -target-addr-start <s> -- Specify where the phony target address range starts.
539 // -target-addr-end <e> -- Specify where the phony target address range ends.
540 // -target-section-sep <d> -- Specify how big a gap should be left between the
541 // end of one section and the start of the next.
542 // Defaults to zero. Set to something big
543 // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
544 //
remapSectionsAndSymbols(const llvm::Triple & TargetTriple,TrivialMemoryManager & MemMgr,RuntimeDyldChecker & Checker)545 static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
546 TrivialMemoryManager &MemMgr,
547 RuntimeDyldChecker &Checker) {
548
549 // Set up a work list (section addr/size pairs).
550 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
551 WorklistT Worklist;
552
553 for (const auto& CodeSection : MemMgr.FunctionMemory)
554 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
555 for (const auto& DataSection : MemMgr.DataMemory)
556 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
557
558 // Apply any section-specific mappings that were requested on the command
559 // line.
560 applySpecificSectionMappings(Checker);
561
562 // Keep an "already allocated" mapping of section target addresses to sizes.
563 // Sections whose address mappings aren't specified on the command line will
564 // allocated around the explicitly mapped sections while maintaining the
565 // minimum separation.
566 std::map<uint64_t, uint64_t> AlreadyAllocated;
567
568 // Move the previously applied mappings (whether explicitly specified on the
569 // command line, or implicitly set by RuntimeDyld) into the already-allocated
570 // map.
571 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
572 I != E;) {
573 WorklistT::iterator Tmp = I;
574 ++I;
575 auto LoadAddr = Checker.getSectionLoadAddress(Tmp->first);
576
577 if (LoadAddr &&
578 *LoadAddr != static_cast<uint64_t>(
579 reinterpret_cast<uintptr_t>(Tmp->first))) {
580 AlreadyAllocated[*LoadAddr] = Tmp->second;
581 Worklist.erase(Tmp);
582 }
583 }
584
585 // If the -target-addr-end option wasn't explicitly passed, then set it to a
586 // sensible default based on the target triple.
587 if (TargetAddrEnd.getNumOccurrences() == 0) {
588 if (TargetTriple.isArch16Bit())
589 TargetAddrEnd = (1ULL << 16) - 1;
590 else if (TargetTriple.isArch32Bit())
591 TargetAddrEnd = (1ULL << 32) - 1;
592 // TargetAddrEnd already has a sensible default for 64-bit systems, so
593 // there's nothing to do in the 64-bit case.
594 }
595
596 // Process any elements remaining in the worklist.
597 while (!Worklist.empty()) {
598 std::pair<void*, uint64_t> CurEntry = Worklist.front();
599 Worklist.pop_front();
600
601 uint64_t NextSectionAddr = TargetAddrStart;
602
603 for (const auto &Alloc : AlreadyAllocated)
604 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
605 break;
606 else
607 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
608
609 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
610 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
611 }
612
613 // Add dummy symbols to the memory manager.
614 for (const auto &Mapping : DummySymbolMappings) {
615 size_t EqualsIdx = Mapping.find_first_of('=');
616
617 if (EqualsIdx == StringRef::npos)
618 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
619 "'. Should be '<symbol name>=<addr>'");
620
621 std::string Symbol = Mapping.substr(0, EqualsIdx);
622 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
623
624 uint64_t Addr;
625 if (StringRef(AddrStr).getAsInteger(0, Addr))
626 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
627
628 MemMgr.addDummySymbol(Symbol, Addr);
629 }
630 }
631
632 // Load and link the objects specified on the command line, but do not execute
633 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
634 // verify the correctness of the linked memory.
linkAndVerify()635 static int linkAndVerify() {
636
637 // Check for missing triple.
638 if (TripleName == "")
639 ErrorAndExit("-triple required when running in -verify mode.");
640
641 // Look up the target and build the disassembler.
642 Triple TheTriple(Triple::normalize(TripleName));
643 std::string ErrorStr;
644 const Target *TheTarget =
645 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
646 if (!TheTarget)
647 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
648
649 TripleName = TheTriple.getTriple();
650
651 std::unique_ptr<MCSubtargetInfo> STI(
652 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
653 if (!STI)
654 ErrorAndExit("Unable to create subtarget info!");
655
656 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
657 if (!MRI)
658 ErrorAndExit("Unable to create target register info!");
659
660 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
661 if (!MAI)
662 ErrorAndExit("Unable to create target asm info!");
663
664 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
665
666 std::unique_ptr<MCDisassembler> Disassembler(
667 TheTarget->createMCDisassembler(*STI, Ctx));
668 if (!Disassembler)
669 ErrorAndExit("Unable to create disassembler!");
670
671 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
672
673 std::unique_ptr<MCInstPrinter> InstPrinter(
674 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
675
676 // Load any dylibs requested on the command line.
677 loadDylibs();
678
679 // Instantiate a dynamic linker.
680 TrivialMemoryManager MemMgr;
681 doPreallocation(MemMgr);
682 RuntimeDyld Dyld(MemMgr, MemMgr);
683 Dyld.setProcessAllSections(true);
684 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
685 llvm::dbgs());
686
687 // If we don't have any input files, read from stdin.
688 if (!InputFileList.size())
689 InputFileList.push_back("-");
690 for (auto &Filename : InputFileList) {
691 // Load the input memory buffer.
692 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
693 MemoryBuffer::getFileOrSTDIN(Filename);
694
695 if (std::error_code EC = InputBuffer.getError())
696 ErrorAndExit("unable to read input: '" + EC.message() + "'");
697
698 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
699 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
700
701 if (!MaybeObj) {
702 std::string Buf;
703 raw_string_ostream OS(Buf);
704 logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
705 OS.flush();
706 ErrorAndExit("unable to create object file: '" + Buf + "'");
707 }
708
709 ObjectFile &Obj = **MaybeObj;
710
711 // Load the object file
712 Dyld.loadObject(Obj);
713 if (Dyld.hasError()) {
714 ErrorAndExit(Dyld.getErrorString());
715 }
716 }
717
718 // Re-map the section addresses into the phony target address space and add
719 // dummy symbols.
720 remapSectionsAndSymbols(TheTriple, MemMgr, Checker);
721
722 // Resolve all the relocations we can.
723 Dyld.resolveRelocations();
724
725 // Register EH frames.
726 Dyld.registerEHFrames();
727
728 int ErrorCode = checkAllExpressions(Checker);
729 if (Dyld.hasError())
730 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
731 Dyld.getErrorString());
732
733 return ErrorCode;
734 }
735
main(int argc,char ** argv)736 int main(int argc, char **argv) {
737 InitLLVM X(argc, argv);
738 ProgramName = argv[0];
739
740 llvm::InitializeAllTargetInfos();
741 llvm::InitializeAllTargetMCs();
742 llvm::InitializeAllDisassemblers();
743
744 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
745
746 switch (Action) {
747 case AC_Execute:
748 return executeInput();
749 case AC_PrintDebugLineInfo:
750 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
751 case AC_PrintLineInfo:
752 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
753 case AC_PrintObjectLineInfo:
754 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
755 case AC_Verify:
756 return linkAndVerify();
757 }
758 }
759