blob: 09539c457a9a9411c37889d4918010ddba2f40ea [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"
Lang Hames79669532019-09-04 20:26:25 +000030#include "llvm/Support/MSVCErrorWorkarounds.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000031#include "llvm/Support/Memory.h"
32#include "llvm/Support/MemoryBuffer.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"
Lang Hames79669532019-09-04 20:26:25 +000036#include "llvm/Support/Timer.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000037#include "llvm/Support/raw_ostream.h"
Lang Hames941f2472019-04-08 21:50:48 +000038
39#include <future>
Lang Hames778ef5b2014-09-04 04:19:54 +000040#include <list>
Lang Hamese1c11382014-06-27 20:20:57 +000041
Jim Grosbach0072cdb2011-03-18 17:11:39 +000042using namespace llvm;
43using namespace llvm::object;
44
Jim Grosbach7cb41d72011-04-13 15:49:40 +000045static cl::list<std::string>
46InputFileList(cl::Positional, cl::ZeroOrMore,
Lang Hames9c755452018-03-31 16:01:01 +000047 cl::desc("<input files>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000048
49enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000050 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000051 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000052 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000053 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000054 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000055};
56
57static cl::opt<ActionType>
58Action(cl::desc("Action to perform:"),
59 cl::init(AC_Execute),
60 cl::values(clEnumValN(AC_Execute, "execute",
61 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000062 clEnumValN(AC_PrintLineInfo, "printline",
63 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000064 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
65 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000066 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
67 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000068 clEnumValN(AC_Verify, "verify",
Mehdi Amini732afdd2016-10-08 19:41:06 +000069 "Load, link and verify the resulting memory image.")));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000070
Jim Grosbachd35159a2011-04-13 15:38:30 +000071static cl::opt<std::string>
72EntryPoint("entry",
73 cl::desc("Function to call as entry point."),
74 cl::init("_main"));
75
Lang Hamesd311c0e2014-05-13 22:37:41 +000076static cl::list<std::string>
77Dylibs("dylib",
78 cl::desc("Add library."),
79 cl::ZeroOrMore);
80
Lang Hamescf49aa32019-04-25 05:02:10 +000081static cl::list<std::string> InputArgv("args", cl::Positional,
82 cl::desc("<program arguments>..."),
83 cl::ZeroOrMore, cl::PositionalEatsArgs);
84
Lang Hamese1c11382014-06-27 20:20:57 +000085static cl::opt<std::string>
86TripleName("triple", cl::desc("Target triple for disassembler"));
87
Petar Jovanovic280e5622015-06-23 22:52:19 +000088static cl::opt<std::string>
89MCPU("mcpu",
90 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
91 cl::value_desc("cpu-name"),
92 cl::init(""));
93
Lang Hamese1c11382014-06-27 20:20:57 +000094static cl::list<std::string>
95CheckFiles("check",
96 cl::desc("File containing RuntimeDyld verifier checks."),
97 cl::ZeroOrMore);
98
Fangrui Songb5f39842019-04-24 02:40:20 +000099static cl::opt<uint64_t>
100 PreallocMemory("preallocate",
101 cl::desc("Allocate memory upfront rather than on-demand"),
102 cl::init(0));
Davide Italianob59ea902015-10-21 22:12:03 +0000103
Fangrui Songb5f39842019-04-24 02:40:20 +0000104static cl::opt<uint64_t> TargetAddrStart(
105 "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);
Lang Hames9cb73532014-07-29 23:43:13 +0000110
Fangrui Songb5f39842019-04-24 02:40:20 +0000111static cl::opt<uint64_t> TargetAddrEnd(
112 "target-addr-end",
113 cl::desc("For -verify only: end of phony target address range."),
114 cl::init(~0ULL), cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000115
Fangrui Songb5f39842019-04-24 02:40:20 +0000116static cl::opt<uint64_t> TargetSectionSep(
117 "target-section-sep",
118 cl::desc("For -verify only: Separation between sections in "
119 "phony target address space."),
120 cl::init(0), cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000121
Lang Hames778ef5b2014-09-04 04:19:54 +0000122static cl::list<std::string>
123SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000124 cl::desc("For -verify only: Map a section to a "
125 "specific address."),
126 cl::ZeroOrMore,
127 cl::Hidden);
128
129static cl::list<std::string>
130DummySymbolMappings("dummy-extern",
131 cl::desc("For -verify only: Inject a symbol into the extern "
132 "symbol table."),
133 cl::ZeroOrMore,
134 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000135
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000136static cl::opt<bool>
137PrintAllocationRequests("print-alloc-requests",
138 cl::desc("Print allocation requests made to the memory "
139 "manager by RuntimeDyld"),
140 cl::Hidden);
141
Lang Hames79669532019-09-04 20:26:25 +0000142static cl::opt<bool> ShowTimes("show-times",
143 cl::desc("Show times for llvm-rtdyld phases"),
144 cl::init(false));
145
Lang Hames941f2472019-04-08 21:50:48 +0000146ExitOnError ExitOnErr;
147
Lang Hames79669532019-09-04 20:26:25 +0000148struct RTDyldTimers {
Lang Hames41adc372019-09-04 20:26:26 +0000149 TimerGroup RTDyldTG{"llvm-rtdyld timers", "timers for llvm-rtdyld phases"};
150 Timer LoadObjectsTimer{"load", "time to load/add object files", RTDyldTG};
151 Timer LinkTimer{"link", "time to link object files", RTDyldTG};
152 Timer RunTimer{"run", "time to execute jitlink'd code", RTDyldTG};
Lang Hames79669532019-09-04 20:26:25 +0000153};
154
155std::unique_ptr<RTDyldTimers> Timers;
156
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000157/* *** */
158
Lang Hames941f2472019-04-08 21:50:48 +0000159using SectionIDMap = StringMap<unsigned>;
160using FileToSectionIDMap = StringMap<SectionIDMap>;
161
162void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
163 for (const auto &KV : FileToSecIDMap) {
164 llvm::dbgs() << "In " << KV.first() << "\n";
165 for (auto &KV2 : KV.second)
166 llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
167 }
168}
169
170Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
171 StringRef FileName, StringRef SectionName) {
172 auto I = FileToSecIDMap.find(FileName);
173 if (I == FileToSecIDMap.end())
174 return make_error<StringError>("No file named " + FileName,
175 inconvertibleErrorCode());
176 auto &SectionIDs = I->second;
177 auto J = SectionIDs.find(SectionName);
178 if (J == SectionIDs.end())
179 return make_error<StringError>("No section named \"" + SectionName +
180 "\" in file " + FileName,
181 inconvertibleErrorCode());
182 return J->second;
183}
184
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000185// A trivial memory manager that doesn't do anything fancy, just uses the
186// support library allocation routines directly.
187class TrivialMemoryManager : public RTDyldMemoryManager {
188public:
Lang Hames941f2472019-04-08 21:50:48 +0000189 struct SectionInfo {
190 SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
191 : Name(Name), MB(std::move(MB)), SectionID(SectionID) {}
192 std::string Name;
193 sys::MemoryBlock MB;
194 unsigned SectionID = ~0U;
195 };
196
197 SmallVector<SectionInfo, 16> FunctionMemory;
198 SmallVector<SectionInfo, 16> DataMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000199
200 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000201 unsigned SectionID,
202 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000203 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000204 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000205 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000206
Lang Hames941f2472019-04-08 21:50:48 +0000207 /// If non null, records subsequent Name -> SectionID mappings.
208 void setSectionIDsMap(SectionIDMap *SecIDMap) {
209 this->SecIDMap = SecIDMap;
210 }
211
Craig Toppere56917c2014-03-08 08:27:28 +0000212 void *getPointerToNamedFunction(const std::string &Name,
213 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000214 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000215 }
216
Craig Toppere56917c2014-03-08 08:27:28 +0000217 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000218
Lang Hames78937c22015-07-04 01:35:26 +0000219 void addDummySymbol(const std::string &Name, uint64_t Addr) {
220 DummyExterns[Name] = Addr;
221 }
222
Lang Hamesad4a9112016-08-01 20:49:11 +0000223 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000224 auto I = DummyExterns.find(Name);
225
226 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000227 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000228
Lang Hamescf49aa32019-04-25 05:02:10 +0000229 if (auto Sym = RTDyldMemoryManager::findSymbol(Name))
230 return Sym;
231 else if (auto Err = Sym.takeError())
232 ExitOnErr(std::move(Err));
233 else
234 ExitOnErr(make_error<StringError>("Could not find definition for \"" +
235 Name + "\"",
236 inconvertibleErrorCode()));
237 llvm_unreachable("Should have returned or exited by now");
Lang Hames78937c22015-07-04 01:35:26 +0000238 }
239
Tim Northover5af339a2015-06-03 18:26:52 +0000240 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
241 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000242 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000243
244 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000245 std::error_code EC;
246 sys::MemoryBlock MB =
247 sys::Memory::allocateMappedMemory(Size, nullptr,
248 sys::Memory::MF_READ |
249 sys::Memory::MF_WRITE,
250 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000251 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000252 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000253
254 PreallocSlab = MB;
255 UsePreallocation = true;
256 SlabSize = Size;
257 }
258
Lang Hames941f2472019-04-08 21:50:48 +0000259 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
260 StringRef SectionName, unsigned SectionID) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000261 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000262 if (CurrentSlabOffset + Size > SlabSize)
263 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
264
265 uintptr_t OldSlabOffset = CurrentSlabOffset;
266 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
267 if (isCode)
Lang Hames941f2472019-04-08 21:50:48 +0000268 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000269 else
Lang Hames941f2472019-04-08 21:50:48 +0000270 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000271 CurrentSlabOffset += Size;
272 return (uint8_t*)OldSlabOffset;
273 }
274
Lang Hames78937c22015-07-04 01:35:26 +0000275private:
276 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000277 sys::MemoryBlock PreallocSlab;
278 bool UsePreallocation = false;
279 uintptr_t SlabSize = 0;
280 uintptr_t CurrentSlabOffset = 0;
Lang Hames941f2472019-04-08 21:50:48 +0000281 SectionIDMap *SecIDMap = nullptr;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000282};
283
Jim Grosbacheff0a402012-01-16 22:26:39 +0000284uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
285 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000286 unsigned SectionID,
287 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000288 if (PrintAllocationRequests)
289 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
290 << Alignment << ", SectionName = " << SectionName << ")\n";
291
Lang Hames941f2472019-04-08 21:50:48 +0000292 if (SecIDMap)
293 (*SecIDMap)[SectionName] = SectionID;
294
Davide Italianob59ea902015-10-21 22:12:03 +0000295 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000296 return allocateFromSlab(Size, Alignment, true /* isCode */,
297 SectionName, SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000298
Lang Hamesafcb70d2017-11-16 23:04:44 +0000299 std::error_code EC;
300 sys::MemoryBlock MB =
301 sys::Memory::allocateMappedMemory(Size, nullptr,
302 sys::Memory::MF_READ |
303 sys::Memory::MF_WRITE,
304 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000305 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000306 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000307 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000308 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000309}
310
311uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
312 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000313 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000314 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000315 bool IsReadOnly) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000316 if (PrintAllocationRequests)
317 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
318 << Alignment << ", SectionName = " << SectionName << ")\n";
319
Lang Hames941f2472019-04-08 21:50:48 +0000320 if (SecIDMap)
321 (*SecIDMap)[SectionName] = SectionID;
322
Davide Italianob59ea902015-10-21 22:12:03 +0000323 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000324 return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
325 SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000326
Lang Hamesafcb70d2017-11-16 23:04:44 +0000327 std::error_code EC;
328 sys::MemoryBlock MB =
329 sys::Memory::allocateMappedMemory(Size, nullptr,
330 sys::Memory::MF_READ |
331 sys::Memory::MF_WRITE,
332 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000333 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000334 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000335 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000336 return (uint8_t*)MB.base();
337}
338
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000339static const char *ProgramName;
340
Lang Hamesee5417d2016-04-05 20:11:24 +0000341static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000342 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000343 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000344}
345
Lang Hamesd311c0e2014-05-13 22:37:41 +0000346static void loadDylibs() {
347 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000348 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000349 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000350 std::string ErrMsg;
351 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
352 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000353 }
354}
355
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000356/* *** */
357
Keno Fischerc780e8e2015-05-21 21:24:32 +0000358static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
359 assert(LoadObjects || !UseDebugObj);
360
Lang Hamesd311c0e2014-05-13 22:37:41 +0000361 // Load any dylibs requested on the command line.
362 loadDylibs();
363
Andrew Kaylord55d7012013-01-25 22:50:58 +0000364 // If we don't have any input files, read from stdin.
365 if (!InputFileList.size())
366 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000367 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000368 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000369 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000370 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000371
372 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000373
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000374 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000375 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000376 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000377 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000378
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000379 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000380 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
381
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000382 if (!MaybeObj) {
383 std::string Buf;
384 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000385 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000386 OS.flush();
387 ErrorAndExit("unable to create object file: '" + Buf + "'");
388 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000389
390 ObjectFile &Obj = **MaybeObj;
391
Keno Fischerc780e8e2015-05-21 21:24:32 +0000392 OwningBinary<ObjectFile> DebugObj;
393 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
394 ObjectFile *SymbolObj = &Obj;
395 if (LoadObjects) {
396 // Load the object file
397 LoadedObjInfo =
398 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000399
Keno Fischerc780e8e2015-05-21 21:24:32 +0000400 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000401 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000402
Keno Fischerc780e8e2015-05-21 21:24:32 +0000403 // Resolve all the relocations we can.
404 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000405
Keno Fischerc780e8e2015-05-21 21:24:32 +0000406 if (UseDebugObj) {
407 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
408 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000409 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000410 }
411 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000412
Rafael Espindolac398e672017-07-19 22:27:28 +0000413 std::unique_ptr<DIContext> Context =
414 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000415
Rafael Espindola6bf32212015-06-24 19:57:32 +0000416 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000417 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000418
Andrew Kaylord55d7012013-01-25 22:50:58 +0000419 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000420 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000421 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000422 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
423 if (!TypeOrErr) {
424 // TODO: Actually report errors helpfully.
425 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000426 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000427 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000428 SymbolRef::Type Type = *TypeOrErr;
429 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000430 Expected<StringRef> Name = Sym.getName();
431 if (!Name) {
432 // TODO: Actually report errors helpfully.
433 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000434 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000435 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000436 Expected<uint64_t> AddrOrErr = Sym.getAddress();
437 if (!AddrOrErr) {
438 // TODO: Actually report errors helpfully.
439 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000440 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000441 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000442 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000443
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000444 object::SectionedAddress Address;
445
Rafael Espindolab109c032015-06-23 02:08:48 +0000446 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000447 // If we're not using the debug object, compute the address of the
448 // symbol in memory (rather than that in the unrelocated object file)
449 // and use that to query the DWARFContext.
450 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000451 auto SecOrErr = Sym.getSection();
452 if (!SecOrErr) {
453 // TODO: Actually report errors helpfully.
454 consumeError(SecOrErr.takeError());
455 continue;
456 }
457 object::section_iterator Sec = *SecOrErr;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000458 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000459 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000460 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000461 if (SectionLoadAddress != 0)
462 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000463 } else if (auto SecOrErr = Sym.getSection())
464 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000465
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000466 outs() << "Function: " << *Name << ", Size = " << Size
467 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000468
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000469 Address.Address = Addr;
470 DILineInfoTable Lines =
471 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000472 for (auto &D : Lines) {
473 outs() << " Line info @ " << D.first - Addr << ": "
474 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000475 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000476 }
477 }
478 }
479
480 return 0;
481}
482
Davide Italianob59ea902015-10-21 22:12:03 +0000483static void doPreallocation(TrivialMemoryManager &MemMgr) {
484 // Allocate a slab of memory upfront, if required. This is used if
485 // we want to test small code models.
486 if (static_cast<intptr_t>(PreallocMemory) < 0)
487 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
488
489 // FIXME: Limit the amount of memory that can be preallocated?
490 if (PreallocMemory != 0)
491 MemMgr.preallocateSlab(PreallocMemory);
492}
493
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000494static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000495 // Load any dylibs requested on the command line.
496 loadDylibs();
497
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000498 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000499 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000500 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000501 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000502
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000503 // If we don't have any input files, read from stdin.
504 if (!InputFileList.size())
505 InputFileList.push_back("-");
Lang Hames79669532019-09-04 20:26:25 +0000506 {
507 TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr);
508 for (auto &File : InputFileList) {
509 // Load the input memory buffer.
510 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
511 MemoryBuffer::getFileOrSTDIN(File);
512 if (std::error_code EC = InputBuffer.getError())
513 ErrorAndExit("unable to read input: '" + EC.message() + "'");
514 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
515 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000516
Lang Hames79669532019-09-04 20:26:25 +0000517 if (!MaybeObj) {
518 std::string Buf;
519 raw_string_ostream OS(Buf);
520 logAllUnhandledErrors(MaybeObj.takeError(), OS);
521 OS.flush();
522 ErrorAndExit("unable to create object file: '" + Buf + "'");
523 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000524
Lang Hames79669532019-09-04 20:26:25 +0000525 ObjectFile &Obj = **MaybeObj;
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000526
Lang Hames79669532019-09-04 20:26:25 +0000527 // Load the object file
528 Dyld.loadObject(Obj);
529 if (Dyld.hasError()) {
530 ErrorAndExit(Dyld.getErrorString());
531 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000532 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000533 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000534
Lang Hames79669532019-09-04 20:26:25 +0000535 {
536 TimeRegion TR(Timers ? &Timers->LinkTimer : nullptr);
537 // Resove all the relocations we can.
538 // FIXME: Error out if there are unresolved relocations.
539 Dyld.resolveRelocations();
540 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000541
Jim Grosbachd35159a2011-04-13 15:38:30 +0000542 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000543 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000544 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000545 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000546
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000547 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000548 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000549
Lang Hames941f2472019-04-08 21:50:48 +0000550 auto &FM_MB = FM.MB;
551
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000552 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000553 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000554 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000555 sys::Memory::MF_READ |
556 sys::Memory::MF_EXEC))
557 ErrorAndExit("unable to mark function executable: '" + EC.message() +
558 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000559 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000560
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000561 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000562 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000563
564 int (*Main)(int, const char**) =
565 (int(*)(int,const char**)) uintptr_t(MainAddress);
Lang Hamescf49aa32019-04-25 05:02:10 +0000566 std::vector<const char *> Argv;
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000567 // Use the name of the first input object module as argv[0] for the target.
Lang Hamescf49aa32019-04-25 05:02:10 +0000568 Argv.push_back(InputFileList[0].data());
569 for (auto &Arg : InputArgv)
570 Argv.push_back(Arg.data());
571 Argv.push_back(nullptr);
Lang Hames79669532019-09-04 20:26:25 +0000572 int Result = 0;
573 {
574 TimeRegion TR(Timers ? &Timers->RunTimer : nullptr);
575 Result = Main(Argv.size() - 1, Argv.data());
576 }
577
578 return Result;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000579}
580
Lang Hamese1c11382014-06-27 20:20:57 +0000581static int checkAllExpressions(RuntimeDyldChecker &Checker) {
582 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000583 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
584 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
585 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000586 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000587 EC.message());
588
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000589 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
590 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000591 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000592 }
593 return 0;
594}
595
Lang Hames941f2472019-04-08 21:50:48 +0000596void applySpecificSectionMappings(RuntimeDyld &Dyld,
597 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000598
599 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000600 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000601 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000602 size_t ComaIdx = Mapping.find_first_of(",");
603
Davide Italiano07557fc2015-11-21 02:15:51 +0000604 if (ComaIdx == StringRef::npos)
605 report_fatal_error("Invalid section specification '" + Mapping +
606 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000607
Lang Hames78937c22015-07-04 01:35:26 +0000608 std::string FileName = SectionIDStr.substr(0, ComaIdx);
609 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000610 unsigned SectionID =
611 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000612
Lang Hames941f2472019-04-08 21:50:48 +0000613 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000614 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000615 uint64_t NewAddr;
616
Davide Italiano07557fc2015-11-21 02:15:51 +0000617 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
618 report_fatal_error("Invalid section address in mapping '" + Mapping +
619 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000620
Lang Hames941f2472019-04-08 21:50:48 +0000621 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000622 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000623}
624
Lang Hames9cb73532014-07-29 23:43:13 +0000625// Scatter sections in all directions!
626// Remaps section addresses for -verify mode. The following command line options
627// can be used to customize the layout of the memory within the phony target's
628// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000629// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000630// -target-addr-end <e> -- Specify where the phony target address range ends.
631// -target-section-sep <d> -- Specify how big a gap should be left between the
632// end of one section and the start of the next.
633// Defaults to zero. Set to something big
634// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
635//
Lang Hames78937c22015-07-04 01:35:26 +0000636static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000637 RuntimeDyld &Dyld,
638 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000639
640 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000641 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000642 WorklistT Worklist;
643
644 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000645 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000646 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000647 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000648
649 // Keep an "already allocated" mapping of section target addresses to sizes.
650 // Sections whose address mappings aren't specified on the command line will
651 // allocated around the explicitly mapped sections while maintaining the
652 // minimum separation.
653 std::map<uint64_t, uint64_t> AlreadyAllocated;
654
Lang Hamesff411502017-05-07 17:19:53 +0000655 // Move the previously applied mappings (whether explicitly specified on the
656 // command line, or implicitly set by RuntimeDyld) into the already-allocated
657 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000658 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
659 I != E;) {
660 WorklistT::iterator Tmp = I;
661 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000662
Lang Hames941f2472019-04-08 21:50:48 +0000663 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
664
665 if (LoadAddr != static_cast<uint64_t>(
666 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000667 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
668 // reason (e.g. zero byte COFF sections). Don't include those sections in
669 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000670 if (LoadAddr != 0)
Lang Hames93d2bdd2019-05-20 20:53:05 +0000671 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.allocatedSize();
Lang Hames778ef5b2014-09-04 04:19:54 +0000672 Worklist.erase(Tmp);
673 }
674 }
Lang Hames9cb73532014-07-29 23:43:13 +0000675
676 // If the -target-addr-end option wasn't explicitly passed, then set it to a
677 // sensible default based on the target triple.
678 if (TargetAddrEnd.getNumOccurrences() == 0) {
679 if (TargetTriple.isArch16Bit())
680 TargetAddrEnd = (1ULL << 16) - 1;
681 else if (TargetTriple.isArch32Bit())
682 TargetAddrEnd = (1ULL << 32) - 1;
683 // TargetAddrEnd already has a sensible default for 64-bit systems, so
684 // there's nothing to do in the 64-bit case.
685 }
686
Lang Hames778ef5b2014-09-04 04:19:54 +0000687 // Process any elements remaining in the worklist.
688 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000689 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000690 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000691
Lang Hames778ef5b2014-09-04 04:19:54 +0000692 uint64_t NextSectionAddr = TargetAddrStart;
693
694 for (const auto &Alloc : AlreadyAllocated)
Lang Hames93d2bdd2019-05-20 20:53:05 +0000695 if (NextSectionAddr + CurEntry->MB.allocatedSize() + TargetSectionSep <=
696 Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000697 break;
698 else
699 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
700
Lang Hames941f2472019-04-08 21:50:48 +0000701 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
Lang Hames93d2bdd2019-05-20 20:53:05 +0000702 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.allocatedSize();
Lang Hames9cb73532014-07-29 23:43:13 +0000703 }
704
Lang Hames78937c22015-07-04 01:35:26 +0000705 // Add dummy symbols to the memory manager.
706 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000707 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000708
Davide Italiano07557fc2015-11-21 02:15:51 +0000709 if (EqualsIdx == StringRef::npos)
710 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
711 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000712
713 std::string Symbol = Mapping.substr(0, EqualsIdx);
714 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
715
716 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000717 if (StringRef(AddrStr).getAsInteger(0, Addr))
718 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000719
720 MemMgr.addDummySymbol(Symbol, Addr);
721 }
Lang Hames9cb73532014-07-29 23:43:13 +0000722}
723
724// Load and link the objects specified on the command line, but do not execute
725// anything. Instead, attach a RuntimeDyldChecker instance and call it to
726// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000727static int linkAndVerify() {
728
729 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000730 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000731 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000732
733 // Look up the target and build the disassembler.
734 Triple TheTriple(Triple::normalize(TripleName));
735 std::string ErrorStr;
736 const Target *TheTarget =
737 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000738 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000739 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000740
Lang Hamese1c11382014-06-27 20:20:57 +0000741 TripleName = TheTriple.getTriple();
742
743 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000744 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000745 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000746 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000747
748 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000749 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000750 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000751
752 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000753 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000754 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000755
756 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
757
758 std::unique_ptr<MCDisassembler> Disassembler(
759 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000760 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000761 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000762
763 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
764
Daniel Sanders50f17232015-09-15 16:17:27 +0000765 std::unique_ptr<MCInstPrinter> InstPrinter(
766 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000767
768 // Load any dylibs requested on the command line.
769 loadDylibs();
770
771 // Instantiate a dynamic linker.
772 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000773 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000774
Lang Hamesc7c1f212019-04-12 18:07:28 +0000775 struct StubID {
776 unsigned SectionID;
777 uint32_t Offset;
778 };
779 using StubInfos = StringMap<StubID>;
780 using StubContainers = StringMap<StubInfos>;
Lang Hames941f2472019-04-08 21:50:48 +0000781
Lang Hamesc7c1f212019-04-12 18:07:28 +0000782 StubContainers StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000783 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000784 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000785
Lang Hamesc7c1f212019-04-12 18:07:28 +0000786 Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
787 StringRef SectionName,
788 StringRef SymbolName, unsigned SectionID,
789 uint32_t StubOffset) {
790 std::string ContainerName =
791 (sys::path::filename(FilePath) + "/" + SectionName).str();
792 StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
793 });
Lang Hames941f2472019-04-08 21:50:48 +0000794
Lang Hamesc7c1f212019-04-12 18:07:28 +0000795 auto GetSymbolInfo =
796 [&Dyld, &MemMgr](
797 StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
798 RuntimeDyldChecker::MemoryRegionInfo SymInfo;
Lang Hames941f2472019-04-08 21:50:48 +0000799
Lang Hamesc7c1f212019-04-12 18:07:28 +0000800 // First get the target address.
801 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
Lang Hames23085ec2019-05-12 22:26:33 +0000802 SymInfo.setTargetAddress(InternalSymbol.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000803 else {
804 // Symbol not found in RuntimeDyld. Fall back to external lookup.
Lang Hames941f2472019-04-08 21:50:48 +0000805#ifdef _MSC_VER
Lang Hamesc7c1f212019-04-12 18:07:28 +0000806 using ExpectedLookupResult =
807 MSVCPExpected<JITSymbolResolver::LookupResult>;
Lang Hames941f2472019-04-08 21:50:48 +0000808#else
809 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
810#endif
811
812 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
813 auto ResultF = ResultP->get_future();
814
Lang Hamesc7c1f212019-04-12 18:07:28 +0000815 MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
816 [=](Expected<JITSymbolResolver::LookupResult> Result) {
817 ResultP->set_value(std::move(Result));
818 });
Lang Hames941f2472019-04-08 21:50:48 +0000819
820 auto Result = ResultF.get();
821 if (!Result)
822 return Result.takeError();
823
824 auto I = Result->find(Symbol);
825 assert(I != Result->end() &&
826 "Expected symbol address if no error occurred");
Lang Hames23085ec2019-05-12 22:26:33 +0000827 SymInfo.setTargetAddress(I->second.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000828 }
Lang Hames941f2472019-04-08 21:50:48 +0000829
Lang Hamesc7c1f212019-04-12 18:07:28 +0000830 // Now find the symbol content if possible (otherwise leave content as a
831 // default-constructed StringRef).
832 if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
833 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
834 if (SectionID != ~0U) {
835 char *CSymAddr = static_cast<char *>(SymAddr);
836 StringRef SecContent = Dyld.getSectionContent(SectionID);
837 uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
Lang Hames23085ec2019-05-12 22:26:33 +0000838 SymInfo.setContent(StringRef(CSymAddr, SymSize));
Lang Hames941f2472019-04-08 21:50:48 +0000839 }
Lang Hamesc7c1f212019-04-12 18:07:28 +0000840 }
841 return SymInfo;
842 };
843
844 auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
845 if (Dyld.getSymbol(Symbol))
846 return true;
847 auto SymInfo = GetSymbolInfo(Symbol);
848 if (!SymInfo) {
849 logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
850 return false;
851 }
Lang Hames23085ec2019-05-12 22:26:33 +0000852 return SymInfo->getTargetAddress() != 0;
Lang Hamesc7c1f212019-04-12 18:07:28 +0000853 };
Lang Hames941f2472019-04-08 21:50:48 +0000854
855 FileToSectionIDMap FileToSecIDMap;
856
Lang Hamesc7c1f212019-04-12 18:07:28 +0000857 auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
858 StringRef SectionName)
859 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
860 auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
861 if (!SectionID)
862 return SectionID.takeError();
863 RuntimeDyldChecker::MemoryRegionInfo SecInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000864 SecInfo.setTargetAddress(Dyld.getSectionLoadAddress(*SectionID));
865 SecInfo.setContent(Dyld.getSectionContent(*SectionID));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000866 return SecInfo;
867 };
Lang Hames941f2472019-04-08 21:50:48 +0000868
Lang Hamesc7c1f212019-04-12 18:07:28 +0000869 auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
870 StringRef SymbolName)
871 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
872 if (!StubMap.count(StubContainer))
873 return make_error<StringError>("Stub container not found: " +
874 StubContainer,
875 inconvertibleErrorCode());
876 if (!StubMap[StubContainer].count(SymbolName))
877 return make_error<StringError>("Symbol name " + SymbolName +
878 " in stub container " + StubContainer,
879 inconvertibleErrorCode());
880 auto &SI = StubMap[StubContainer][SymbolName];
881 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000882 StubMemInfo.setTargetAddress(Dyld.getSectionLoadAddress(SI.SectionID) +
883 SI.Offset);
884 StubMemInfo.setContent(
885 Dyld.getSectionContent(SI.SectionID).substr(SI.Offset));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000886 return StubMemInfo;
887 };
Lang Hames941f2472019-04-08 21:50:48 +0000888
889 // We will initialize this below once we have the first object file and can
890 // know the endianness.
891 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000892
893 // If we don't have any input files, read from stdin.
894 if (!InputFileList.size())
895 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000896 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000897 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000898 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000899 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000900
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000901 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000902 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000903
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000904 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000905 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
906
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000907 if (!MaybeObj) {
908 std::string Buf;
909 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000910 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000911 OS.flush();
912 ErrorAndExit("unable to create object file: '" + Buf + "'");
913 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000914
915 ObjectFile &Obj = **MaybeObj;
916
Lang Hames941f2472019-04-08 21:50:48 +0000917 if (!Checker)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000918 Checker = std::make_unique<RuntimeDyldChecker>(
Lang Hamesc7c1f212019-04-12 18:07:28 +0000919 IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
920 GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
921 Disassembler.get(), InstPrinter.get(), dbgs());
Lang Hames941f2472019-04-08 21:50:48 +0000922
923 auto FileName = sys::path::filename(InputFile);
Lang Hames941f2472019-04-08 21:50:48 +0000924 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
925
Lang Hamese1c11382014-06-27 20:20:57 +0000926 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000927 Dyld.loadObject(Obj);
928 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000929 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000930 }
931 }
932
Lang Hames78937c22015-07-04 01:35:26 +0000933 // Re-map the section addresses into the phony target address space and add
934 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000935 applySpecificSectionMappings(Dyld, FileToSecIDMap);
936 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000937
Lang Hamese1c11382014-06-27 20:20:57 +0000938 // Resolve all the relocations we can.
939 Dyld.resolveRelocations();
940
Lang Hames925e51b2014-09-03 05:42:52 +0000941 // Register EH frames.
942 Dyld.registerEHFrames();
943
Lang Hames941f2472019-04-08 21:50:48 +0000944 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000945 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000946 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000947 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000948
949 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000950}
951
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000952int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000953 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000954 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000955
Lang Hamese1c11382014-06-27 20:20:57 +0000956 llvm::InitializeAllTargetInfos();
957 llvm::InitializeAllTargetMCs();
958 llvm::InitializeAllDisassemblers();
959
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000960 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
961
Lang Hames941f2472019-04-08 21:50:48 +0000962 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
963
Lang Hames79669532019-09-04 20:26:25 +0000964 Timers = ShowTimes ? std::make_unique<RTDyldTimers>() : nullptr;
965
966 int Result;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000967 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000968 case AC_Execute:
Lang Hames79669532019-09-04 20:26:25 +0000969 Result = executeInput();
970 break;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000971 case AC_PrintDebugLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000972 Result =
973 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ true);
974 break;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000975 case AC_PrintLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000976 Result =
977 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ false);
978 break;
Keno Fischer281b6942015-05-30 19:44:53 +0000979 case AC_PrintObjectLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000980 Result =
981 printLineInfoForInput(/* LoadObjects */ false, /* UseDebugObj */ false);
982 break;
Lang Hamese1c11382014-06-27 20:20:57 +0000983 case AC_Verify:
Lang Hames79669532019-09-04 20:26:25 +0000984 Result = linkAndVerify();
985 break;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000986 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000987}