Remove 'using std::error_code' from tools.
[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/ExecutionEngine/ObjectBuffer.h"
17 #include "llvm/ExecutionEngine/ObjectImage.h"
18 #include "llvm/ExecutionEngine/RuntimeDyld.h"
19 #include "llvm/Object/MachO.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/DynamicLibrary.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Memory.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <system_error>
29 using namespace llvm;
30 using namespace llvm::object;
31
32 static cl::list<std::string>
33 InputFileList(cl::Positional, cl::ZeroOrMore,
34               cl::desc("<input file>"));
35
36 enum ActionType {
37   AC_Execute,
38   AC_PrintLineInfo
39 };
40
41 static cl::opt<ActionType>
42 Action(cl::desc("Action to perform:"),
43        cl::init(AC_Execute),
44        cl::values(clEnumValN(AC_Execute, "execute",
45                              "Load, link, and execute the inputs."),
46                   clEnumValN(AC_PrintLineInfo, "printline",
47                              "Load, link, and print line information for each function."),
48                   clEnumValEnd));
49
50 static cl::opt<std::string>
51 EntryPoint("entry",
52            cl::desc("Function to call as entry point."),
53            cl::init("_main"));
54
55 static cl::list<std::string>
56 Dylibs("dylib",
57        cl::desc("Add library."),
58        cl::ZeroOrMore);
59
60 /* *** */
61
62 // A trivial memory manager that doesn't do anything fancy, just uses the
63 // support library allocation routines directly.
64 class TrivialMemoryManager : public RTDyldMemoryManager {
65 public:
66   SmallVector<sys::MemoryBlock, 16> FunctionMemory;
67   SmallVector<sys::MemoryBlock, 16> DataMemory;
68
69   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
70                                unsigned SectionID,
71                                StringRef SectionName) override;
72   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
73                                unsigned SectionID, StringRef SectionName,
74                                bool IsReadOnly) override;
75
76   void *getPointerToNamedFunction(const std::string &Name,
77                                   bool AbortOnFailure = true) override {
78     return nullptr;
79   }
80
81   bool finalizeMemory(std::string *ErrMsg) override { return false; }
82
83   // Invalidate instruction cache for sections with execute permissions.
84   // Some platforms with separate data cache and instruction cache require
85   // explicit cache flush, otherwise JIT code manipulations (like resolved
86   // relocations) will get to the data cache but not to the instruction cache.
87   virtual void invalidateInstructionCache();
88 };
89
90 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
91                                                    unsigned Alignment,
92                                                    unsigned SectionID,
93                                                    StringRef SectionName) {
94   sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
95   FunctionMemory.push_back(MB);
96   return (uint8_t*)MB.base();
97 }
98
99 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
100                                                    unsigned Alignment,
101                                                    unsigned SectionID,
102                                                    StringRef SectionName,
103                                                    bool IsReadOnly) {
104   sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
105   DataMemory.push_back(MB);
106   return (uint8_t*)MB.base();
107 }
108
109 void TrivialMemoryManager::invalidateInstructionCache() {
110   for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
111     sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
112                                             FunctionMemory[i].size());
113
114   for (int i = 0, e = DataMemory.size(); i != e; ++i)
115     sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
116                                             DataMemory[i].size());
117 }
118
119 static const char *ProgramName;
120
121 static void Message(const char *Type, const Twine &Msg) {
122   errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
123 }
124
125 static int Error(const Twine &Msg) {
126   Message("error", Msg);
127   return 1;
128 }
129
130 static void loadDylibs() {
131   for (const std::string &Dylib : Dylibs) {
132     if (sys::fs::is_regular_file(Dylib)) {
133       std::string ErrMsg;
134       if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
135         llvm::errs() << "Error loading '" << Dylib << "': "
136                      << ErrMsg << "\n";
137     } else
138       llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
139   }
140 }
141
142
143 /* *** */
144
145 static int printLineInfoForInput() {
146   // Load any dylibs requested on the command line.
147   loadDylibs();
148
149   // If we don't have any input files, read from stdin.
150   if (!InputFileList.size())
151     InputFileList.push_back("-");
152   for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
153     // Instantiate a dynamic linker.
154     TrivialMemoryManager MemMgr;
155     RuntimeDyld Dyld(&MemMgr);
156
157     // Load the input memory buffer.
158     std::unique_ptr<MemoryBuffer> InputBuffer;
159     std::unique_ptr<ObjectImage> LoadedObject;
160     if (std::error_code ec =
161             MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
162       return Error("unable to read input: '" + ec.message() + "'");
163
164     // Load the object file
165     LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
166     if (!LoadedObject) {
167       return Error(Dyld.getErrorString());
168     }
169
170     // Resolve all the relocations we can.
171     Dyld.resolveRelocations();
172
173     std::unique_ptr<DIContext> Context(
174         DIContext::getDWARFContext(LoadedObject->getObjectFile()));
175
176     // Use symbol info to iterate functions in the object.
177     for (object::symbol_iterator I = LoadedObject->begin_symbols(),
178                                  E = LoadedObject->end_symbols();
179          I != E; ++I) {
180       object::SymbolRef::Type SymType;
181       if (I->getType(SymType)) continue;
182       if (SymType == object::SymbolRef::ST_Function) {
183         StringRef  Name;
184         uint64_t   Addr;
185         uint64_t   Size;
186         if (I->getName(Name)) continue;
187         if (I->getAddress(Addr)) continue;
188         if (I->getSize(Size)) continue;
189
190         outs() << "Function: " << Name << ", Size = " << Size << "\n";
191
192         DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
193         DILineInfoTable::iterator  Begin = Lines.begin();
194         DILineInfoTable::iterator  End = Lines.end();
195         for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
196           outs() << "  Line info @ " << It->first - Addr << ": "
197                  << It->second.FileName << ", line:" << It->second.Line << "\n";
198         }
199       }
200     }
201   }
202
203   return 0;
204 }
205
206 static int executeInput() {
207   // Load any dylibs requested on the command line.
208   loadDylibs();
209
210   // Instantiate a dynamic linker.
211   TrivialMemoryManager MemMgr;
212   RuntimeDyld Dyld(&MemMgr);
213
214   // If we don't have any input files, read from stdin.
215   if (!InputFileList.size())
216     InputFileList.push_back("-");
217   for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
218     // Load the input memory buffer.
219     std::unique_ptr<MemoryBuffer> InputBuffer;
220     std::unique_ptr<ObjectImage> LoadedObject;
221     if (std::error_code ec =
222             MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
223       return Error("unable to read input: '" + ec.message() + "'");
224
225     // Load the object file
226     LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
227     if (!LoadedObject) {
228       return Error(Dyld.getErrorString());
229     }
230   }
231
232   // Resolve all the relocations we can.
233   Dyld.resolveRelocations();
234   // Clear instruction cache before code will be executed.
235   MemMgr.invalidateInstructionCache();
236
237   // FIXME: Error out if there are unresolved relocations.
238
239   // Get the address of the entry point (_main by default).
240   void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
241   if (!MainAddress)
242     return Error("no definition for '" + EntryPoint + "'");
243
244   // Invalidate the instruction cache for each loaded function.
245   for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
246     sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
247     // Make sure the memory is executable.
248     std::string ErrorStr;
249     sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
250     if (!sys::Memory::setExecutable(Data, &ErrorStr))
251       return Error("unable to mark function executable: '" + ErrorStr + "'");
252   }
253
254   // Dispatch to _main().
255   errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
256
257   int (*Main)(int, const char**) =
258     (int(*)(int,const char**)) uintptr_t(MainAddress);
259   const char **Argv = new const char*[2];
260   // Use the name of the first input object module as argv[0] for the target.
261   Argv[0] = InputFileList[0].c_str();
262   Argv[1] = nullptr;
263   return Main(1, Argv);
264 }
265
266 int main(int argc, char **argv) {
267   sys::PrintStackTraceOnErrorSignal();
268   PrettyStackTraceProgram X(argc, argv);
269
270   ProgramName = argv[0];
271   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
272
273   cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
274
275   switch (Action) {
276   case AC_Execute:
277     return executeInput();
278   case AC_PrintLineInfo:
279     return printLineInfoForInput();
280   }
281 }