blob: 87d381e994fdce7983336cf6e35459ad2013d52a [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"
Andrew Kayloradc70562012-10-02 21:18:39 +000016#include "llvm/ExecutionEngine/ObjectBuffer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ExecutionEngine/ObjectImage.h"
18#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"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCInstPrinter.h"
25#include "llvm/MC/MCRegisterInfo.h"
Rafael Espindola6e040c02013-04-26 20:07:33 +000026#include "llvm/Object/MachO.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000027#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000028#include "llvm/Support/DynamicLibrary.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000029#include "llvm/Support/ManagedStatic.h"
30#include "llvm/Support/Memory.h"
31#include "llvm/Support/MemoryBuffer.h"
Alp Toker9f679322013-11-05 09:33:43 +000032#include "llvm/Support/PrettyStackTrace.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000033#include "llvm/Support/raw_ostream.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"
Lang Hames778ef5b2014-09-04 04:19:54 +000037#include <list>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000038#include <system_error>
Lang Hamese1c11382014-06-27 20:20:57 +000039
Jim Grosbach0072cdb2011-03-18 17:11:39 +000040using namespace llvm;
41using namespace llvm::object;
42
Jim Grosbach7cb41d72011-04-13 15:49:40 +000043static cl::list<std::string>
44InputFileList(cl::Positional, cl::ZeroOrMore,
45 cl::desc("<input file>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000046
47enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000048 AC_Execute,
Lang Hamese1c11382014-06-27 20:20:57 +000049 AC_PrintLineInfo,
50 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000051};
52
53static cl::opt<ActionType>
54Action(cl::desc("Action to perform:"),
55 cl::init(AC_Execute),
56 cl::values(clEnumValN(AC_Execute, "execute",
57 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000058 clEnumValN(AC_PrintLineInfo, "printline",
59 "Load, link, and print line information for each function."),
Lang Hamese1c11382014-06-27 20:20:57 +000060 clEnumValN(AC_Verify, "verify",
61 "Load, link and verify the resulting memory image."),
Jim Grosbach0072cdb2011-03-18 17:11:39 +000062 clEnumValEnd));
63
Jim Grosbachd35159a2011-04-13 15:38:30 +000064static cl::opt<std::string>
65EntryPoint("entry",
66 cl::desc("Function to call as entry point."),
67 cl::init("_main"));
68
Lang Hamesd311c0e2014-05-13 22:37:41 +000069static cl::list<std::string>
70Dylibs("dylib",
71 cl::desc("Add library."),
72 cl::ZeroOrMore);
73
Lang Hamese1c11382014-06-27 20:20:57 +000074static cl::opt<std::string>
75TripleName("triple", cl::desc("Target triple for disassembler"));
76
77static cl::list<std::string>
78CheckFiles("check",
79 cl::desc("File containing RuntimeDyld verifier checks."),
80 cl::ZeroOrMore);
81
Lang Hames9cb73532014-07-29 23:43:13 +000082static cl::opt<uint64_t>
83TargetAddrStart("target-addr-start",
84 cl::desc("For -verify only: start of phony target address "
85 "range."),
86 cl::init(4096), // Start at "page 1" - no allocating at "null".
87 cl::Hidden);
88
89static cl::opt<uint64_t>
90TargetAddrEnd("target-addr-end",
91 cl::desc("For -verify only: end of phony target address range."),
92 cl::init(~0ULL),
93 cl::Hidden);
94
95static cl::opt<uint64_t>
96TargetSectionSep("target-section-sep",
97 cl::desc("For -verify only: Separation between sections in "
98 "phony target address space."),
99 cl::init(0),
100 cl::Hidden);
101
Lang Hames778ef5b2014-09-04 04:19:54 +0000102static cl::list<std::string>
103SpecificSectionMappings("map-section",
104 cl::desc("Map a section to a specific address."),
105 cl::ZeroOrMore);
106
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000107/* *** */
108
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000109// A trivial memory manager that doesn't do anything fancy, just uses the
110// support library allocation routines directly.
111class TrivialMemoryManager : public RTDyldMemoryManager {
112public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000113 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000114 SmallVector<sys::MemoryBlock, 16> DataMemory;
115
116 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000117 unsigned SectionID,
118 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000119 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000120 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000121 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000122
Craig Toppere56917c2014-03-08 08:27:28 +0000123 void *getPointerToNamedFunction(const std::string &Name,
124 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000125 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000126 }
127
Craig Toppere56917c2014-03-08 08:27:28 +0000128 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000129
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000130 // Invalidate instruction cache for sections with execute permissions.
131 // Some platforms with separate data cache and instruction cache require
132 // explicit cache flush, otherwise JIT code manipulations (like resolved
133 // relocations) will get to the data cache but not to the instruction cache.
134 virtual void invalidateInstructionCache();
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000135};
136
Jim Grosbacheff0a402012-01-16 22:26:39 +0000137uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
138 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000139 unsigned SectionID,
140 StringRef SectionName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000141 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000142 FunctionMemory.push_back(MB);
143 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000144}
145
146uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
147 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000148 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000149 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000150 bool IsReadOnly) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000151 sys::MemoryBlock MB = sys::Memory::AllocateRWX(Size, nullptr, nullptr);
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000152 DataMemory.push_back(MB);
153 return (uint8_t*)MB.base();
154}
155
156void TrivialMemoryManager::invalidateInstructionCache() {
157 for (int i = 0, e = FunctionMemory.size(); i != e; ++i)
158 sys::Memory::InvalidateInstructionCache(FunctionMemory[i].base(),
159 FunctionMemory[i].size());
160
161 for (int i = 0, e = DataMemory.size(); i != e; ++i)
162 sys::Memory::InvalidateInstructionCache(DataMemory[i].base(),
163 DataMemory[i].size());
Jim Grosbacheff0a402012-01-16 22:26:39 +0000164}
165
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000166static const char *ProgramName;
167
168static void Message(const char *Type, const Twine &Msg) {
169 errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
170}
171
172static int Error(const Twine &Msg) {
173 Message("error", Msg);
174 return 1;
175}
176
Lang Hamesd311c0e2014-05-13 22:37:41 +0000177static void loadDylibs() {
178 for (const std::string &Dylib : Dylibs) {
179 if (sys::fs::is_regular_file(Dylib)) {
180 std::string ErrMsg;
181 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
182 llvm::errs() << "Error loading '" << Dylib << "': "
183 << ErrMsg << "\n";
184 } else
185 llvm::errs() << "Dylib not found: '" << Dylib << "'.\n";
186 }
187}
188
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000189/* *** */
190
Andrew Kaylord55d7012013-01-25 22:50:58 +0000191static int printLineInfoForInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000192 // Load any dylibs requested on the command line.
193 loadDylibs();
194
Andrew Kaylord55d7012013-01-25 22:50:58 +0000195 // If we don't have any input files, read from stdin.
196 if (!InputFileList.size())
197 InputFileList.push_back("-");
198 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
199 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000200 TrivialMemoryManager MemMgr;
201 RuntimeDyld Dyld(&MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000202
203 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000204
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000205 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
206 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
207 if (std::error_code EC = InputBuffer.getError())
208 return Error("unable to read input: '" + EC.message() + "'");
209
210 std::unique_ptr<ObjectImage> LoadedObject;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000211 // Load the object file
David Blaikieed9709d2014-09-03 19:48:09 +0000212 LoadedObject = Dyld.loadObject(
213 llvm::make_unique<ObjectBuffer>(std::move(*InputBuffer)));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000214 if (!LoadedObject) {
215 return Error(Dyld.getErrorString());
216 }
217
218 // Resolve all the relocations we can.
219 Dyld.resolveRelocations();
220
Ahmed Charles56440fd2014-03-06 05:51:42 +0000221 std::unique_ptr<DIContext> Context(
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +0000222 DIContext::getDWARFContext(*LoadedObject->getObjectFile()));
Andrew Kaylord55d7012013-01-25 22:50:58 +0000223
224 // Use symbol info to iterate functions in the object.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000225 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
226 E = LoadedObject->end_symbols();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000227 I != E; ++I) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000228 object::SymbolRef::Type SymType;
229 if (I->getType(SymType)) continue;
230 if (SymType == object::SymbolRef::ST_Function) {
231 StringRef Name;
232 uint64_t Addr;
233 uint64_t Size;
234 if (I->getName(Name)) continue;
235 if (I->getAddress(Addr)) continue;
236 if (I->getSize(Size)) continue;
237
238 outs() << "Function: " << Name << ", Size = " << Size << "\n";
239
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000240 DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
241 DILineInfoTable::iterator Begin = Lines.begin();
242 DILineInfoTable::iterator End = Lines.end();
243 for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
244 outs() << " Line info @ " << It->first - Addr << ": "
Alexey Samsonovd0109992014-04-18 21:36:39 +0000245 << It->second.FileName << ", line:" << It->second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000246 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000247 }
248 }
249 }
250
251 return 0;
252}
253
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000254static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000255 // Load any dylibs requested on the command line.
256 loadDylibs();
257
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000258 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000259 TrivialMemoryManager MemMgr;
260 RuntimeDyld Dyld(&MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000261
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000262 // If we don't have any input files, read from stdin.
263 if (!InputFileList.size())
264 InputFileList.push_back("-");
265 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
266 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000267 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
268 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
269 if (std::error_code EC = InputBuffer.getError())
270 return Error("unable to read input: '" + EC.message() + "'");
Ahmed Charles56440fd2014-03-06 05:51:42 +0000271 std::unique_ptr<ObjectImage> LoadedObject;
Andrew Kayloradc70562012-10-02 21:18:39 +0000272 // Load the object file
David Blaikieed9709d2014-09-03 19:48:09 +0000273 LoadedObject = Dyld.loadObject(
274 llvm::make_unique<ObjectBuffer>(std::move(*InputBuffer)));
Andrew Kayloradc70562012-10-02 21:18:39 +0000275 if (!LoadedObject) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000276 return Error(Dyld.getErrorString());
277 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000278 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000279
Jim Grosbach733d3052011-04-12 21:20:41 +0000280 // Resolve all the relocations we can.
281 Dyld.resolveRelocations();
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000282 // Clear instruction cache before code will be executed.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000283 MemMgr.invalidateInstructionCache();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000284
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000285 // FIXME: Error out if there are unresolved relocations.
286
Jim Grosbachd35159a2011-04-13 15:38:30 +0000287 // Get the address of the entry point (_main by default).
288 void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000289 if (!MainAddress)
Jim Grosbachd35159a2011-04-13 15:38:30 +0000290 return Error("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000291
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000292 // Invalidate the instruction cache for each loaded function.
Benjamin Kramer5d62ad22013-08-03 22:18:45 +0000293 for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
294 sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000295 // Make sure the memory is executable.
296 std::string ErrorStr;
297 sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
298 if (!sys::Memory::setExecutable(Data, &ErrorStr))
299 return Error("unable to mark function executable: '" + ErrorStr + "'");
300 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000301
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000302 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000303 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000304
305 int (*Main)(int, const char**) =
306 (int(*)(int,const char**)) uintptr_t(MainAddress);
307 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000308 // Use the name of the first input object module as argv[0] for the target.
309 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000310 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000311 return Main(1, Argv);
312}
313
Lang Hamese1c11382014-06-27 20:20:57 +0000314static int checkAllExpressions(RuntimeDyldChecker &Checker) {
315 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000316 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
317 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
318 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hamese1c11382014-06-27 20:20:57 +0000319 return Error("unable to read input '" + CheckerFileName + "': " +
320 EC.message());
321
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000322 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
323 CheckerFileBuf.get().get()))
Lang Hamese1c11382014-06-27 20:20:57 +0000324 return Error("some checks in '" + CheckerFileName + "' failed");
325 }
326 return 0;
327}
328
Lang Hames778ef5b2014-09-04 04:19:54 +0000329std::map<void*, uint64_t>
330applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
331
332 std::map<void*, uint64_t> SpecificMappings;
333
334 for (StringRef Mapping : SpecificSectionMappings) {
335
336 size_t EqualsIdx = Mapping.find_first_of("=");
337 StringRef SectionIDStr = Mapping.substr(0, EqualsIdx);
338 size_t ComaIdx = Mapping.find_first_of(",");
339
340 if (ComaIdx == StringRef::npos) {
341 errs() << "Invalid section specification '" << Mapping
342 << "'. Should be '<file name>,<section name>=<addr>'\n";
343 exit(1);
344 }
345
346 StringRef FileName = SectionIDStr.substr(0, ComaIdx);
347 StringRef SectionName = SectionIDStr.substr(ComaIdx + 1);
348
349 uint64_t OldAddrInt;
350 std::string ErrorMsg;
351 std::tie(OldAddrInt, ErrorMsg) =
352 Checker.getSectionAddr(FileName, SectionName, true);
353
354 if (ErrorMsg != "") {
355 errs() << ErrorMsg;
356 exit(1);
357 }
358
359 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
360
361 StringRef NewAddrStr = Mapping.substr(EqualsIdx + 1);
362 uint64_t NewAddr;
363
364 if (NewAddrStr.getAsInteger(0, NewAddr)) {
365 errs() << "Invalid section address in mapping: " << Mapping << "\n";
366 exit(1);
367 }
368
369 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
370 SpecificMappings[OldAddr] = NewAddr;
371 }
372
373 return SpecificMappings;
374}
375
Lang Hames9cb73532014-07-29 23:43:13 +0000376// Scatter sections in all directions!
377// Remaps section addresses for -verify mode. The following command line options
378// can be used to customize the layout of the memory within the phony target's
379// address space:
380// -target-addr-start <s> -- Specify where the phony target addres range starts.
381// -target-addr-end <e> -- Specify where the phony target address range ends.
382// -target-section-sep <d> -- Specify how big a gap should be left between the
383// end of one section and the start of the next.
384// Defaults to zero. Set to something big
385// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
386//
387void remapSections(const llvm::Triple &TargetTriple,
388 const TrivialMemoryManager &MemMgr,
Lang Hames778ef5b2014-09-04 04:19:54 +0000389 RuntimeDyldChecker &Checker) {
390
391 // Set up a work list (section addr/size pairs).
392 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
393 WorklistT Worklist;
394
395 for (const auto& CodeSection : MemMgr.FunctionMemory)
396 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
397 for (const auto& DataSection : MemMgr.DataMemory)
398 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
399
400 // Apply any section-specific mappings that were requested on the command
401 // line.
402 typedef std::map<void*, uint64_t> AppliedMappingsT;
403 AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
404
405 // Keep an "already allocated" mapping of section target addresses to sizes.
406 // Sections whose address mappings aren't specified on the command line will
407 // allocated around the explicitly mapped sections while maintaining the
408 // minimum separation.
409 std::map<uint64_t, uint64_t> AlreadyAllocated;
410
411 // Move the previously applied mappings into the already-allocated map.
412 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
413 I != E;) {
414 WorklistT::iterator Tmp = I;
415 ++I;
416 AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
417
418 if (AI != AppliedMappings.end()) {
419 AlreadyAllocated[AI->second] = Tmp->second;
420 Worklist.erase(Tmp);
421 }
422 }
Lang Hames9cb73532014-07-29 23:43:13 +0000423
424 // If the -target-addr-end option wasn't explicitly passed, then set it to a
425 // sensible default based on the target triple.
426 if (TargetAddrEnd.getNumOccurrences() == 0) {
427 if (TargetTriple.isArch16Bit())
428 TargetAddrEnd = (1ULL << 16) - 1;
429 else if (TargetTriple.isArch32Bit())
430 TargetAddrEnd = (1ULL << 32) - 1;
431 // TargetAddrEnd already has a sensible default for 64-bit systems, so
432 // there's nothing to do in the 64-bit case.
433 }
434
Lang Hames778ef5b2014-09-04 04:19:54 +0000435 // Process any elements remaining in the worklist.
436 while (!Worklist.empty()) {
437 std::pair<void*, uint64_t> CurEntry = Worklist.front();
438 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000439
Lang Hames778ef5b2014-09-04 04:19:54 +0000440 uint64_t NextSectionAddr = TargetAddrStart;
441
442 for (const auto &Alloc : AlreadyAllocated)
443 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
444 break;
445 else
446 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
447
448 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
449 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000450 }
451
Lang Hames9cb73532014-07-29 23:43:13 +0000452}
453
454// Load and link the objects specified on the command line, but do not execute
455// anything. Instead, attach a RuntimeDyldChecker instance and call it to
456// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000457static int linkAndVerify() {
458
459 // Check for missing triple.
460 if (TripleName == "") {
461 llvm::errs() << "Error: -triple required when running in -verify mode.\n";
462 return 1;
463 }
464
465 // Look up the target and build the disassembler.
466 Triple TheTriple(Triple::normalize(TripleName));
467 std::string ErrorStr;
468 const Target *TheTarget =
469 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
470 if (!TheTarget) {
471 llvm::errs() << "Error accessing target '" << TripleName << "': "
472 << ErrorStr << "\n";
473 return 1;
474 }
475 TripleName = TheTriple.getTriple();
476
477 std::unique_ptr<MCSubtargetInfo> STI(
478 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
479 assert(STI && "Unable to create subtarget info!");
480
481 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
482 assert(MRI && "Unable to create target register info!");
483
484 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
485 assert(MAI && "Unable to create target asm info!");
486
487 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
488
489 std::unique_ptr<MCDisassembler> Disassembler(
490 TheTarget->createMCDisassembler(*STI, Ctx));
491 assert(Disassembler && "Unable to create disassembler!");
492
493 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
494
495 std::unique_ptr<MCInstPrinter> InstPrinter(
496 TheTarget->createMCInstPrinter(0, *MAI, *MII, *MRI, *STI));
497
498 // Load any dylibs requested on the command line.
499 loadDylibs();
500
501 // Instantiate a dynamic linker.
502 TrivialMemoryManager MemMgr;
503 RuntimeDyld Dyld(&MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000504 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000505 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
506 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000507
508 // If we don't have any input files, read from stdin.
509 if (!InputFileList.size())
510 InputFileList.push_back("-");
511 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
512 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000513 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
514 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
515 if (std::error_code EC = InputBuffer.getError())
516 return Error("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000517
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000518 std::unique_ptr<ObjectImage> LoadedObject;
Lang Hamese1c11382014-06-27 20:20:57 +0000519 // Load the object file
David Blaikieed9709d2014-09-03 19:48:09 +0000520 LoadedObject = Dyld.loadObject(
521 llvm::make_unique<ObjectBuffer>(std::move(*InputBuffer)));
Lang Hamese1c11382014-06-27 20:20:57 +0000522 if (!LoadedObject) {
523 return Error(Dyld.getErrorString());
524 }
525 }
526
Lang Hames375385f2014-07-30 03:12:41 +0000527 // Re-map the section addresses into the phony target address space.
Lang Hames778ef5b2014-09-04 04:19:54 +0000528 remapSections(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000529
Lang Hamese1c11382014-06-27 20:20:57 +0000530 // Resolve all the relocations we can.
531 Dyld.resolveRelocations();
532
Lang Hames925e51b2014-09-03 05:42:52 +0000533 // Register EH frames.
534 Dyld.registerEHFrames();
535
Lang Hamesae172682014-08-05 20:51:46 +0000536 int ErrorCode = checkAllExpressions(Checker);
537 if (Dyld.hasError()) {
538 errs() << "RTDyld reported an error applying relocations:\n "
539 << Dyld.getErrorString() << "\n";
540 ErrorCode = 1;
541 }
542
543 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000544}
545
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000546int main(int argc, char **argv) {
Alp Toker9f679322013-11-05 09:33:43 +0000547 sys::PrintStackTraceOnErrorSignal();
548 PrettyStackTraceProgram X(argc, argv);
549
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000550 ProgramName = argv[0];
551 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
552
Lang Hamese1c11382014-06-27 20:20:57 +0000553 llvm::InitializeAllTargetInfos();
554 llvm::InitializeAllTargetMCs();
555 llvm::InitializeAllDisassemblers();
556
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000557 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
558
559 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000560 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000561 return executeInput();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000562 case AC_PrintLineInfo:
563 return printLineInfoForInput();
Lang Hamese1c11382014-06-27 20:20:57 +0000564 case AC_Verify:
565 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000566 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000567}