blob: e87f1e2d4c19813f638595ebe3e7dc0b614a7e2b [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,
Lang Hamese1c11382014-06-27 20:20:57 +000050 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000051 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000052 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000053};
54
55static cl::opt<ActionType>
56Action(cl::desc("Action to perform:"),
57 cl::init(AC_Execute),
58 cl::values(clEnumValN(AC_Execute, "execute",
59 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000060 clEnumValN(AC_PrintLineInfo, "printline",
61 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000062 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
63 "Load, link, and print line information for each function using the debug object"),
Lang Hamese1c11382014-06-27 20:20:57 +000064 clEnumValN(AC_Verify, "verify",
65 "Load, link and verify the resulting memory image."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000066 clEnumValEnd));
67
Jim Grosbachd35159a2011-04-13 15:38:30 +000068static cl::opt<std::string>
69EntryPoint("entry",
70 cl::desc("Function to call as entry point."),
71 cl::init("_main"));
72
Lang Hamesd311c0e2014-05-13 22:37:41 +000073static cl::list<std::string>
74Dylibs("dylib",
75 cl::desc("Add library."),
76 cl::ZeroOrMore);
77
Lang Hamese1c11382014-06-27 20:20:57 +000078static cl::opt<std::string>
79TripleName("triple", cl::desc("Target triple for disassembler"));
80
81static cl::list<std::string>
82CheckFiles("check",
83 cl::desc("File containing RuntimeDyld verifier checks."),
84 cl::ZeroOrMore);
85
Lang Hames9cb73532014-07-29 23:43:13 +000086static cl::opt<uint64_t>
87TargetAddrStart("target-addr-start",
88 cl::desc("For -verify only: start of phony target address "
89 "range."),
90 cl::init(4096), // Start at "page 1" - no allocating at "null".
91 cl::Hidden);
92
93static cl::opt<uint64_t>
94TargetAddrEnd("target-addr-end",
95 cl::desc("For -verify only: end of phony target address range."),
96 cl::init(~0ULL),
97 cl::Hidden);
98
99static cl::opt<uint64_t>
100TargetSectionSep("target-section-sep",
101 cl::desc("For -verify only: Separation between sections in "
102 "phony target address space."),
103 cl::init(0),
104 cl::Hidden);
105
Lang Hames778ef5b2014-09-04 04:19:54 +0000106static cl::list<std::string>
107SpecificSectionMappings("map-section",
108 cl::desc("Map a section to a specific address."),
109 cl::ZeroOrMore);
110
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000111/* *** */
112
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000113// A trivial memory manager that doesn't do anything fancy, just uses the
114// support library allocation routines directly.
115class TrivialMemoryManager : public RTDyldMemoryManager {
116public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000117 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000118 SmallVector<sys::MemoryBlock, 16> DataMemory;
119
120 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000121 unsigned SectionID,
122 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000123 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000124 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000125 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000126
Craig Toppere56917c2014-03-08 08:27:28 +0000127 void *getPointerToNamedFunction(const std::string &Name,
128 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000129 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000130 }
131
Craig Toppere56917c2014-03-08 08:27:28 +0000132 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000133
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000134 // Invalidate instruction cache for sections with execute permissions.
135 // Some platforms with separate data cache and instruction cache require
136 // explicit cache flush, otherwise JIT code manipulations (like resolved
137 // relocations) will get to the data cache but not to the instruction cache.
138 virtual void invalidateInstructionCache();
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000139};
140
Jim Grosbacheff0a402012-01-16 22:26:39 +0000141uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
142 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000143 unsigned SectionID,
144 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000145 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000146 FunctionMemory.push_back(MB);
147 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000148}
149
150uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
151 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000152 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000153 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000154 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000155 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000156 DataMemory.push_back(MB);
157 return (uint8_t*)MB.base();
158}
159
160void TrivialMemoryManager::invalidateInstructionCache() {
161 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
162 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
163 FunctionMemory[i].size());
164
165 for (int i = 0, e = DataMemory.size(); i != e; ++i)
166 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
167 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000168}
169
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000170static const char *ProgramName;
171
172static void Message(const char *Type, const Twine &Msg) {
173 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
174}
175
176static int Error(const Twine &Msg) {
177 Message("error", Msg);
178 return 1;
179}
180
Lang Hamesd311c0e2014-05-13 22:37:41 +0000181static void loadDylibs() {
182 for (const std::string &Dylib : Dylibs) {
183 if (sys::fs::is_regular_file(Dylib)) {
184 std::string ErrMsg;
185 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
186 llvm::errs() << "Error loading '" << Dylib << "': "
187 << ErrMsg << "\n";
188 } else
189 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
190 }
191}
192
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000193/* *** */
194
Keno Fischerc780e8e2015-05-21 21:24:32 +0000195static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
196 assert(LoadObjects || !UseDebugObj);
197
Lang Hamesd311c0e2014-05-13 22:37:41 +0000198 // Load any dylibs requested on the command line.
199 loadDylibs();
200
Andrew Kaylord55d7012013-01-25 22:50:58 +0000201 // If we don't have any input files, read from stdin.
202 if (!InputFileList.size())
203 InputFileList.push_back("-");
204 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
205 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000206 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000207 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000208
209 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000210
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000211 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
212 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
213 if (std::error_code EC = InputBuffer.getError())
214 return Error("unable to read input: '" + EC.message() + "'");
215
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000216 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
217 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
218
219 if (std::error_code EC = MaybeObj.getError())
220 return Error("unable to create object file: '" + EC.message() + "'");
221
222 ObjectFile &Obj = **MaybeObj;
223
Keno Fischerc780e8e2015-05-21 21:24:32 +0000224 OwningBinary<ObjectFile> DebugObj;
225 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
226 ObjectFile *SymbolObj = &Obj;
227 if (LoadObjects) {
228 // Load the object file
229 LoadedObjInfo =
230 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000231
Keno Fischerc780e8e2015-05-21 21:24:32 +0000232 if (Dyld.hasError())
233 return Error(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000234
Keno Fischerc780e8e2015-05-21 21:24:32 +0000235 // Resolve all the relocations we can.
236 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000237
Keno Fischerc780e8e2015-05-21 21:24:32 +0000238 if (UseDebugObj) {
239 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
240 SymbolObj = DebugObj.getBinary();
241 }
242 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000243
Ahmed Charles56440fd2014-03-06 05:51:42 +0000244 std::unique_ptr<DIContext> Context(
Keno Fischerc780e8e2015-05-21 21:24:32 +0000245 new DWARFContextInMemory(*SymbolObj,LoadedObjInfo.get()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000246
247 // Use symbol info to iterate functions in the object.
Keno Fischerc780e8e2015-05-21 21:24:32 +0000248 for (object::symbol_iterator I = SymbolObj->symbol_begin(),
249 E = SymbolObj->symbol_end();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000250 I != E; ++I) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000251 object::SymbolRef::Type SymType;
252 if (I->getType(SymType)) continue;
253 if (SymType == object::SymbolRef::ST_Function) {
254 StringRef Name;
255 uint64_t Addr;
256 uint64_t Size;
257 if (I->getName(Name)) continue;
258 if (I->getAddress(Addr)) continue;
259 if (I->getSize(Size)) continue;
260
Keno Fischerc780e8e2015-05-21 21:24:32 +0000261 // If we're not using the debug object, compute the address of the
262 // symbol in memory (rather than that in the unrelocated object file)
263 // and use that to query the DWARFContext.
264 if (!UseDebugObj && LoadObjects) {
265 object::section_iterator Sec(SymbolObj->section_end());
266 I->getSection(Sec);
267 StringRef SecName;
268 Sec->getName(SecName);
269 uint64_t SectionLoadAddress =
270 LoadedObjInfo->getSectionLoadAddress(SecName);
271 if (SectionLoadAddress != 0)
272 Addr += SectionLoadAddress - Sec->getAddress();
273 }
274
275 outs() << "Function: " << Name << ", Size = " << Size << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000276
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000277 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
278 DILineInfoTable::iterator Begin = Lines.begin();
279 DILineInfoTable::iterator End = Lines.end();
280 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
281 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000282 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000283 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000284 }
285 }
286 }
287
288 return 0;
289}
290
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000291static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000292 // Load any dylibs requested on the command line.
293 loadDylibs();
294
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000295 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000296 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000297 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000298
Lang Hamesc3246ad2015-04-15 21:18:41 +0000299 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
300 // in RuntimeDyldELF.
301 // This fixme should be fixed ASAP. This is a very brittle workaround.
302 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
303
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000304 // If we don't have any input files, read from stdin.
305 if (!InputFileList.size())
306 InputFileList.push_back("-");
307 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
308 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000309 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
310 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
311 if (std::error_code EC = InputBuffer.getError())
312 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000313 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
314 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
315
316 if (std::error_code EC = MaybeObj.getError())
317 return Error("unable to create object file: '" + EC.message() + "'");
318
319 ObjectFile &Obj = **MaybeObj;
Lang Hamesc3246ad2015-04-15 21:18:41 +0000320 InputBuffers.push_back(std::move(*InputBuffer));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000321
Andrew Kayloradc70562012-10-02 21:18:39 +0000322 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000323 Dyld.loadObject(Obj);
324 if (Dyld.hasError()) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000325 return Error(Dyld.getErrorString());
326 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000327 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000328
Jim Grosbach733d3052011-04-12 21:20:41 +0000329 // Resolve all the relocations we can.
330 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000331 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000332 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000333
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000334 // FIXME: Error out if there are unresolved relocations.
335
Jim Grosbachd35159a2011-04-13 15:38:30 +0000336 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000337 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000338 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000339 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000340
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000341 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000342 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
343 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000344 // Make sure the memory is executable.
345 std::string ErrorStr;
346 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
347 if (!sys::Memory::setExecutable(Data, &ErrorStr))
348 return Error("unable to mark function executable: '" + ErrorStr + "'");
349 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000350
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000351 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000352 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000353
354 int (*Main)(int, const char**) =
355 (int(*)(int,const char**)) uintptr_t(MainAddress);
356 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000357 // Use the name of the first input object module as argv[0] for the target.
358 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000359 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000360 return Main(1, Argv);
361}
362
Lang Hamese1c11382014-06-27 20:20:57 +0000363static int checkAllExpressions(RuntimeDyldChecker &Checker) {
364 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000365 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
366 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
367 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hamese1c11382014-06-27 20:20:57 +0000368 return Error("unable to read input '" + CheckerFileName + "': " +
369 EC.message());
370
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000371 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
372 CheckerFileBuf.get().get()))
Lang Hamese1c11382014-06-27 20:20:57 +0000373 return Error("some checks in '" + CheckerFileName + "' failed");
374 }
375 return 0;
376}
377
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000378static std::map<void *, uint64_t>
Lang Hames778ef5b2014-09-04 04:19:54 +0000379applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
380
381 std::map<void*, uint64_t> SpecificMappings;
382
383 for (StringRef Mapping : SpecificSectionMappings) {
384
385 size_t EqualsIdx = Mapping.find_first_of("=");
386 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
387 size_t ComaIdx = Mapping.find_first_of(",");
388
389 if (ComaIdx == StringRef::npos) {
390 errs() << "Invalid section specification '" << Mapping
391 << "'. Should be '<file name>,<section name>=<addr>'\n";
392 exit(1);
393 }
394
395 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
396 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
397
398 uint64_t OldAddrInt;
399 std::string ErrorMsg;
400 std::tie(OldAddrInt, ErrorMsg) =
401 Checker.getSectionAddr(FileName, SectionName, true);
402
403 if (ErrorMsg != "") {
404 errs() << ErrorMsg;
405 exit(1);
406 }
407
408 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
409
410 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
411 uint64_t NewAddr;
412
413 if (NewAddrStr.getAsInteger(0, NewAddr)) {
414 errs() << "Invalid section address in mapping: " << Mapping << "\n";
415 exit(1);
416 }
417
418 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
419 SpecificMappings[OldAddr] = NewAddr;
420 }
421
422 return SpecificMappings;
423}
424
Lang Hames9cb73532014-07-29 23:43:13 +0000425// Scatter sections in all directions!
426// Remaps section addresses for -verify mode. The following command line options
427// can be used to customize the layout of the memory within the phony target's
428// address space:
429// -target-addr-start <s> -- Specify where the phony target addres range starts.
430// -target-addr-end <e> -- Specify where the phony target address range ends.
431// -target-section-sep <d> -- Specify how big a gap should be left between the
432// end of one section and the start of the next.
433// Defaults to zero. Set to something big
434// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
435//
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000436static void remapSections(const llvm::Triple &TargetTriple,
437 const TrivialMemoryManager &MemMgr,
438 RuntimeDyldChecker &Checker) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000439
440 // Set up a work list (section addr/size pairs).
441 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
442 WorklistT Worklist;
443
444 for (const auto& CodeSection : MemMgr.FunctionMemory)
445 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
446 for (const auto& DataSection : MemMgr.DataMemory)
447 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
448
449 // Apply any section-specific mappings that were requested on the command
450 // line.
451 typedef std::map<void*, uint64_t> AppliedMappingsT;
452 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
453
454 // Keep an "already allocated" mapping of section target addresses to sizes.
455 // Sections whose address mappings aren't specified on the command line will
456 // allocated around the explicitly mapped sections while maintaining the
457 // minimum separation.
458 std::map<uint64_t, uint64_t> AlreadyAllocated;
459
460 // Move the previously applied mappings into the already-allocated map.
461 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
462 I != E;) {
463 WorklistT::iterator Tmp = I;
464 ++I;
465 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
466
467 if (AI != AppliedMappings.end()) {
468 AlreadyAllocated[AI->second] = Tmp->second;
469 Worklist.erase(Tmp);
470 }
471 }
Lang Hames9cb73532014-07-29 23:43:13 +0000472
473 // If the -target-addr-end option wasn't explicitly passed, then set it to a
474 // sensible default based on the target triple.
475 if (TargetAddrEnd.getNumOccurrences() == 0) {
476 if (TargetTriple.isArch16Bit())
477 TargetAddrEnd = (1ULL << 16) - 1;
478 else if (TargetTriple.isArch32Bit())
479 TargetAddrEnd = (1ULL << 32) - 1;
480 // TargetAddrEnd already has a sensible default for 64-bit systems, so
481 // there's nothing to do in the 64-bit case.
482 }
483
Lang Hames778ef5b2014-09-04 04:19:54 +0000484 // Process any elements remaining in the worklist.
485 while (!Worklist.empty()) {
486 std::pair<void*, uint64_t> CurEntry = Worklist.front();
487 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000488
Lang Hames778ef5b2014-09-04 04:19:54 +0000489 uint64_t NextSectionAddr = TargetAddrStart;
490
491 for (const auto &Alloc : AlreadyAllocated)
492 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
493 break;
494 else
495 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
496
497 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
498 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000499 }
500
Lang Hames9cb73532014-07-29 23:43:13 +0000501}
502
503// Load and link the objects specified on the command line, but do not execute
504// anything. Instead, attach a RuntimeDyldChecker instance and call it to
505// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000506static int linkAndVerify() {
507
508 // Check for missing triple.
509 if (TripleName == "") {
510 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
511 return 1;
512 }
513
514 // Look up the target and build the disassembler.
515 Triple TheTriple(Triple::normalize(TripleName));
516 std::string ErrorStr;
517 const Target *TheTarget =
518 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
519 if (!TheTarget) {
520 llvm::errs() << "Error accessing target '" << TripleName << "': "
521 << ErrorStr << "\n";
522 return 1;
523 }
524 TripleName = TheTriple.getTriple();
525
526 std::unique_ptr<MCSubtargetInfo> STI(
527 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
528 assert(STI && "Unable to create subtarget info!");
529
530 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
531 assert(MRI && "Unable to create target register info!");
532
533 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
534 assert(MAI && "Unable to create target asm info!");
535
536 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
537
538 std::unique_ptr<MCDisassembler> Disassembler(
539 TheTarget->createMCDisassembler(*STI, Ctx));
540 assert(Disassembler && "Unable to create disassembler!");
541
542 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
543
544 std::unique_ptr<MCInstPrinter> InstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000545 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000546
547 // Load any dylibs requested on the command line.
548 loadDylibs();
549
550 // Instantiate a dynamic linker.
551 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000552 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000553 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000554 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
555 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000556
Lang Hamesc3246ad2015-04-15 21:18:41 +0000557 // FIXME: Preserve buffers until resolveRelocations time to work around a bug
558 // in RuntimeDyldELF.
559 // This fixme should be fixed ASAP. This is a very brittle workaround.
560 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
561
Lang Hamese1c11382014-06-27 20:20:57 +0000562 // If we don't have any input files, read from stdin.
563 if (!InputFileList.size())
564 InputFileList.push_back("-");
565 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
566 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000567 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
568 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000569
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000570 if (std::error_code EC = InputBuffer.getError())
571 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000572
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000573 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
574 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
575
576 if (std::error_code EC = MaybeObj.getError())
577 return Error("unable to create object file: '" + EC.message() + "'");
578
579 ObjectFile &Obj = **MaybeObj;
Lang Hamesc3246ad2015-04-15 21:18:41 +0000580 InputBuffers.push_back(std::move(*InputBuffer));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000581
Lang Hamese1c11382014-06-27 20:20:57 +0000582 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000583 Dyld.loadObject(Obj);
584 if (Dyld.hasError()) {
Lang Hamese1c11382014-06-27 20:20:57 +0000585 return Error(Dyld.getErrorString());
586 }
587 }
588
Lang Hames375385f2014-07-30 03:12:41 +0000589 // Re-map the section addresses into the phony target address space.
Lang Hames778ef5b2014-09-04 04:19:54 +0000590 remapSections(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000591
Lang Hamese1c11382014-06-27 20:20:57 +0000592 // Resolve all the relocations we can.
593 Dyld.resolveRelocations();
594
Lang Hames925e51b2014-09-03 05:42:52 +0000595 // Register EH frames.
596 Dyld.registerEHFrames();
597
Lang Hamesae172682014-08-05 20:51:46 +0000598 int ErrorCode = checkAllExpressions(Checker);
599 if (Dyld.hasError()) {
600 errs() << "RTDyld reported an error applying relocations:\n "
601 << Dyld.getErrorString() << "\n";
602 ErrorCode = 1;
603 }
604
605 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000606}
607
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000608int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000609 sys::PrintStackTraceOnErrorSignal();
610 PrettyStackTraceProgram X(argc, argv);
611
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000612 ProgramName = argv[0];
613 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
614
Lang Hamese1c11382014-06-27 20:20:57 +0000615 llvm::InitializeAllTargetInfos();
616 llvm::InitializeAllTargetMCs();
617 llvm::InitializeAllDisassemblers();
618
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000619 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
620
621 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000622 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000623 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000624 case AC_PrintDebugLineInfo:
625 return printLineInfoForInput(true,true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000626 case AC_PrintLineInfo:
Keno Fischerc780e8e2015-05-21 21:24:32 +0000627 return printLineInfoForInput(true,false);
Lang Hamese1c11382014-06-27 20:20:57 +0000628 case AC_Verify:
629 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000630 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000631}