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