blob: bef6a1a044e3ec9c3a326ab65593f1558bf9076f [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();
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000142};
143
Jim Grosbacheff0a402012-01-16 22:26:39 +0000144uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
145 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000146 unsigned SectionID,
147 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000148 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000149 FunctionMemory.push_back(MB);
150 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000151}
152
153uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
154 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000155 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000156 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000157 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000158 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000159 DataMemory.push_back(MB);
160 return (uint8_t*)MB.base();
161}
162
163void 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());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000171}
172
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000173static const char *ProgramName;
174
175static void Message(const char *Type, const Twine &Msg) {
176 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
177}
178
179static int Error(const Twine &Msg) {
180 Message("error", Msg);
181 return 1;
182}
183
Lang Hamesd311c0e2014-05-13 22:37:41 +0000184static 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
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000196/* *** */
197
Keno Fischerc780e8e2015-05-21 21:24:32 +0000198static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
199 assert(LoadObjects || !UseDebugObj);
200
Lang Hamesd311c0e2014-05-13 22:37:41 +0000201 // Load any dylibs requested on the command line.
202 loadDylibs();
203
Andrew Kaylord55d7012013-01-25 22:50:58 +0000204 // 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.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000209 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000210 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000211
212 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000213
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000214 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
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000219 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
Keno Fischerc780e8e2015-05-21 21:24:32 +0000227 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);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000234
Keno Fischerc780e8e2015-05-21 21:24:32 +0000235 if (Dyld.hasError())
236 return Error(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000237
Keno Fischerc780e8e2015-05-21 21:24:32 +0000238 // Resolve all the relocations we can.
239 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000240
Keno Fischerc780e8e2015-05-21 21:24:32 +0000241 if (UseDebugObj) {
242 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
243 SymbolObj = DebugObj.getBinary();
244 }
245 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000246
Ahmed Charles56440fd2014-03-06 05:51:42 +0000247 std::unique_ptr<DIContext> Context(
Keno Fischerc780e8e2015-05-21 21:24:32 +0000248 new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000249
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000250 // FIXME: This is generally useful. Figure out a place in lib/Object to
251 // put utility functions.
252 std::map<object::SectionRef, std::vector<uint64_t>> FuncAddresses;
253 if (!isa<ELFObjectFileBase>(SymbolObj)) {
254 for (object::SymbolRef Sym : SymbolObj->symbols()) {
255 object::SymbolRef::Type SymType;
256 if (Sym.getType(SymType))
257 continue;
258 if (SymType != object::SymbolRef::ST_Function)
259 continue;
260 uint64_t Addr;
261 if (Sym.getAddress(Addr))
262 continue;
263 object::section_iterator Sec = SymbolObj->section_end();
264 if (Sym.getSection(Sec))
265 continue;
266 std::vector<uint64_t> &Addrs = FuncAddresses[*Sec];
267 if (Addrs.empty()) {
268 uint64_t SecAddr = Sec->getAddress();
269 uint64_t SecSize = Sec->getSize();
270 Addrs.push_back(SecAddr + SecSize);
271 }
272 Addrs.push_back(Addr);
273 }
274 for (auto &Pair : FuncAddresses) {
275 std::vector<uint64_t> &Addrs = Pair.second;
276 array_pod_sort(Addrs.begin(), Addrs.end());
277 }
278 }
279
Andrew Kaylord55d7012013-01-25 22:50:58 +0000280 // Use symbol info to iterate functions in the object.
Rafael Espindolada176272015-05-31 22:13:51 +0000281 for (object::SymbolRef Sym : SymbolObj->symbols()) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000282 object::SymbolRef::Type SymType;
Rafael Espindolada176272015-05-31 22:13:51 +0000283 if (Sym.getType(SymType))
284 continue;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000285 if (SymType == object::SymbolRef::ST_Function) {
286 StringRef Name;
287 uint64_t Addr;
Rafael Espindolada176272015-05-31 22:13:51 +0000288 if (Sym.getName(Name))
289 continue;
290 if (Sym.getAddress(Addr))
291 continue;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000292
293 uint64_t Size;
294 if (isa<ELFObjectFileBase>(SymbolObj)) {
Rafael Espindola5eb02e42015-06-01 00:27:26 +0000295 Size = Sym.getSize();
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000296 } else {
297 object::section_iterator Sec = SymbolObj->section_end();
298 if (Sym.getSection(Sec))
299 continue;
300 const std::vector<uint64_t> &Addrs = FuncAddresses[*Sec];
301 auto AddrI = std::find(Addrs.begin(), Addrs.end(), Addr);
302 assert(AddrI != Addrs.end() && (AddrI + 1) != Addrs.end());
303 assert(*AddrI == Addr);
304 Size = *(AddrI + 1) - Addr;
305 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000306
Keno Fischerc780e8e2015-05-21 21:24:32 +0000307 // If we're not using the debug object, compute the address of the
308 // symbol in memory (rather than that in the unrelocated object file)
309 // and use that to query the DWARFContext.
310 if (!UseDebugObj && LoadObjects) {
311 object::section_iterator Sec(SymbolObj->section_end());
Rafael Espindolada176272015-05-31 22:13:51 +0000312 Sym.getSection(Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000313 StringRef SecName;
314 Sec->getName(SecName);
315 uint64_t SectionLoadAddress =
316 LoadedObjInfo->getSectionLoadAddress(SecName);
317 if (SectionLoadAddress != 0)
318 Addr += SectionLoadAddress - Sec->getAddress();
319 }
320
321 outs() << "Function: " << Name << ", Size = " << Size << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000322
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000323 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
324 DILineInfoTable::iterator Begin = Lines.begin();
325 DILineInfoTable::iterator End = Lines.end();
326 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
327 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000328 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000329 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000330 }
331 }
332 }
333
334 return 0;
335}
336
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000337static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000338 // Load any dylibs requested on the command line.
339 loadDylibs();
340
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000341 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000342 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000343 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000344
Lang Hamesc3246ad2015-04-15 21:18:41 +0000345 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
346 // in RuntimeDyldELF.
347 // This fixme should be fixed ASAP. This is a very brittle workaround.
348 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
349
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000350 // If we don't have any input files, read from stdin.
351 if (!InputFileList.size())
352 InputFileList.push_back("-");
353 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
354 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000355 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
356 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
357 if (std::error_code EC = InputBuffer.getError())
358 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000359 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
360 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
361
362 if (std::error_code EC = MaybeObj.getError())
363 return Error("unable to create object file: '" + EC.message() + "'");
364
365 ObjectFile &Obj = **MaybeObj;
Lang Hamesc3246ad2015-04-15 21:18:41 +0000366 InputBuffers.push_back(std::move(*InputBuffer));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000367
Andrew Kayloradc70562012-10-02 21:18:39 +0000368 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000369 Dyld.loadObject(Obj);
370 if (Dyld.hasError()) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000371 return Error(Dyld.getErrorString());
372 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000373 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000374
Jim Grosbach733d3052011-04-12 21:20:41 +0000375 // Resolve all the relocations we can.
376 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000377 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000378 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000379
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000380 // FIXME: Error out if there are unresolved relocations.
381
Jim Grosbachd35159a2011-04-13 15:38:30 +0000382 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000383 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000384 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000385 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000386
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000387 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000388 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
389 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000390 // Make sure the memory is executable.
391 std::string ErrorStr;
392 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
393 if (!sys::Memory::setExecutable(Data, &ErrorStr))
394 return Error("unable to mark function executable: '" + ErrorStr + "'");
395 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000396
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000397 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000398 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000399
400 int (*Main)(int, const char**) =
401 (int(*)(int,const char**)) uintptr_t(MainAddress);
402 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000403 // Use the name of the first input object module as argv[0] for the target.
404 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000405 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000406 return Main(1, Argv);
407}
408
Lang Hamese1c11382014-06-27 20:20:57 +0000409static int checkAllExpressions(RuntimeDyldChecker &Checker) {
410 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000411 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
412 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
413 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hamese1c11382014-06-27 20:20:57 +0000414 return Error("unable to read input '" + CheckerFileName + "': " +
415 EC.message());
416
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000417 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
418 CheckerFileBuf.get().get()))
Lang Hamese1c11382014-06-27 20:20:57 +0000419 return Error("some checks in '" + CheckerFileName + "' failed");
420 }
421 return 0;
422}
423
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000424static std::map<void *, uint64_t>
Lang Hames778ef5b2014-09-04 04:19:54 +0000425applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
426
427 std::map<void*, uint64_t> SpecificMappings;
428
429 for (StringRef Mapping : SpecificSectionMappings) {
430
431 size_t EqualsIdx = Mapping.find_first_of("=");
432 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
433 size_t ComaIdx = Mapping.find_first_of(",");
434
435 if (ComaIdx == StringRef::npos) {
436 errs() << "Invalid section specification '" << Mapping
437 << "'. Should be '<file name>,<section name>=<addr>'\n";
438 exit(1);
439 }
440
441 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
442 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
443
444 uint64_t OldAddrInt;
445 std::string ErrorMsg;
446 std::tie(OldAddrInt, ErrorMsg) =
447 Checker.getSectionAddr(FileName, SectionName, true);
448
449 if (ErrorMsg != "") {
450 errs() << ErrorMsg;
451 exit(1);
452 }
453
454 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
455
456 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
457 uint64_t NewAddr;
458
459 if (NewAddrStr.getAsInteger(0, NewAddr)) {
460 errs() << "Invalid section address in mapping: " << Mapping << "\n";
461 exit(1);
462 }
463
464 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
465 SpecificMappings[OldAddr] = NewAddr;
466 }
467
468 return SpecificMappings;
469}
470
Lang Hames9cb73532014-07-29 23:43:13 +0000471// Scatter sections in all directions!
472// Remaps section addresses for -verify mode. The following command line options
473// can be used to customize the layout of the memory within the phony target's
474// address space:
475// -target-addr-start <s> -- Specify where the phony target addres range starts.
476// -target-addr-end <e> -- Specify where the phony target address range ends.
477// -target-section-sep <d> -- Specify how big a gap should be left between the
478// end of one section and the start of the next.
479// Defaults to zero. Set to something big
480// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
481//
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000482static void remapSections(const llvm::Triple &TargetTriple,
483 const TrivialMemoryManager &MemMgr,
484 RuntimeDyldChecker &Checker) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000485
486 // Set up a work list (section addr/size pairs).
487 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
488 WorklistT Worklist;
489
490 for (const auto& CodeSection : MemMgr.FunctionMemory)
491 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
492 for (const auto& DataSection : MemMgr.DataMemory)
493 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
494
495 // Apply any section-specific mappings that were requested on the command
496 // line.
497 typedef std::map<void*, uint64_t> AppliedMappingsT;
498 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
499
500 // Keep an "already allocated" mapping of section target addresses to sizes.
501 // Sections whose address mappings aren't specified on the command line will
502 // allocated around the explicitly mapped sections while maintaining the
503 // minimum separation.
504 std::map<uint64_t, uint64_t> AlreadyAllocated;
505
506 // Move the previously applied mappings into the already-allocated map.
507 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
508 I != E;) {
509 WorklistT::iterator Tmp = I;
510 ++I;
511 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
512
513 if (AI != AppliedMappings.end()) {
514 AlreadyAllocated[AI->second] = Tmp->second;
515 Worklist.erase(Tmp);
516 }
517 }
Lang Hames9cb73532014-07-29 23:43:13 +0000518
519 // If the -target-addr-end option wasn't explicitly passed, then set it to a
520 // sensible default based on the target triple.
521 if (TargetAddrEnd.getNumOccurrences() == 0) {
522 if (TargetTriple.isArch16Bit())
523 TargetAddrEnd = (1ULL << 16) - 1;
524 else if (TargetTriple.isArch32Bit())
525 TargetAddrEnd = (1ULL << 32) - 1;
526 // TargetAddrEnd already has a sensible default for 64-bit systems, so
527 // there's nothing to do in the 64-bit case.
528 }
529
Lang Hames778ef5b2014-09-04 04:19:54 +0000530 // Process any elements remaining in the worklist.
531 while (!Worklist.empty()) {
532 std::pair<void*, uint64_t> CurEntry = Worklist.front();
533 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000534
Lang Hames778ef5b2014-09-04 04:19:54 +0000535 uint64_t NextSectionAddr = TargetAddrStart;
536
537 for (const auto &Alloc : AlreadyAllocated)
538 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
539 break;
540 else
541 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
542
543 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
544 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000545 }
546
Lang Hames9cb73532014-07-29 23:43:13 +0000547}
548
549// Load and link the objects specified on the command line, but do not execute
550// anything. Instead, attach a RuntimeDyldChecker instance and call it to
551// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000552static int linkAndVerify() {
553
554 // Check for missing triple.
555 if (TripleName == "") {
556 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
557 return 1;
558 }
559
560 // Look up the target and build the disassembler.
561 Triple TheTriple(Triple::normalize(TripleName));
562 std::string ErrorStr;
563 const Target *TheTarget =
564 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
565 if (!TheTarget) {
566 llvm::errs() << "Error accessing target '" << TripleName << "': "
567 << ErrorStr << "\n";
568 return 1;
569 }
570 TripleName = TheTriple.getTriple();
571
572 std::unique_ptr<MCSubtargetInfo> STI(
573 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
574 assert(STI && "Unable to create subtarget info!");
575
576 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
577 assert(MRI && "Unable to create target register info!");
578
579 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
580 assert(MAI && "Unable to create target asm info!");
581
582 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
583
584 std::unique_ptr<MCDisassembler> Disassembler(
585 TheTarget->createMCDisassembler(*STI, Ctx));
586 assert(Disassembler && "Unable to create disassembler!");
587
588 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
589
590 std::unique_ptr<MCInstPrinter> InstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000591 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000592
593 // Load any dylibs requested on the command line.
594 loadDylibs();
595
596 // Instantiate a dynamic linker.
597 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000598 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000599 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000600 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
601 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000602
Lang Hamesc3246ad2015-04-15 21:18:41 +0000603 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
604 // in RuntimeDyldELF.
605 // This fixme should be fixed ASAP. This is a very brittle workaround.
606 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
607
Lang Hamese1c11382014-06-27 20:20:57 +0000608 // If we don't have any input files, read from stdin.
609 if (!InputFileList.size())
610 InputFileList.push_back("-");
611 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
612 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000613 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
614 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000615
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000616 if (std::error_code EC = InputBuffer.getError())
617 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000618
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000619 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
620 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
621
622 if (std::error_code EC = MaybeObj.getError())
623 return Error("unable to create object file: '" + EC.message() + "'");
624
625 ObjectFile &Obj = **MaybeObj;
Lang Hamesc3246ad2015-04-15 21:18:41 +0000626 InputBuffers.push_back(std::move(*InputBuffer));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000627
Lang Hamese1c11382014-06-27 20:20:57 +0000628 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000629 Dyld.loadObject(Obj);
630 if (Dyld.hasError()) {
Lang Hamese1c11382014-06-27 20:20:57 +0000631 return Error(Dyld.getErrorString());
632 }
633 }
634
Lang Hames375385f2014-07-30 03:12:41 +0000635 // Re-map the section addresses into the phony target address space.
Lang Hames778ef5b2014-09-04 04:19:54 +0000636 remapSections(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000637
Lang Hamese1c11382014-06-27 20:20:57 +0000638 // Resolve all the relocations we can.
639 Dyld.resolveRelocations();
640
Lang Hames925e51b2014-09-03 05:42:52 +0000641 // Register EH frames.
642 Dyld.registerEHFrames();
643
Lang Hamesae172682014-08-05 20:51:46 +0000644 int ErrorCode = checkAllExpressions(Checker);
645 if (Dyld.hasError()) {
646 errs() << "RTDyld reported an error applying relocations:\n "
647 << Dyld.getErrorString() << "\n";
648 ErrorCode = 1;
649 }
650
651 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000652}
653
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000654int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000655 sys::PrintStackTraceOnErrorSignal();
656 PrettyStackTraceProgram X(argc, argv);
657
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000658 ProgramName = argv[0];
659 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
660
Lang Hamese1c11382014-06-27 20:20:57 +0000661 llvm::InitializeAllTargetInfos();
662 llvm::InitializeAllTargetMCs();
663 llvm::InitializeAllDisassemblers();
664
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000665 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
666
667 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000668 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000669 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000670 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000671 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000672 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000673 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
674 case AC_PrintObjectLineInfo:
675 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000676 case AC_Verify:
677 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000678 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000679}