blob: c38e42307dd10c1ae31ebac67c4b639eade7f50d [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"
Andrew Kaylord55d7012013-01-25 22:50:58 +000015#include "llvm/DebugInfo/DIContext.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "llvm/ExecutionEngine/RuntimeDyld.h"
Lang Hamese1c11382014-06-27 20:20:57 +000017#include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
18#include "llvm/MC/MCAsmInfo.h"
19#include "llvm/MC/MCContext.h"
20#include "llvm/MC/MCDisassembler.h"
21#include "llvm/MC/MCInstrInfo.h"
22#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCRegisterInfo.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000024#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000025#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000026#include "llvm/Support/DynamicLibrary.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000027#include "llvm/Support/ManagedStatic.h"
28#include "llvm/Support/Memory.h"
29#include "llvm/Support/MemoryBuffer.h"
Alp Toker9f679322013-11-05 09:33:43 +000030#include "llvm/Support/PrettyStackTrace.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000031#include "llvm/Support/raw_ostream.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"
Lang Hames778ef5b2014-09-04 04:19:54 +000035#include <list>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000036#include <system_error>
Lang Hamese1c11382014-06-27 20:20:57 +000037
Jim Grosbach0072cdb2011-03-18 17:11:39 +000038using namespace llvm;
39using namespace llvm::object;
40
Jim Grosbach7cb41d72011-04-13 15:49:40 +000041static cl::list<std::string>
42InputFileList(cl::Positional, cl::ZeroOrMore,
43 cl::desc("<input file>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000044
45enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000046 AC_Execute,
Lang Hamese1c11382014-06-27 20:20:57 +000047 AC_PrintLineInfo,
48 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000049};
50
51static cl::opt<ActionType>
52Action(cl::desc("Action to perform:"),
53 cl::init(AC_Execute),
54 cl::values(clEnumValN(AC_Execute, "execute",
55 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000056 clEnumValN(AC_PrintLineInfo, "printline",
57 "Load, link, and print line information for each function."),
Lang Hamese1c11382014-06-27 20:20:57 +000058 clEnumValN(AC_Verify, "verify",
59 "Load, link and verify the resulting memory image."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000060 clEnumValEnd));
61
Jim Grosbachd35159a2011-04-13 15:38:30 +000062static cl::opt<std::string>
63EntryPoint("entry",
64 cl::desc("Function to call as entry point."),
65 cl::init("_main"));
66
Lang Hamesd311c0e2014-05-13 22:37:41 +000067static cl::list<std::string>
68Dylibs("dylib",
69 cl::desc("Add library."),
70 cl::ZeroOrMore);
71
Lang Hamese1c11382014-06-27 20:20:57 +000072static cl::opt<std::string>
73TripleName("triple", cl::desc("Target triple for disassembler"));
74
75static cl::list<std::string>
76CheckFiles("check",
77 cl::desc("File containing RuntimeDyld verifier checks."),
78 cl::ZeroOrMore);
79
Lang Hames9cb73532014-07-29 23:43:13 +000080static cl::opt<uint64_t>
81TargetAddrStart("target-addr-start",
82 cl::desc("For -verify only: start of phony target address "
83 "range."),
84 cl::init(4096), // Start at "page 1" - no allocating at "null".
85 cl::Hidden);
86
87static cl::opt<uint64_t>
88TargetAddrEnd("target-addr-end",
89 cl::desc("For -verify only: end of phony target address range."),
90 cl::init(~0ULL),
91 cl::Hidden);
92
93static cl::opt<uint64_t>
94TargetSectionSep("target-section-sep",
95 cl::desc("For -verify only: Separation between sections in "
96 "phony target address space."),
97 cl::init(0),
98 cl::Hidden);
99
Lang Hames778ef5b2014-09-04 04:19:54 +0000100static cl::list<std::string>
101SpecificSectionMappings("map-section",
102 cl::desc("Map a section to a specific address."),
103 cl::ZeroOrMore);
104
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000105/* *** */
106
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000107// A trivial memory manager that doesn't do anything fancy, just uses the
108// support library allocation routines directly.
109class TrivialMemoryManager : public RTDyldMemoryManager {
110public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000111 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000112 SmallVector<sys::MemoryBlock, 16> DataMemory;
113
114 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000115 unsigned SectionID,
116 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000117 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000118 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000119 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000120
Craig Toppere56917c2014-03-08 08:27:28 +0000121 void *getPointerToNamedFunction(const std::string &Name,
122 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000123 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000124 }
125
Craig Toppere56917c2014-03-08 08:27:28 +0000126 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000127
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000128 // Invalidate instruction cache for sections with execute permissions.
129 // Some platforms with separate data cache and instruction cache require
130 // explicit cache flush, otherwise JIT code manipulations (like resolved
131 // relocations) will get to the data cache but not to the instruction cache.
132 virtual void invalidateInstructionCache();
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000133};
134
Jim Grosbacheff0a402012-01-16 22:26:39 +0000135uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
136 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000137 unsigned SectionID,
138 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000139 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000140 FunctionMemory.push_back(MB);
141 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000142}
143
144uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
145 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000146 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000147 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000148 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000149 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000150 DataMemory.push_back(MB);
151 return (uint8_t*)MB.base();
152}
153
154void TrivialMemoryManager::invalidateInstructionCache() {
155 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
156 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
157 FunctionMemory[i].size());
158
159 for (int i = 0, e = DataMemory.size(); i != e; ++i)
160 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
161 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000162}
163
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000164static const char *ProgramName;
165
166static void Message(const char *Type, const Twine &Msg) {
167 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
168}
169
170static int Error(const Twine &Msg) {
171 Message("error", Msg);
172 return 1;
173}
174
Lang Hamesd311c0e2014-05-13 22:37:41 +0000175static void loadDylibs() {
176 for (const std::string &Dylib : Dylibs) {
177 if (sys::fs::is_regular_file(Dylib)) {
178 std::string ErrMsg;
179 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
180 llvm::errs() << "Error loading '" << Dylib << "': "
181 << ErrMsg << "\n";
182 } else
183 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
184 }
185}
186
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000187/* *** */
188
Andrew Kaylord55d7012013-01-25 22:50:58 +0000189static int printLineInfoForInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000190 // Load any dylibs requested on the command line.
191 loadDylibs();
192
Andrew Kaylord55d7012013-01-25 22:50:58 +0000193 // If we don't have any input files, read from stdin.
194 if (!InputFileList.size())
195 InputFileList.push_back("-");
196 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
197 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000198 TrivialMemoryManager MemMgr;
199 RuntimeDyld Dyld(&MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000200
201 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000202
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000203 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
204 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
205 if (std::error_code EC = InputBuffer.getError())
206 return Error("unable to read input: '" + EC.message() + "'");
207
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000208 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
209 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
210
211 if (std::error_code EC = MaybeObj.getError())
212 return Error("unable to create object file: '" + EC.message() + "'");
213
214 ObjectFile &Obj = **MaybeObj;
215
Andrew Kaylord55d7012013-01-25 22:50:58 +0000216 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000217 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo =
218 Dyld.loadObject(Obj);
219
220 if (Dyld.hasError())
Andrew Kaylord55d7012013-01-25 22:50:58 +0000221 return Error(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000222
223 // Resolve all the relocations we can.
224 Dyld.resolveRelocations();
225
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000226 OwningBinary<ObjectFile> DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
227
Ahmed Charles56440fd2014-03-06 05:51:42 +0000228 std::unique_ptr<DIContext> Context(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000229 DIContext::getDWARFContext(*DebugObj.getBinary()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000230
231 // Use symbol info to iterate functions in the object.
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000232 for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
233 E = DebugObj.getBinary()->symbol_end();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000234 I != E; ++I) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000235 object::SymbolRef::Type SymType;
236 if (I->getType(SymType)) continue;
237 if (SymType == object::SymbolRef::ST_Function) {
238 StringRef Name;
239 uint64_t Addr;
240 uint64_t Size;
241 if (I->getName(Name)) continue;
242 if (I->getAddress(Addr)) continue;
243 if (I->getSize(Size)) continue;
244
245 outs() << "Function: " << Name << ", Size = " << Size << "\n";
246
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000247 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
248 DILineInfoTable::iterator Begin = Lines.begin();
249 DILineInfoTable::iterator End = Lines.end();
250 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
251 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000252 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000253 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000254 }
255 }
256 }
257
258 return 0;
259}
260
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000261static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000262 // Load any dylibs requested on the command line.
263 loadDylibs();
264
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000265 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000266 TrivialMemoryManager MemMgr;
267 RuntimeDyld Dyld(&MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000268
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000269 // If we don't have any input files, read from stdin.
270 if (!InputFileList.size())
271 InputFileList.push_back("-");
272 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
273 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000274 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
275 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
276 if (std::error_code EC = InputBuffer.getError())
277 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000278 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
279 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
280
281 if (std::error_code EC = MaybeObj.getError())
282 return Error("unable to create object file: '" + EC.message() + "'");
283
284 ObjectFile &Obj = **MaybeObj;
285
Andrew Kayloradc70562012-10-02 21:18:39 +0000286 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000287 Dyld.loadObject(Obj);
288 if (Dyld.hasError()) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000289 return Error(Dyld.getErrorString());
290 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000291 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000292
Jim Grosbach733d3052011-04-12 21:20:41 +0000293 // Resolve all the relocations we can.
294 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000295 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000296 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000297
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000298 // FIXME: Error out if there are unresolved relocations.
299
Jim Grosbachd35159a2011-04-13 15:38:30 +0000300 // Get the address of the entry point (_main by default).
301 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000302 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000303 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000304
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000305 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000306 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
307 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000308 // Make sure the memory is executable.
309 std::string ErrorStr;
310 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
311 if (!sys::Memory::setExecutable(Data, &ErrorStr))
312 return Error("unable to mark function executable: '" + ErrorStr + "'");
313 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000314
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000315 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000316 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000317
318 int (*Main)(int, const char**) =
319 (int(*)(int,const char**)) uintptr_t(MainAddress);
320 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000321 // Use the name of the first input object module as argv[0] for the target.
322 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000323 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000324 return Main(1, Argv);
325}
326
Lang Hamese1c11382014-06-27 20:20:57 +0000327static int checkAllExpressions(RuntimeDyldChecker &Checker) {
328 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000329 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
330 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
331 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hamese1c11382014-06-27 20:20:57 +0000332 return Error("unable to read input '" + CheckerFileName + "': " +
333 EC.message());
334
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000335 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
336 CheckerFileBuf.get().get()))
Lang Hamese1c11382014-06-27 20:20:57 +0000337 return Error("some checks in '" + CheckerFileName + "' failed");
338 }
339 return 0;
340}
341
Lang Hames778ef5b2014-09-04 04:19:54 +0000342std::map<void*, uint64_t>
343applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
344
345 std::map<void*, uint64_t> SpecificMappings;
346
347 for (StringRef Mapping : SpecificSectionMappings) {
348
349 size_t EqualsIdx = Mapping.find_first_of("=");
350 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
351 size_t ComaIdx = Mapping.find_first_of(",");
352
353 if (ComaIdx == StringRef::npos) {
354 errs() << "Invalid section specification '" << Mapping
355 << "'. Should be '<file name>,<section name>=<addr>'\n";
356 exit(1);
357 }
358
359 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
360 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
361
362 uint64_t OldAddrInt;
363 std::string ErrorMsg;
364 std::tie(OldAddrInt, ErrorMsg) =
365 Checker.getSectionAddr(FileName, SectionName, true);
366
367 if (ErrorMsg != "") {
368 errs() << ErrorMsg;
369 exit(1);
370 }
371
372 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
373
374 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
375 uint64_t NewAddr;
376
377 if (NewAddrStr.getAsInteger(0, NewAddr)) {
378 errs() << "Invalid section address in mapping: " << Mapping << "\n";
379 exit(1);
380 }
381
382 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
383 SpecificMappings[OldAddr] = NewAddr;
384 }
385
386 return SpecificMappings;
387}
388
Lang Hames9cb73532014-07-29 23:43:13 +0000389// Scatter sections in all directions!
390// Remaps section addresses for -verify mode. The following command line options
391// can be used to customize the layout of the memory within the phony target's
392// address space:
393// -target-addr-start <s> -- Specify where the phony target addres range starts.
394// -target-addr-end <e> -- Specify where the phony target address range ends.
395// -target-section-sep <d> -- Specify how big a gap should be left between the
396// end of one section and the start of the next.
397// Defaults to zero. Set to something big
398// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
399//
400void remapSections(const llvm::Triple &TargetTriple,
401 const TrivialMemoryManager &MemMgr,
Lang Hames778ef5b2014-09-04 04:19:54 +0000402 RuntimeDyldChecker &Checker) {
403
404 // Set up a work list (section addr/size pairs).
405 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
406 WorklistT Worklist;
407
408 for (const auto& CodeSection : MemMgr.FunctionMemory)
409 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
410 for (const auto& DataSection : MemMgr.DataMemory)
411 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
412
413 // Apply any section-specific mappings that were requested on the command
414 // line.
415 typedef std::map<void*, uint64_t> AppliedMappingsT;
416 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
417
418 // Keep an "already allocated" mapping of section target addresses to sizes.
419 // Sections whose address mappings aren't specified on the command line will
420 // allocated around the explicitly mapped sections while maintaining the
421 // minimum separation.
422 std::map<uint64_t, uint64_t> AlreadyAllocated;
423
424 // Move the previously applied mappings into the already-allocated map.
425 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
426 I != E;) {
427 WorklistT::iterator Tmp = I;
428 ++I;
429 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
430
431 if (AI != AppliedMappings.end()) {
432 AlreadyAllocated[AI->second] = Tmp->second;
433 Worklist.erase(Tmp);
434 }
435 }
Lang Hames9cb73532014-07-29 23:43:13 +0000436
437 // If the -target-addr-end option wasn't explicitly passed, then set it to a
438 // sensible default based on the target triple.
439 if (TargetAddrEnd.getNumOccurrences() == 0) {
440 if (TargetTriple.isArch16Bit())
441 TargetAddrEnd = (1ULL << 16) - 1;
442 else if (TargetTriple.isArch32Bit())
443 TargetAddrEnd = (1ULL << 32) - 1;
444 // TargetAddrEnd already has a sensible default for 64-bit systems, so
445 // there's nothing to do in the 64-bit case.
446 }
447
Lang Hames778ef5b2014-09-04 04:19:54 +0000448 // Process any elements remaining in the worklist.
449 while (!Worklist.empty()) {
450 std::pair<void*, uint64_t> CurEntry = Worklist.front();
451 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000452
Lang Hames778ef5b2014-09-04 04:19:54 +0000453 uint64_t NextSectionAddr = TargetAddrStart;
454
455 for (const auto &Alloc : AlreadyAllocated)
456 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
457 break;
458 else
459 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
460
461 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
462 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000463 }
464
Lang Hames9cb73532014-07-29 23:43:13 +0000465}
466
467// Load and link the objects specified on the command line, but do not execute
468// anything. Instead, attach a RuntimeDyldChecker instance and call it to
469// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000470static int linkAndVerify() {
471
472 // Check for missing triple.
473 if (TripleName == "") {
474 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
475 return 1;
476 }
477
478 // Look up the target and build the disassembler.
479 Triple TheTriple(Triple::normalize(TripleName));
480 std::string ErrorStr;
481 const Target *TheTarget =
482 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
483 if (!TheTarget) {
484 llvm::errs() << "Error accessing target '" << TripleName << "': "
485 << ErrorStr << "\n";
486 return 1;
487 }
488 TripleName = TheTriple.getTriple();
489
490 std::unique_ptr<MCSubtargetInfo> STI(
491 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
492 assert(STI && "Unable to create subtarget info!");
493
494 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
495 assert(MRI && "Unable to create target register info!");
496
497 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
498 assert(MAI && "Unable to create target asm info!");
499
500 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
501
502 std::unique_ptr<MCDisassembler> Disassembler(
503 TheTarget->createMCDisassembler(*STI, Ctx));
504 assert(Disassembler && "Unable to create disassembler!");
505
506 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
507
508 std::unique_ptr<MCInstPrinter> InstPrinter(
509 TheTarget->createMCInstPrinter(0, *MAI, *MII, *MRI, *STI));
510
511 // Load any dylibs requested on the command line.
512 loadDylibs();
513
514 // Instantiate a dynamic linker.
515 TrivialMemoryManager MemMgr;
516 RuntimeDyld Dyld(&MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000517 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000518 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
519 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000520
521 // If we don't have any input files, read from stdin.
522 if (!InputFileList.size())
523 InputFileList.push_back("-");
524 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
525 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000526 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
527 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000528
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000529 if (std::error_code EC = InputBuffer.getError())
530 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000531
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000532 ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
533 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
534
535 if (std::error_code EC = MaybeObj.getError())
536 return Error("unable to create object file: '" + EC.message() + "'");
537
538 ObjectFile &Obj = **MaybeObj;
539
Lang Hamese1c11382014-06-27 20:20:57 +0000540 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000541 Dyld.loadObject(Obj);
542 if (Dyld.hasError()) {
Lang Hamese1c11382014-06-27 20:20:57 +0000543 return Error(Dyld.getErrorString());
544 }
545 }
546
Lang Hames375385f2014-07-30 03:12:41 +0000547 // Re-map the section addresses into the phony target address space.
Lang Hames778ef5b2014-09-04 04:19:54 +0000548 remapSections(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000549
Lang Hamese1c11382014-06-27 20:20:57 +0000550 // Resolve all the relocations we can.
551 Dyld.resolveRelocations();
552
Lang Hames925e51b2014-09-03 05:42:52 +0000553 // Register EH frames.
554 Dyld.registerEHFrames();
555
Lang Hamesae172682014-08-05 20:51:46 +0000556 int ErrorCode = checkAllExpressions(Checker);
557 if (Dyld.hasError()) {
558 errs() << "RTDyld reported an error applying relocations:\n "
559 << Dyld.getErrorString() << "\n";
560 ErrorCode = 1;
561 }
562
563 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000564}
565
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000566int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000567 sys::PrintStackTraceOnErrorSignal();
568 PrettyStackTraceProgram X(argc, argv);
569
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000570 ProgramName = argv[0];
571 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
572
Lang Hamese1c11382014-06-27 20:20:57 +0000573 llvm::InitializeAllTargetInfos();
574 llvm::InitializeAllTargetMCs();
575 llvm::InitializeAllDisassemblers();
576
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000577 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
578
579 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000580 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000581 return executeInput();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000582 case AC_PrintLineInfo:
583 return printLineInfoForInput();
Lang Hamese1c11382014-06-27 20:20:57 +0000584 case AC_Verify:
585 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000586 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000587}