defe98ae0f4322fbe37c047e717e2515094f5f7a
[oota-llvm.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.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/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 #include <system_error>
40
41 using namespace llvm;
42 using namespace llvm::object;
43
44 static cl::list<std::string>
45 InputFileList(cl::Positional, cl::ZeroOrMore,
46               cl::desc("<input file>"));
47
48 enum ActionType {
49   AC_Execute,
50   AC_PrintObjectLineInfo,
51   AC_PrintLineInfo,
52   AC_PrintDebugLineInfo,
53   AC_Verify
54 };
55
56 static cl::opt<ActionType>
57 Action(cl::desc("Action to perform:"),
58        cl::init(AC_Execute),
59        cl::values(clEnumValN(AC_Execute, "execute",
60                              "Load, link, and execute the inputs."),
61                   clEnumValN(AC_PrintLineInfo, "printline",
62                              "Load, link, and print line information for each function."),
63                   clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
64                              "Load, link, and print line information for each function using the debug object"),
65                   clEnumValN(AC_PrintObjectLineInfo, "printobjline",
66                              "Like -printlineinfo but does not load the object first"),
67                   clEnumValN(AC_Verify, "verify",
68                              "Load, link and verify the resulting memory image."),
69                   clEnumValEnd));
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::list<std::string>
85 CheckFiles("check",
86            cl::desc("File containing RuntimeDyld verifier checks."),
87            cl::ZeroOrMore);
88
89 static cl::opt<uint64_t>
90 TargetAddrStart("target-addr-start",
91                 cl::desc("For -verify only: start of phony target address "
92                          "range."),
93                 cl::init(4096), // Start at "page 1" - no allocating at "null".
94                 cl::Hidden);
95
96 static cl::opt<uint64_t>
97 TargetAddrEnd("target-addr-end",
98               cl::desc("For -verify only: end of phony target address range."),
99               cl::init(~0ULL),
100               cl::Hidden);
101
102 static cl::opt<uint64_t>
103 TargetSectionSep("target-section-sep",
104                  cl::desc("For -verify only: Separation between sections in "
105                           "phony target address space."),
106                  cl::init(0),
107                  cl::Hidden);
108
109 static cl::list<std::string>
110 SpecificSectionMappings("map-section",
111                         cl::desc("Map a section to a specific address."),
112                         cl::ZeroOrMore);
113
114 /* *** */
115
116 // A trivial memory manager that doesn't do anything fancy, just uses the
117 // support library allocation routines directly.
118 class TrivialMemoryManager : public RTDyldMemoryManager {
119 public:
120   SmallVector<sys::MemoryBlock, 16> FunctionMemory;
121   SmallVector<sys::MemoryBlock, 16> DataMemory;
122
123   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
124                                unsigned SectionID,
125                                StringRef SectionName) override;
126   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
127                                unsigned SectionID, StringRef SectionName,
128                                bool IsReadOnly) override;
129
130   void *getPointerToNamedFunction(const std::string &Name,
131                                   bool AbortOnFailure = true) override {
132     return nullptr;
133   }
134
135   bool finalizeMemory(std::string *ErrMsg) override { return false; }
136
137   // Invalidate instruction cache for sections with execute permissions.
138   // Some platforms with separate data cache and instruction cache require
139   // explicit cache flush, otherwise JIT code manipulations (like resolved
140   // relocations) will get to the data cache but not to the instruction cache.
141   virtual void invalidateInstructionCache();
142 };
143
144 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
145                                                    unsigned Alignment,
146                                                    unsigned SectionID,
147                                                    StringRef SectionName) {
148   sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
149   FunctionMemory.push_back(MB);
150   return (uint8_t*)MB.base();
151 }
152
153 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
154                                                    unsigned Alignment,
155                                                    unsigned SectionID,
156                                                    StringRef SectionName,
157                                                    bool IsReadOnly) {
158   sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
159   DataMemory.push_back(MB);
160   return (uint8_t*)MB.base();
161 }
162
163 void TrivialMemoryManager::invalidateInstructionCache() {
164   for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
165     sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
166                                             FunctionMemory[i].size());
167
168   for (int i = 0, e = DataMemory.size(); i != e; ++i)
169     sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
170                                             DataMemory[i].size());
171 }
172
173 static const char *ProgramName;
174
175 static void Message(const char *Type, const Twine &Msg) {
176   errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
177 }
178
179 static int Error(const Twine &Msg) {
180   Message("error", Msg);
181   return 1;
182 }
183
184 static void loadDylibs() {
185   for (const std::string &Dylib : Dylibs) {
186     if (sys::fs::is_regular_file(Dylib)) {
187       std::string ErrMsg;
188       if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
189         llvm::errs() << "Error loading '" << Dylib << "': "
190                      << ErrMsg << "\n";
191     } else
192       llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
193   }
194 }
195
196 /* *** */
197
198 static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
199   assert(LoadObjects || !UseDebugObj);
200
201   // Load any dylibs requested on the command line.
202   loadDylibs();
203
204   // If we don't have any input files, read from stdin.
205   if (!InputFileList.size())
206     InputFileList.push_back("-");
207   for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
208     // Instantiate a dynamic linker.
209     TrivialMemoryManager MemMgr;
210     RuntimeDyld Dyld(MemMgr, MemMgr);
211
212     // Load the input memory buffer.
213
214     ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
215         MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
216     if (std::error_code EC = InputBuffer.getError())
217       return Error("unable to read input: '" + EC.message() + "'");
218
219     ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
220       ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
221
222     if (std::error_code EC = MaybeObj.getError())
223       return Error("unable to create object file: '" + EC.message() + "'");
224
225     ObjectFile &Obj = **MaybeObj;
226
227     OwningBinary<ObjectFile> DebugObj;
228     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
229     ObjectFile *SymbolObj = &Obj;
230     if (LoadObjects) {
231       // Load the object file
232       LoadedObjInfo =
233         Dyld.loadObject(Obj);
234
235       if (Dyld.hasError())
236         return Error(Dyld.getErrorString());
237
238       // Resolve all the relocations we can.
239       Dyld.resolveRelocations();
240
241       if (UseDebugObj) {
242         DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
243         SymbolObj = DebugObj.getBinary();
244       }
245     }
246
247     std::unique_ptr<DIContext> Context(
248       new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
249
250     // Use symbol info to iterate functions in the object.
251     for (object::symbol_iterator I = SymbolObj->symbol_begin(),
252                                  E = SymbolObj->symbol_end();
253          I != E; ++I) {
254       object::SymbolRef::Type SymType;
255       if (I->getType(SymType)) continue;
256       if (SymType == object::SymbolRef::ST_Function) {
257         StringRef  Name;
258         uint64_t   Addr;
259         uint64_t   Size;
260         if (I->getName(Name)) continue;
261         if (I->getAddress(Addr)) continue;
262         if (I->getSize(Size)) continue;
263
264         // If we're not using the debug object, compute the address of the
265         // symbol in memory (rather than that in the unrelocated object file)
266         // and use that to query the DWARFContext.
267         if (!UseDebugObj && LoadObjects) {
268           object::section_iterator Sec(SymbolObj->section_end());
269           I->getSection(Sec);
270           StringRef SecName;
271           Sec->getName(SecName);
272           uint64_t SectionLoadAddress =
273             LoadedObjInfo->getSectionLoadAddress(SecName);
274           if (SectionLoadAddress != 0)
275             Addr += SectionLoadAddress - Sec->getAddress();
276         }
277
278         outs() << "Function: " << Name << ", Size = " << Size << ", Addr = " << Addr << "\n";
279
280         DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
281         DILineInfoTable::iterator  Begin = Lines.begin();
282         DILineInfoTable::iterator  End = Lines.end();
283         for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
284           outs() << "  Line info @ " << It->first - Addr << ": "
285                  << It->second.FileName << ", line:" << It->second.Line << "\n";
286         }
287       }
288     }
289   }
290
291   return 0;
292 }
293
294 static int executeInput() {
295   // Load any dylibs requested on the command line.
296   loadDylibs();
297
298   // Instantiate a dynamic linker.
299   TrivialMemoryManager MemMgr;
300   RuntimeDyld Dyld(MemMgr, MemMgr);
301
302   // FIXME: Preserve buffers until resolveRelocations time to work around a bug
303   //        in RuntimeDyldELF.
304   // This fixme should be fixed ASAP. This is a very brittle workaround.
305   std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
306
307   // If we don't have any input files, read from stdin.
308   if (!InputFileList.size())
309     InputFileList.push_back("-");
310   for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
311     // Load the input memory buffer.
312     ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
313         MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
314     if (std::error_code EC = InputBuffer.getError())
315       return Error("unable to read input: '" + EC.message() + "'");
316     ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
317       ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
318
319     if (std::error_code EC = MaybeObj.getError())
320       return Error("unable to create object file: '" + EC.message() + "'");
321
322     ObjectFile &Obj = **MaybeObj;
323     InputBuffers.push_back(std::move(*InputBuffer));
324
325     // Load the object file
326     Dyld.loadObject(Obj);
327     if (Dyld.hasError()) {
328       return Error(Dyld.getErrorString());
329     }
330   }
331
332   // Resolve all the relocations we can.
333   Dyld.resolveRelocations();
334   // Clear instruction cache before code will be executed.
335   MemMgr.invalidateInstructionCache();
336
337   // FIXME: Error out if there are unresolved relocations.
338
339   // Get the address of the entry point (_main by default).
340   void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
341   if (!MainAddress)
342     return Error("no definition for '" + EntryPoint + "'");
343
344   // Invalidate the instruction cache for each loaded function.
345   for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
346     sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
347     // Make sure the memory is executable.
348     std::string ErrorStr;
349     sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
350     if (!sys::Memory::setExecutable(Data, &ErrorStr))
351       return Error("unable to mark function executable: '" + ErrorStr + "'");
352   }
353
354   // Dispatch to _main().
355   errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
356
357   int (*Main)(int, const char**) =
358     (int(*)(int,const char**)) uintptr_t(MainAddress);
359   const char **Argv = new const char*[2];
360   // Use the name of the first input object module as argv[0] for the target.
361   Argv[0] = InputFileList[0].c_str();
362   Argv[1] = nullptr;
363   return Main(1, Argv);
364 }
365
366 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
367   for (const auto& CheckerFileName : CheckFiles) {
368     ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
369         MemoryBuffer::getFileOrSTDIN(CheckerFileName);
370     if (std::error_code EC = CheckerFileBuf.getError())
371       return Error("unable to read input '" + CheckerFileName + "': " +
372                    EC.message());
373
374     if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
375                                        CheckerFileBuf.get().get()))
376       return Error("some checks in '" + CheckerFileName + "' failed");
377   }
378   return 0;
379 }
380
381 static std::map<void *, uint64_t>
382 applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
383
384   std::map<void*, uint64_t> SpecificMappings;
385
386   for (StringRef Mapping : SpecificSectionMappings) {
387
388     size_t EqualsIdx = Mapping.find_first_of("=");
389     StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
390     size_t ComaIdx = Mapping.find_first_of(",");
391
392     if (ComaIdx == StringRef::npos) {
393       errs() << "Invalid section specification '" << Mapping
394              << "'. Should be '<file name>,<section name>=<addr>'\n";
395       exit(1);
396     }
397
398     StringRef FileName = SectionIDStr.substr(0, ComaIdx);
399     StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
400
401     uint64_t OldAddrInt;
402     std::string ErrorMsg;
403     std::tie(OldAddrInt, ErrorMsg) =
404       Checker.getSectionAddr(FileName, SectionName, true);
405
406     if (ErrorMsg != "") {
407       errs() << ErrorMsg;
408       exit(1);
409     }
410
411     void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
412
413     StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
414     uint64_t NewAddr;
415
416     if (NewAddrStr.getAsInteger(0, NewAddr)) {
417       errs() << "Invalid section address in mapping: " << Mapping << "\n";
418       exit(1);
419     }
420
421     Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
422     SpecificMappings[OldAddr] = NewAddr;
423   }
424
425   return SpecificMappings;
426 }
427
428 // Scatter sections in all directions!
429 // Remaps section addresses for -verify mode. The following command line options
430 // can be used to customize the layout of the memory within the phony target's
431 // address space:
432 // -target-addr-start <s> -- Specify where the phony target addres range starts.
433 // -target-addr-end   <e> -- Specify where the phony target address range ends.
434 // -target-section-sep <d> -- Specify how big a gap should be left between the
435 //                            end of one section and the start of the next.
436 //                            Defaults to zero. Set to something big
437 //                            (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
438 //
439 static void remapSections(const llvm::Triple &TargetTriple,
440                           const TrivialMemoryManager &MemMgr,
441                           RuntimeDyldChecker &Checker) {
442
443   // Set up a work list (section addr/size pairs).
444   typedef std::list<std::pair<void*, uint64_t>> WorklistT;
445   WorklistT Worklist;
446
447   for (const auto& CodeSection : MemMgr.FunctionMemory)
448     Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
449   for (const auto& DataSection : MemMgr.DataMemory)
450     Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
451
452   // Apply any section-specific mappings that were requested on the command
453   // line.
454   typedef std::map<void*, uint64_t> AppliedMappingsT;
455   AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
456
457   // Keep an "already allocated" mapping of section target addresses to sizes.
458   // Sections whose address mappings aren't specified on the command line will
459   // allocated around the explicitly mapped sections while maintaining the
460   // minimum separation.
461   std::map<uint64_t, uint64_t> AlreadyAllocated;
462
463   // Move the previously applied mappings into the already-allocated map.
464   for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
465        I != E;) {
466     WorklistT::iterator Tmp = I;
467     ++I;
468     AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
469
470     if (AI != AppliedMappings.end()) {
471       AlreadyAllocated[AI->second] = Tmp->second;
472       Worklist.erase(Tmp);
473     }
474   }
475
476   // If the -target-addr-end option wasn't explicitly passed, then set it to a
477   // sensible default based on the target triple.
478   if (TargetAddrEnd.getNumOccurrences() == 0) {
479     if (TargetTriple.isArch16Bit())
480       TargetAddrEnd = (1ULL << 16) - 1;
481     else if (TargetTriple.isArch32Bit())
482       TargetAddrEnd = (1ULL << 32) - 1;
483     // TargetAddrEnd already has a sensible default for 64-bit systems, so
484     // there's nothing to do in the 64-bit case.
485   }
486
487   // Process any elements remaining in the worklist.
488   while (!Worklist.empty()) {
489     std::pair<void*, uint64_t> CurEntry = Worklist.front();
490     Worklist.pop_front();
491
492     uint64_t NextSectionAddr = TargetAddrStart;
493
494     for (const auto &Alloc : AlreadyAllocated)
495       if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
496         break;
497       else
498         NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
499
500     AlreadyAllocated[NextSectionAddr] = CurEntry.second;
501     Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
502   }
503
504 }
505
506 // Load and link the objects specified on the command line, but do not execute
507 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
508 // verify the correctness of the linked memory.
509 static int linkAndVerify() {
510
511   // Check for missing triple.
512   if (TripleName == "") {
513     llvm::errs() << "Error: -triple required when running in -verify mode.\n";
514     return 1;
515   }
516
517   // Look up the target and build the disassembler.
518   Triple TheTriple(Triple::normalize(TripleName));
519   std::string ErrorStr;
520   const Target *TheTarget =
521     TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
522   if (!TheTarget) {
523     llvm::errs() << "Error accessing target '" << TripleName << "': "
524                  << ErrorStr << "\n";
525     return 1;
526   }
527   TripleName = TheTriple.getTriple();
528
529   std::unique_ptr<MCSubtargetInfo> STI(
530     TheTarget->createMCSubtargetInfo(TripleName, "", ""));
531   assert(STI && "Unable to create subtarget info!");
532
533   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
534   assert(MRI && "Unable to create target register info!");
535
536   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
537   assert(MAI && "Unable to create target asm info!");
538
539   MCContext Ctx(MAI.get(), MRI.get(), nullptr);
540
541   std::unique_ptr<MCDisassembler> Disassembler(
542     TheTarget->createMCDisassembler(*STI, Ctx));
543   assert(Disassembler && "Unable to create disassembler!");
544
545   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
546
547   std::unique_ptr<MCInstPrinter> InstPrinter(
548       TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
549
550   // Load any dylibs requested on the command line.
551   loadDylibs();
552
553   // Instantiate a dynamic linker.
554   TrivialMemoryManager MemMgr;
555   RuntimeDyld Dyld(MemMgr, MemMgr);
556   Dyld.setProcessAllSections(true);
557   RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
558                              llvm::dbgs());
559
560   // FIXME: Preserve buffers until resolveRelocations time to work around a bug
561   //        in RuntimeDyldELF.
562   // This fixme should be fixed ASAP. This is a very brittle workaround.
563   std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
564
565   // If we don't have any input files, read from stdin.
566   if (!InputFileList.size())
567     InputFileList.push_back("-");
568   for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
569     // Load the input memory buffer.
570     ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
571         MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
572
573     if (std::error_code EC = InputBuffer.getError())
574       return Error("unable to read input: '" + EC.message() + "'");
575
576     ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
577       ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
578
579     if (std::error_code EC = MaybeObj.getError())
580       return Error("unable to create object file: '" + EC.message() + "'");
581
582     ObjectFile &Obj = **MaybeObj;
583     InputBuffers.push_back(std::move(*InputBuffer));
584
585     // Load the object file
586     Dyld.loadObject(Obj);
587     if (Dyld.hasError()) {
588       return Error(Dyld.getErrorString());
589     }
590   }
591
592   // Re-map the section addresses into the phony target address space.
593   remapSections(TheTriple, MemMgr, Checker);
594
595   // Resolve all the relocations we can.
596   Dyld.resolveRelocations();
597
598   // Register EH frames.
599   Dyld.registerEHFrames();
600
601   int ErrorCode = checkAllExpressions(Checker);
602   if (Dyld.hasError()) {
603     errs() << "RTDyld reported an error applying relocations:\n  "
604            << Dyld.getErrorString() << "\n";
605     ErrorCode = 1;
606   }
607
608   return ErrorCode;
609 }
610
611 int main(int argc, char **argv) {
612   sys::PrintStackTraceOnErrorSignal();
613   PrettyStackTraceProgram X(argc, argv);
614
615   ProgramName = argv[0];
616   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
617
618   llvm::InitializeAllTargetInfos();
619   llvm::InitializeAllTargetMCs();
620   llvm::InitializeAllDisassemblers();
621
622   cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
623
624   switch (Action) {
625   case AC_Execute:
626     return executeInput();
627   case AC_PrintDebugLineInfo:
628     return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
629   case AC_PrintLineInfo:
630     return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
631   case AC_PrintObjectLineInfo:
632     return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
633   case AC_Verify:
634     return linkAndVerify();
635   }
636 }