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