blob: e7820bc6265e875829e179117aabedfe5888444e [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 {
149 TimerGroup RTDyldTimers{"llvm-rtdyld timers",
150 "timers for llvm-rtdyld phases"};
151 Timer LoadObjectsTimer{"load", "time to load/add object files", RTDyldTimers};
152 Timer LinkTimer{"link", "time to link object files", RTDyldTimers};
153 Timer RunTimer{"run", "time to execute jitlink'd code", RTDyldTimers};
154};
155
156std::unique_ptr<RTDyldTimers> Timers;
157
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000158/* *** */
159
Lang Hames941f2472019-04-08 21:50:48 +0000160using SectionIDMap = StringMap<unsigned>;
161using FileToSectionIDMap = StringMap<SectionIDMap>;
162
163void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
164 for (const auto &KV : FileToSecIDMap) {
165 llvm::dbgs() << "In " << KV.first() << "\n";
166 for (auto &KV2 : KV.second)
167 llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
168 }
169}
170
171Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
172 StringRef FileName, StringRef SectionName) {
173 auto I = FileToSecIDMap.find(FileName);
174 if (I == FileToSecIDMap.end())
175 return make_error<StringError>("No file named " + FileName,
176 inconvertibleErrorCode());
177 auto &SectionIDs = I->second;
178 auto J = SectionIDs.find(SectionName);
179 if (J == SectionIDs.end())
180 return make_error<StringError>("No section named \"" + SectionName +
181 "\" in file " + FileName,
182 inconvertibleErrorCode());
183 return J->second;
184}
185
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000186// A trivial memory manager that doesn't do anything fancy, just uses the
187// support library allocation routines directly.
188class TrivialMemoryManager : public RTDyldMemoryManager {
189public:
Lang Hames941f2472019-04-08 21:50:48 +0000190 struct SectionInfo {
191 SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
192 : Name(Name), MB(std::move(MB)), SectionID(SectionID) {}
193 std::string Name;
194 sys::MemoryBlock MB;
195 unsigned SectionID = ~0U;
196 };
197
198 SmallVector<SectionInfo, 16> FunctionMemory;
199 SmallVector<SectionInfo, 16> DataMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000200
201 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000202 unsigned SectionID,
203 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000204 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000205 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000206 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000207
Lang Hames941f2472019-04-08 21:50:48 +0000208 /// If non null, records subsequent Name -> SectionID mappings.
209 void setSectionIDsMap(SectionIDMap *SecIDMap) {
210 this->SecIDMap = SecIDMap;
211 }
212
Craig Toppere56917c2014-03-08 08:27:28 +0000213 void *getPointerToNamedFunction(const std::string &Name,
214 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000215 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000216 }
217
Craig Toppere56917c2014-03-08 08:27:28 +0000218 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000219
Lang Hames78937c22015-07-04 01:35:26 +0000220 void addDummySymbol(const std::string &Name, uint64_t Addr) {
221 DummyExterns[Name] = Addr;
222 }
223
Lang Hamesad4a9112016-08-01 20:49:11 +0000224 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000225 auto I = DummyExterns.find(Name);
226
227 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000228 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000229
Lang Hamescf49aa32019-04-25 05:02:10 +0000230 if (auto Sym = RTDyldMemoryManager::findSymbol(Name))
231 return Sym;
232 else if (auto Err = Sym.takeError())
233 ExitOnErr(std::move(Err));
234 else
235 ExitOnErr(make_error<StringError>("Could not find definition for \"" +
236 Name + "\"",
237 inconvertibleErrorCode()));
238 llvm_unreachable("Should have returned or exited by now");
Lang Hames78937c22015-07-04 01:35:26 +0000239 }
240
Tim Northover5af339a2015-06-03 18:26:52 +0000241 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
242 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000243 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000244
245 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000246 std::error_code EC;
247 sys::MemoryBlock MB =
248 sys::Memory::allocateMappedMemory(Size, nullptr,
249 sys::Memory::MF_READ |
250 sys::Memory::MF_WRITE,
251 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000252 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000253 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000254
255 PreallocSlab = MB;
256 UsePreallocation = true;
257 SlabSize = Size;
258 }
259
Lang Hames941f2472019-04-08 21:50:48 +0000260 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
261 StringRef SectionName, unsigned SectionID) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000262 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000263 if (CurrentSlabOffset + Size > SlabSize)
264 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
265
266 uintptr_t OldSlabOffset = CurrentSlabOffset;
267 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
268 if (isCode)
Lang Hames941f2472019-04-08 21:50:48 +0000269 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000270 else
Lang Hames941f2472019-04-08 21:50:48 +0000271 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000272 CurrentSlabOffset += Size;
273 return (uint8_t*)OldSlabOffset;
274 }
275
Lang Hames78937c22015-07-04 01:35:26 +0000276private:
277 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000278 sys::MemoryBlock PreallocSlab;
279 bool UsePreallocation = false;
280 uintptr_t SlabSize = 0;
281 uintptr_t CurrentSlabOffset = 0;
Lang Hames941f2472019-04-08 21:50:48 +0000282 SectionIDMap *SecIDMap = nullptr;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000283};
284
Jim Grosbacheff0a402012-01-16 22:26:39 +0000285uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
286 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000287 unsigned SectionID,
288 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000289 if (PrintAllocationRequests)
290 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
291 << Alignment << ", SectionName = " << SectionName << ")\n";
292
Lang Hames941f2472019-04-08 21:50:48 +0000293 if (SecIDMap)
294 (*SecIDMap)[SectionName] = SectionID;
295
Davide Italianob59ea902015-10-21 22:12:03 +0000296 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000297 return allocateFromSlab(Size, Alignment, true /* isCode */,
298 SectionName, SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000299
Lang Hamesafcb70d2017-11-16 23:04:44 +0000300 std::error_code EC;
301 sys::MemoryBlock MB =
302 sys::Memory::allocateMappedMemory(Size, nullptr,
303 sys::Memory::MF_READ |
304 sys::Memory::MF_WRITE,
305 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000306 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000307 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000308 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000309 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000310}
311
312uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
313 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000314 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000315 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000316 bool IsReadOnly) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000317 if (PrintAllocationRequests)
318 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
319 << Alignment << ", SectionName = " << SectionName << ")\n";
320
Lang Hames941f2472019-04-08 21:50:48 +0000321 if (SecIDMap)
322 (*SecIDMap)[SectionName] = SectionID;
323
Davide Italianob59ea902015-10-21 22:12:03 +0000324 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000325 return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
326 SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000327
Lang Hamesafcb70d2017-11-16 23:04:44 +0000328 std::error_code EC;
329 sys::MemoryBlock MB =
330 sys::Memory::allocateMappedMemory(Size, nullptr,
331 sys::Memory::MF_READ |
332 sys::Memory::MF_WRITE,
333 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000334 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000335 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000336 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000337 return (uint8_t*)MB.base();
338}
339
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000340static const char *ProgramName;
341
Lang Hamesee5417d2016-04-05 20:11:24 +0000342static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000343 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000344 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000345}
346
Lang Hamesd311c0e2014-05-13 22:37:41 +0000347static void loadDylibs() {
348 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000349 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000350 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000351 std::string ErrMsg;
352 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
353 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000354 }
355}
356
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000357/* *** */
358
Keno Fischerc780e8e2015-05-21 21:24:32 +0000359static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
360 assert(LoadObjects || !UseDebugObj);
361
Lang Hamesd311c0e2014-05-13 22:37:41 +0000362 // Load any dylibs requested on the command line.
363 loadDylibs();
364
Andrew Kaylord55d7012013-01-25 22:50:58 +0000365 // If we don't have any input files, read from stdin.
366 if (!InputFileList.size())
367 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000368 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000369 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000370 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000371 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000372
373 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000374
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000375 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000376 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000377 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000378 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000379
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000380 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000381 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
382
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000383 if (!MaybeObj) {
384 std::string Buf;
385 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000386 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000387 OS.flush();
388 ErrorAndExit("unable to create object file: '" + Buf + "'");
389 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000390
391 ObjectFile &Obj = **MaybeObj;
392
Keno Fischerc780e8e2015-05-21 21:24:32 +0000393 OwningBinary<ObjectFile> DebugObj;
394 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
395 ObjectFile *SymbolObj = &Obj;
396 if (LoadObjects) {
397 // Load the object file
398 LoadedObjInfo =
399 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000400
Keno Fischerc780e8e2015-05-21 21:24:32 +0000401 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000402 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000403
Keno Fischerc780e8e2015-05-21 21:24:32 +0000404 // Resolve all the relocations we can.
405 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000406
Keno Fischerc780e8e2015-05-21 21:24:32 +0000407 if (UseDebugObj) {
408 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
409 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000410 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000411 }
412 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000413
Rafael Espindolac398e672017-07-19 22:27:28 +0000414 std::unique_ptr<DIContext> Context =
415 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000416
Rafael Espindola6bf32212015-06-24 19:57:32 +0000417 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000418 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000419
Andrew Kaylord55d7012013-01-25 22:50:58 +0000420 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000421 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000422 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000423 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
424 if (!TypeOrErr) {
425 // TODO: Actually report errors helpfully.
426 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000427 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000428 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000429 SymbolRef::Type Type = *TypeOrErr;
430 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000431 Expected<StringRef> Name = Sym.getName();
432 if (!Name) {
433 // TODO: Actually report errors helpfully.
434 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000435 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000436 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000437 Expected<uint64_t> AddrOrErr = Sym.getAddress();
438 if (!AddrOrErr) {
439 // TODO: Actually report errors helpfully.
440 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000441 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000442 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000443 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000444
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000445 object::SectionedAddress Address;
446
Rafael Espindolab109c032015-06-23 02:08:48 +0000447 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000448 // If we're not using the debug object, compute the address of the
449 // symbol in memory (rather than that in the unrelocated object file)
450 // and use that to query the DWARFContext.
451 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000452 auto SecOrErr = Sym.getSection();
453 if (!SecOrErr) {
454 // TODO: Actually report errors helpfully.
455 consumeError(SecOrErr.takeError());
456 continue;
457 }
458 object::section_iterator Sec = *SecOrErr;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000459 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000460 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000461 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000462 if (SectionLoadAddress != 0)
463 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000464 } else if (auto SecOrErr = Sym.getSection())
465 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000466
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000467 outs() << "Function: " << *Name << ", Size = " << Size
468 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000469
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000470 Address.Address = Addr;
471 DILineInfoTable Lines =
472 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000473 for (auto &D : Lines) {
474 outs() << " Line info @ " << D.first - Addr << ": "
475 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000476 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000477 }
478 }
479 }
480
481 return 0;
482}
483
Davide Italianob59ea902015-10-21 22:12:03 +0000484static void doPreallocation(TrivialMemoryManager &MemMgr) {
485 // Allocate a slab of memory upfront, if required. This is used if
486 // we want to test small code models.
487 if (static_cast<intptr_t>(PreallocMemory) < 0)
488 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
489
490 // FIXME: Limit the amount of memory that can be preallocated?
491 if (PreallocMemory != 0)
492 MemMgr.preallocateSlab(PreallocMemory);
493}
494
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000495static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000496 // Load any dylibs requested on the command line.
497 loadDylibs();
498
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000499 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000500 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000501 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000502 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000503
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000504 // If we don't have any input files, read from stdin.
505 if (!InputFileList.size())
506 InputFileList.push_back("-");
Lang Hames79669532019-09-04 20:26:25 +0000507 {
508 TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr);
509 for (auto &File : InputFileList) {
510 // Load the input memory buffer.
511 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
512 MemoryBuffer::getFileOrSTDIN(File);
513 if (std::error_code EC = InputBuffer.getError())
514 ErrorAndExit("unable to read input: '" + EC.message() + "'");
515 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
516 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000517
Lang Hames79669532019-09-04 20:26:25 +0000518 if (!MaybeObj) {
519 std::string Buf;
520 raw_string_ostream OS(Buf);
521 logAllUnhandledErrors(MaybeObj.takeError(), OS);
522 OS.flush();
523 ErrorAndExit("unable to create object file: '" + Buf + "'");
524 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000525
Lang Hames79669532019-09-04 20:26:25 +0000526 ObjectFile &Obj = **MaybeObj;
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000527
Lang Hames79669532019-09-04 20:26:25 +0000528 // Load the object file
529 Dyld.loadObject(Obj);
530 if (Dyld.hasError()) {
531 ErrorAndExit(Dyld.getErrorString());
532 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000533 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000534 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000535
Lang Hames79669532019-09-04 20:26:25 +0000536 {
537 TimeRegion TR(Timers ? &Timers->LinkTimer : nullptr);
538 // Resove all the relocations we can.
539 // FIXME: Error out if there are unresolved relocations.
540 Dyld.resolveRelocations();
541 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000542
Jim Grosbachd35159a2011-04-13 15:38:30 +0000543 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000544 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000545 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000546 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000547
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000548 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000549 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000550
Lang Hames941f2472019-04-08 21:50:48 +0000551 auto &FM_MB = FM.MB;
552
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000553 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000554 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000555 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000556 sys::Memory::MF_READ |
557 sys::Memory::MF_EXEC))
558 ErrorAndExit("unable to mark function executable: '" + EC.message() +
559 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000560 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000561
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000562 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000563 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000564
565 int (*Main)(int, const char**) =
566 (int(*)(int,const char**)) uintptr_t(MainAddress);
Lang Hamescf49aa32019-04-25 05:02:10 +0000567 std::vector<const char *> Argv;
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000568 // Use the name of the first input object module as argv[0] for the target.
Lang Hamescf49aa32019-04-25 05:02:10 +0000569 Argv.push_back(InputFileList[0].data());
570 for (auto &Arg : InputArgv)
571 Argv.push_back(Arg.data());
572 Argv.push_back(nullptr);
Lang Hames79669532019-09-04 20:26:25 +0000573 int Result = 0;
574 {
575 TimeRegion TR(Timers ? &Timers->RunTimer : nullptr);
576 Result = Main(Argv.size() - 1, Argv.data());
577 }
578
579 return Result;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000580}
581
Lang Hamese1c11382014-06-27 20:20:57 +0000582static int checkAllExpressions(RuntimeDyldChecker &Checker) {
583 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000584 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
585 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
586 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000587 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000588 EC.message());
589
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000590 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
591 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000592 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000593 }
594 return 0;
595}
596
Lang Hames941f2472019-04-08 21:50:48 +0000597void applySpecificSectionMappings(RuntimeDyld &Dyld,
598 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000599
600 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000601 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000602 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000603 size_t ComaIdx = Mapping.find_first_of(",");
604
Davide Italiano07557fc2015-11-21 02:15:51 +0000605 if (ComaIdx == StringRef::npos)
606 report_fatal_error("Invalid section specification '" + Mapping +
607 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000608
Lang Hames78937c22015-07-04 01:35:26 +0000609 std::string FileName = SectionIDStr.substr(0, ComaIdx);
610 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000611 unsigned SectionID =
612 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000613
Lang Hames941f2472019-04-08 21:50:48 +0000614 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000615 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000616 uint64_t NewAddr;
617
Davide Italiano07557fc2015-11-21 02:15:51 +0000618 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
619 report_fatal_error("Invalid section address in mapping '" + Mapping +
620 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000621
Lang Hames941f2472019-04-08 21:50:48 +0000622 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000623 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000624}
625
Lang Hames9cb73532014-07-29 23:43:13 +0000626// Scatter sections in all directions!
627// Remaps section addresses for -verify mode. The following command line options
628// can be used to customize the layout of the memory within the phony target's
629// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000630// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000631// -target-addr-end <e> -- Specify where the phony target address range ends.
632// -target-section-sep <d> -- Specify how big a gap should be left between the
633// end of one section and the start of the next.
634// Defaults to zero. Set to something big
635// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
636//
Lang Hames78937c22015-07-04 01:35:26 +0000637static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000638 RuntimeDyld &Dyld,
639 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000640
641 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000642 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000643 WorklistT Worklist;
644
645 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000646 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000647 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000648 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000649
650 // Keep an "already allocated" mapping of section target addresses to sizes.
651 // Sections whose address mappings aren't specified on the command line will
652 // allocated around the explicitly mapped sections while maintaining the
653 // minimum separation.
654 std::map<uint64_t, uint64_t> AlreadyAllocated;
655
Lang Hamesff411502017-05-07 17:19:53 +0000656 // Move the previously applied mappings (whether explicitly specified on the
657 // command line, or implicitly set by RuntimeDyld) into the already-allocated
658 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000659 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
660 I != E;) {
661 WorklistT::iterator Tmp = I;
662 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000663
Lang Hames941f2472019-04-08 21:50:48 +0000664 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
665
666 if (LoadAddr != static_cast<uint64_t>(
667 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000668 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
669 // reason (e.g. zero byte COFF sections). Don't include those sections in
670 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000671 if (LoadAddr != 0)
Lang Hames93d2bdd2019-05-20 20:53:05 +0000672 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.allocatedSize();
Lang Hames778ef5b2014-09-04 04:19:54 +0000673 Worklist.erase(Tmp);
674 }
675 }
Lang Hames9cb73532014-07-29 23:43:13 +0000676
677 // If the -target-addr-end option wasn't explicitly passed, then set it to a
678 // sensible default based on the target triple.
679 if (TargetAddrEnd.getNumOccurrences() == 0) {
680 if (TargetTriple.isArch16Bit())
681 TargetAddrEnd = (1ULL << 16) - 1;
682 else if (TargetTriple.isArch32Bit())
683 TargetAddrEnd = (1ULL << 32) - 1;
684 // TargetAddrEnd already has a sensible default for 64-bit systems, so
685 // there's nothing to do in the 64-bit case.
686 }
687
Lang Hames778ef5b2014-09-04 04:19:54 +0000688 // Process any elements remaining in the worklist.
689 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000690 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000691 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000692
Lang Hames778ef5b2014-09-04 04:19:54 +0000693 uint64_t NextSectionAddr = TargetAddrStart;
694
695 for (const auto &Alloc : AlreadyAllocated)
Lang Hames93d2bdd2019-05-20 20:53:05 +0000696 if (NextSectionAddr + CurEntry->MB.allocatedSize() + TargetSectionSep <=
697 Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000698 break;
699 else
700 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
701
Lang Hames941f2472019-04-08 21:50:48 +0000702 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
Lang Hames93d2bdd2019-05-20 20:53:05 +0000703 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.allocatedSize();
Lang Hames9cb73532014-07-29 23:43:13 +0000704 }
705
Lang Hames78937c22015-07-04 01:35:26 +0000706 // Add dummy symbols to the memory manager.
707 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000708 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000709
Davide Italiano07557fc2015-11-21 02:15:51 +0000710 if (EqualsIdx == StringRef::npos)
711 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
712 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000713
714 std::string Symbol = Mapping.substr(0, EqualsIdx);
715 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
716
717 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000718 if (StringRef(AddrStr).getAsInteger(0, Addr))
719 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000720
721 MemMgr.addDummySymbol(Symbol, Addr);
722 }
Lang Hames9cb73532014-07-29 23:43:13 +0000723}
724
725// Load and link the objects specified on the command line, but do not execute
726// anything. Instead, attach a RuntimeDyldChecker instance and call it to
727// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000728static int linkAndVerify() {
729
730 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000731 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000732 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000733
734 // Look up the target and build the disassembler.
735 Triple TheTriple(Triple::normalize(TripleName));
736 std::string ErrorStr;
737 const Target *TheTarget =
738 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000739 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000740 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000741
Lang Hamese1c11382014-06-27 20:20:57 +0000742 TripleName = TheTriple.getTriple();
743
744 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000745 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000746 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000747 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000748
749 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000750 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000751 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000752
753 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000754 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000755 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000756
757 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
758
759 std::unique_ptr<MCDisassembler> Disassembler(
760 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000761 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000762 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000763
764 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
765
Daniel Sanders50f17232015-09-15 16:17:27 +0000766 std::unique_ptr<MCInstPrinter> InstPrinter(
767 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000768
769 // Load any dylibs requested on the command line.
770 loadDylibs();
771
772 // Instantiate a dynamic linker.
773 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000774 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000775
Lang Hamesc7c1f212019-04-12 18:07:28 +0000776 struct StubID {
777 unsigned SectionID;
778 uint32_t Offset;
779 };
780 using StubInfos = StringMap<StubID>;
781 using StubContainers = StringMap<StubInfos>;
Lang Hames941f2472019-04-08 21:50:48 +0000782
Lang Hamesc7c1f212019-04-12 18:07:28 +0000783 StubContainers StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000784 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000785 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000786
Lang Hamesc7c1f212019-04-12 18:07:28 +0000787 Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
788 StringRef SectionName,
789 StringRef SymbolName, unsigned SectionID,
790 uint32_t StubOffset) {
791 std::string ContainerName =
792 (sys::path::filename(FilePath) + "/" + SectionName).str();
793 StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
794 });
Lang Hames941f2472019-04-08 21:50:48 +0000795
Lang Hamesc7c1f212019-04-12 18:07:28 +0000796 auto GetSymbolInfo =
797 [&Dyld, &MemMgr](
798 StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
799 RuntimeDyldChecker::MemoryRegionInfo SymInfo;
Lang Hames941f2472019-04-08 21:50:48 +0000800
Lang Hamesc7c1f212019-04-12 18:07:28 +0000801 // First get the target address.
802 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
Lang Hames23085ec2019-05-12 22:26:33 +0000803 SymInfo.setTargetAddress(InternalSymbol.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000804 else {
805 // Symbol not found in RuntimeDyld. Fall back to external lookup.
Lang Hames941f2472019-04-08 21:50:48 +0000806#ifdef _MSC_VER
Lang Hamesc7c1f212019-04-12 18:07:28 +0000807 using ExpectedLookupResult =
808 MSVCPExpected<JITSymbolResolver::LookupResult>;
Lang Hames941f2472019-04-08 21:50:48 +0000809#else
810 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
811#endif
812
813 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
814 auto ResultF = ResultP->get_future();
815
Lang Hamesc7c1f212019-04-12 18:07:28 +0000816 MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
817 [=](Expected<JITSymbolResolver::LookupResult> Result) {
818 ResultP->set_value(std::move(Result));
819 });
Lang Hames941f2472019-04-08 21:50:48 +0000820
821 auto Result = ResultF.get();
822 if (!Result)
823 return Result.takeError();
824
825 auto I = Result->find(Symbol);
826 assert(I != Result->end() &&
827 "Expected symbol address if no error occurred");
Lang Hames23085ec2019-05-12 22:26:33 +0000828 SymInfo.setTargetAddress(I->second.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000829 }
Lang Hames941f2472019-04-08 21:50:48 +0000830
Lang Hamesc7c1f212019-04-12 18:07:28 +0000831 // Now find the symbol content if possible (otherwise leave content as a
832 // default-constructed StringRef).
833 if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
834 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
835 if (SectionID != ~0U) {
836 char *CSymAddr = static_cast<char *>(SymAddr);
837 StringRef SecContent = Dyld.getSectionContent(SectionID);
838 uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
Lang Hames23085ec2019-05-12 22:26:33 +0000839 SymInfo.setContent(StringRef(CSymAddr, SymSize));
Lang Hames941f2472019-04-08 21:50:48 +0000840 }
Lang Hamesc7c1f212019-04-12 18:07:28 +0000841 }
842 return SymInfo;
843 };
844
845 auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
846 if (Dyld.getSymbol(Symbol))
847 return true;
848 auto SymInfo = GetSymbolInfo(Symbol);
849 if (!SymInfo) {
850 logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
851 return false;
852 }
Lang Hames23085ec2019-05-12 22:26:33 +0000853 return SymInfo->getTargetAddress() != 0;
Lang Hamesc7c1f212019-04-12 18:07:28 +0000854 };
Lang Hames941f2472019-04-08 21:50:48 +0000855
856 FileToSectionIDMap FileToSecIDMap;
857
Lang Hamesc7c1f212019-04-12 18:07:28 +0000858 auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
859 StringRef SectionName)
860 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
861 auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
862 if (!SectionID)
863 return SectionID.takeError();
864 RuntimeDyldChecker::MemoryRegionInfo SecInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000865 SecInfo.setTargetAddress(Dyld.getSectionLoadAddress(*SectionID));
866 SecInfo.setContent(Dyld.getSectionContent(*SectionID));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000867 return SecInfo;
868 };
Lang Hames941f2472019-04-08 21:50:48 +0000869
Lang Hamesc7c1f212019-04-12 18:07:28 +0000870 auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
871 StringRef SymbolName)
872 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
873 if (!StubMap.count(StubContainer))
874 return make_error<StringError>("Stub container not found: " +
875 StubContainer,
876 inconvertibleErrorCode());
877 if (!StubMap[StubContainer].count(SymbolName))
878 return make_error<StringError>("Symbol name " + SymbolName +
879 " in stub container " + StubContainer,
880 inconvertibleErrorCode());
881 auto &SI = StubMap[StubContainer][SymbolName];
882 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000883 StubMemInfo.setTargetAddress(Dyld.getSectionLoadAddress(SI.SectionID) +
884 SI.Offset);
885 StubMemInfo.setContent(
886 Dyld.getSectionContent(SI.SectionID).substr(SI.Offset));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000887 return StubMemInfo;
888 };
Lang Hames941f2472019-04-08 21:50:48 +0000889
890 // We will initialize this below once we have the first object file and can
891 // know the endianness.
892 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000893
894 // If we don't have any input files, read from stdin.
895 if (!InputFileList.size())
896 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000897 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000898 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000899 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000900 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000901
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000902 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000903 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000904
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000905 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000906 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
907
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000908 if (!MaybeObj) {
909 std::string Buf;
910 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000911 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000912 OS.flush();
913 ErrorAndExit("unable to create object file: '" + Buf + "'");
914 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000915
916 ObjectFile &Obj = **MaybeObj;
917
Lang Hames941f2472019-04-08 21:50:48 +0000918 if (!Checker)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000919 Checker = std::make_unique<RuntimeDyldChecker>(
Lang Hamesc7c1f212019-04-12 18:07:28 +0000920 IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
921 GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
922 Disassembler.get(), InstPrinter.get(), dbgs());
Lang Hames941f2472019-04-08 21:50:48 +0000923
924 auto FileName = sys::path::filename(InputFile);
Lang Hames941f2472019-04-08 21:50:48 +0000925 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
926
Lang Hamese1c11382014-06-27 20:20:57 +0000927 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000928 Dyld.loadObject(Obj);
929 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000930 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000931 }
932 }
933
Lang Hames78937c22015-07-04 01:35:26 +0000934 // Re-map the section addresses into the phony target address space and add
935 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000936 applySpecificSectionMappings(Dyld, FileToSecIDMap);
937 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000938
Lang Hamese1c11382014-06-27 20:20:57 +0000939 // Resolve all the relocations we can.
940 Dyld.resolveRelocations();
941
Lang Hames925e51b2014-09-03 05:42:52 +0000942 // Register EH frames.
943 Dyld.registerEHFrames();
944
Lang Hames941f2472019-04-08 21:50:48 +0000945 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000946 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000947 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000948 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000949
950 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000951}
952
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000953int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000954 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000955 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000956
Lang Hamese1c11382014-06-27 20:20:57 +0000957 llvm::InitializeAllTargetInfos();
958 llvm::InitializeAllTargetMCs();
959 llvm::InitializeAllDisassemblers();
960
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000961 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
962
Lang Hames941f2472019-04-08 21:50:48 +0000963 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
964
Lang Hames79669532019-09-04 20:26:25 +0000965 Timers = ShowTimes ? std::make_unique<RTDyldTimers>() : nullptr;
966
967 int Result;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000968 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000969 case AC_Execute:
Lang Hames79669532019-09-04 20:26:25 +0000970 Result = executeInput();
971 break;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000972 case AC_PrintDebugLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000973 Result =
974 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ true);
975 break;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000976 case AC_PrintLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000977 Result =
978 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ false);
979 break;
Keno Fischer281b6942015-05-30 19:44:53 +0000980 case AC_PrintObjectLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000981 Result =
982 printLineInfoForInput(/* LoadObjects */ false, /* UseDebugObj */ false);
983 break;
Lang Hamese1c11382014-06-27 20:20:57 +0000984 case AC_Verify:
Lang Hames79669532019-09-04 20:26:25 +0000985 Result = linkAndVerify();
986 break;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000987 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000988}