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