blob: 69d70e948081e39e6b9fc7d7e51ff870ca8aa38a [file] [log] [blame]
Jim Grosbach0072cdb2011-03-18 17:11:39 +00001//===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jim Grosbach0072cdb2011-03-18 17:11:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This is a testing tool for use with the MC-JIT LLVM components.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000013#include "llvm/ADT/StringMap.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000014#include "llvm/DebugInfo/DIContext.h"
15#include "llvm/DebugInfo/DWARF/DWARFContext.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"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000021#include "llvm/MC/MCDisassembler/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"
Pete Cooper3de83e42015-05-15 21:58:42 +000025#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindolab109c032015-06-23 02:08:48 +000026#include "llvm/Object/SymbolSize.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"
Rui Ueyama197194b2018-04-13 18:26:06 +000029#include "llvm/Support/InitLLVM.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000030#include "llvm/Support/Memory.h"
31#include "llvm/Support/MemoryBuffer.h"
Lang Hamese1c11382014-06-27 20:20:57 +000032#include "llvm/Support/TargetRegistry.h"
33#include "llvm/Support/TargetSelect.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000034#include "llvm/Support/raw_ostream.h"
Lang Hames778ef5b2014-09-04 04:19:54 +000035#include <list>
Lang Hamese1c11382014-06-27 20:20:57 +000036
Jim Grosbach0072cdb2011-03-18 17:11:39 +000037using namespace llvm;
38using namespace llvm::object;
39
Jim Grosbach7cb41d72011-04-13 15:49:40 +000040static cl::list<std::string>
41InputFileList(cl::Positional, cl::ZeroOrMore,
Lang Hames9c755452018-03-31 16:01:01 +000042 cl::desc("<input files>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000043
44enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000045 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000046 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000047 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000048 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000049 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."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000059 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
60 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000061 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
62 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000063 clEnumValN(AC_Verify, "verify",
Mehdi Amini732afdd2016-10-08 19:41:06 +000064 "Load, link and verify the resulting memory image.")));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000065
Jim Grosbachd35159a2011-04-13 15:38:30 +000066static cl::opt<std::string>
67EntryPoint("entry",
68 cl::desc("Function to call as entry point."),
69 cl::init("_main"));
70
Lang Hamesd311c0e2014-05-13 22:37:41 +000071static cl::list<std::string>
72Dylibs("dylib",
73 cl::desc("Add library."),
74 cl::ZeroOrMore);
75
Lang Hamese1c11382014-06-27 20:20:57 +000076static cl::opt<std::string>
77TripleName("triple", cl::desc("Target triple for disassembler"));
78
Petar Jovanovic280e5622015-06-23 22:52:19 +000079static cl::opt<std::string>
80MCPU("mcpu",
81 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
82 cl::value_desc("cpu-name"),
83 cl::init(""));
84
Lang Hamese1c11382014-06-27 20:20:57 +000085static cl::list<std::string>
86CheckFiles("check",
87 cl::desc("File containing RuntimeDyld verifier checks."),
88 cl::ZeroOrMore);
89
Lang Hames776f1d52018-10-23 01:36:33 +000090// Tracking BUG: 19665
91// http://llvm.org/bugs/show_bug.cgi?id=19665
92//
93// Do not change these options to cl::opt<uint64_t> since this silently breaks
94// argument parsing.
95static cl::opt<unsigned long long>
Davide Italianob59ea902015-10-21 22:12:03 +000096PreallocMemory("preallocate",
97 cl::desc("Allocate memory upfront rather than on-demand"),
98 cl::init(0));
99
Lang Hames776f1d52018-10-23 01:36:33 +0000100static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000101TargetAddrStart("target-addr-start",
102 cl::desc("For -verify only: start of phony target address "
103 "range."),
104 cl::init(4096), // Start at "page 1" - no allocating at "null".
105 cl::Hidden);
106
Lang Hames776f1d52018-10-23 01:36:33 +0000107static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000108TargetAddrEnd("target-addr-end",
109 cl::desc("For -verify only: end of phony target address range."),
110 cl::init(~0ULL),
111 cl::Hidden);
112
Lang Hames776f1d52018-10-23 01:36:33 +0000113static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000114TargetSectionSep("target-section-sep",
115 cl::desc("For -verify only: Separation between sections in "
116 "phony target address space."),
117 cl::init(0),
118 cl::Hidden);
119
Lang Hames778ef5b2014-09-04 04:19:54 +0000120static cl::list<std::string>
121SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000122 cl::desc("For -verify only: Map a section to a "
123 "specific address."),
124 cl::ZeroOrMore,
125 cl::Hidden);
126
127static cl::list<std::string>
128DummySymbolMappings("dummy-extern",
129 cl::desc("For -verify only: Inject a symbol into the extern "
130 "symbol table."),
131 cl::ZeroOrMore,
132 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000133
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000134static cl::opt<bool>
135PrintAllocationRequests("print-alloc-requests",
136 cl::desc("Print allocation requests made to the memory "
137 "manager by RuntimeDyld"),
138 cl::Hidden);
139
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000140/* *** */
141
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000142// A trivial memory manager that doesn't do anything fancy, just uses the
143// support library allocation routines directly.
144class TrivialMemoryManager : public RTDyldMemoryManager {
145public:
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000146 SmallVector<sys::MemoryBlock, 16> FunctionMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000147 SmallVector<sys::MemoryBlock, 16> DataMemory;
148
149 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000150 unsigned SectionID,
151 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000152 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000153 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000154 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000155
Craig Toppere56917c2014-03-08 08:27:28 +0000156 void *getPointerToNamedFunction(const std::string &Name,
157 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000158 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000159 }
160
Craig Toppere56917c2014-03-08 08:27:28 +0000161 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000162
Lang Hames78937c22015-07-04 01:35:26 +0000163 void addDummySymbol(const std::string &Name, uint64_t Addr) {
164 DummyExterns[Name] = Addr;
165 }
166
Lang Hamesad4a9112016-08-01 20:49:11 +0000167 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000168 auto I = DummyExterns.find(Name);
169
170 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000171 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000172
173 return RTDyldMemoryManager::findSymbol(Name);
174 }
175
Tim Northover5af339a2015-06-03 18:26:52 +0000176 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
177 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000178 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000179
180 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000181 std::error_code EC;
182 sys::MemoryBlock MB =
183 sys::Memory::allocateMappedMemory(Size, nullptr,
184 sys::Memory::MF_READ |
185 sys::Memory::MF_WRITE,
186 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000187 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000188 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000189
190 PreallocSlab = MB;
191 UsePreallocation = true;
192 SlabSize = Size;
193 }
194
195 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000196 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000197 if (CurrentSlabOffset + Size > SlabSize)
198 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
199
200 uintptr_t OldSlabOffset = CurrentSlabOffset;
201 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
202 if (isCode)
203 FunctionMemory.push_back(MB);
204 else
205 DataMemory.push_back(MB);
206 CurrentSlabOffset += Size;
207 return (uint8_t*)OldSlabOffset;
208 }
209
Lang Hames78937c22015-07-04 01:35:26 +0000210private:
211 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000212 sys::MemoryBlock PreallocSlab;
213 bool UsePreallocation = false;
214 uintptr_t SlabSize = 0;
215 uintptr_t CurrentSlabOffset = 0;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000216};
217
Jim Grosbacheff0a402012-01-16 22:26:39 +0000218uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
219 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000220 unsigned SectionID,
221 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000222 if (PrintAllocationRequests)
223 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
224 << Alignment << ", SectionName = " << SectionName << ")\n";
225
Davide Italianob59ea902015-10-21 22:12:03 +0000226 if (UsePreallocation)
227 return allocateFromSlab(Size, Alignment, true /* isCode */);
228
Lang Hamesafcb70d2017-11-16 23:04:44 +0000229 std::error_code EC;
230 sys::MemoryBlock MB =
231 sys::Memory::allocateMappedMemory(Size, nullptr,
232 sys::Memory::MF_READ |
233 sys::Memory::MF_WRITE,
234 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000235 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000236 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000237 FunctionMemory.push_back(MB);
238 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000239}
240
241uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
242 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000243 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000244 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000245 bool IsReadOnly) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000246 if (PrintAllocationRequests)
247 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
248 << Alignment << ", SectionName = " << SectionName << ")\n";
249
Davide Italianob59ea902015-10-21 22:12:03 +0000250 if (UsePreallocation)
251 return allocateFromSlab(Size, Alignment, false /* isCode */);
252
Lang Hamesafcb70d2017-11-16 23:04:44 +0000253 std::error_code EC;
254 sys::MemoryBlock MB =
255 sys::Memory::allocateMappedMemory(Size, nullptr,
256 sys::Memory::MF_READ |
257 sys::Memory::MF_WRITE,
258 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000259 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000260 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000261 DataMemory.push_back(MB);
262 return (uint8_t*)MB.base();
263}
264
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000265static const char *ProgramName;
266
Lang Hamesee5417d2016-04-05 20:11:24 +0000267static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000268 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000269 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000270}
271
Lang Hamesd311c0e2014-05-13 22:37:41 +0000272static void loadDylibs() {
273 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000274 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000275 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000276 std::string ErrMsg;
277 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
278 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000279 }
280}
281
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000282/* *** */
283
Keno Fischerc780e8e2015-05-21 21:24:32 +0000284static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
285 assert(LoadObjects || !UseDebugObj);
286
Lang Hamesd311c0e2014-05-13 22:37:41 +0000287 // Load any dylibs requested on the command line.
288 loadDylibs();
289
Andrew Kaylord55d7012013-01-25 22:50:58 +0000290 // If we don't have any input files, read from stdin.
291 if (!InputFileList.size())
292 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000293 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000294 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000295 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000296 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000297
298 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000299
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000300 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000301 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000302 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000303 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000304
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000305 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000306 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
307
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000308 if (!MaybeObj) {
309 std::string Buf;
310 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000311 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000312 OS.flush();
313 ErrorAndExit("unable to create object file: '" + Buf + "'");
314 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000315
316 ObjectFile &Obj = **MaybeObj;
317
Keno Fischerc780e8e2015-05-21 21:24:32 +0000318 OwningBinary<ObjectFile> DebugObj;
319 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
320 ObjectFile *SymbolObj = &Obj;
321 if (LoadObjects) {
322 // Load the object file
323 LoadedObjInfo =
324 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000325
Keno Fischerc780e8e2015-05-21 21:24:32 +0000326 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000327 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000328
Keno Fischerc780e8e2015-05-21 21:24:32 +0000329 // Resolve all the relocations we can.
330 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000331
Keno Fischerc780e8e2015-05-21 21:24:32 +0000332 if (UseDebugObj) {
333 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
334 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000335 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000336 }
337 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000338
Rafael Espindolac398e672017-07-19 22:27:28 +0000339 std::unique_ptr<DIContext> Context =
340 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000341
Rafael Espindola6bf32212015-06-24 19:57:32 +0000342 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000343 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000344
Andrew Kaylord55d7012013-01-25 22:50:58 +0000345 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000346 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000347 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000348 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
349 if (!TypeOrErr) {
350 // TODO: Actually report errors helpfully.
351 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000352 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000353 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000354 SymbolRef::Type Type = *TypeOrErr;
355 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000356 Expected<StringRef> Name = Sym.getName();
357 if (!Name) {
358 // TODO: Actually report errors helpfully.
359 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000360 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000361 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000362 Expected<uint64_t> AddrOrErr = Sym.getAddress();
363 if (!AddrOrErr) {
364 // TODO: Actually report errors helpfully.
365 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000366 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000367 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000368 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000369
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000370 object::SectionedAddress Address;
371
Rafael Espindolab109c032015-06-23 02:08:48 +0000372 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000373 // If we're not using the debug object, compute the address of the
374 // symbol in memory (rather than that in the unrelocated object file)
375 // and use that to query the DWARFContext.
376 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000377 auto SecOrErr = Sym.getSection();
378 if (!SecOrErr) {
379 // TODO: Actually report errors helpfully.
380 consumeError(SecOrErr.takeError());
381 continue;
382 }
383 object::section_iterator Sec = *SecOrErr;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000384 StringRef SecName;
385 Sec->getName(SecName);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000386 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000387 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000388 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000389 if (SectionLoadAddress != 0)
390 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000391 } else if (auto SecOrErr = Sym.getSection())
392 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000393
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000394 outs() << "Function: " << *Name << ", Size = " << Size
395 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000396
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000397 Address.Address = Addr;
398 DILineInfoTable Lines =
399 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000400 for (auto &D : Lines) {
401 outs() << " Line info @ " << D.first - Addr << ": "
402 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000403 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000404 }
405 }
406 }
407
408 return 0;
409}
410
Davide Italianob59ea902015-10-21 22:12:03 +0000411static void doPreallocation(TrivialMemoryManager &MemMgr) {
412 // Allocate a slab of memory upfront, if required. This is used if
413 // we want to test small code models.
414 if (static_cast<intptr_t>(PreallocMemory) < 0)
415 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
416
417 // FIXME: Limit the amount of memory that can be preallocated?
418 if (PreallocMemory != 0)
419 MemMgr.preallocateSlab(PreallocMemory);
420}
421
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000422static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000423 // Load any dylibs requested on the command line.
424 loadDylibs();
425
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000426 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000427 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000428 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000429 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000430
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000431 // If we don't have any input files, read from stdin.
432 if (!InputFileList.size())
433 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000434 for (auto &File : InputFileList) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000435 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000436 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000437 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000438 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000439 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000440 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000441 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
442
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000443 if (!MaybeObj) {
444 std::string Buf;
445 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000446 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000447 OS.flush();
448 ErrorAndExit("unable to create object file: '" + Buf + "'");
449 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000450
451 ObjectFile &Obj = **MaybeObj;
452
Andrew Kayloradc70562012-10-02 21:18:39 +0000453 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000454 Dyld.loadObject(Obj);
455 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000456 ErrorAndExit(Dyld.getErrorString());
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000457 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000458 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000459
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000460 // Resove all the relocations we can.
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000461 // FIXME: Error out if there are unresolved relocations.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000462 Dyld.resolveRelocations();
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000463
Jim Grosbachd35159a2011-04-13 15:38:30 +0000464 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000465 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000466 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000467 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000468
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000469 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000470 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000471
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000472 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000473 // setExecutable will call InvalidateInstructionCache.
Lang Hamesafcb70d2017-11-16 23:04:44 +0000474 if (auto EC = sys::Memory::protectMappedMemory(FM,
475 sys::Memory::MF_READ |
476 sys::Memory::MF_EXEC))
477 ErrorAndExit("unable to mark function executable: '" + EC.message() +
478 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000479 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000480
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000481 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000482 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000483
484 int (*Main)(int, const char**) =
485 (int(*)(int,const char**)) uintptr_t(MainAddress);
486 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000487 // Use the name of the first input object module as argv[0] for the target.
488 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000489 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000490 return Main(1, Argv);
491}
492
Lang Hamese1c11382014-06-27 20:20:57 +0000493static int checkAllExpressions(RuntimeDyldChecker &Checker) {
494 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000495 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
496 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
497 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000498 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000499 EC.message());
500
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000501 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
502 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000503 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000504 }
505 return 0;
506}
507
Lang Hamesff411502017-05-07 17:19:53 +0000508void applySpecificSectionMappings(RuntimeDyldChecker &Checker) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000509
510 for (StringRef Mapping : SpecificSectionMappings) {
511
512 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000513 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000514 size_t ComaIdx = Mapping.find_first_of(",");
515
Davide Italiano07557fc2015-11-21 02:15:51 +0000516 if (ComaIdx == StringRef::npos)
517 report_fatal_error("Invalid section specification '" + Mapping +
518 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000519
Lang Hames78937c22015-07-04 01:35:26 +0000520 std::string FileName = SectionIDStr.substr(0, ComaIdx);
521 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000522
523 uint64_t OldAddrInt;
524 std::string ErrorMsg;
525 std::tie(OldAddrInt, ErrorMsg) =
526 Checker.getSectionAddr(FileName, SectionName, true);
527
Davide Italiano07557fc2015-11-21 02:15:51 +0000528 if (ErrorMsg != "")
529 report_fatal_error(ErrorMsg);
Lang Hames778ef5b2014-09-04 04:19:54 +0000530
531 void* OldAddr = reinterpret_cast<void*>(static_cast<uintptr_t>(OldAddrInt));
532
Lang Hames78937c22015-07-04 01:35:26 +0000533 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000534 uint64_t NewAddr;
535
Davide Italiano07557fc2015-11-21 02:15:51 +0000536 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
537 report_fatal_error("Invalid section address in mapping '" + Mapping +
538 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000539
540 Checker.getRTDyld().mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000541 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000542}
543
Lang Hames9cb73532014-07-29 23:43:13 +0000544// Scatter sections in all directions!
545// Remaps section addresses for -verify mode. The following command line options
546// can be used to customize the layout of the memory within the phony target's
547// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000548// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000549// -target-addr-end <e> -- Specify where the phony target address range ends.
550// -target-section-sep <d> -- Specify how big a gap should be left between the
551// end of one section and the start of the next.
552// Defaults to zero. Set to something big
553// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
554//
Lang Hames78937c22015-07-04 01:35:26 +0000555static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
556 TrivialMemoryManager &MemMgr,
557 RuntimeDyldChecker &Checker) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000558
559 // Set up a work list (section addr/size pairs).
560 typedef std::list<std::pair<void*, uint64_t>> WorklistT;
561 WorklistT Worklist;
562
563 for (const auto& CodeSection : MemMgr.FunctionMemory)
564 Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
565 for (const auto& DataSection : MemMgr.DataMemory)
566 Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
567
568 // Apply any section-specific mappings that were requested on the command
569 // line.
Lang Hamesff411502017-05-07 17:19:53 +0000570 applySpecificSectionMappings(Checker);
Lang Hames778ef5b2014-09-04 04:19:54 +0000571
572 // Keep an "already allocated" mapping of section target addresses to sizes.
573 // Sections whose address mappings aren't specified on the command line will
574 // allocated around the explicitly mapped sections while maintaining the
575 // minimum separation.
576 std::map<uint64_t, uint64_t> AlreadyAllocated;
577
Lang Hamesff411502017-05-07 17:19:53 +0000578 // Move the previously applied mappings (whether explicitly specified on the
579 // command line, or implicitly set by RuntimeDyld) into the already-allocated
580 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000581 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
582 I != E;) {
583 WorklistT::iterator Tmp = I;
584 ++I;
Lang Hamesff411502017-05-07 17:19:53 +0000585 auto LoadAddr = Checker.getSectionLoadAddress(Tmp->first);
Lang Hames778ef5b2014-09-04 04:19:54 +0000586
Lang Hamesff411502017-05-07 17:19:53 +0000587 if (LoadAddr &&
588 *LoadAddr != static_cast<uint64_t>(
589 reinterpret_cast<uintptr_t>(Tmp->first))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000590 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
591 // reason (e.g. zero byte COFF sections). Don't include those sections in
592 // the allocation map.
593 if (*LoadAddr != 0)
594 AlreadyAllocated[*LoadAddr] = Tmp->second;
Lang Hames778ef5b2014-09-04 04:19:54 +0000595 Worklist.erase(Tmp);
596 }
597 }
Lang Hames9cb73532014-07-29 23:43:13 +0000598
599 // If the -target-addr-end option wasn't explicitly passed, then set it to a
600 // sensible default based on the target triple.
601 if (TargetAddrEnd.getNumOccurrences() == 0) {
602 if (TargetTriple.isArch16Bit())
603 TargetAddrEnd = (1ULL << 16) - 1;
604 else if (TargetTriple.isArch32Bit())
605 TargetAddrEnd = (1ULL << 32) - 1;
606 // TargetAddrEnd already has a sensible default for 64-bit systems, so
607 // there's nothing to do in the 64-bit case.
608 }
609
Lang Hames778ef5b2014-09-04 04:19:54 +0000610 // Process any elements remaining in the worklist.
611 while (!Worklist.empty()) {
612 std::pair<void*, uint64_t> CurEntry = Worklist.front();
613 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000614
Lang Hames778ef5b2014-09-04 04:19:54 +0000615 uint64_t NextSectionAddr = TargetAddrStart;
616
617 for (const auto &Alloc : AlreadyAllocated)
618 if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
619 break;
620 else
621 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
622
623 AlreadyAllocated[NextSectionAddr] = CurEntry.second;
624 Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
Lang Hames9cb73532014-07-29 23:43:13 +0000625 }
626
Lang Hames78937c22015-07-04 01:35:26 +0000627 // Add dummy symbols to the memory manager.
628 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000629 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000630
Davide Italiano07557fc2015-11-21 02:15:51 +0000631 if (EqualsIdx == StringRef::npos)
632 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
633 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000634
635 std::string Symbol = Mapping.substr(0, EqualsIdx);
636 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
637
638 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000639 if (StringRef(AddrStr).getAsInteger(0, Addr))
640 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000641
642 MemMgr.addDummySymbol(Symbol, Addr);
643 }
Lang Hames9cb73532014-07-29 23:43:13 +0000644}
645
646// Load and link the objects specified on the command line, but do not execute
647// anything. Instead, attach a RuntimeDyldChecker instance and call it to
648// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000649static int linkAndVerify() {
650
651 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000652 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000653 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000654
655 // Look up the target and build the disassembler.
656 Triple TheTriple(Triple::normalize(TripleName));
657 std::string ErrorStr;
658 const Target *TheTarget =
659 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000660 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000661 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000662
Lang Hamese1c11382014-06-27 20:20:57 +0000663 TripleName = TheTriple.getTriple();
664
665 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000666 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000667 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000668 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000669
670 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000671 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000672 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000673
674 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000675 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000676 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000677
678 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
679
680 std::unique_ptr<MCDisassembler> Disassembler(
681 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000682 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000683 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000684
685 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
686
Daniel Sanders50f17232015-09-15 16:17:27 +0000687 std::unique_ptr<MCInstPrinter> InstPrinter(
688 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000689
690 // Load any dylibs requested on the command line.
691 loadDylibs();
692
693 // Instantiate a dynamic linker.
694 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000695 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000696 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000697 Dyld.setProcessAllSections(true);
Lang Hamesf7acddd2014-07-22 22:47:39 +0000698 RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
699 llvm::dbgs());
Lang Hamese1c11382014-06-27 20:20:57 +0000700
701 // If we don't have any input files, read from stdin.
702 if (!InputFileList.size())
703 InputFileList.push_back("-");
Davide Italianod91bf8e2015-10-10 00:45:24 +0000704 for (auto &Filename : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000705 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000706 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italianod91bf8e2015-10-10 00:45:24 +0000707 MemoryBuffer::getFileOrSTDIN(Filename);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000708
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000709 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000710 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000711
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000712 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000713 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
714
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000715 if (!MaybeObj) {
716 std::string Buf;
717 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000718 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000719 OS.flush();
720 ErrorAndExit("unable to create object file: '" + Buf + "'");
721 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000722
723 ObjectFile &Obj = **MaybeObj;
724
Lang Hamese1c11382014-06-27 20:20:57 +0000725 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000726 Dyld.loadObject(Obj);
727 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000728 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000729 }
730 }
731
Lang Hames78937c22015-07-04 01:35:26 +0000732 // Re-map the section addresses into the phony target address space and add
733 // dummy symbols.
734 remapSectionsAndSymbols(TheTriple, MemMgr, Checker);
Lang Hames375385f2014-07-30 03:12:41 +0000735
Lang Hamese1c11382014-06-27 20:20:57 +0000736 // Resolve all the relocations we can.
737 Dyld.resolveRelocations();
738
Lang Hames925e51b2014-09-03 05:42:52 +0000739 // Register EH frames.
740 Dyld.registerEHFrames();
741
Lang Hamesae172682014-08-05 20:51:46 +0000742 int ErrorCode = checkAllExpressions(Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000743 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000744 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000745 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000746
747 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000748}
749
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000750int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000751 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000752 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000753
Lang Hamese1c11382014-06-27 20:20:57 +0000754 llvm::InitializeAllTargetInfos();
755 llvm::InitializeAllTargetMCs();
756 llvm::InitializeAllDisassemblers();
757
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000758 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
759
760 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000761 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000762 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000763 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000764 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000765 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000766 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
767 case AC_PrintObjectLineInfo:
768 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000769 case AC_Verify:
770 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000771 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000772}