blob: f857b2ef9735fd2b53ce5bdfc2e4e2a76599e637 [file] [log] [blame]
Jim Grosbach0072cdb2011-03-18 17:11:39 +00001//===-- 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
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000014#include "llvm/ADT/StringMap.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000015#include "llvm/DebugInfo/DIContext.h"
16#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Lang Hames633fe142015-03-30 03:37:06 +000017#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ExecutionEngine/RuntimeDyld.h"
Lang Hamese1c11382014-06-27 20:20:57 +000019#include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCDisassembler.h"
Lang Hamese1c11382014-06-27 20:20:57 +000023#include "llvm/MC/MCInstPrinter.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000024#include "llvm/MC/MCInstrInfo.h"
Lang Hamese1c11382014-06-27 20:20:57 +000025#include "llvm/MC/MCRegisterInfo.h"
Pete Cooper3de83e42015-05-15 21:58:42 +000026#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000027#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000028#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000029#include "llvm/Support/DynamicLibrary.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000030#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/Memory.h"
32#include "llvm/Support/MemoryBuffer.h"
Alp Toker9f679322013-11-05 09:33:43 +000033#include "llvm/Support/PrettyStackTrace.h"
Lang Hamese1c11382014-06-27 20:20:57 +000034#include "llvm/Support/Signals.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000037#include "llvm/Support/raw_ostream.h"
Lang Hames778ef5b2014-09-04 04:19:54 +000038#include <list>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000039#include <system_error>
Lang Hamese1c11382014-06-27 20:20:57 +000040
Jim Grosbach0072cdb2011-03-18 17:11:39 +000041using namespace llvm;
42using namespace llvm::object;
43
Jim Grosbach7cb41d72011-04-13 15:49:40 +000044static cl::list<std::string>
45InputFileList(cl::Positional, cl::ZeroOrMore,
46 cl::desc("<input file>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000047
48enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000049 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000050 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000051 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000052 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000053 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000054};
55
56static cl::opt<ActionType>
57Action(cl::desc("Action to perform:"),
58 cl::init(AC_Execute),
59 cl::values(clEnumValN(AC_Execute, "execute",
60 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000061 clEnumValN(AC_PrintLineInfo, "printline",
62 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000063 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
64 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000065 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
66 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000067 clEnumValN(AC_Verify, "verify",
68 "Load, link and verify the resulting memory image."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000069 clEnumValEnd));
70
Jim Grosbachd35159a2011-04-13 15:38:30 +000071static cl::opt<std::string>
72EntryPoint("entry",
73 cl::desc("Function to call as entry point."),
74 cl::init("_main"));
75
Lang Hamesd311c0e2014-05-13 22:37:41 +000076static cl::list<std::string>
77Dylibs("dylib",
78 cl::desc("Add library."),
79 cl::ZeroOrMore);
80
Lang Hamese1c11382014-06-27 20:20:57 +000081static cl::opt<std::string>
82TripleName("triple", cl::desc("Target triple for disassembler"));
83
84static cl::list<std::string>
85CheckFiles("check",
86 cl::desc("File containing RuntimeDyld verifier checks."),
87 cl::ZeroOrMore);
88
Lang Hames9cb73532014-07-29 23:43:13 +000089static cl::opt<uint64_t>
90TargetAddrStart("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
96static cl::opt<uint64_t>
97TargetAddrEnd("target-addr-end",
98 cl::desc("For -verify only: end of phony target address range."),
99 cl::init(~0ULL),
100 cl::Hidden);
101
102static cl::opt<uint64_t>
103TargetSectionSep("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
Lang Hames778ef5b2014-09-04 04:19:54 +0000109static cl::list<std::string>
110SpecificSectionMappings("map-section",
111 cl::desc("Map a section to a specific address."),
112 cl::ZeroOrMore);
113
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000114/* *** */
115
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000116// A trivial memory manager that doesn't do anything fancy, just uses the
117// support library allocation routines directly.
118class TrivialMemoryManager : public RTDyldMemoryManager {
119public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000120 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000121 SmallVector<sys::MemoryBlock, 16> DataMemory;
122
123 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000124 unsigned SectionID,
125 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000126 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000127 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000128 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000129
Craig Toppere56917c2014-03-08 08:27:28 +0000130 void *getPointerToNamedFunction(const std::string &Name,
131 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000132 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000133 }
134
Craig Toppere56917c2014-03-08 08:27:28 +0000135 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000136
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000137 // 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();
Tim Northover5af339a2015-06-03 18:26:52 +0000142
143 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
144 size_t Size) override {}
145 void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
146 size_t Size) override {}
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000147};
148
Jim Grosbacheff0a402012-01-16 22:26:39 +0000149uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
150 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000151 unsigned SectionID,
152 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000153 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000154 FunctionMemory.push_back(MB);
155 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000156}
157
158uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
159 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000160 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000161 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000162 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000163 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000164 DataMemory.push_back(MB);
165 return (uint8_t*)MB.base();
166}
167
168void TrivialMemoryManager::invalidateInstructionCache() {
169 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
170 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
171 FunctionMemory[i].size());
172
173 for (int i = 0, e = DataMemory.size(); i != e; ++i)
174 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
175 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000176}
177
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000178static const char *ProgramName;
179
180static void Message(const char *Type, const Twine &Msg) {
181 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
182}
183
184static int Error(const Twine &Msg) {
185 Message("error", Msg);
186 return 1;
187}
188
Lang Hamesd311c0e2014-05-13 22:37:41 +0000189static void loadDylibs() {
190 for (const std::string &Dylib : Dylibs) {
191 if (sys::fs::is_regular_file(Dylib)) {
192 std::string ErrMsg;
193 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
194 llvm::errs() << "Error loading '" << Dylib << "': "
195 << ErrMsg << "\n";
196 } else
197 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
198 }
199}
200
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000201/* *** */
202
Keno Fischerc780e8e2015-05-21 21:24:32 +0000203static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
204 assert(LoadObjects || !UseDebugObj);
205
Lang Hamesd311c0e2014-05-13 22:37:41 +0000206 // Load any dylibs requested on the command line.
207 loadDylibs();
208
Andrew Kaylord55d7012013-01-25 22:50:58 +0000209 // If we don't have any input files, read from stdin.
210 if (!InputFileList.size())
211 InputFileList.push_back("-");
212 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
213 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000214 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000215 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000216
217 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000218
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000219 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
220 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
221 if (std::error_code EC = InputBuffer.getError())
222 return Error("unable to read input: '" + EC.message() + "'");
223
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000224 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
225 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
226
227 if (std::error_code EC = MaybeObj.getError())
228 return Error("unable to create object file: '" + EC.message() + "'");
229
230 ObjectFile &Obj = **MaybeObj;
231
Keno Fischerc780e8e2015-05-21 21:24:32 +0000232 OwningBinary<ObjectFile> DebugObj;
233 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
234 ObjectFile *SymbolObj = &Obj;
235 if (LoadObjects) {
236 // Load the object file
237 LoadedObjInfo =
238 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000239
Keno Fischerc780e8e2015-05-21 21:24:32 +0000240 if (Dyld.hasError())
241 return Error(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000242
Keno Fischerc780e8e2015-05-21 21:24:32 +0000243 // Resolve all the relocations we can.
244 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000245
Keno Fischerc780e8e2015-05-21 21:24:32 +0000246 if (UseDebugObj) {
247 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
248 SymbolObj = DebugObj.getBinary();
249 }
250 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000251
Ahmed Charles56440fd2014-03-06 05:51:42 +0000252 std::unique_ptr<DIContext> Context(
Keno Fischerc780e8e2015-05-21 21:24:32 +0000253 new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000254
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000255 // FIXME: This is generally useful. Figure out a place in lib/Object to
256 // put utility functions.
257 std::map<object::SectionRef, std::vector<uint64_t>> FuncAddresses;
258 if (!isa<ELFObjectFileBase>(SymbolObj)) {
259 for (object::SymbolRef Sym : SymbolObj->symbols()) {
260 object::SymbolRef::Type SymType;
261 if (Sym.getType(SymType))
262 continue;
263 if (SymType != object::SymbolRef::ST_Function)
264 continue;
265 uint64_t Addr;
266 if (Sym.getAddress(Addr))
267 continue;
268 object::section_iterator Sec = SymbolObj->section_end();
269 if (Sym.getSection(Sec))
270 continue;
271 std::vector<uint64_t> &Addrs = FuncAddresses[*Sec];
272 if (Addrs.empty()) {
273 uint64_t SecAddr = Sec->getAddress();
274 uint64_t SecSize = Sec->getSize();
275 Addrs.push_back(SecAddr + SecSize);
276 }
277 Addrs.push_back(Addr);
278 }
279 for (auto &Pair : FuncAddresses) {
280 std::vector<uint64_t> &Addrs = Pair.second;
281 array_pod_sort(Addrs.begin(), Addrs.end());
282 }
283 }
284
Andrew Kaylord55d7012013-01-25 22:50:58 +0000285 // Use symbol info to iterate functions in the object.
Rafael Espindolada176272015-05-31 22:13:51 +0000286 for (object::SymbolRef Sym : SymbolObj->symbols()) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000287 object::SymbolRef::Type SymType;
Rafael Espindolada176272015-05-31 22:13:51 +0000288 if (Sym.getType(SymType))
289 continue;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000290 if (SymType == object::SymbolRef::ST_Function) {
291 StringRef Name;
292 uint64_t Addr;
Rafael Espindolada176272015-05-31 22:13:51 +0000293 if (Sym.getName(Name))
294 continue;
295 if (Sym.getAddress(Addr))
296 continue;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000297
298 uint64_t Size;
299 if (isa<ELFObjectFileBase>(SymbolObj)) {
Rafael Espindola5eb02e42015-06-01 00:27:26 +0000300 Size = Sym.getSize();
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000301 } else {
302 object::section_iterator Sec = SymbolObj->section_end();
303 if (Sym.getSection(Sec))
304 continue;
305 const std::vector<uint64_t> &Addrs = FuncAddresses[*Sec];
306 auto AddrI = std::find(Addrs.begin(), Addrs.end(), Addr);
307 assert(AddrI != Addrs.end() && (AddrI + 1) != Addrs.end());
308 assert(*AddrI == Addr);
309 Size = *(AddrI + 1) - Addr;
310 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000311
Keno Fischerc780e8e2015-05-21 21:24:32 +0000312 // If we're not using the debug object, compute the address of the
313 // symbol in memory (rather than that in the unrelocated object file)
314 // and use that to query the DWARFContext.
315 if (!UseDebugObj && LoadObjects) {
316 object::section_iterator Sec(SymbolObj->section_end());
Rafael Espindolada176272015-05-31 22:13:51 +0000317 Sym.getSection(Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000318 StringRef SecName;
319 Sec->getName(SecName);
320 uint64_t SectionLoadAddress =
321 LoadedObjInfo->getSectionLoadAddress(SecName);
322 if (SectionLoadAddress != 0)
323 Addr += SectionLoadAddress - Sec->getAddress();
324 }
325
326 outs() << "Function: " << Name << ", Size = " << Size << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000327
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000328 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
329 DILineInfoTable::iterator Begin = Lines.begin();
330 DILineInfoTable::iterator End = Lines.end();
331 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
332 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000333 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000334 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000335 }
336 }
337 }
338
339 return 0;
340}
341
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000342static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000343 // Load any dylibs requested on the command line.
344 loadDylibs();
345
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000346 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000347 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000348 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000349
Lang Hamesc3246ad2015-04-15 21:18:41 +0000350 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
351 // in RuntimeDyldELF.
352 // This fixme should be fixed ASAP. This is a very brittle workaround.
353 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
354
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000355 // If we don't have any input files, read from stdin.
356 if (!InputFileList.size())
357 InputFileList.push_back("-");
358 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
359 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000360 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
361 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
362 if (std::error_code EC = InputBuffer.getError())
363 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000364 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
365 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
366
367 if (std::error_code EC = MaybeObj.getError())
368 return Error("unable to create object file: '" + EC.message() + "'");
369
370 ObjectFile &Obj = **MaybeObj;
Lang Hamesc3246ad2015-04-15 21:18:41 +0000371 InputBuffers.push_back(std::move(*InputBuffer));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000372
Andrew Kayloradc70562012-10-02 21:18:39 +0000373 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000374 Dyld.loadObject(Obj);
375 if (Dyld.hasError()) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000376 return Error(Dyld.getErrorString());
377 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000378 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000379
Jim Grosbach733d3052011-04-12 21:20:41 +0000380 // Resolve all the relocations we can.
381 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000382 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000383 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000384
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000385 // FIXME: Error out if there are unresolved relocations.
386
Jim Grosbachd35159a2011-04-13 15:38:30 +0000387 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000388 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000389 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000390 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000391
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000392 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000393 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
394 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000395 // Make sure the memory is executable.
396 std::string ErrorStr;
397 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
398 if (!sys::Memory::setExecutable(Data, &ErrorStr))
399 return Error("unable to mark function executable: '" + ErrorStr + "'");
400 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000401
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000402 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000403 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000404
405 int (*Main)(int, const char**) =
406 (int(*)(int,const char**)) uintptr_t(MainAddress);
407 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000408 // Use the name of the first input object module as argv[0] for the target.
409 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000410 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000411 return Main(1, Argv);
412}
413
Lang Hamese1c11382014-06-27 20:20:57 +0000414static int checkAllExpressions(RuntimeDyldChecker &Checker) {
415 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000416 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
417 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
418 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hamese1c11382014-06-27 20:20:57 +0000419 return Error("unable to read input '" + CheckerFileName + "': " +
420 EC.message());
421
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000422 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
423 CheckerFileBuf.get().get()))
Lang Hamese1c11382014-06-27 20:20:57 +0000424 return Error("some checks in '" + CheckerFileName + "' failed");
425 }
426 return 0;
427}
428
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000429static std::map<void *, uint64_t>
Lang Hames778ef5b2014-09-04 04:19:54 +0000430applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
431
432 std::map<void*, uint64_t> SpecificMappings;
433
434 for (StringRef Mapping : SpecificSectionMappings) {
435
436 size_t EqualsIdx = Mapping.find_first_of("=");
437 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
438 size_t ComaIdx = Mapping.find_first_of(",");
439
440 if (ComaIdx == StringRef::npos) {
441 errs() << "Invalid section specification '" << Mapping
442 << "'. Should be '<file name>,<section name>=<addr>'\n";
443 exit(1);
444 }
445
446 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
447 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
448
449 uint64_t OldAddrInt;
450 std::string ErrorMsg;
451 std::tie(OldAddrInt, ErrorMsg) =
452 Checker.getSectionAddr(FileName, SectionName, true);
453
454 if (ErrorMsg != "") {
455 errs() << ErrorMsg;
456 exit(1);
457 }
458
459 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
460
461 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
462 uint64_t NewAddr;
463
464 if (NewAddrStr.getAsInteger(0, NewAddr)) {
465 errs() << "Invalid section address in mapping: " << Mapping << "\n";
466 exit(1);
467 }
468
469 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
470 SpecificMappings[OldAddr] = NewAddr;
471 }
472
473 return SpecificMappings;
474}
475
Lang Hames9cb73532014-07-29 23:43:13 +0000476// Scatter sections in all directions!
477// Remaps section addresses for -verify mode. The following command line options
478// can be used to customize the layout of the memory within the phony target's
479// address space:
480// -target-addr-start <s> -- Specify where the phony target addres range starts.
481// -target-addr-end <e> -- Specify where the phony target address range ends.
482// -target-section-sep <d> -- Specify how big a gap should be left between the
483// end of one section and the start of the next.
484// Defaults to zero. Set to something big
485// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
486//
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000487static void remapSections(const llvm::Triple &TargetTriple,
488 const TrivialMemoryManager &MemMgr,
489 RuntimeDyldChecker &Checker) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000490
491 // Set up a work list (section addr/size pairs).
492 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
493 WorklistT Worklist;
494
495 for (const auto& CodeSection : MemMgr.FunctionMemory)
496 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
497 for (const auto& DataSection : MemMgr.DataMemory)
498 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
499
500 // Apply any section-specific mappings that were requested on the command
501 // line.
502 typedef std::map<void*, uint64_t> AppliedMappingsT;
503 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
504
505 // Keep an "already allocated" mapping of section target addresses to sizes.
506 // Sections whose address mappings aren't specified on the command line will
507 // allocated around the explicitly mapped sections while maintaining the
508 // minimum separation.
509 std::map<uint64_t, uint64_t> AlreadyAllocated;
510
511 // Move the previously applied mappings into the already-allocated map.
512 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
513 I != E;) {
514 WorklistT::iterator Tmp = I;
515 ++I;
516 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
517
518 if (AI != AppliedMappings.end()) {
519 AlreadyAllocated[AI->second] = Tmp->second;
520 Worklist.erase(Tmp);
521 }
522 }
Lang Hames9cb73532014-07-29 23:43:13 +0000523
524 // If the -target-addr-end option wasn't explicitly passed, then set it to a
525 // sensible default based on the target triple.
526 if (TargetAddrEnd.getNumOccurrences() == 0) {
527 if (TargetTriple.isArch16Bit())
528 TargetAddrEnd = (1ULL << 16) - 1;
529 else if (TargetTriple.isArch32Bit())
530 TargetAddrEnd = (1ULL << 32) - 1;
531 // TargetAddrEnd already has a sensible default for 64-bit systems, so
532 // there's nothing to do in the 64-bit case.
533 }
534
Lang Hames778ef5b2014-09-04 04:19:54 +0000535 // Process any elements remaining in the worklist.
536 while (!Worklist.empty()) {
537 std::pair<void*, uint64_t> CurEntry = Worklist.front();
538 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000539
Lang Hames778ef5b2014-09-04 04:19:54 +0000540 uint64_t NextSectionAddr = TargetAddrStart;
541
542 for (const auto &Alloc : AlreadyAllocated)
543 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
544 break;
545 else
546 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
547
548 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
549 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000550 }
551
Lang Hames9cb73532014-07-29 23:43:13 +0000552}
553
554// Load and link the objects specified on the command line, but do not execute
555// anything. Instead, attach a RuntimeDyldChecker instance and call it to
556// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000557static int linkAndVerify() {
558
559 // Check for missing triple.
560 if (TripleName == "") {
561 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
562 return 1;
563 }
564
565 // Look up the target and build the disassembler.
566 Triple TheTriple(Triple::normalize(TripleName));
567 std::string ErrorStr;
568 const Target *TheTarget =
569 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
570 if (!TheTarget) {
571 llvm::errs() << "Error accessing target '" << TripleName << "': "
572 << ErrorStr << "\n";
573 return 1;
574 }
575 TripleName = TheTriple.getTriple();
576
577 std::unique_ptr<MCSubtargetInfo> STI(
578 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
579 assert(STI && "Unable to create subtarget info!");
580
581 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
582 assert(MRI && "Unable to create target register info!");
583
584 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
585 assert(MAI && "Unable to create target asm info!");
586
587 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
588
589 std::unique_ptr<MCDisassembler> Disassembler(
590 TheTarget->createMCDisassembler(*STI, Ctx));
591 assert(Disassembler && "Unable to create disassembler!");
592
593 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
594
595 std::unique_ptr<MCInstPrinter> InstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000596 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000597
598 // Load any dylibs requested on the command line.
599 loadDylibs();
600
601 // Instantiate a dynamic linker.
602 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000603 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000604 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000605 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
606 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000607
Lang Hamesc3246ad2015-04-15 21:18:41 +0000608 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
609 // in RuntimeDyldELF.
610 // This fixme should be fixed ASAP. This is a very brittle workaround.
611 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
612
Lang Hamese1c11382014-06-27 20:20:57 +0000613 // If we don't have any input files, read from stdin.
614 if (!InputFileList.size())
615 InputFileList.push_back("-");
616 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
617 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000618 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
619 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000620
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000621 if (std::error_code EC = InputBuffer.getError())
622 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000623
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000624 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
625 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
626
627 if (std::error_code EC = MaybeObj.getError())
628 return Error("unable to create object file: '" + EC.message() + "'");
629
630 ObjectFile &Obj = **MaybeObj;
Lang Hamesc3246ad2015-04-15 21:18:41 +0000631 InputBuffers.push_back(std::move(*InputBuffer));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000632
Lang Hamese1c11382014-06-27 20:20:57 +0000633 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000634 Dyld.loadObject(Obj);
635 if (Dyld.hasError()) {
Lang Hamese1c11382014-06-27 20:20:57 +0000636 return Error(Dyld.getErrorString());
637 }
638 }
639
Lang Hames375385f2014-07-30 03:12:41 +0000640 // Re-map the section addresses into the phony target address space.
Lang Hames778ef5b2014-09-04 04:19:54 +0000641 remapSections(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000642
Lang Hamese1c11382014-06-27 20:20:57 +0000643 // Resolve all the relocations we can.
644 Dyld.resolveRelocations();
645
Lang Hames925e51b2014-09-03 05:42:52 +0000646 // Register EH frames.
647 Dyld.registerEHFrames();
648
Lang Hamesae172682014-08-05 20:51:46 +0000649 int ErrorCode = checkAllExpressions(Checker);
650 if (Dyld.hasError()) {
651 errs() << "RTDyld reported an error applying relocations:\n "
652 << Dyld.getErrorString() << "\n";
653 ErrorCode = 1;
654 }
655
656 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000657}
658
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000659int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000660 sys::PrintStackTraceOnErrorSignal();
661 PrettyStackTraceProgram X(argc, argv);
662
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000663 ProgramName = argv[0];
664 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
665
Lang Hamese1c11382014-06-27 20:20:57 +0000666 llvm::InitializeAllTargetInfos();
667 llvm::InitializeAllTargetMCs();
668 llvm::InitializeAllDisassemblers();
669
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000670 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
671
672 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000673 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000674 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000675 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000676 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000677 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000678 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
679 case AC_PrintObjectLineInfo:
680 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000681 case AC_Verify:
682 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000683 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000684}