blob: be5dbdd1c559711329896cc259a2eaf6dc733038 [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"
Mirko Brkusanin4b63ca12019-10-23 12:24:35 +020026#include "llvm/MC/MCTargetOptions.h"
Rafael Espindolab109c032015-06-23 02:08:48 +000027#include "llvm/Object/SymbolSize.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000028#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000029#include "llvm/Support/DynamicLibrary.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000030#include "llvm/Support/InitLLVM.h"
Lang Hames79669532019-09-04 20:26:25 +000031#include "llvm/Support/MSVCErrorWorkarounds.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000032#include "llvm/Support/Memory.h"
33#include "llvm/Support/MemoryBuffer.h"
Lang Hames941f2472019-04-08 21:50:48 +000034#include "llvm/Support/Path.h"
Lang Hamese1c11382014-06-27 20:20:57 +000035#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
Lang Hames79669532019-09-04 20:26:25 +000037#include "llvm/Support/Timer.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000038#include "llvm/Support/raw_ostream.h"
Lang Hames941f2472019-04-08 21:50:48 +000039
40#include <future>
Lang Hames778ef5b2014-09-04 04:19:54 +000041#include <list>
Lang Hamese1c11382014-06-27 20:20:57 +000042
Jim Grosbach0072cdb2011-03-18 17:11:39 +000043using namespace llvm;
44using namespace llvm::object;
45
Jim Grosbach7cb41d72011-04-13 15:49:40 +000046static cl::list<std::string>
47InputFileList(cl::Positional, cl::ZeroOrMore,
Lang Hames9c755452018-03-31 16:01:01 +000048 cl::desc("<input files>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000049
50enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000051 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000052 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000053 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000054 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000055 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000056};
57
58static cl::opt<ActionType>
59Action(cl::desc("Action to perform:"),
60 cl::init(AC_Execute),
61 cl::values(clEnumValN(AC_Execute, "execute",
62 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000063 clEnumValN(AC_PrintLineInfo, "printline",
64 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000065 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
66 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000067 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
68 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000069 clEnumValN(AC_Verify, "verify",
Mehdi Amini732afdd2016-10-08 19:41:06 +000070 "Load, link and verify the resulting memory image.")));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000071
Jim Grosbachd35159a2011-04-13 15:38:30 +000072static cl::opt<std::string>
73EntryPoint("entry",
74 cl::desc("Function to call as entry point."),
75 cl::init("_main"));
76
Lang Hamesd311c0e2014-05-13 22:37:41 +000077static cl::list<std::string>
78Dylibs("dylib",
79 cl::desc("Add library."),
80 cl::ZeroOrMore);
81
Lang Hamescf49aa32019-04-25 05:02:10 +000082static cl::list<std::string> InputArgv("args", cl::Positional,
83 cl::desc("<program arguments>..."),
84 cl::ZeroOrMore, cl::PositionalEatsArgs);
85
Lang Hamese1c11382014-06-27 20:20:57 +000086static cl::opt<std::string>
87TripleName("triple", cl::desc("Target triple for disassembler"));
88
Petar Jovanovic280e5622015-06-23 22:52:19 +000089static cl::opt<std::string>
90MCPU("mcpu",
91 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
92 cl::value_desc("cpu-name"),
93 cl::init(""));
94
Lang Hamese1c11382014-06-27 20:20:57 +000095static cl::list<std::string>
96CheckFiles("check",
97 cl::desc("File containing RuntimeDyld verifier checks."),
98 cl::ZeroOrMore);
99
Fangrui Songb5f39842019-04-24 02:40:20 +0000100static cl::opt<uint64_t>
101 PreallocMemory("preallocate",
102 cl::desc("Allocate memory upfront rather than on-demand"),
103 cl::init(0));
Davide Italianob59ea902015-10-21 22:12:03 +0000104
Fangrui Songb5f39842019-04-24 02:40:20 +0000105static cl::opt<uint64_t> TargetAddrStart(
106 "target-addr-start",
107 cl::desc("For -verify only: start of phony target address "
108 "range."),
109 cl::init(4096), // Start at "page 1" - no allocating at "null".
110 cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000111
Fangrui Songb5f39842019-04-24 02:40:20 +0000112static cl::opt<uint64_t> TargetAddrEnd(
113 "target-addr-end",
114 cl::desc("For -verify only: end of phony target address range."),
115 cl::init(~0ULL), cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000116
Fangrui Songb5f39842019-04-24 02:40:20 +0000117static cl::opt<uint64_t> TargetSectionSep(
118 "target-section-sep",
119 cl::desc("For -verify only: Separation between sections in "
120 "phony target address space."),
121 cl::init(0), cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000122
Lang Hames778ef5b2014-09-04 04:19:54 +0000123static cl::list<std::string>
124SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000125 cl::desc("For -verify only: Map a section to a "
126 "specific address."),
127 cl::ZeroOrMore,
128 cl::Hidden);
129
130static cl::list<std::string>
131DummySymbolMappings("dummy-extern",
132 cl::desc("For -verify only: Inject a symbol into the extern "
133 "symbol table."),
134 cl::ZeroOrMore,
135 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000136
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000137static cl::opt<bool>
138PrintAllocationRequests("print-alloc-requests",
139 cl::desc("Print allocation requests made to the memory "
140 "manager by RuntimeDyld"),
141 cl::Hidden);
142
Lang Hames79669532019-09-04 20:26:25 +0000143static cl::opt<bool> ShowTimes("show-times",
144 cl::desc("Show times for llvm-rtdyld phases"),
145 cl::init(false));
146
Lang Hames941f2472019-04-08 21:50:48 +0000147ExitOnError ExitOnErr;
148
Lang Hames79669532019-09-04 20:26:25 +0000149struct RTDyldTimers {
Lang Hames41adc372019-09-04 20:26:26 +0000150 TimerGroup RTDyldTG{"llvm-rtdyld timers", "timers for llvm-rtdyld phases"};
151 Timer LoadObjectsTimer{"load", "time to load/add object files", RTDyldTG};
152 Timer LinkTimer{"link", "time to link object files", RTDyldTG};
153 Timer RunTimer{"run", "time to execute jitlink'd code", RTDyldTG};
Lang Hames79669532019-09-04 20:26:25 +0000154};
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)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100192 : Name(std::string(Name)), MB(std::move(MB)), SectionID(SectionID) {}
Lang Hames941f2472019-04-08 21:50:48 +0000193 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("=");
Benjamin Krameradcd0262020-01-28 20:23:46 +0100602 std::string SectionIDStr = std::string(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();
Benjamin Krameradcd0262020-01-28 20:23:46 +0100615 std::string NewAddrStr = std::string(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
Mirko Brkusanin4b63ca12019-10-23 12:24:35 +0200753 MCTargetOptions MCOptions;
754 std::unique_ptr<MCAsmInfo> MAI(
755 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
Davide Italianoebb27af2015-11-21 05:49:07 +0000756 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000757 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000758
759 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
760
761 std::unique_ptr<MCDisassembler> Disassembler(
762 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000763 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000764 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000765
766 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
767
Daniel Sanders50f17232015-09-15 16:17:27 +0000768 std::unique_ptr<MCInstPrinter> InstPrinter(
769 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000770
771 // Load any dylibs requested on the command line.
772 loadDylibs();
773
774 // Instantiate a dynamic linker.
775 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000776 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000777
Lang Hamesc7c1f212019-04-12 18:07:28 +0000778 struct StubID {
779 unsigned SectionID;
780 uint32_t Offset;
781 };
782 using StubInfos = StringMap<StubID>;
783 using StubContainers = StringMap<StubInfos>;
Lang Hames941f2472019-04-08 21:50:48 +0000784
Lang Hamesc7c1f212019-04-12 18:07:28 +0000785 StubContainers StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000786 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000787 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000788
Lang Hamesc7c1f212019-04-12 18:07:28 +0000789 Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
790 StringRef SectionName,
791 StringRef SymbolName, unsigned SectionID,
792 uint32_t StubOffset) {
793 std::string ContainerName =
794 (sys::path::filename(FilePath) + "/" + SectionName).str();
795 StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
796 });
Lang Hames941f2472019-04-08 21:50:48 +0000797
Lang Hamesc7c1f212019-04-12 18:07:28 +0000798 auto GetSymbolInfo =
799 [&Dyld, &MemMgr](
800 StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
801 RuntimeDyldChecker::MemoryRegionInfo SymInfo;
Lang Hames941f2472019-04-08 21:50:48 +0000802
Lang Hamesc7c1f212019-04-12 18:07:28 +0000803 // First get the target address.
804 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
Lang Hames23085ec2019-05-12 22:26:33 +0000805 SymInfo.setTargetAddress(InternalSymbol.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000806 else {
807 // Symbol not found in RuntimeDyld. Fall back to external lookup.
Lang Hames941f2472019-04-08 21:50:48 +0000808#ifdef _MSC_VER
Lang Hamesc7c1f212019-04-12 18:07:28 +0000809 using ExpectedLookupResult =
810 MSVCPExpected<JITSymbolResolver::LookupResult>;
Lang Hames941f2472019-04-08 21:50:48 +0000811#else
812 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
813#endif
814
815 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
816 auto ResultF = ResultP->get_future();
817
Lang Hamesc7c1f212019-04-12 18:07:28 +0000818 MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
819 [=](Expected<JITSymbolResolver::LookupResult> Result) {
820 ResultP->set_value(std::move(Result));
821 });
Lang Hames941f2472019-04-08 21:50:48 +0000822
823 auto Result = ResultF.get();
824 if (!Result)
825 return Result.takeError();
826
827 auto I = Result->find(Symbol);
828 assert(I != Result->end() &&
829 "Expected symbol address if no error occurred");
Lang Hames23085ec2019-05-12 22:26:33 +0000830 SymInfo.setTargetAddress(I->second.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000831 }
Lang Hames941f2472019-04-08 21:50:48 +0000832
Lang Hamesc7c1f212019-04-12 18:07:28 +0000833 // Now find the symbol content if possible (otherwise leave content as a
834 // default-constructed StringRef).
835 if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
836 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
837 if (SectionID != ~0U) {
838 char *CSymAddr = static_cast<char *>(SymAddr);
839 StringRef SecContent = Dyld.getSectionContent(SectionID);
840 uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
Lang Hames23085ec2019-05-12 22:26:33 +0000841 SymInfo.setContent(StringRef(CSymAddr, SymSize));
Lang Hames941f2472019-04-08 21:50:48 +0000842 }
Lang Hamesc7c1f212019-04-12 18:07:28 +0000843 }
844 return SymInfo;
845 };
846
847 auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
848 if (Dyld.getSymbol(Symbol))
849 return true;
850 auto SymInfo = GetSymbolInfo(Symbol);
851 if (!SymInfo) {
852 logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
853 return false;
854 }
Lang Hames23085ec2019-05-12 22:26:33 +0000855 return SymInfo->getTargetAddress() != 0;
Lang Hamesc7c1f212019-04-12 18:07:28 +0000856 };
Lang Hames941f2472019-04-08 21:50:48 +0000857
858 FileToSectionIDMap FileToSecIDMap;
859
Lang Hamesc7c1f212019-04-12 18:07:28 +0000860 auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
861 StringRef SectionName)
862 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
863 auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
864 if (!SectionID)
865 return SectionID.takeError();
866 RuntimeDyldChecker::MemoryRegionInfo SecInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000867 SecInfo.setTargetAddress(Dyld.getSectionLoadAddress(*SectionID));
868 SecInfo.setContent(Dyld.getSectionContent(*SectionID));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000869 return SecInfo;
870 };
Lang Hames941f2472019-04-08 21:50:48 +0000871
Lang Hamesc7c1f212019-04-12 18:07:28 +0000872 auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
873 StringRef SymbolName)
874 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
875 if (!StubMap.count(StubContainer))
876 return make_error<StringError>("Stub container not found: " +
877 StubContainer,
878 inconvertibleErrorCode());
879 if (!StubMap[StubContainer].count(SymbolName))
880 return make_error<StringError>("Symbol name " + SymbolName +
881 " in stub container " + StubContainer,
882 inconvertibleErrorCode());
883 auto &SI = StubMap[StubContainer][SymbolName];
884 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000885 StubMemInfo.setTargetAddress(Dyld.getSectionLoadAddress(SI.SectionID) +
886 SI.Offset);
887 StubMemInfo.setContent(
888 Dyld.getSectionContent(SI.SectionID).substr(SI.Offset));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000889 return StubMemInfo;
890 };
Lang Hames941f2472019-04-08 21:50:48 +0000891
892 // We will initialize this below once we have the first object file and can
893 // know the endianness.
894 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000895
896 // If we don't have any input files, read from stdin.
897 if (!InputFileList.size())
898 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000899 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000900 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000901 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000902 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000903
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000904 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000905 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000906
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000907 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000908 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
909
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000910 if (!MaybeObj) {
911 std::string Buf;
912 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000913 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000914 OS.flush();
915 ErrorAndExit("unable to create object file: '" + Buf + "'");
916 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000917
918 ObjectFile &Obj = **MaybeObj;
919
Lang Hames941f2472019-04-08 21:50:48 +0000920 if (!Checker)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000921 Checker = std::make_unique<RuntimeDyldChecker>(
Lang Hamesc7c1f212019-04-12 18:07:28 +0000922 IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
923 GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
924 Disassembler.get(), InstPrinter.get(), dbgs());
Lang Hames941f2472019-04-08 21:50:48 +0000925
926 auto FileName = sys::path::filename(InputFile);
Lang Hames941f2472019-04-08 21:50:48 +0000927 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
928
Lang Hamese1c11382014-06-27 20:20:57 +0000929 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000930 Dyld.loadObject(Obj);
931 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000932 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000933 }
934 }
935
Lang Hames78937c22015-07-04 01:35:26 +0000936 // Re-map the section addresses into the phony target address space and add
937 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000938 applySpecificSectionMappings(Dyld, FileToSecIDMap);
939 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000940
Lang Hamese1c11382014-06-27 20:20:57 +0000941 // Resolve all the relocations we can.
942 Dyld.resolveRelocations();
943
Lang Hames925e51b2014-09-03 05:42:52 +0000944 // Register EH frames.
945 Dyld.registerEHFrames();
946
Lang Hames941f2472019-04-08 21:50:48 +0000947 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000948 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000949 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000950 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000951
952 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000953}
954
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000955int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000956 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000957 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000958
Lang Hamese1c11382014-06-27 20:20:57 +0000959 llvm::InitializeAllTargetInfos();
960 llvm::InitializeAllTargetMCs();
961 llvm::InitializeAllDisassemblers();
962
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000963 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
964
Lang Hames941f2472019-04-08 21:50:48 +0000965 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
966
Lang Hames79669532019-09-04 20:26:25 +0000967 Timers = ShowTimes ? std::make_unique<RTDyldTimers>() : nullptr;
968
969 int Result;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000970 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000971 case AC_Execute:
Lang Hames79669532019-09-04 20:26:25 +0000972 Result = executeInput();
973 break;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000974 case AC_PrintDebugLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000975 Result =
976 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ true);
977 break;
Andrew Kaylord55d7012013-01-25 22:50:58 +0000978 case AC_PrintLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000979 Result =
980 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ false);
981 break;
Keno Fischer281b6942015-05-30 19:44:53 +0000982 case AC_PrintObjectLineInfo:
Lang Hames79669532019-09-04 20:26:25 +0000983 Result =
984 printLineInfoForInput(/* LoadObjects */ false, /* UseDebugObj */ false);
985 break;
Lang Hamese1c11382014-06-27 20:20:57 +0000986 case AC_Verify:
Lang Hames79669532019-09-04 20:26:25 +0000987 Result = linkAndVerify();
988 break;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000989 }
Sjoerd Meijer5f349d52019-09-16 10:30:37 +0000990 return Result;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000991}