blob: 5a5d035d27dd5dfd870fc73a377fb82d3cc82eeb [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 Hames941f2472019-04-08 21:50:48 +000032#include "llvm/Support/Path.h"
Lang Hamese1c11382014-06-27 20:20:57 +000033#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Support/TargetSelect.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/raw_ostream.h"
Lang Hames941f2472019-04-08 21:50:48 +000036
37#include <future>
Lang Hames778ef5b2014-09-04 04:19:54 +000038#include <list>
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,
Lang Hames9c755452018-03-31 16:01:01 +000045 cl::desc("<input files>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000046
47enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000048 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000049 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000050 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000051 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000052 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000053};
54
55static cl::opt<ActionType>
56Action(cl::desc("Action to perform:"),
57 cl::init(AC_Execute),
58 cl::values(clEnumValN(AC_Execute, "execute",
59 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000060 clEnumValN(AC_PrintLineInfo, "printline",
61 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000062 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
63 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000064 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
65 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000066 clEnumValN(AC_Verify, "verify",
Mehdi Amini732afdd2016-10-08 19:41:06 +000067 "Load, link and verify the resulting memory image.")));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000068
Jim Grosbachd35159a2011-04-13 15:38:30 +000069static cl::opt<std::string>
70EntryPoint("entry",
71 cl::desc("Function to call as entry point."),
72 cl::init("_main"));
73
Lang Hamesd311c0e2014-05-13 22:37:41 +000074static cl::list<std::string>
75Dylibs("dylib",
76 cl::desc("Add library."),
77 cl::ZeroOrMore);
78
Lang Hamese1c11382014-06-27 20:20:57 +000079static cl::opt<std::string>
80TripleName("triple", cl::desc("Target triple for disassembler"));
81
Petar Jovanovic280e5622015-06-23 22:52:19 +000082static cl::opt<std::string>
83MCPU("mcpu",
84 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
85 cl::value_desc("cpu-name"),
86 cl::init(""));
87
Lang Hamese1c11382014-06-27 20:20:57 +000088static cl::list<std::string>
89CheckFiles("check",
90 cl::desc("File containing RuntimeDyld verifier checks."),
91 cl::ZeroOrMore);
92
Lang Hames776f1d52018-10-23 01:36:33 +000093// Tracking BUG: 19665
94// http://llvm.org/bugs/show_bug.cgi?id=19665
95//
96// Do not change these options to cl::opt<uint64_t> since this silently breaks
97// argument parsing.
98static cl::opt<unsigned long long>
Davide Italianob59ea902015-10-21 22:12:03 +000099PreallocMemory("preallocate",
100 cl::desc("Allocate memory upfront rather than on-demand"),
101 cl::init(0));
102
Lang Hames776f1d52018-10-23 01:36:33 +0000103static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000104TargetAddrStart("target-addr-start",
105 cl::desc("For -verify only: start of phony target address "
106 "range."),
107 cl::init(4096), // Start at "page 1" - no allocating at "null".
108 cl::Hidden);
109
Lang Hames776f1d52018-10-23 01:36:33 +0000110static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000111TargetAddrEnd("target-addr-end",
112 cl::desc("For -verify only: end of phony target address range."),
113 cl::init(~0ULL),
114 cl::Hidden);
115
Lang Hames776f1d52018-10-23 01:36:33 +0000116static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000117TargetSectionSep("target-section-sep",
118 cl::desc("For -verify only: Separation between sections in "
119 "phony target address space."),
120 cl::init(0),
121 cl::Hidden);
122
Lang Hames778ef5b2014-09-04 04:19:54 +0000123static cl::list<std::string>
124SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000125 cl::desc("For -verify only: Map a section to a "
126 "specific address."),
127 cl::ZeroOrMore,
128 cl::Hidden);
129
130static cl::list<std::string>
131DummySymbolMappings("dummy-extern",
132 cl::desc("For -verify only: Inject a symbol into the extern "
133 "symbol table."),
134 cl::ZeroOrMore,
135 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000136
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000137static cl::opt<bool>
138PrintAllocationRequests("print-alloc-requests",
139 cl::desc("Print allocation requests made to the memory "
140 "manager by RuntimeDyld"),
141 cl::Hidden);
142
Lang Hames941f2472019-04-08 21:50:48 +0000143ExitOnError ExitOnErr;
144
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000145/* *** */
146
Lang Hames941f2472019-04-08 21:50:48 +0000147using SectionIDMap = StringMap<unsigned>;
148using FileToSectionIDMap = StringMap<SectionIDMap>;
149
150void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
151 for (const auto &KV : FileToSecIDMap) {
152 llvm::dbgs() << "In " << KV.first() << "\n";
153 for (auto &KV2 : KV.second)
154 llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
155 }
156}
157
158Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
159 StringRef FileName, StringRef SectionName) {
160 auto I = FileToSecIDMap.find(FileName);
161 if (I == FileToSecIDMap.end())
162 return make_error<StringError>("No file named " + FileName,
163 inconvertibleErrorCode());
164 auto &SectionIDs = I->second;
165 auto J = SectionIDs.find(SectionName);
166 if (J == SectionIDs.end())
167 return make_error<StringError>("No section named \"" + SectionName +
168 "\" in file " + FileName,
169 inconvertibleErrorCode());
170 return J->second;
171}
172
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000173// A trivial memory manager that doesn't do anything fancy, just uses the
174// support library allocation routines directly.
175class TrivialMemoryManager : public RTDyldMemoryManager {
176public:
Lang Hames941f2472019-04-08 21:50:48 +0000177 struct SectionInfo {
178 SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
179 : Name(Name), MB(std::move(MB)), SectionID(SectionID) {}
180 std::string Name;
181 sys::MemoryBlock MB;
182 unsigned SectionID = ~0U;
183 };
184
185 SmallVector<SectionInfo, 16> FunctionMemory;
186 SmallVector<SectionInfo, 16> DataMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000187
188 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000189 unsigned SectionID,
190 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000191 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000192 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000193 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000194
Lang Hames941f2472019-04-08 21:50:48 +0000195 /// If non null, records subsequent Name -> SectionID mappings.
196 void setSectionIDsMap(SectionIDMap *SecIDMap) {
197 this->SecIDMap = SecIDMap;
198 }
199
Craig Toppere56917c2014-03-08 08:27:28 +0000200 void *getPointerToNamedFunction(const std::string &Name,
201 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000202 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000203 }
204
Craig Toppere56917c2014-03-08 08:27:28 +0000205 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000206
Lang Hames78937c22015-07-04 01:35:26 +0000207 void addDummySymbol(const std::string &Name, uint64_t Addr) {
208 DummyExterns[Name] = Addr;
209 }
210
Lang Hamesad4a9112016-08-01 20:49:11 +0000211 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000212 auto I = DummyExterns.find(Name);
213
214 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000215 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000216
217 return RTDyldMemoryManager::findSymbol(Name);
218 }
219
Tim Northover5af339a2015-06-03 18:26:52 +0000220 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
221 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000222 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000223
224 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000225 std::error_code EC;
226 sys::MemoryBlock MB =
227 sys::Memory::allocateMappedMemory(Size, nullptr,
228 sys::Memory::MF_READ |
229 sys::Memory::MF_WRITE,
230 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000231 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000232 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000233
234 PreallocSlab = MB;
235 UsePreallocation = true;
236 SlabSize = Size;
237 }
238
Lang Hames941f2472019-04-08 21:50:48 +0000239 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
240 StringRef SectionName, unsigned SectionID) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000241 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000242 if (CurrentSlabOffset + Size > SlabSize)
243 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
244
245 uintptr_t OldSlabOffset = CurrentSlabOffset;
246 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
247 if (isCode)
Lang Hames941f2472019-04-08 21:50:48 +0000248 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000249 else
Lang Hames941f2472019-04-08 21:50:48 +0000250 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000251 CurrentSlabOffset += Size;
252 return (uint8_t*)OldSlabOffset;
253 }
254
Lang Hames78937c22015-07-04 01:35:26 +0000255private:
256 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000257 sys::MemoryBlock PreallocSlab;
258 bool UsePreallocation = false;
259 uintptr_t SlabSize = 0;
260 uintptr_t CurrentSlabOffset = 0;
Lang Hames941f2472019-04-08 21:50:48 +0000261 SectionIDMap *SecIDMap = nullptr;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000262};
263
Jim Grosbacheff0a402012-01-16 22:26:39 +0000264uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
265 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000266 unsigned SectionID,
267 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000268 if (PrintAllocationRequests)
269 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
270 << Alignment << ", SectionName = " << SectionName << ")\n";
271
Lang Hames941f2472019-04-08 21:50:48 +0000272 dbgs() << " Registering code section \"" << SectionName << "\"\n";
273 if (SecIDMap)
274 (*SecIDMap)[SectionName] = SectionID;
275
Davide Italianob59ea902015-10-21 22:12:03 +0000276 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000277 return allocateFromSlab(Size, Alignment, true /* isCode */,
278 SectionName, SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000279
Lang Hamesafcb70d2017-11-16 23:04:44 +0000280 std::error_code EC;
281 sys::MemoryBlock MB =
282 sys::Memory::allocateMappedMemory(Size, nullptr,
283 sys::Memory::MF_READ |
284 sys::Memory::MF_WRITE,
285 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000286 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000287 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000288 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000289 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000290}
291
292uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
293 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000294 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000295 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000296 bool IsReadOnly) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000297 if (PrintAllocationRequests)
298 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
299 << Alignment << ", SectionName = " << SectionName << ")\n";
300
Lang Hames941f2472019-04-08 21:50:48 +0000301 dbgs() << " Registering code section \"" << SectionName << "\"\n";
302 if (SecIDMap)
303 (*SecIDMap)[SectionName] = SectionID;
304
Davide Italianob59ea902015-10-21 22:12:03 +0000305 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000306 return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
307 SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000308
Lang Hamesafcb70d2017-11-16 23:04:44 +0000309 std::error_code EC;
310 sys::MemoryBlock MB =
311 sys::Memory::allocateMappedMemory(Size, nullptr,
312 sys::Memory::MF_READ |
313 sys::Memory::MF_WRITE,
314 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000315 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000316 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000317 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000318 return (uint8_t*)MB.base();
319}
320
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000321static const char *ProgramName;
322
Lang Hamesee5417d2016-04-05 20:11:24 +0000323static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000324 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000325 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000326}
327
Lang Hamesd311c0e2014-05-13 22:37:41 +0000328static void loadDylibs() {
329 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000330 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000331 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000332 std::string ErrMsg;
333 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
334 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000335 }
336}
337
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000338/* *** */
339
Keno Fischerc780e8e2015-05-21 21:24:32 +0000340static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
341 assert(LoadObjects || !UseDebugObj);
342
Lang Hamesd311c0e2014-05-13 22:37:41 +0000343 // Load any dylibs requested on the command line.
344 loadDylibs();
345
Andrew Kaylord55d7012013-01-25 22:50:58 +0000346 // If we don't have any input files, read from stdin.
347 if (!InputFileList.size())
348 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000349 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000350 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000351 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000352 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000353
354 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000355
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000356 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000357 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000358 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000359 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000360
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000361 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000362 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
363
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000364 if (!MaybeObj) {
365 std::string Buf;
366 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000367 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000368 OS.flush();
369 ErrorAndExit("unable to create object file: '" + Buf + "'");
370 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000371
372 ObjectFile &Obj = **MaybeObj;
373
Keno Fischerc780e8e2015-05-21 21:24:32 +0000374 OwningBinary<ObjectFile> DebugObj;
375 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
376 ObjectFile *SymbolObj = &Obj;
377 if (LoadObjects) {
378 // Load the object file
379 LoadedObjInfo =
380 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000381
Keno Fischerc780e8e2015-05-21 21:24:32 +0000382 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000383 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000384
Keno Fischerc780e8e2015-05-21 21:24:32 +0000385 // Resolve all the relocations we can.
386 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000387
Keno Fischerc780e8e2015-05-21 21:24:32 +0000388 if (UseDebugObj) {
389 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
390 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000391 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000392 }
393 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000394
Rafael Espindolac398e672017-07-19 22:27:28 +0000395 std::unique_ptr<DIContext> Context =
396 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000397
Rafael Espindola6bf32212015-06-24 19:57:32 +0000398 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000399 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000400
Andrew Kaylord55d7012013-01-25 22:50:58 +0000401 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000402 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000403 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000404 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
405 if (!TypeOrErr) {
406 // TODO: Actually report errors helpfully.
407 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000408 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000409 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000410 SymbolRef::Type Type = *TypeOrErr;
411 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000412 Expected<StringRef> Name = Sym.getName();
413 if (!Name) {
414 // TODO: Actually report errors helpfully.
415 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000416 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000417 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000418 Expected<uint64_t> AddrOrErr = Sym.getAddress();
419 if (!AddrOrErr) {
420 // TODO: Actually report errors helpfully.
421 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000422 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000423 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000424 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000425
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000426 object::SectionedAddress Address;
427
Rafael Espindolab109c032015-06-23 02:08:48 +0000428 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000429 // If we're not using the debug object, compute the address of the
430 // symbol in memory (rather than that in the unrelocated object file)
431 // and use that to query the DWARFContext.
432 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000433 auto SecOrErr = Sym.getSection();
434 if (!SecOrErr) {
435 // TODO: Actually report errors helpfully.
436 consumeError(SecOrErr.takeError());
437 continue;
438 }
439 object::section_iterator Sec = *SecOrErr;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000440 StringRef SecName;
441 Sec->getName(SecName);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000442 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000443 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000444 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000445 if (SectionLoadAddress != 0)
446 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000447 } else if (auto SecOrErr = Sym.getSection())
448 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000449
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000450 outs() << "Function: " << *Name << ", Size = " << Size
451 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000452
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000453 Address.Address = Addr;
454 DILineInfoTable Lines =
455 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000456 for (auto &D : Lines) {
457 outs() << " Line info @ " << D.first - Addr << ": "
458 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000459 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000460 }
461 }
462 }
463
464 return 0;
465}
466
Davide Italianob59ea902015-10-21 22:12:03 +0000467static void doPreallocation(TrivialMemoryManager &MemMgr) {
468 // Allocate a slab of memory upfront, if required. This is used if
469 // we want to test small code models.
470 if (static_cast<intptr_t>(PreallocMemory) < 0)
471 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
472
473 // FIXME: Limit the amount of memory that can be preallocated?
474 if (PreallocMemory != 0)
475 MemMgr.preallocateSlab(PreallocMemory);
476}
477
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000478static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000479 // Load any dylibs requested on the command line.
480 loadDylibs();
481
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000482 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000483 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000484 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000485 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000486
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000487 // If we don't have any input files, read from stdin.
488 if (!InputFileList.size())
489 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000490 for (auto &File : InputFileList) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000491 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000492 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000493 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000494 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000495 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000496 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000497 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
498
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000499 if (!MaybeObj) {
500 std::string Buf;
501 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000502 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000503 OS.flush();
504 ErrorAndExit("unable to create object file: '" + Buf + "'");
505 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000506
507 ObjectFile &Obj = **MaybeObj;
508
Andrew Kayloradc70562012-10-02 21:18:39 +0000509 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000510 Dyld.loadObject(Obj);
511 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000512 ErrorAndExit(Dyld.getErrorString());
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000513 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000514 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000515
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000516 // Resove all the relocations we can.
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000517 // FIXME: Error out if there are unresolved relocations.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000518 Dyld.resolveRelocations();
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000519
Jim Grosbachd35159a2011-04-13 15:38:30 +0000520 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000521 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000522 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000523 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000524
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000525 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000526 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000527
Lang Hames941f2472019-04-08 21:50:48 +0000528 auto &FM_MB = FM.MB;
529
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000530 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000531 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000532 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000533 sys::Memory::MF_READ |
534 sys::Memory::MF_EXEC))
535 ErrorAndExit("unable to mark function executable: '" + EC.message() +
536 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000537 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000538
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000539 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000540 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000541
542 int (*Main)(int, const char**) =
543 (int(*)(int,const char**)) uintptr_t(MainAddress);
544 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000545 // Use the name of the first input object module as argv[0] for the target.
546 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000547 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000548 return Main(1, Argv);
549}
550
Lang Hamese1c11382014-06-27 20:20:57 +0000551static int checkAllExpressions(RuntimeDyldChecker &Checker) {
552 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000553 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
554 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
555 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000556 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000557 EC.message());
558
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000559 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
560 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000561 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000562 }
563 return 0;
564}
565
Lang Hames941f2472019-04-08 21:50:48 +0000566void applySpecificSectionMappings(RuntimeDyld &Dyld,
567 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000568
569 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000570 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000571 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000572 size_t ComaIdx = Mapping.find_first_of(",");
573
Davide Italiano07557fc2015-11-21 02:15:51 +0000574 if (ComaIdx == StringRef::npos)
575 report_fatal_error("Invalid section specification '" + Mapping +
576 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000577
Lang Hames78937c22015-07-04 01:35:26 +0000578 std::string FileName = SectionIDStr.substr(0, ComaIdx);
579 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000580 unsigned SectionID =
581 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000582
Lang Hames941f2472019-04-08 21:50:48 +0000583 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000584 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000585 uint64_t NewAddr;
586
Davide Italiano07557fc2015-11-21 02:15:51 +0000587 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
588 report_fatal_error("Invalid section address in mapping '" + Mapping +
589 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000590
Lang Hames941f2472019-04-08 21:50:48 +0000591 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000592 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000593}
594
Lang Hames9cb73532014-07-29 23:43:13 +0000595// Scatter sections in all directions!
596// Remaps section addresses for -verify mode. The following command line options
597// can be used to customize the layout of the memory within the phony target's
598// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000599// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000600// -target-addr-end <e> -- Specify where the phony target address range ends.
601// -target-section-sep <d> -- Specify how big a gap should be left between the
602// end of one section and the start of the next.
603// Defaults to zero. Set to something big
604// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
605//
Lang Hames78937c22015-07-04 01:35:26 +0000606static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000607 RuntimeDyld &Dyld,
608 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000609
610 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000611 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000612 WorklistT Worklist;
613
614 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000615 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000616 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000617 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000618
619 // Keep an "already allocated" mapping of section target addresses to sizes.
620 // Sections whose address mappings aren't specified on the command line will
621 // allocated around the explicitly mapped sections while maintaining the
622 // minimum separation.
623 std::map<uint64_t, uint64_t> AlreadyAllocated;
624
Lang Hamesff411502017-05-07 17:19:53 +0000625 // Move the previously applied mappings (whether explicitly specified on the
626 // command line, or implicitly set by RuntimeDyld) into the already-allocated
627 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000628 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
629 I != E;) {
630 WorklistT::iterator Tmp = I;
631 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000632
Lang Hames941f2472019-04-08 21:50:48 +0000633 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
634
635 if (LoadAddr != static_cast<uint64_t>(
636 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000637 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
638 // reason (e.g. zero byte COFF sections). Don't include those sections in
639 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000640 if (LoadAddr != 0)
641 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.size();
Lang Hames778ef5b2014-09-04 04:19:54 +0000642 Worklist.erase(Tmp);
643 }
644 }
Lang Hames9cb73532014-07-29 23:43:13 +0000645
646 // If the -target-addr-end option wasn't explicitly passed, then set it to a
647 // sensible default based on the target triple.
648 if (TargetAddrEnd.getNumOccurrences() == 0) {
649 if (TargetTriple.isArch16Bit())
650 TargetAddrEnd = (1ULL << 16) - 1;
651 else if (TargetTriple.isArch32Bit())
652 TargetAddrEnd = (1ULL << 32) - 1;
653 // TargetAddrEnd already has a sensible default for 64-bit systems, so
654 // there's nothing to do in the 64-bit case.
655 }
656
Lang Hames778ef5b2014-09-04 04:19:54 +0000657 // Process any elements remaining in the worklist.
658 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000659 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000660 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000661
Lang Hames778ef5b2014-09-04 04:19:54 +0000662 uint64_t NextSectionAddr = TargetAddrStart;
663
664 for (const auto &Alloc : AlreadyAllocated)
Lang Hames941f2472019-04-08 21:50:48 +0000665 if (NextSectionAddr + CurEntry->MB.size() + TargetSectionSep <= Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000666 break;
667 else
668 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
669
Lang Hames941f2472019-04-08 21:50:48 +0000670 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
671 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.size();
Lang Hames9cb73532014-07-29 23:43:13 +0000672 }
673
Lang Hames78937c22015-07-04 01:35:26 +0000674 // Add dummy symbols to the memory manager.
675 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000676 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000677
Davide Italiano07557fc2015-11-21 02:15:51 +0000678 if (EqualsIdx == StringRef::npos)
679 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
680 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000681
682 std::string Symbol = Mapping.substr(0, EqualsIdx);
683 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
684
685 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000686 if (StringRef(AddrStr).getAsInteger(0, Addr))
687 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000688
689 MemMgr.addDummySymbol(Symbol, Addr);
690 }
Lang Hames9cb73532014-07-29 23:43:13 +0000691}
692
693// Load and link the objects specified on the command line, but do not execute
694// anything. Instead, attach a RuntimeDyldChecker instance and call it to
695// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000696static int linkAndVerify() {
697
698 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000699 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000700 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000701
702 // Look up the target and build the disassembler.
703 Triple TheTriple(Triple::normalize(TripleName));
704 std::string ErrorStr;
705 const Target *TheTarget =
706 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000707 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000708 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000709
Lang Hamese1c11382014-06-27 20:20:57 +0000710 TripleName = TheTriple.getTriple();
711
712 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000713 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000714 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000715 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000716
717 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000718 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000719 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000720
721 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000722 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000723 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000724
725 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
726
727 std::unique_ptr<MCDisassembler> Disassembler(
728 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000729 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000730 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000731
732 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
733
Daniel Sanders50f17232015-09-15 16:17:27 +0000734 std::unique_ptr<MCInstPrinter> InstPrinter(
735 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000736
737 // Load any dylibs requested on the command line.
738 loadDylibs();
739
740 // Instantiate a dynamic linker.
741 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000742 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000743
744 using StubOffsets = StringMap<uint32_t>;
745 using SectionStubs = StringMap<StubOffsets>;
746 using FileStubs = StringMap<SectionStubs>;
747
748 FileStubs StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000749 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000750 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000751
752 Dyld.setNotifyStubEmitted(
753 [&StubMap](StringRef FilePath, StringRef SectionName,
754 StringRef SymbolName, uint32_t StubOffset) {
755 StubMap[sys::path::filename(FilePath)][SectionName][SymbolName] =
756 StubOffset;
757 });
758
759 auto GetSymbolAddress =
760 [&Dyld, &MemMgr](StringRef Symbol) -> Expected<JITTargetAddress> {
761 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
762 return InternalSymbol.getAddress();
763
764#ifdef _MSC_VER
765 using ExpectedLookupResult = MSVCPExpected<JITSymbolResolver::LookupResult>;
766#else
767 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
768#endif
769
770 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
771 auto ResultF = ResultP->get_future();
772
773 MemMgr.lookup(
774 JITSymbolResolver::LookupSet({Symbol}),
775 [=](Expected<JITSymbolResolver::LookupResult> Result) {
776 ResultP->set_value(std::move(Result));
777 });
778
779 auto Result = ResultF.get();
780 if (!Result)
781 return Result.takeError();
782
783 auto I = Result->find(Symbol);
784 assert(I != Result->end() &&
785 "Expected symbol address if no error occurred");
786 return I->second.getAddress();
787 };
788
789 auto IsSymbolValid =
790 [&Dyld, GetSymbolAddress](StringRef Symbol) {
791 if (Dyld.getSymbol(Symbol))
792 return true;
793 auto Addr = GetSymbolAddress(Symbol);
794 if (!Addr) {
795 logAllUnhandledErrors(Addr.takeError(), errs(), "RTDyldChecker: ");
796 return false;
797 }
798 return *Addr != 0;
799 };
800
801 FileToSectionIDMap FileToSecIDMap;
802
803 auto GetSectionAddress =
804 [&Dyld, &FileToSecIDMap](StringRef FileName, StringRef SectionName) {
805 unsigned SectionID =
806 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
807 return Dyld.getSectionLoadAddress(SectionID);
808 };
809
810 auto GetSectionContent =
811 [&Dyld, &FileToSecIDMap](StringRef FileName, StringRef SectionName) {
812 unsigned SectionID =
813 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
814 return Dyld.getSectionContent(SectionID);
815 };
816
817
818 auto GetSymbolContents =
819 [&Dyld](StringRef Symbol) {
820 auto *SymAddr = static_cast<char*>(Dyld.getSymbolLocalAddress(Symbol));
821 if (!SymAddr)
822 return StringRef();
823 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
824 if (SectionID == ~0U)
825 return StringRef();
826 StringRef SecContent = Dyld.getSectionContent(SectionID);
827 uint64_t SymSize = SecContent.size() - (SymAddr - SecContent.data());
828 return StringRef(SymAddr, SymSize);
829 };
830
831 auto GetStubOffset =
832 [&StubMap](StringRef FileName, StringRef SectionName, StringRef SymbolName) -> Expected<uint32_t> {
833 if (!StubMap.count(FileName))
834 return make_error<StringError>("File name not found", inconvertibleErrorCode());
835 if (!StubMap[FileName].count(SectionName))
836 return make_error<StringError>("Section name not found", inconvertibleErrorCode());
837 if (!StubMap[FileName][SectionName].count(SymbolName))
838 return make_error<StringError>("Symbol name not found", inconvertibleErrorCode());
839 return StubMap[FileName][SectionName][SymbolName];
840 };
841
842 // We will initialize this below once we have the first object file and can
843 // know the endianness.
844 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000845
846 // If we don't have any input files, read from stdin.
847 if (!InputFileList.size())
848 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000849 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000850 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000851 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000852 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000853
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000854 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000855 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000856
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000857 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000858 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
859
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000860 if (!MaybeObj) {
861 std::string Buf;
862 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000863 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000864 OS.flush();
865 ErrorAndExit("unable to create object file: '" + Buf + "'");
866 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000867
868 ObjectFile &Obj = **MaybeObj;
869
Lang Hames941f2472019-04-08 21:50:48 +0000870 if (!Checker)
871 Checker =
872 llvm::make_unique<RuntimeDyldChecker>(IsSymbolValid, GetSymbolAddress,
873 GetSymbolContents,
874 GetSectionAddress,
875 GetSectionContent, GetStubOffset,
876 Obj.isLittleEndian()
877 ? support::little
878 : support::big,
879 Disassembler.get(),
880 InstPrinter.get(), dbgs());
881
882 auto FileName = sys::path::filename(InputFile);
883 dbgs() << "In " << FileName << ":\n";
884 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
885
Lang Hamese1c11382014-06-27 20:20:57 +0000886 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000887 Dyld.loadObject(Obj);
888 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000889 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000890 }
891 }
892
Lang Hames78937c22015-07-04 01:35:26 +0000893 // Re-map the section addresses into the phony target address space and add
894 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000895 applySpecificSectionMappings(Dyld, FileToSecIDMap);
896 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000897
Lang Hamese1c11382014-06-27 20:20:57 +0000898 // Resolve all the relocations we can.
899 Dyld.resolveRelocations();
900
Lang Hames925e51b2014-09-03 05:42:52 +0000901 // Register EH frames.
902 Dyld.registerEHFrames();
903
Lang Hames941f2472019-04-08 21:50:48 +0000904 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000905 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000906 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000907 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000908
909 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000910}
911
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000912int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000913 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000914 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000915
Lang Hamese1c11382014-06-27 20:20:57 +0000916 llvm::InitializeAllTargetInfos();
917 llvm::InitializeAllTargetMCs();
918 llvm::InitializeAllDisassemblers();
919
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000920 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
921
Lang Hames941f2472019-04-08 21:50:48 +0000922 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
923
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000924 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000925 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000926 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000927 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000928 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000929 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000930 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
931 case AC_PrintObjectLineInfo:
932 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000933 case AC_Verify:
934 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000935 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000936}