]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306956, and update
[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() override {}
179
180   void preallocateSlab(uint64_t Size) {
181     std::string Err;
182     sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, &Err);
183     if (!MB.base())
184       report_fatal_error("Can't allocate enough memory: " + Err);
185
186     PreallocSlab = MB;
187     UsePreallocation = true;
188     SlabSize = Size;
189   }
190
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
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::string Err;
226   sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, &Err);
227   if (!MB.base())
228     report_fatal_error("MemoryManager allocation failed: " + Err);
229   FunctionMemory.push_back(MB);
230   return (uint8_t*)MB.base();
231 }
232
233 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
234                                                    unsigned Alignment,
235                                                    unsigned SectionID,
236                                                    StringRef SectionName,
237                                                    bool IsReadOnly) {
238   if (PrintAllocationRequests)
239     outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
240            << Alignment << ", SectionName = " << SectionName << ")\n";
241
242   if (UsePreallocation)
243     return allocateFromSlab(Size, Alignment, false /* isCode */);
244
245   std::string Err;
246   sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, &Err);
247   if (!MB.base())
248     report_fatal_error("MemoryManager allocation failed: " + Err);
249   DataMemory.push_back(MB);
250   return (uint8_t*)MB.base();
251 }
252
253 static const char *ProgramName;
254
255 static void ErrorAndExit(const Twine &Msg) {
256   errs() << ProgramName << ": error: " << Msg << "\n";
257   exit(1);
258 }
259
260 static void loadDylibs() {
261   for (const std::string &Dylib : Dylibs) {
262     if (!sys::fs::is_regular_file(Dylib))
263       report_fatal_error("Dylib not found: '" + Dylib + "'.");
264     std::string ErrMsg;
265     if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
266       report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
267   }
268 }
269
270 /* *** */
271
272 static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
273   assert(LoadObjects || !UseDebugObj);
274
275   // Load any dylibs requested on the command line.
276   loadDylibs();
277
278   // If we don't have any input files, read from stdin.
279   if (!InputFileList.size())
280     InputFileList.push_back("-");
281   for (auto &File : InputFileList) {
282     // Instantiate a dynamic linker.
283     TrivialMemoryManager MemMgr;
284     RuntimeDyld Dyld(MemMgr, MemMgr);
285
286     // Load the input memory buffer.
287
288     ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
289         MemoryBuffer::getFileOrSTDIN(File);
290     if (std::error_code EC = InputBuffer.getError())
291       ErrorAndExit("unable to read input: '" + EC.message() + "'");
292
293     Expected<std::unique_ptr<ObjectFile>> MaybeObj(
294       ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
295
296     if (!MaybeObj) {
297       std::string Buf;
298       raw_string_ostream OS(Buf);
299       logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
300       OS.flush();
301       ErrorAndExit("unable to create object file: '" + Buf + "'");
302     }
303
304     ObjectFile &Obj = **MaybeObj;
305
306     OwningBinary<ObjectFile> DebugObj;
307     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
308     ObjectFile *SymbolObj = &Obj;
309     if (LoadObjects) {
310       // Load the object file
311       LoadedObjInfo =
312         Dyld.loadObject(Obj);
313
314       if (Dyld.hasError())
315         ErrorAndExit(Dyld.getErrorString());
316
317       // Resolve all the relocations we can.
318       Dyld.resolveRelocations();
319
320       if (UseDebugObj) {
321         DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
322         SymbolObj = DebugObj.getBinary();
323         LoadedObjInfo.reset();
324       }
325     }
326
327     std::unique_ptr<DIContext> Context(
328       new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
329
330     std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
331         object::computeSymbolSizes(*SymbolObj);
332
333     // Use symbol info to iterate functions in the object.
334     for (const auto &P : SymAddr) {
335       object::SymbolRef Sym = P.first;
336       Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
337       if (!TypeOrErr) {
338         // TODO: Actually report errors helpfully.
339         consumeError(TypeOrErr.takeError());
340         continue;
341       }
342       SymbolRef::Type Type = *TypeOrErr;
343       if (Type == object::SymbolRef::ST_Function) {
344         Expected<StringRef> Name = Sym.getName();
345         if (!Name) {
346           // TODO: Actually report errors helpfully.
347           consumeError(Name.takeError());
348           continue;
349         }
350         Expected<uint64_t> AddrOrErr = Sym.getAddress();
351         if (!AddrOrErr) {
352           // TODO: Actually report errors helpfully.
353           consumeError(AddrOrErr.takeError());
354           continue;
355         }
356         uint64_t Addr = *AddrOrErr;
357
358         uint64_t Size = P.second;
359         // If we're not using the debug object, compute the address of the
360         // symbol in memory (rather than that in the unrelocated object file)
361         // and use that to query the DWARFContext.
362         if (!UseDebugObj && LoadObjects) {
363           auto SecOrErr = Sym.getSection();
364           if (!SecOrErr) {
365             // TODO: Actually report errors helpfully.
366             consumeError(SecOrErr.takeError());
367             continue;
368           }
369           object::section_iterator Sec = *SecOrErr;
370           StringRef SecName;
371           Sec->getName(SecName);
372           uint64_t SectionLoadAddress =
373             LoadedObjInfo->getSectionLoadAddress(*Sec);
374           if (SectionLoadAddress != 0)
375             Addr += SectionLoadAddress - Sec->getAddress();
376         }
377
378         outs() << "Function: " << *Name << ", Size = " << Size
379                << ", Addr = " << Addr << "\n";
380
381         DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
382         for (auto &D : Lines) {
383           outs() << "  Line info @ " << D.first - Addr << ": "
384                  << D.second.FileName << ", line:" << D.second.Line << "\n";
385         }
386       }
387     }
388   }
389
390   return 0;
391 }
392
393 static void doPreallocation(TrivialMemoryManager &MemMgr) {
394   // Allocate a slab of memory upfront, if required. This is used if
395   // we want to test small code models.
396   if (static_cast<intptr_t>(PreallocMemory) < 0)
397     report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
398
399   // FIXME: Limit the amount of memory that can be preallocated?
400   if (PreallocMemory != 0)
401     MemMgr.preallocateSlab(PreallocMemory);
402 }
403
404 static int executeInput() {
405   // Load any dylibs requested on the command line.
406   loadDylibs();
407
408   // Instantiate a dynamic linker.
409   TrivialMemoryManager MemMgr;
410   doPreallocation(MemMgr);
411   RuntimeDyld Dyld(MemMgr, MemMgr);
412
413   // If we don't have any input files, read from stdin.
414   if (!InputFileList.size())
415     InputFileList.push_back("-");
416   for (auto &File : InputFileList) {
417     // Load the input memory buffer.
418     ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
419         MemoryBuffer::getFileOrSTDIN(File);
420     if (std::error_code EC = InputBuffer.getError())
421       ErrorAndExit("unable to read input: '" + EC.message() + "'");
422     Expected<std::unique_ptr<ObjectFile>> MaybeObj(
423       ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
424
425     if (!MaybeObj) {
426       std::string Buf;
427       raw_string_ostream OS(Buf);
428       logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
429       OS.flush();
430       ErrorAndExit("unable to create object file: '" + Buf + "'");
431     }
432
433     ObjectFile &Obj = **MaybeObj;
434
435     // Load the object file
436     Dyld.loadObject(Obj);
437     if (Dyld.hasError()) {
438       ErrorAndExit(Dyld.getErrorString());
439     }
440   }
441
442   // Resove all the relocations we can.
443   // FIXME: Error out if there are unresolved relocations.
444   Dyld.resolveRelocations();
445
446   // Get the address of the entry point (_main by default).
447   void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
448   if (!MainAddress)
449     ErrorAndExit("no definition for '" + EntryPoint + "'");
450
451   // Invalidate the instruction cache for each loaded function.
452   for (auto &FM : MemMgr.FunctionMemory) {
453
454     // Make sure the memory is executable.
455     // setExecutable will call InvalidateInstructionCache.
456     std::string ErrorStr;
457     if (!sys::Memory::setExecutable(FM, &ErrorStr))
458       ErrorAndExit("unable to mark function executable: '" + ErrorStr + "'");
459   }
460
461   // Dispatch to _main().
462   errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
463
464   int (*Main)(int, const char**) =
465     (int(*)(int,const char**)) uintptr_t(MainAddress);
466   const char **Argv = new const char*[2];
467   // Use the name of the first input object module as argv[0] for the target.
468   Argv[0] = InputFileList[0].c_str();
469   Argv[1] = nullptr;
470   return Main(1, Argv);
471 }
472
473 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
474   for (const auto& CheckerFileName : CheckFiles) {
475     ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
476         MemoryBuffer::getFileOrSTDIN(CheckerFileName);
477     if (std::error_code EC = CheckerFileBuf.getError())
478       ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
479                    EC.message());
480
481     if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
482                                        CheckerFileBuf.get().get()))
483       ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
484   }
485   return 0;
486 }
487
488 void applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
489
490   for (StringRef Mapping : SpecificSectionMappings) {
491
492     size_t EqualsIdx = Mapping.find_first_of("=");
493     std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
494     size_t ComaIdx = Mapping.find_first_of(",");
495
496     if (ComaIdx == StringRef::npos)
497       report_fatal_error("Invalid section specification '" + Mapping +
498                          "'. Should be '<file name>,<section name>=<addr>'");
499
500     std::string FileName = SectionIDStr.substr(0, ComaIdx);
501     std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
502
503     uint64_t OldAddrInt;
504     std::string ErrorMsg;
505     std::tie(OldAddrInt, ErrorMsg) =
506       Checker.getSectionAddr(FileName, SectionName, true);
507
508     if (ErrorMsg != "")
509       report_fatal_error(ErrorMsg);
510
511     void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
512
513     std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
514     uint64_t NewAddr;
515
516     if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
517       report_fatal_error("Invalid section address in mapping '" + Mapping +
518                          "'.");
519
520     Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
521   }
522 }
523
524 // Scatter sections in all directions!
525 // Remaps section addresses for -verify mode. The following command line options
526 // can be used to customize the layout of the memory within the phony target's
527 // address space:
528 // -target-addr-start <s> -- Specify where the phony target address range starts.
529 // -target-addr-end   <e> -- Specify where the phony target address range ends.
530 // -target-section-sep <d> -- Specify how big a gap should be left between the
531 //                            end of one section and the start of the next.
532 //                            Defaults to zero. Set to something big
533 //                            (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
534 //
535 static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
536                                     TrivialMemoryManager &MemMgr,
537                                     RuntimeDyldChecker &Checker) {
538
539   // Set up a work list (section addr/size pairs).
540   typedef std::list<std::pair<void*, uint64_t>> WorklistT;
541   WorklistT Worklist;
542
543   for (const auto& CodeSection : MemMgr.FunctionMemory)
544     Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
545   for (const auto& DataSection : MemMgr.DataMemory)
546     Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
547
548   // Apply any section-specific mappings that were requested on the command
549   // line.
550   applySpecificSectionMappings(Checker);
551
552   // Keep an "already allocated" mapping of section target addresses to sizes.
553   // Sections whose address mappings aren't specified on the command line will
554   // allocated around the explicitly mapped sections while maintaining the
555   // minimum separation.
556   std::map<uint64_t, uint64_t> AlreadyAllocated;
557
558   // Move the previously applied mappings (whether explicitly specified on the
559   // command line, or implicitly set by RuntimeDyld) into the already-allocated
560   // map.
561   for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
562        I != E;) {
563     WorklistT::iterator Tmp = I;
564     ++I;
565     auto LoadAddr = Checker.getSectionLoadAddress(Tmp->first);
566
567     if (LoadAddr &&
568         *LoadAddr != static_cast<uint64_t>(
569                        reinterpret_cast<uintptr_t>(Tmp->first))) {
570       AlreadyAllocated[*LoadAddr] = Tmp->second;
571       Worklist.erase(Tmp);
572     }
573   }
574
575   // If the -target-addr-end option wasn't explicitly passed, then set it to a
576   // sensible default based on the target triple.
577   if (TargetAddrEnd.getNumOccurrences() == 0) {
578     if (TargetTriple.isArch16Bit())
579       TargetAddrEnd = (1ULL << 16) - 1;
580     else if (TargetTriple.isArch32Bit())
581       TargetAddrEnd = (1ULL << 32) - 1;
582     // TargetAddrEnd already has a sensible default for 64-bit systems, so
583     // there's nothing to do in the 64-bit case.
584   }
585
586   // Process any elements remaining in the worklist.
587   while (!Worklist.empty()) {
588     std::pair<void*, uint64_t> CurEntry = Worklist.front();
589     Worklist.pop_front();
590
591     uint64_t NextSectionAddr = TargetAddrStart;
592
593     for (const auto &Alloc : AlreadyAllocated)
594       if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
595         break;
596       else
597         NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
598
599     AlreadyAllocated[NextSectionAddr] = CurEntry.second;
600     Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
601   }
602
603   // Add dummy symbols to the memory manager.
604   for (const auto &Mapping : DummySymbolMappings) {
605     size_t EqualsIdx = Mapping.find_first_of('=');
606
607     if (EqualsIdx == StringRef::npos)
608       report_fatal_error("Invalid dummy symbol specification '" + Mapping +
609                          "'. Should be '<symbol name>=<addr>'");
610
611     std::string Symbol = Mapping.substr(0, EqualsIdx);
612     std::string AddrStr = Mapping.substr(EqualsIdx + 1);
613
614     uint64_t Addr;
615     if (StringRef(AddrStr).getAsInteger(0, Addr))
616       report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
617
618     MemMgr.addDummySymbol(Symbol, Addr);
619   }
620 }
621
622 // Load and link the objects specified on the command line, but do not execute
623 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
624 // verify the correctness of the linked memory.
625 static int linkAndVerify() {
626
627   // Check for missing triple.
628   if (TripleName == "")
629     ErrorAndExit("-triple required when running in -verify mode.");
630
631   // Look up the target and build the disassembler.
632   Triple TheTriple(Triple::normalize(TripleName));
633   std::string ErrorStr;
634   const Target *TheTarget =
635     TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
636   if (!TheTarget)
637     ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
638
639   TripleName = TheTriple.getTriple();
640
641   std::unique_ptr<MCSubtargetInfo> STI(
642     TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
643   if (!STI)
644     ErrorAndExit("Unable to create subtarget info!");
645
646   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
647   if (!MRI)
648     ErrorAndExit("Unable to create target register info!");
649
650   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
651   if (!MAI)
652     ErrorAndExit("Unable to create target asm info!");
653
654   MCContext Ctx(MAI.get(), MRI.get(), nullptr);
655
656   std::unique_ptr<MCDisassembler> Disassembler(
657     TheTarget->createMCDisassembler(*STI, Ctx));
658   if (!Disassembler)
659     ErrorAndExit("Unable to create disassembler!");
660
661   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
662
663   std::unique_ptr<MCInstPrinter> InstPrinter(
664       TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
665
666   // Load any dylibs requested on the command line.
667   loadDylibs();
668
669   // Instantiate a dynamic linker.
670   TrivialMemoryManager MemMgr;
671   doPreallocation(MemMgr);
672   RuntimeDyld Dyld(MemMgr, MemMgr);
673   Dyld.setProcessAllSections(true);
674   RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
675                              llvm::dbgs());
676
677   // If we don't have any input files, read from stdin.
678   if (!InputFileList.size())
679     InputFileList.push_back("-");
680   for (auto &Filename : InputFileList) {
681     // Load the input memory buffer.
682     ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
683         MemoryBuffer::getFileOrSTDIN(Filename);
684
685     if (std::error_code EC = InputBuffer.getError())
686       ErrorAndExit("unable to read input: '" + EC.message() + "'");
687
688     Expected<std::unique_ptr<ObjectFile>> MaybeObj(
689       ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
690
691     if (!MaybeObj) {
692       std::string Buf;
693       raw_string_ostream OS(Buf);
694       logAllUnhandledErrors(MaybeObj.takeError(), OS, "");
695       OS.flush();
696       ErrorAndExit("unable to create object file: '" + Buf + "'");
697     }
698
699     ObjectFile &Obj = **MaybeObj;
700
701     // Load the object file
702     Dyld.loadObject(Obj);
703     if (Dyld.hasError()) {
704       ErrorAndExit(Dyld.getErrorString());
705     }
706   }
707
708   // Re-map the section addresses into the phony target address space and add
709   // dummy symbols.
710   remapSectionsAndSymbols(TheTriple, MemMgr, Checker);
711
712   // Resolve all the relocations we can.
713   Dyld.resolveRelocations();
714
715   // Register EH frames.
716   Dyld.registerEHFrames();
717
718   int ErrorCode = checkAllExpressions(Checker);
719   if (Dyld.hasError())
720     ErrorAndExit("RTDyld reported an error applying relocations:\n  " +
721                  Dyld.getErrorString());
722
723   return ErrorCode;
724 }
725
726 int main(int argc, char **argv) {
727   sys::PrintStackTraceOnErrorSignal(argv[0]);
728   PrettyStackTraceProgram X(argc, argv);
729
730   ProgramName = argv[0];
731   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
732
733   llvm::InitializeAllTargetInfos();
734   llvm::InitializeAllTargetMCs();
735   llvm::InitializeAllDisassemblers();
736
737   cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
738
739   switch (Action) {
740   case AC_Execute:
741     return executeInput();
742   case AC_PrintDebugLineInfo:
743     return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
744   case AC_PrintLineInfo:
745     return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
746   case AC_PrintObjectLineInfo:
747     return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
748   case AC_Verify:
749     return linkAndVerify();
750   }
751 }