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