blob: fde61eafac94e6a544315642e24576d95b99455e [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"
Simon Pilgrim563f35a2019-04-09 10:15:10 +000032#include "llvm/Support/MSVCErrorWorkarounds.h"
Lang Hames941f2472019-04-08 21:50:48 +000033#include "llvm/Support/Path.h"
Lang Hamese1c11382014-06-27 20:20:57 +000034#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/TargetSelect.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000036#include "llvm/Support/raw_ostream.h"
Lang Hames941f2472019-04-08 21:50:48 +000037
38#include <future>
Lang Hames778ef5b2014-09-04 04:19:54 +000039#include <list>
Lang Hamese1c11382014-06-27 20:20:57 +000040
Jim Grosbach0072cdb2011-03-18 17:11:39 +000041using namespace llvm;
42using namespace llvm::object;
43
Jim Grosbach7cb41d72011-04-13 15:49:40 +000044static cl::list<std::string>
45InputFileList(cl::Positional, cl::ZeroOrMore,
Lang Hames9c755452018-03-31 16:01:01 +000046 cl::desc("<input files>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000047
48enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000049 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000050 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000051 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000052 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000053 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000054};
55
56static cl::opt<ActionType>
57Action(cl::desc("Action to perform:"),
58 cl::init(AC_Execute),
59 cl::values(clEnumValN(AC_Execute, "execute",
60 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000061 clEnumValN(AC_PrintLineInfo, "printline",
62 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000063 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
64 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000065 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
66 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000067 clEnumValN(AC_Verify, "verify",
Mehdi Amini732afdd2016-10-08 19:41:06 +000068 "Load, link and verify the resulting memory image.")));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000069
Jim Grosbachd35159a2011-04-13 15:38:30 +000070static cl::opt<std::string>
71EntryPoint("entry",
72 cl::desc("Function to call as entry point."),
73 cl::init("_main"));
74
Lang Hamesd311c0e2014-05-13 22:37:41 +000075static cl::list<std::string>
76Dylibs("dylib",
77 cl::desc("Add library."),
78 cl::ZeroOrMore);
79
Lang Hamese1c11382014-06-27 20:20:57 +000080static cl::opt<std::string>
81TripleName("triple", cl::desc("Target triple for disassembler"));
82
Petar Jovanovic280e5622015-06-23 22:52:19 +000083static cl::opt<std::string>
84MCPU("mcpu",
85 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
86 cl::value_desc("cpu-name"),
87 cl::init(""));
88
Lang Hamese1c11382014-06-27 20:20:57 +000089static cl::list<std::string>
90CheckFiles("check",
91 cl::desc("File containing RuntimeDyld verifier checks."),
92 cl::ZeroOrMore);
93
Lang Hames776f1d52018-10-23 01:36:33 +000094// Tracking BUG: 19665
95// http://llvm.org/bugs/show_bug.cgi?id=19665
96//
97// Do not change these options to cl::opt<uint64_t> since this silently breaks
98// argument parsing.
99static cl::opt<unsigned long long>
Davide Italianob59ea902015-10-21 22:12:03 +0000100PreallocMemory("preallocate",
101 cl::desc("Allocate memory upfront rather than on-demand"),
102 cl::init(0));
103
Lang Hames776f1d52018-10-23 01:36:33 +0000104static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000105TargetAddrStart("target-addr-start",
106 cl::desc("For -verify only: start of phony target address "
107 "range."),
108 cl::init(4096), // Start at "page 1" - no allocating at "null".
109 cl::Hidden);
110
Lang Hames776f1d52018-10-23 01:36:33 +0000111static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000112TargetAddrEnd("target-addr-end",
113 cl::desc("For -verify only: end of phony target address range."),
114 cl::init(~0ULL),
115 cl::Hidden);
116
Lang Hames776f1d52018-10-23 01:36:33 +0000117static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000118TargetSectionSep("target-section-sep",
119 cl::desc("For -verify only: Separation between sections in "
120 "phony target address space."),
121 cl::init(0),
122 cl::Hidden);
123
Lang Hames778ef5b2014-09-04 04:19:54 +0000124static cl::list<std::string>
125SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000126 cl::desc("For -verify only: Map a section to a "
127 "specific address."),
128 cl::ZeroOrMore,
129 cl::Hidden);
130
131static cl::list<std::string>
132DummySymbolMappings("dummy-extern",
133 cl::desc("For -verify only: Inject a symbol into the extern "
134 "symbol table."),
135 cl::ZeroOrMore,
136 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000137
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000138static cl::opt<bool>
139PrintAllocationRequests("print-alloc-requests",
140 cl::desc("Print allocation requests made to the memory "
141 "manager by RuntimeDyld"),
142 cl::Hidden);
143
Lang Hames941f2472019-04-08 21:50:48 +0000144ExitOnError ExitOnErr;
145
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000146/* *** */
147
Lang Hames941f2472019-04-08 21:50:48 +0000148using SectionIDMap = StringMap<unsigned>;
149using FileToSectionIDMap = StringMap<SectionIDMap>;
150
151void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
152 for (const auto &KV : FileToSecIDMap) {
153 llvm::dbgs() << "In " << KV.first() << "\n";
154 for (auto &KV2 : KV.second)
155 llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
156 }
157}
158
159Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
160 StringRef FileName, StringRef SectionName) {
161 auto I = FileToSecIDMap.find(FileName);
162 if (I == FileToSecIDMap.end())
163 return make_error<StringError>("No file named " + FileName,
164 inconvertibleErrorCode());
165 auto &SectionIDs = I->second;
166 auto J = SectionIDs.find(SectionName);
167 if (J == SectionIDs.end())
168 return make_error<StringError>("No section named \"" + SectionName +
169 "\" in file " + FileName,
170 inconvertibleErrorCode());
171 return J->second;
172}
173
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000174// A trivial memory manager that doesn't do anything fancy, just uses the
175// support library allocation routines directly.
176class TrivialMemoryManager : public RTDyldMemoryManager {
177public:
Lang Hames941f2472019-04-08 21:50:48 +0000178 struct SectionInfo {
179 SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
180 : Name(Name), MB(std::move(MB)), SectionID(SectionID) {}
181 std::string Name;
182 sys::MemoryBlock MB;
183 unsigned SectionID = ~0U;
184 };
185
186 SmallVector<SectionInfo, 16> FunctionMemory;
187 SmallVector<SectionInfo, 16> DataMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000188
189 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000190 unsigned SectionID,
191 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000192 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000193 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000194 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000195
Lang Hames941f2472019-04-08 21:50:48 +0000196 /// If non null, records subsequent Name -> SectionID mappings.
197 void setSectionIDsMap(SectionIDMap *SecIDMap) {
198 this->SecIDMap = SecIDMap;
199 }
200
Craig Toppere56917c2014-03-08 08:27:28 +0000201 void *getPointerToNamedFunction(const std::string &Name,
202 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000203 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000204 }
205
Craig Toppere56917c2014-03-08 08:27:28 +0000206 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000207
Lang Hames78937c22015-07-04 01:35:26 +0000208 void addDummySymbol(const std::string &Name, uint64_t Addr) {
209 DummyExterns[Name] = Addr;
210 }
211
Lang Hamesad4a9112016-08-01 20:49:11 +0000212 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000213 auto I = DummyExterns.find(Name);
214
215 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000216 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000217
218 return RTDyldMemoryManager::findSymbol(Name);
219 }
220
Tim Northover5af339a2015-06-03 18:26:52 +0000221 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
222 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000223 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000224
225 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000226 std::error_code EC;
227 sys::MemoryBlock MB =
228 sys::Memory::allocateMappedMemory(Size, nullptr,
229 sys::Memory::MF_READ |
230 sys::Memory::MF_WRITE,
231 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000232 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000233 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000234
235 PreallocSlab = MB;
236 UsePreallocation = true;
237 SlabSize = Size;
238 }
239
Lang Hames941f2472019-04-08 21:50:48 +0000240 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
241 StringRef SectionName, unsigned SectionID) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000242 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000243 if (CurrentSlabOffset + Size > SlabSize)
244 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
245
246 uintptr_t OldSlabOffset = CurrentSlabOffset;
247 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
248 if (isCode)
Lang Hames941f2472019-04-08 21:50:48 +0000249 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000250 else
Lang Hames941f2472019-04-08 21:50:48 +0000251 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000252 CurrentSlabOffset += Size;
253 return (uint8_t*)OldSlabOffset;
254 }
255
Lang Hames78937c22015-07-04 01:35:26 +0000256private:
257 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000258 sys::MemoryBlock PreallocSlab;
259 bool UsePreallocation = false;
260 uintptr_t SlabSize = 0;
261 uintptr_t CurrentSlabOffset = 0;
Lang Hames941f2472019-04-08 21:50:48 +0000262 SectionIDMap *SecIDMap = nullptr;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000263};
264
Jim Grosbacheff0a402012-01-16 22:26:39 +0000265uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
266 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000267 unsigned SectionID,
268 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000269 if (PrintAllocationRequests)
270 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
271 << Alignment << ", SectionName = " << SectionName << ")\n";
272
Lang Hames941f2472019-04-08 21:50:48 +0000273 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 if (SecIDMap)
302 (*SecIDMap)[SectionName] = SectionID;
303
Davide Italianob59ea902015-10-21 22:12:03 +0000304 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000305 return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
306 SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000307
Lang Hamesafcb70d2017-11-16 23:04:44 +0000308 std::error_code EC;
309 sys::MemoryBlock MB =
310 sys::Memory::allocateMappedMemory(Size, nullptr,
311 sys::Memory::MF_READ |
312 sys::Memory::MF_WRITE,
313 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000314 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000315 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000316 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000317 return (uint8_t*)MB.base();
318}
319
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000320static const char *ProgramName;
321
Lang Hamesee5417d2016-04-05 20:11:24 +0000322static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000323 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000324 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000325}
326
Lang Hamesd311c0e2014-05-13 22:37:41 +0000327static void loadDylibs() {
328 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000329 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000330 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000331 std::string ErrMsg;
332 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
333 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000334 }
335}
336
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000337/* *** */
338
Keno Fischerc780e8e2015-05-21 21:24:32 +0000339static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
340 assert(LoadObjects || !UseDebugObj);
341
Lang Hamesd311c0e2014-05-13 22:37:41 +0000342 // Load any dylibs requested on the command line.
343 loadDylibs();
344
Andrew Kaylord55d7012013-01-25 22:50:58 +0000345 // If we don't have any input files, read from stdin.
346 if (!InputFileList.size())
347 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000348 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000349 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000350 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000351 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000352
353 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000354
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000355 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000356 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000357 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000358 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000359
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000360 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000361 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
362
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000363 if (!MaybeObj) {
364 std::string Buf;
365 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000366 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000367 OS.flush();
368 ErrorAndExit("unable to create object file: '" + Buf + "'");
369 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000370
371 ObjectFile &Obj = **MaybeObj;
372
Keno Fischerc780e8e2015-05-21 21:24:32 +0000373 OwningBinary<ObjectFile> DebugObj;
374 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
375 ObjectFile *SymbolObj = &Obj;
376 if (LoadObjects) {
377 // Load the object file
378 LoadedObjInfo =
379 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000380
Keno Fischerc780e8e2015-05-21 21:24:32 +0000381 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000382 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000383
Keno Fischerc780e8e2015-05-21 21:24:32 +0000384 // Resolve all the relocations we can.
385 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000386
Keno Fischerc780e8e2015-05-21 21:24:32 +0000387 if (UseDebugObj) {
388 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
389 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000390 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000391 }
392 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000393
Rafael Espindolac398e672017-07-19 22:27:28 +0000394 std::unique_ptr<DIContext> Context =
395 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000396
Rafael Espindola6bf32212015-06-24 19:57:32 +0000397 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000398 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000399
Andrew Kaylord55d7012013-01-25 22:50:58 +0000400 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000401 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000402 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000403 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
404 if (!TypeOrErr) {
405 // TODO: Actually report errors helpfully.
406 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000407 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000408 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000409 SymbolRef::Type Type = *TypeOrErr;
410 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000411 Expected<StringRef> Name = Sym.getName();
412 if (!Name) {
413 // TODO: Actually report errors helpfully.
414 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000415 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000416 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000417 Expected<uint64_t> AddrOrErr = Sym.getAddress();
418 if (!AddrOrErr) {
419 // TODO: Actually report errors helpfully.
420 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000421 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000422 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000423 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000424
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000425 object::SectionedAddress Address;
426
Rafael Espindolab109c032015-06-23 02:08:48 +0000427 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000428 // If we're not using the debug object, compute the address of the
429 // symbol in memory (rather than that in the unrelocated object file)
430 // and use that to query the DWARFContext.
431 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000432 auto SecOrErr = Sym.getSection();
433 if (!SecOrErr) {
434 // TODO: Actually report errors helpfully.
435 consumeError(SecOrErr.takeError());
436 continue;
437 }
438 object::section_iterator Sec = *SecOrErr;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000439 StringRef SecName;
440 Sec->getName(SecName);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000441 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000442 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000443 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000444 if (SectionLoadAddress != 0)
445 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000446 } else if (auto SecOrErr = Sym.getSection())
447 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000448
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000449 outs() << "Function: " << *Name << ", Size = " << Size
450 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000451
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000452 Address.Address = Addr;
453 DILineInfoTable Lines =
454 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000455 for (auto &D : Lines) {
456 outs() << " Line info @ " << D.first - Addr << ": "
457 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000458 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000459 }
460 }
461 }
462
463 return 0;
464}
465
Davide Italianob59ea902015-10-21 22:12:03 +0000466static void doPreallocation(TrivialMemoryManager &MemMgr) {
467 // Allocate a slab of memory upfront, if required. This is used if
468 // we want to test small code models.
469 if (static_cast<intptr_t>(PreallocMemory) < 0)
470 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
471
472 // FIXME: Limit the amount of memory that can be preallocated?
473 if (PreallocMemory != 0)
474 MemMgr.preallocateSlab(PreallocMemory);
475}
476
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000477static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000478 // Load any dylibs requested on the command line.
479 loadDylibs();
480
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000481 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000482 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000483 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000484 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000485
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000486 // If we don't have any input files, read from stdin.
487 if (!InputFileList.size())
488 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000489 for (auto &File : InputFileList) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000490 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000491 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000492 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000493 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000494 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000495 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000496 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
497
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000498 if (!MaybeObj) {
499 std::string Buf;
500 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000501 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000502 OS.flush();
503 ErrorAndExit("unable to create object file: '" + Buf + "'");
504 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000505
506 ObjectFile &Obj = **MaybeObj;
507
Andrew Kayloradc70562012-10-02 21:18:39 +0000508 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000509 Dyld.loadObject(Obj);
510 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000511 ErrorAndExit(Dyld.getErrorString());
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000512 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000513 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000514
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000515 // Resove all the relocations we can.
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000516 // FIXME: Error out if there are unresolved relocations.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000517 Dyld.resolveRelocations();
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000518
Jim Grosbachd35159a2011-04-13 15:38:30 +0000519 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000520 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000521 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000522 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000523
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000524 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000525 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000526
Lang Hames941f2472019-04-08 21:50:48 +0000527 auto &FM_MB = FM.MB;
528
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000529 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000530 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000531 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000532 sys::Memory::MF_READ |
533 sys::Memory::MF_EXEC))
534 ErrorAndExit("unable to mark function executable: '" + EC.message() +
535 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000536 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000537
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000538 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000539 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000540
541 int (*Main)(int, const char**) =
542 (int(*)(int,const char**)) uintptr_t(MainAddress);
543 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000544 // Use the name of the first input object module as argv[0] for the target.
545 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000546 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000547 return Main(1, Argv);
548}
549
Lang Hamese1c11382014-06-27 20:20:57 +0000550static int checkAllExpressions(RuntimeDyldChecker &Checker) {
551 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000552 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
553 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
554 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000555 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000556 EC.message());
557
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000558 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
559 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000560 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000561 }
562 return 0;
563}
564
Lang Hames941f2472019-04-08 21:50:48 +0000565void applySpecificSectionMappings(RuntimeDyld &Dyld,
566 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000567
568 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000569 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000570 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000571 size_t ComaIdx = Mapping.find_first_of(",");
572
Davide Italiano07557fc2015-11-21 02:15:51 +0000573 if (ComaIdx == StringRef::npos)
574 report_fatal_error("Invalid section specification '" + Mapping +
575 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000576
Lang Hames78937c22015-07-04 01:35:26 +0000577 std::string FileName = SectionIDStr.substr(0, ComaIdx);
578 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000579 unsigned SectionID =
580 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000581
Lang Hames941f2472019-04-08 21:50:48 +0000582 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000583 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000584 uint64_t NewAddr;
585
Davide Italiano07557fc2015-11-21 02:15:51 +0000586 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
587 report_fatal_error("Invalid section address in mapping '" + Mapping +
588 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000589
Lang Hames941f2472019-04-08 21:50:48 +0000590 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000591 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000592}
593
Lang Hames9cb73532014-07-29 23:43:13 +0000594// Scatter sections in all directions!
595// Remaps section addresses for -verify mode. The following command line options
596// can be used to customize the layout of the memory within the phony target's
597// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000598// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000599// -target-addr-end <e> -- Specify where the phony target address range ends.
600// -target-section-sep <d> -- Specify how big a gap should be left between the
601// end of one section and the start of the next.
602// Defaults to zero. Set to something big
603// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
604//
Lang Hames78937c22015-07-04 01:35:26 +0000605static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000606 RuntimeDyld &Dyld,
607 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000608
609 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000610 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000611 WorklistT Worklist;
612
613 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000614 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000615 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000616 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000617
618 // Keep an "already allocated" mapping of section target addresses to sizes.
619 // Sections whose address mappings aren't specified on the command line will
620 // allocated around the explicitly mapped sections while maintaining the
621 // minimum separation.
622 std::map<uint64_t, uint64_t> AlreadyAllocated;
623
Lang Hamesff411502017-05-07 17:19:53 +0000624 // Move the previously applied mappings (whether explicitly specified on the
625 // command line, or implicitly set by RuntimeDyld) into the already-allocated
626 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000627 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
628 I != E;) {
629 WorklistT::iterator Tmp = I;
630 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000631
Lang Hames941f2472019-04-08 21:50:48 +0000632 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
633
634 if (LoadAddr != static_cast<uint64_t>(
635 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000636 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
637 // reason (e.g. zero byte COFF sections). Don't include those sections in
638 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000639 if (LoadAddr != 0)
640 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.size();
Lang Hames778ef5b2014-09-04 04:19:54 +0000641 Worklist.erase(Tmp);
642 }
643 }
Lang Hames9cb73532014-07-29 23:43:13 +0000644
645 // If the -target-addr-end option wasn't explicitly passed, then set it to a
646 // sensible default based on the target triple.
647 if (TargetAddrEnd.getNumOccurrences() == 0) {
648 if (TargetTriple.isArch16Bit())
649 TargetAddrEnd = (1ULL << 16) - 1;
650 else if (TargetTriple.isArch32Bit())
651 TargetAddrEnd = (1ULL << 32) - 1;
652 // TargetAddrEnd already has a sensible default for 64-bit systems, so
653 // there's nothing to do in the 64-bit case.
654 }
655
Lang Hames778ef5b2014-09-04 04:19:54 +0000656 // Process any elements remaining in the worklist.
657 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000658 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000659 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000660
Lang Hames778ef5b2014-09-04 04:19:54 +0000661 uint64_t NextSectionAddr = TargetAddrStart;
662
663 for (const auto &Alloc : AlreadyAllocated)
Lang Hames941f2472019-04-08 21:50:48 +0000664 if (NextSectionAddr + CurEntry->MB.size() + TargetSectionSep <= Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000665 break;
666 else
667 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
668
Lang Hames941f2472019-04-08 21:50:48 +0000669 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
670 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.size();
Lang Hames9cb73532014-07-29 23:43:13 +0000671 }
672
Lang Hames78937c22015-07-04 01:35:26 +0000673 // Add dummy symbols to the memory manager.
674 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000675 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000676
Davide Italiano07557fc2015-11-21 02:15:51 +0000677 if (EqualsIdx == StringRef::npos)
678 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
679 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000680
681 std::string Symbol = Mapping.substr(0, EqualsIdx);
682 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
683
684 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000685 if (StringRef(AddrStr).getAsInteger(0, Addr))
686 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000687
688 MemMgr.addDummySymbol(Symbol, Addr);
689 }
Lang Hames9cb73532014-07-29 23:43:13 +0000690}
691
692// Load and link the objects specified on the command line, but do not execute
693// anything. Instead, attach a RuntimeDyldChecker instance and call it to
694// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000695static int linkAndVerify() {
696
697 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000698 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000699 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000700
701 // Look up the target and build the disassembler.
702 Triple TheTriple(Triple::normalize(TripleName));
703 std::string ErrorStr;
704 const Target *TheTarget =
705 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000706 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000707 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000708
Lang Hamese1c11382014-06-27 20:20:57 +0000709 TripleName = TheTriple.getTriple();
710
711 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000712 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000713 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000714 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000715
716 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000717 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000718 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000719
720 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000721 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000722 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000723
724 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
725
726 std::unique_ptr<MCDisassembler> Disassembler(
727 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000728 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000729 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000730
731 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
732
Daniel Sanders50f17232015-09-15 16:17:27 +0000733 std::unique_ptr<MCInstPrinter> InstPrinter(
734 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000735
736 // Load any dylibs requested on the command line.
737 loadDylibs();
738
739 // Instantiate a dynamic linker.
740 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000741 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000742
Lang Hamesc7c1f212019-04-12 18:07:28 +0000743 struct StubID {
744 unsigned SectionID;
745 uint32_t Offset;
746 };
747 using StubInfos = StringMap<StubID>;
748 using StubContainers = StringMap<StubInfos>;
Lang Hames941f2472019-04-08 21:50:48 +0000749
Lang Hamesc7c1f212019-04-12 18:07:28 +0000750 StubContainers StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000751 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000752 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000753
Lang Hamesc7c1f212019-04-12 18:07:28 +0000754 Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
755 StringRef SectionName,
756 StringRef SymbolName, unsigned SectionID,
757 uint32_t StubOffset) {
758 std::string ContainerName =
759 (sys::path::filename(FilePath) + "/" + SectionName).str();
760 StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
761 });
Lang Hames941f2472019-04-08 21:50:48 +0000762
Lang Hamesc7c1f212019-04-12 18:07:28 +0000763 auto GetSymbolInfo =
764 [&Dyld, &MemMgr](
765 StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
766 RuntimeDyldChecker::MemoryRegionInfo SymInfo;
Lang Hames941f2472019-04-08 21:50:48 +0000767
Lang Hamesc7c1f212019-04-12 18:07:28 +0000768 // First get the target address.
769 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
770 SymInfo.TargetAddress = InternalSymbol.getAddress();
771 else {
772 // Symbol not found in RuntimeDyld. Fall back to external lookup.
Lang Hames941f2472019-04-08 21:50:48 +0000773#ifdef _MSC_VER
Lang Hamesc7c1f212019-04-12 18:07:28 +0000774 using ExpectedLookupResult =
775 MSVCPExpected<JITSymbolResolver::LookupResult>;
Lang Hames941f2472019-04-08 21:50:48 +0000776#else
777 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
778#endif
779
780 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
781 auto ResultF = ResultP->get_future();
782
Lang Hamesc7c1f212019-04-12 18:07:28 +0000783 MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
784 [=](Expected<JITSymbolResolver::LookupResult> Result) {
785 ResultP->set_value(std::move(Result));
786 });
Lang Hames941f2472019-04-08 21:50:48 +0000787
788 auto Result = ResultF.get();
789 if (!Result)
790 return Result.takeError();
791
792 auto I = Result->find(Symbol);
793 assert(I != Result->end() &&
794 "Expected symbol address if no error occurred");
Lang Hamesc7c1f212019-04-12 18:07:28 +0000795 SymInfo.TargetAddress = I->second.getAddress();
796 }
Lang Hames941f2472019-04-08 21:50:48 +0000797
Lang Hamesc7c1f212019-04-12 18:07:28 +0000798 // Now find the symbol content if possible (otherwise leave content as a
799 // default-constructed StringRef).
800 if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
801 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
802 if (SectionID != ~0U) {
803 char *CSymAddr = static_cast<char *>(SymAddr);
804 StringRef SecContent = Dyld.getSectionContent(SectionID);
805 uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
806 SymInfo.Content = StringRef(CSymAddr, SymSize);
Lang Hames941f2472019-04-08 21:50:48 +0000807 }
Lang Hamesc7c1f212019-04-12 18:07:28 +0000808 }
809 return SymInfo;
810 };
811
812 auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
813 if (Dyld.getSymbol(Symbol))
814 return true;
815 auto SymInfo = GetSymbolInfo(Symbol);
816 if (!SymInfo) {
817 logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
818 return false;
819 }
820 return SymInfo->TargetAddress != 0;
821 };
Lang Hames941f2472019-04-08 21:50:48 +0000822
823 FileToSectionIDMap FileToSecIDMap;
824
Lang Hamesc7c1f212019-04-12 18:07:28 +0000825 auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
826 StringRef SectionName)
827 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
828 auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
829 if (!SectionID)
830 return SectionID.takeError();
831 RuntimeDyldChecker::MemoryRegionInfo SecInfo;
832 SecInfo.TargetAddress = Dyld.getSectionLoadAddress(*SectionID);
833 SecInfo.Content = Dyld.getSectionContent(*SectionID);
834 return SecInfo;
835 };
Lang Hames941f2472019-04-08 21:50:48 +0000836
Lang Hamesc7c1f212019-04-12 18:07:28 +0000837 auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
838 StringRef SymbolName)
839 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
840 if (!StubMap.count(StubContainer))
841 return make_error<StringError>("Stub container not found: " +
842 StubContainer,
843 inconvertibleErrorCode());
844 if (!StubMap[StubContainer].count(SymbolName))
845 return make_error<StringError>("Symbol name " + SymbolName +
846 " in stub container " + StubContainer,
847 inconvertibleErrorCode());
848 auto &SI = StubMap[StubContainer][SymbolName];
849 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
850 StubMemInfo.TargetAddress =
851 Dyld.getSectionLoadAddress(SI.SectionID) + SI.Offset;
852 StubMemInfo.Content =
853 Dyld.getSectionContent(SI.SectionID).substr(SI.Offset);
854 return StubMemInfo;
855 };
Lang Hames941f2472019-04-08 21:50:48 +0000856
857 // We will initialize this below once we have the first object file and can
858 // know the endianness.
859 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000860
861 // If we don't have any input files, read from stdin.
862 if (!InputFileList.size())
863 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000864 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000865 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000866 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000867 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000868
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000869 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000870 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000871
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000872 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000873 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
874
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000875 if (!MaybeObj) {
876 std::string Buf;
877 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000878 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000879 OS.flush();
880 ErrorAndExit("unable to create object file: '" + Buf + "'");
881 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000882
883 ObjectFile &Obj = **MaybeObj;
884
Lang Hames941f2472019-04-08 21:50:48 +0000885 if (!Checker)
Lang Hamesc7c1f212019-04-12 18:07:28 +0000886 Checker = llvm::make_unique<RuntimeDyldChecker>(
887 IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
888 GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
889 Disassembler.get(), InstPrinter.get(), dbgs());
Lang Hames941f2472019-04-08 21:50:48 +0000890
891 auto FileName = sys::path::filename(InputFile);
Lang Hames941f2472019-04-08 21:50:48 +0000892 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
893
Lang Hamese1c11382014-06-27 20:20:57 +0000894 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000895 Dyld.loadObject(Obj);
896 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000897 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000898 }
899 }
900
Lang Hames78937c22015-07-04 01:35:26 +0000901 // Re-map the section addresses into the phony target address space and add
902 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000903 applySpecificSectionMappings(Dyld, FileToSecIDMap);
904 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000905
Lang Hamese1c11382014-06-27 20:20:57 +0000906 // Resolve all the relocations we can.
907 Dyld.resolveRelocations();
908
Lang Hames925e51b2014-09-03 05:42:52 +0000909 // Register EH frames.
910 Dyld.registerEHFrames();
911
Lang Hames941f2472019-04-08 21:50:48 +0000912 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000913 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000914 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000915 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000916
917 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000918}
919
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000920int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000921 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000922 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000923
Lang Hamese1c11382014-06-27 20:20:57 +0000924 llvm::InitializeAllTargetInfos();
925 llvm::InitializeAllTargetMCs();
926 llvm::InitializeAllDisassemblers();
927
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000928 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
929
Lang Hames941f2472019-04-08 21:50:48 +0000930 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
931
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000932 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000933 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000934 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000935 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000936 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000937 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000938 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
939 case AC_PrintObjectLineInfo:
940 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000941 case AC_Verify:
942 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000943 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000944}