blob: c2c3498c9b8368049bb19ba6be167c36d537b311 [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 Turner82af9432015-01-30 18:07:45 +000015#include "llvm/DebugInfo/DWARF/DIContext.h"
Lang Hames633fe142015-03-30 03:37:06 +000016#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ExecutionEngine/RuntimeDyld.h"
Lang Hamese1c11382014-06-27 20:20:57 +000018#include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCDisassembler.h"
Lang Hamese1c11382014-06-27 20:20:57 +000022#include "llvm/MC/MCInstPrinter.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000023#include "llvm/MC/MCInstrInfo.h"
Lang Hamese1c11382014-06-27 20:20:57 +000024#include "llvm/MC/MCRegisterInfo.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000025#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000026#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000027#include "llvm/Support/DynamicLibrary.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000028#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/Memory.h"
30#include "llvm/Support/MemoryBuffer.h"
Alp Toker9f679322013-11-05 09:33:43 +000031#include "llvm/Support/PrettyStackTrace.h"
Lang Hamese1c11382014-06-27 20:20:57 +000032#include "llvm/Support/Signals.h"
33#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Support/TargetSelect.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/raw_ostream.h"
Lang Hames778ef5b2014-09-04 04:19:54 +000036#include <list>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000037#include <system_error>
Lang Hamese1c11382014-06-27 20:20:57 +000038
Jim Grosbach0072cdb2011-03-18 17:11:39 +000039using namespace llvm;
40using namespace llvm::object;
41
Jim Grosbach7cb41d72011-04-13 15:49:40 +000042static cl::list<std::string>
43InputFileList(cl::Positional, cl::ZeroOrMore,
44 cl::desc("<input file>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000045
46enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000047 AC_Execute,
Lang Hamese1c11382014-06-27 20:20:57 +000048 AC_PrintLineInfo,
49 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000050};
51
52static cl::opt<ActionType>
53Action(cl::desc("Action to perform:"),
54 cl::init(AC_Execute),
55 cl::values(clEnumValN(AC_Execute, "execute",
56 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000057 clEnumValN(AC_PrintLineInfo, "printline",
58 "Load, link, and print line information for each function."),
Lang Hamese1c11382014-06-27 20:20:57 +000059 clEnumValN(AC_Verify, "verify",
60 "Load, link and verify the resulting memory image."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000061 clEnumValEnd));
62
Jim Grosbachd35159a2011-04-13 15:38:30 +000063static cl::opt<std::string>
64EntryPoint("entry",
65 cl::desc("Function to call as entry point."),
66 cl::init("_main"));
67
Lang Hamesd311c0e2014-05-13 22:37:41 +000068static cl::list<std::string>
69Dylibs("dylib",
70 cl::desc("Add library."),
71 cl::ZeroOrMore);
72
Lang Hamese1c11382014-06-27 20:20:57 +000073static cl::opt<std::string>
74TripleName("triple", cl::desc("Target triple for disassembler"));
75
76static cl::list<std::string>
77CheckFiles("check",
78 cl::desc("File containing RuntimeDyld verifier checks."),
79 cl::ZeroOrMore);
80
Lang Hames9cb73532014-07-29 23:43:13 +000081static cl::opt<uint64_t>
82TargetAddrStart("target-addr-start",
83 cl::desc("For -verify only: start of phony target address "
84 "range."),
85 cl::init(4096), // Start at "page 1" - no allocating at "null".
86 cl::Hidden);
87
88static cl::opt<uint64_t>
89TargetAddrEnd("target-addr-end",
90 cl::desc("For -verify only: end of phony target address range."),
91 cl::init(~0ULL),
92 cl::Hidden);
93
94static cl::opt<uint64_t>
95TargetSectionSep("target-section-sep",
96 cl::desc("For -verify only: Separation between sections in "
97 "phony target address space."),
98 cl::init(0),
99 cl::Hidden);
100
Lang Hames778ef5b2014-09-04 04:19:54 +0000101static cl::list<std::string>
102SpecificSectionMappings("map-section",
103 cl::desc("Map a section to a specific address."),
104 cl::ZeroOrMore);
105
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000106/* *** */
107
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000108// A trivial memory manager that doesn't do anything fancy, just uses the
109// support library allocation routines directly.
110class TrivialMemoryManager : public RTDyldMemoryManager {
111public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000112 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000113 SmallVector<sys::MemoryBlock, 16> DataMemory;
114
115 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000116 unsigned SectionID,
117 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000118 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000119 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000120 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000121
Craig Toppere56917c2014-03-08 08:27:28 +0000122 void *getPointerToNamedFunction(const std::string &Name,
123 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000124 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000125 }
126
Craig Toppere56917c2014-03-08 08:27:28 +0000127 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000128
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000129 // Invalidate instruction cache for sections with execute permissions.
130 // Some platforms with separate data cache and instruction cache require
131 // explicit cache flush, otherwise JIT code manipulations (like resolved
132 // relocations) will get to the data cache but not to the instruction cache.
133 virtual void invalidateInstructionCache();
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000134};
135
Jim Grosbacheff0a402012-01-16 22:26:39 +0000136uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
137 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000138 unsigned SectionID,
139 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000140 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000141 FunctionMemory.push_back(MB);
142 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000143}
144
145uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
146 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000147 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000148 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000149 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000150 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000151 DataMemory.push_back(MB);
152 return (uint8_t*)MB.base();
153}
154
155void TrivialMemoryManager::invalidateInstructionCache() {
156 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
157 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
158 FunctionMemory[i].size());
159
160 for (int i = 0, e = DataMemory.size(); i != e; ++i)
161 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
162 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000163}
164
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000165static const char *ProgramName;
166
167static void Message(const char *Type, const Twine &Msg) {
168 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
169}
170
171static int Error(const Twine &Msg) {
172 Message("error", Msg);
173 return 1;
174}
175
Lang Hamesd311c0e2014-05-13 22:37:41 +0000176static void loadDylibs() {
177 for (const std::string &Dylib : Dylibs) {
178 if (sys::fs::is_regular_file(Dylib)) {
179 std::string ErrMsg;
180 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
181 llvm::errs() << "Error loading '" << Dylib << "': "
182 << ErrMsg << "\n";
183 } else
184 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
185 }
186}
187
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000188/* *** */
189
Andrew Kaylord55d7012013-01-25 22:50:58 +0000190static int printLineInfoForInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000191 // Load any dylibs requested on the command line.
192 loadDylibs();
193
Andrew Kaylord55d7012013-01-25 22:50:58 +0000194 // If we don't have any input files, read from stdin.
195 if (!InputFileList.size())
196 InputFileList.push_back("-");
197 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
198 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000199 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000200 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000201
202 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000203
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000204 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
205 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
206 if (std::error_code EC = InputBuffer.getError())
207 return Error("unable to read input: '" + EC.message() + "'");
208
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000209 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
210 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
211
212 if (std::error_code EC = MaybeObj.getError())
213 return Error("unable to create object file: '" + EC.message() + "'");
214
215 ObjectFile &Obj = **MaybeObj;
216
Andrew Kaylord55d7012013-01-25 22:50:58 +0000217 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000218 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo =
219 Dyld.loadObject(Obj);
220
221 if (Dyld.hasError())
Andrew Kaylord55d7012013-01-25 22:50:58 +0000222 return Error(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000223
224 // Resolve all the relocations we can.
225 Dyld.resolveRelocations();
226
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000227 OwningBinary<ObjectFile> DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
228
Ahmed Charles56440fd2014-03-06 05:51:42 +0000229 std::unique_ptr<DIContext> Context(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000230 DIContext::getDWARFContext(*DebugObj.getBinary()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000231
232 // Use symbol info to iterate functions in the object.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000233 for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
234 E = DebugObj.getBinary()->symbol_end();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000235 I != E; ++I) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000236 object::SymbolRef::Type SymType;
237 if (I->getType(SymType)) continue;
238 if (SymType == object::SymbolRef::ST_Function) {
239 StringRef Name;
240 uint64_t Addr;
241 uint64_t Size;
242 if (I->getName(Name)) continue;
243 if (I->getAddress(Addr)) continue;
244 if (I->getSize(Size)) continue;
245
246 outs() << "Function: " << Name << ", Size = " << Size << "\n";
247
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000248 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
249 DILineInfoTable::iterator Begin = Lines.begin();
250 DILineInfoTable::iterator End = Lines.end();
251 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
252 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000253 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000254 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000255 }
256 }
257 }
258
259 return 0;
260}
261
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000262static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000263 // Load any dylibs requested on the command line.
264 loadDylibs();
265
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000266 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000267 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000268 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000269
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000270 // If we don't have any input files, read from stdin.
271 if (!InputFileList.size())
272 InputFileList.push_back("-");
273 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
274 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000275 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
276 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
277 if (std::error_code EC = InputBuffer.getError())
278 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000279 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
280 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
281
282 if (std::error_code EC = MaybeObj.getError())
283 return Error("unable to create object file: '" + EC.message() + "'");
284
285 ObjectFile &Obj = **MaybeObj;
286
Andrew Kayloradc70562012-10-02 21:18:39 +0000287 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000288 Dyld.loadObject(Obj);
289 if (Dyld.hasError()) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000290 return Error(Dyld.getErrorString());
291 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000292 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000293
Jim Grosbach733d3052011-04-12 21:20:41 +0000294 // Resolve all the relocations we can.
295 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000296 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000297 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000298
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000299 // FIXME: Error out if there are unresolved relocations.
300
Jim Grosbachd35159a2011-04-13 15:38:30 +0000301 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000302 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000303 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000304 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000305
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000306 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000307 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
308 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000309 // Make sure the memory is executable.
310 std::string ErrorStr;
311 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
312 if (!sys::Memory::setExecutable(Data, &ErrorStr))
313 return Error("unable to mark function executable: '" + ErrorStr + "'");
314 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000315
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000316 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000317 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000318
319 int (*Main)(int, const char**) =
320 (int(*)(int,const char**)) uintptr_t(MainAddress);
321 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000322 // Use the name of the first input object module as argv[0] for the target.
323 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000324 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000325 return Main(1, Argv);
326}
327
Lang Hamese1c11382014-06-27 20:20:57 +0000328static int checkAllExpressions(RuntimeDyldChecker &Checker) {
329 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000330 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
331 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
332 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hamese1c11382014-06-27 20:20:57 +0000333 return Error("unable to read input '" + CheckerFileName + "': " +
334 EC.message());
335
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000336 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
337 CheckerFileBuf.get().get()))
Lang Hamese1c11382014-06-27 20:20:57 +0000338 return Error("some checks in '" + CheckerFileName + "' failed");
339 }
340 return 0;
341}
342
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000343static std::map<void *, uint64_t>
Lang Hames778ef5b2014-09-04 04:19:54 +0000344applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
345
346 std::map<void*, uint64_t> SpecificMappings;
347
348 for (StringRef Mapping : SpecificSectionMappings) {
349
350 size_t EqualsIdx = Mapping.find_first_of("=");
351 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
352 size_t ComaIdx = Mapping.find_first_of(",");
353
354 if (ComaIdx == StringRef::npos) {
355 errs() << "Invalid section specification '" << Mapping
356 << "'. Should be '<file name>,<section name>=<addr>'\n";
357 exit(1);
358 }
359
360 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
361 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
362
363 uint64_t OldAddrInt;
364 std::string ErrorMsg;
365 std::tie(OldAddrInt, ErrorMsg) =
366 Checker.getSectionAddr(FileName, SectionName, true);
367
368 if (ErrorMsg != "") {
369 errs() << ErrorMsg;
370 exit(1);
371 }
372
373 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
374
375 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
376 uint64_t NewAddr;
377
378 if (NewAddrStr.getAsInteger(0, NewAddr)) {
379 errs() << "Invalid section address in mapping: " << Mapping << "\n";
380 exit(1);
381 }
382
383 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
384 SpecificMappings[OldAddr] = NewAddr;
385 }
386
387 return SpecificMappings;
388}
389
Lang Hames9cb73532014-07-29 23:43:13 +0000390// Scatter sections in all directions!
391// Remaps section addresses for -verify mode. The following command line options
392// can be used to customize the layout of the memory within the phony target's
393// address space:
394// -target-addr-start <s> -- Specify where the phony target addres range starts.
395// -target-addr-end <e> -- Specify where the phony target address range ends.
396// -target-section-sep <d> -- Specify how big a gap should be left between the
397// end of one section and the start of the next.
398// Defaults to zero. Set to something big
399// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
400//
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000401static void remapSections(const llvm::Triple &TargetTriple,
402 const TrivialMemoryManager &MemMgr,
403 RuntimeDyldChecker &Checker) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000404
405 // Set up a work list (section addr/size pairs).
406 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
407 WorklistT Worklist;
408
409 for (const auto& CodeSection : MemMgr.FunctionMemory)
410 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
411 for (const auto& DataSection : MemMgr.DataMemory)
412 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
413
414 // Apply any section-specific mappings that were requested on the command
415 // line.
416 typedef std::map<void*, uint64_t> AppliedMappingsT;
417 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
418
419 // Keep an "already allocated" mapping of section target addresses to sizes.
420 // Sections whose address mappings aren't specified on the command line will
421 // allocated around the explicitly mapped sections while maintaining the
422 // minimum separation.
423 std::map<uint64_t, uint64_t> AlreadyAllocated;
424
425 // Move the previously applied mappings into the already-allocated map.
426 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
427 I != E;) {
428 WorklistT::iterator Tmp = I;
429 ++I;
430 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
431
432 if (AI != AppliedMappings.end()) {
433 AlreadyAllocated[AI->second] = Tmp->second;
434 Worklist.erase(Tmp);
435 }
436 }
Lang Hames9cb73532014-07-29 23:43:13 +0000437
438 // If the -target-addr-end option wasn't explicitly passed, then set it to a
439 // sensible default based on the target triple.
440 if (TargetAddrEnd.getNumOccurrences() == 0) {
441 if (TargetTriple.isArch16Bit())
442 TargetAddrEnd = (1ULL << 16) - 1;
443 else if (TargetTriple.isArch32Bit())
444 TargetAddrEnd = (1ULL << 32) - 1;
445 // TargetAddrEnd already has a sensible default for 64-bit systems, so
446 // there's nothing to do in the 64-bit case.
447 }
448
Lang Hames778ef5b2014-09-04 04:19:54 +0000449 // Process any elements remaining in the worklist.
450 while (!Worklist.empty()) {
451 std::pair<void*, uint64_t> CurEntry = Worklist.front();
452 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000453
Lang Hames778ef5b2014-09-04 04:19:54 +0000454 uint64_t NextSectionAddr = TargetAddrStart;
455
456 for (const auto &Alloc : AlreadyAllocated)
457 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
458 break;
459 else
460 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
461
462 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
463 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000464 }
465
Lang Hames9cb73532014-07-29 23:43:13 +0000466}
467
468// Load and link the objects specified on the command line, but do not execute
469// anything. Instead, attach a RuntimeDyldChecker instance and call it to
470// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000471static int linkAndVerify() {
472
473 // Check for missing triple.
474 if (TripleName == "") {
475 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
476 return 1;
477 }
478
479 // Look up the target and build the disassembler.
480 Triple TheTriple(Triple::normalize(TripleName));
481 std::string ErrorStr;
482 const Target *TheTarget =
483 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
484 if (!TheTarget) {
485 llvm::errs() << "Error accessing target '" << TripleName << "': "
486 << ErrorStr << "\n";
487 return 1;
488 }
489 TripleName = TheTriple.getTriple();
490
491 std::unique_ptr<MCSubtargetInfo> STI(
492 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
493 assert(STI && "Unable to create subtarget info!");
494
495 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
496 assert(MRI && "Unable to create target register info!");
497
498 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
499 assert(MAI && "Unable to create target asm info!");
500
501 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
502
503 std::unique_ptr<MCDisassembler> Disassembler(
504 TheTarget->createMCDisassembler(*STI, Ctx));
505 assert(Disassembler && "Unable to create disassembler!");
506
507 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
508
509 std::unique_ptr<MCInstPrinter> InstPrinter(
510 TheTarget->createMCInstPrinter(0, *MAI, *MII, *MRI, *STI));
511
512 // Load any dylibs requested on the command line.
513 loadDylibs();
514
515 // Instantiate a dynamic linker.
516 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000517 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000518 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000519 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
520 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000521
522 // If we don't have any input files, read from stdin.
523 if (!InputFileList.size())
524 InputFileList.push_back("-");
525 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
526 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000527 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
528 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000529
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000530 if (std::error_code EC = InputBuffer.getError())
531 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000532
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000533 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
534 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
535
536 if (std::error_code EC = MaybeObj.getError())
537 return Error("unable to create object file: '" + EC.message() + "'");
538
539 ObjectFile &Obj = **MaybeObj;
540
Lang Hamese1c11382014-06-27 20:20:57 +0000541 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000542 Dyld.loadObject(Obj);
543 if (Dyld.hasError()) {
Lang Hamese1c11382014-06-27 20:20:57 +0000544 return Error(Dyld.getErrorString());
545 }
546 }
547
Lang Hames375385f2014-07-30 03:12:41 +0000548 // Re-map the section addresses into the phony target address space.
Lang Hames778ef5b2014-09-04 04:19:54 +0000549 remapSections(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000550
Lang Hamese1c11382014-06-27 20:20:57 +0000551 // Resolve all the relocations we can.
552 Dyld.resolveRelocations();
553
Lang Hames925e51b2014-09-03 05:42:52 +0000554 // Register EH frames.
555 Dyld.registerEHFrames();
556
Lang Hamesae172682014-08-05 20:51:46 +0000557 int ErrorCode = checkAllExpressions(Checker);
558 if (Dyld.hasError()) {
559 errs() << "RTDyld reported an error applying relocations:\n "
560 << Dyld.getErrorString() << "\n";
561 ErrorCode = 1;
562 }
563
564 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000565}
566
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000567int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000568 sys::PrintStackTraceOnErrorSignal();
569 PrettyStackTraceProgram X(argc, argv);
570
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000571 ProgramName = argv[0];
572 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
573
Lang Hamese1c11382014-06-27 20:20:57 +0000574 llvm::InitializeAllTargetInfos();
575 llvm::InitializeAllTargetMCs();
576 llvm::InitializeAllDisassemblers();
577
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000578 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
579
580 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000581 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000582 return executeInput();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000583 case AC_PrintLineInfo:
584 return printLineInfoForInput();
Lang Hamese1c11382014-06-27 20:20:57 +0000585 case AC_Verify:
586 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000587 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000588}