blob: b866ca7e0ad9adc19618a02db25a5c4bb95bf550 [file] [log] [blame]
Jim Grosbach0072cdb2011-03-18 17:11:39 +00001//===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jim Grosbach0072cdb2011-03-18 17:11:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This is a testing tool for use with the MC-JIT LLVM components.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000013#include "llvm/ADT/StringMap.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000014#include "llvm/DebugInfo/DIContext.h"
15#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Lang Hames633fe142015-03-30 03:37:06 +000016#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ExecutionEngine/RuntimeDyld.h"
Lang Hamese1c11382014-06-27 20:20:57 +000018#include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000021#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Lang Hamese1c11382014-06-27 20:20:57 +000022#include "llvm/MC/MCInstPrinter.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000023#include "llvm/MC/MCInstrInfo.h"
Lang Hamese1c11382014-06-27 20:20:57 +000024#include "llvm/MC/MCRegisterInfo.h"
Pete Cooper3de83e42015-05-15 21:58:42 +000025#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindolab109c032015-06-23 02:08:48 +000026#include "llvm/Object/SymbolSize.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000027#include "llvm/Support/CommandLine.h"
Lang Hamesd311c0e2014-05-13 22:37:41 +000028#include "llvm/Support/DynamicLibrary.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000029#include "llvm/Support/InitLLVM.h"
Jim Grosbach0072cdb2011-03-18 17:11:39 +000030#include "llvm/Support/Memory.h"
31#include "llvm/Support/MemoryBuffer.h"
Simon Pilgrim563f35a2019-04-09 10:15:10 +000032#include "llvm/Support/MSVCErrorWorkarounds.h"
Lang Hames941f2472019-04-08 21:50:48 +000033#include "llvm/Support/Path.h"
Lang Hamese1c11382014-06-27 20:20:57 +000034#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/TargetSelect.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000036#include "llvm/Support/raw_ostream.h"
Lang Hames941f2472019-04-08 21:50:48 +000037
38#include <future>
Lang Hames778ef5b2014-09-04 04:19:54 +000039#include <list>
Lang Hamese1c11382014-06-27 20:20:57 +000040
Jim Grosbach0072cdb2011-03-18 17:11:39 +000041using namespace llvm;
42using namespace llvm::object;
43
Jim Grosbach7cb41d72011-04-13 15:49:40 +000044static cl::list<std::string>
45InputFileList(cl::Positional, cl::ZeroOrMore,
Lang Hames9c755452018-03-31 16:01:01 +000046 cl::desc("<input files>"));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000047
48enum ActionType {
Andrew Kaylord55d7012013-01-25 22:50:58 +000049 AC_Execute,
Keno Fischer281b6942015-05-30 19:44:53 +000050 AC_PrintObjectLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000051 AC_PrintLineInfo,
Keno Fischerc780e8e2015-05-21 21:24:32 +000052 AC_PrintDebugLineInfo,
Lang Hamese1c11382014-06-27 20:20:57 +000053 AC_Verify
Jim Grosbach0072cdb2011-03-18 17:11:39 +000054};
55
56static cl::opt<ActionType>
57Action(cl::desc("Action to perform:"),
58 cl::init(AC_Execute),
59 cl::values(clEnumValN(AC_Execute, "execute",
60 "Load, link, and execute the inputs."),
Andrew Kaylord55d7012013-01-25 22:50:58 +000061 clEnumValN(AC_PrintLineInfo, "printline",
62 "Load, link, and print line information for each function."),
Keno Fischerc780e8e2015-05-21 21:24:32 +000063 clEnumValN(AC_PrintDebugLineInfo, "printdebugline",
64 "Load, link, and print line information for each function using the debug object"),
Keno Fischer281b6942015-05-30 19:44:53 +000065 clEnumValN(AC_PrintObjectLineInfo, "printobjline",
66 "Like -printlineinfo but does not load the object first"),
Lang Hamese1c11382014-06-27 20:20:57 +000067 clEnumValN(AC_Verify, "verify",
Mehdi Amini732afdd2016-10-08 19:41:06 +000068 "Load, link and verify the resulting memory image.")));
Jim Grosbach0072cdb2011-03-18 17:11:39 +000069
Jim Grosbachd35159a2011-04-13 15:38:30 +000070static cl::opt<std::string>
71EntryPoint("entry",
72 cl::desc("Function to call as entry point."),
73 cl::init("_main"));
74
Lang Hamesd311c0e2014-05-13 22:37:41 +000075static cl::list<std::string>
76Dylibs("dylib",
77 cl::desc("Add library."),
78 cl::ZeroOrMore);
79
Lang Hamese1c11382014-06-27 20:20:57 +000080static cl::opt<std::string>
81TripleName("triple", cl::desc("Target triple for disassembler"));
82
Petar Jovanovic280e5622015-06-23 22:52:19 +000083static cl::opt<std::string>
84MCPU("mcpu",
85 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
86 cl::value_desc("cpu-name"),
87 cl::init(""));
88
Lang Hamese1c11382014-06-27 20:20:57 +000089static cl::list<std::string>
90CheckFiles("check",
91 cl::desc("File containing RuntimeDyld verifier checks."),
92 cl::ZeroOrMore);
93
Lang Hames776f1d52018-10-23 01:36:33 +000094// Tracking BUG: 19665
95// http://llvm.org/bugs/show_bug.cgi?id=19665
96//
97// Do not change these options to cl::opt<uint64_t> since this silently breaks
98// argument parsing.
99static cl::opt<unsigned long long>
Davide Italianob59ea902015-10-21 22:12:03 +0000100PreallocMemory("preallocate",
101 cl::desc("Allocate memory upfront rather than on-demand"),
102 cl::init(0));
103
Lang Hames776f1d52018-10-23 01:36:33 +0000104static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000105TargetAddrStart("target-addr-start",
106 cl::desc("For -verify only: start of phony target address "
107 "range."),
108 cl::init(4096), // Start at "page 1" - no allocating at "null".
109 cl::Hidden);
110
Lang Hames776f1d52018-10-23 01:36:33 +0000111static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000112TargetAddrEnd("target-addr-end",
113 cl::desc("For -verify only: end of phony target address range."),
114 cl::init(~0ULL),
115 cl::Hidden);
116
Lang Hames776f1d52018-10-23 01:36:33 +0000117static cl::opt<unsigned long long>
Lang Hames9cb73532014-07-29 23:43:13 +0000118TargetSectionSep("target-section-sep",
119 cl::desc("For -verify only: Separation between sections in "
120 "phony target address space."),
121 cl::init(0),
122 cl::Hidden);
123
Lang Hames778ef5b2014-09-04 04:19:54 +0000124static cl::list<std::string>
125SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000126 cl::desc("For -verify only: Map a section to a "
127 "specific address."),
128 cl::ZeroOrMore,
129 cl::Hidden);
130
131static cl::list<std::string>
132DummySymbolMappings("dummy-extern",
133 cl::desc("For -verify only: Inject a symbol into the extern "
134 "symbol table."),
135 cl::ZeroOrMore,
136 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000137
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000138static cl::opt<bool>
139PrintAllocationRequests("print-alloc-requests",
140 cl::desc("Print allocation requests made to the memory "
141 "manager by RuntimeDyld"),
142 cl::Hidden);
143
Lang Hames941f2472019-04-08 21:50:48 +0000144ExitOnError ExitOnErr;
145
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000146/* *** */
147
Lang Hames941f2472019-04-08 21:50:48 +0000148using SectionIDMap = StringMap<unsigned>;
149using FileToSectionIDMap = StringMap<SectionIDMap>;
150
151void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
152 for (const auto &KV : FileToSecIDMap) {
153 llvm::dbgs() << "In " << KV.first() << "\n";
154 for (auto &KV2 : KV.second)
155 llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
156 }
157}
158
159Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
160 StringRef FileName, StringRef SectionName) {
161 auto I = FileToSecIDMap.find(FileName);
162 if (I == FileToSecIDMap.end())
163 return make_error<StringError>("No file named " + FileName,
164 inconvertibleErrorCode());
165 auto &SectionIDs = I->second;
166 auto J = SectionIDs.find(SectionName);
167 if (J == SectionIDs.end())
168 return make_error<StringError>("No section named \"" + SectionName +
169 "\" in file " + FileName,
170 inconvertibleErrorCode());
171 return J->second;
172}
173
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000174// A trivial memory manager that doesn't do anything fancy, just uses the
175// support library allocation routines directly.
176class TrivialMemoryManager : public RTDyldMemoryManager {
177public:
Lang Hames941f2472019-04-08 21:50:48 +0000178 struct SectionInfo {
179 SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
180 : Name(Name), MB(std::move(MB)), SectionID(SectionID) {}
181 std::string Name;
182 sys::MemoryBlock MB;
183 unsigned SectionID = ~0U;
184 };
185
186 SmallVector<SectionInfo, 16> FunctionMemory;
187 SmallVector<SectionInfo, 16> DataMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000188
189 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000190 unsigned SectionID,
191 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000192 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000193 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000194 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000195
Lang Hames941f2472019-04-08 21:50:48 +0000196 /// If non null, records subsequent Name -> SectionID mappings.
197 void setSectionIDsMap(SectionIDMap *SecIDMap) {
198 this->SecIDMap = SecIDMap;
199 }
200
Craig Toppere56917c2014-03-08 08:27:28 +0000201 void *getPointerToNamedFunction(const std::string &Name,
202 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000203 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000204 }
205
Craig Toppere56917c2014-03-08 08:27:28 +0000206 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000207
Lang Hames78937c22015-07-04 01:35:26 +0000208 void addDummySymbol(const std::string &Name, uint64_t Addr) {
209 DummyExterns[Name] = Addr;
210 }
211
Lang Hamesad4a9112016-08-01 20:49:11 +0000212 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000213 auto I = DummyExterns.find(Name);
214
215 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000216 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000217
218 return RTDyldMemoryManager::findSymbol(Name);
219 }
220
Tim Northover5af339a2015-06-03 18:26:52 +0000221 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
222 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000223 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000224
225 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000226 std::error_code EC;
227 sys::MemoryBlock MB =
228 sys::Memory::allocateMappedMemory(Size, nullptr,
229 sys::Memory::MF_READ |
230 sys::Memory::MF_WRITE,
231 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000232 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000233 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000234
235 PreallocSlab = MB;
236 UsePreallocation = true;
237 SlabSize = Size;
238 }
239
Lang Hames941f2472019-04-08 21:50:48 +0000240 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
241 StringRef SectionName, unsigned SectionID) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000242 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000243 if (CurrentSlabOffset + Size > SlabSize)
244 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
245
246 uintptr_t OldSlabOffset = CurrentSlabOffset;
247 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
248 if (isCode)
Lang Hames941f2472019-04-08 21:50:48 +0000249 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000250 else
Lang Hames941f2472019-04-08 21:50:48 +0000251 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000252 CurrentSlabOffset += Size;
253 return (uint8_t*)OldSlabOffset;
254 }
255
Lang Hames78937c22015-07-04 01:35:26 +0000256private:
257 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000258 sys::MemoryBlock PreallocSlab;
259 bool UsePreallocation = false;
260 uintptr_t SlabSize = 0;
261 uintptr_t CurrentSlabOffset = 0;
Lang Hames941f2472019-04-08 21:50:48 +0000262 SectionIDMap *SecIDMap = nullptr;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000263};
264
Jim Grosbacheff0a402012-01-16 22:26:39 +0000265uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
266 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000267 unsigned SectionID,
268 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000269 if (PrintAllocationRequests)
270 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
271 << Alignment << ", SectionName = " << SectionName << ")\n";
272
Lang Hames941f2472019-04-08 21:50:48 +0000273 dbgs() << " Registering code section \"" << SectionName << "\"\n";
274 if (SecIDMap)
275 (*SecIDMap)[SectionName] = SectionID;
276
Davide Italianob59ea902015-10-21 22:12:03 +0000277 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000278 return allocateFromSlab(Size, Alignment, true /* isCode */,
279 SectionName, SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000280
Lang Hamesafcb70d2017-11-16 23:04:44 +0000281 std::error_code EC;
282 sys::MemoryBlock MB =
283 sys::Memory::allocateMappedMemory(Size, nullptr,
284 sys::Memory::MF_READ |
285 sys::Memory::MF_WRITE,
286 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000287 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000288 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000289 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000290 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000291}
292
293uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
294 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000295 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000296 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000297 bool IsReadOnly) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000298 if (PrintAllocationRequests)
299 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
300 << Alignment << ", SectionName = " << SectionName << ")\n";
301
Lang Hames941f2472019-04-08 21:50:48 +0000302 dbgs() << " Registering code section \"" << SectionName << "\"\n";
303 if (SecIDMap)
304 (*SecIDMap)[SectionName] = SectionID;
305
Davide Italianob59ea902015-10-21 22:12:03 +0000306 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000307 return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
308 SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000309
Lang Hamesafcb70d2017-11-16 23:04:44 +0000310 std::error_code EC;
311 sys::MemoryBlock MB =
312 sys::Memory::allocateMappedMemory(Size, nullptr,
313 sys::Memory::MF_READ |
314 sys::Memory::MF_WRITE,
315 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000316 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000317 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000318 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000319 return (uint8_t*)MB.base();
320}
321
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000322static const char *ProgramName;
323
Lang Hamesee5417d2016-04-05 20:11:24 +0000324static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000325 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000326 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000327}
328
Lang Hamesd311c0e2014-05-13 22:37:41 +0000329static void loadDylibs() {
330 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000331 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000332 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000333 std::string ErrMsg;
334 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
335 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000336 }
337}
338
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000339/* *** */
340
Keno Fischerc780e8e2015-05-21 21:24:32 +0000341static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
342 assert(LoadObjects || !UseDebugObj);
343
Lang Hamesd311c0e2014-05-13 22:37:41 +0000344 // Load any dylibs requested on the command line.
345 loadDylibs();
346
Andrew Kaylord55d7012013-01-25 22:50:58 +0000347 // If we don't have any input files, read from stdin.
348 if (!InputFileList.size())
349 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000350 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000351 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000352 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000353 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000354
355 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000356
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000357 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000358 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000359 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000360 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000361
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000362 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000363 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
364
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000365 if (!MaybeObj) {
366 std::string Buf;
367 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000368 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000369 OS.flush();
370 ErrorAndExit("unable to create object file: '" + Buf + "'");
371 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000372
373 ObjectFile &Obj = **MaybeObj;
374
Keno Fischerc780e8e2015-05-21 21:24:32 +0000375 OwningBinary<ObjectFile> DebugObj;
376 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
377 ObjectFile *SymbolObj = &Obj;
378 if (LoadObjects) {
379 // Load the object file
380 LoadedObjInfo =
381 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000382
Keno Fischerc780e8e2015-05-21 21:24:32 +0000383 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000384 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000385
Keno Fischerc780e8e2015-05-21 21:24:32 +0000386 // Resolve all the relocations we can.
387 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000388
Keno Fischerc780e8e2015-05-21 21:24:32 +0000389 if (UseDebugObj) {
390 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
391 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000392 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000393 }
394 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000395
Rafael Espindolac398e672017-07-19 22:27:28 +0000396 std::unique_ptr<DIContext> Context =
397 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000398
Rafael Espindola6bf32212015-06-24 19:57:32 +0000399 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000400 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000401
Andrew Kaylord55d7012013-01-25 22:50:58 +0000402 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000403 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000404 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000405 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
406 if (!TypeOrErr) {
407 // TODO: Actually report errors helpfully.
408 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000409 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000410 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000411 SymbolRef::Type Type = *TypeOrErr;
412 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000413 Expected<StringRef> Name = Sym.getName();
414 if (!Name) {
415 // TODO: Actually report errors helpfully.
416 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000417 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000418 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000419 Expected<uint64_t> AddrOrErr = Sym.getAddress();
420 if (!AddrOrErr) {
421 // TODO: Actually report errors helpfully.
422 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000423 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000424 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000425 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000426
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000427 object::SectionedAddress Address;
428
Rafael Espindolab109c032015-06-23 02:08:48 +0000429 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000430 // If we're not using the debug object, compute the address of the
431 // symbol in memory (rather than that in the unrelocated object file)
432 // and use that to query the DWARFContext.
433 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000434 auto SecOrErr = Sym.getSection();
435 if (!SecOrErr) {
436 // TODO: Actually report errors helpfully.
437 consumeError(SecOrErr.takeError());
438 continue;
439 }
440 object::section_iterator Sec = *SecOrErr;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000441 StringRef SecName;
442 Sec->getName(SecName);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000443 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000444 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000445 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000446 if (SectionLoadAddress != 0)
447 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000448 } else if (auto SecOrErr = Sym.getSection())
449 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000450
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000451 outs() << "Function: " << *Name << ", Size = " << Size
452 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000453
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000454 Address.Address = Addr;
455 DILineInfoTable Lines =
456 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000457 for (auto &D : Lines) {
458 outs() << " Line info @ " << D.first - Addr << ": "
459 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000460 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000461 }
462 }
463 }
464
465 return 0;
466}
467
Davide Italianob59ea902015-10-21 22:12:03 +0000468static void doPreallocation(TrivialMemoryManager &MemMgr) {
469 // Allocate a slab of memory upfront, if required. This is used if
470 // we want to test small code models.
471 if (static_cast<intptr_t>(PreallocMemory) < 0)
472 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
473
474 // FIXME: Limit the amount of memory that can be preallocated?
475 if (PreallocMemory != 0)
476 MemMgr.preallocateSlab(PreallocMemory);
477}
478
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000479static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000480 // Load any dylibs requested on the command line.
481 loadDylibs();
482
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000483 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000484 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000485 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000486 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000487
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000488 // If we don't have any input files, read from stdin.
489 if (!InputFileList.size())
490 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000491 for (auto &File : InputFileList) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000492 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000493 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000494 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000495 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000496 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000497 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000498 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
499
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000500 if (!MaybeObj) {
501 std::string Buf;
502 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000503 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000504 OS.flush();
505 ErrorAndExit("unable to create object file: '" + Buf + "'");
506 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000507
508 ObjectFile &Obj = **MaybeObj;
509
Andrew Kayloradc70562012-10-02 21:18:39 +0000510 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000511 Dyld.loadObject(Obj);
512 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000513 ErrorAndExit(Dyld.getErrorString());
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000514 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000515 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000516
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000517 // Resove all the relocations we can.
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000518 // FIXME: Error out if there are unresolved relocations.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000519 Dyld.resolveRelocations();
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000520
Jim Grosbachd35159a2011-04-13 15:38:30 +0000521 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000522 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000523 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000524 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000525
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000526 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000527 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000528
Lang Hames941f2472019-04-08 21:50:48 +0000529 auto &FM_MB = FM.MB;
530
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000531 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000532 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000533 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000534 sys::Memory::MF_READ |
535 sys::Memory::MF_EXEC))
536 ErrorAndExit("unable to mark function executable: '" + EC.message() +
537 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000538 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000539
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000540 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000541 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000542
543 int (*Main)(int, const char**) =
544 (int(*)(int,const char**)) uintptr_t(MainAddress);
545 const char **Argv = new const char*[2];
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000546 // Use the name of the first input object module as argv[0] for the target.
547 Argv[0] = InputFileList[0].c_str();
Craig Toppere6cb63e2014-04-25 04:24:47 +0000548 Argv[1] = nullptr;
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000549 return Main(1, Argv);
550}
551
Lang Hamese1c11382014-06-27 20:20:57 +0000552static int checkAllExpressions(RuntimeDyldChecker &Checker) {
553 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000554 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
555 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
556 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000557 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000558 EC.message());
559
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000560 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
561 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000562 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000563 }
564 return 0;
565}
566
Lang Hames941f2472019-04-08 21:50:48 +0000567void applySpecificSectionMappings(RuntimeDyld &Dyld,
568 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000569
570 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000571 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000572 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000573 size_t ComaIdx = Mapping.find_first_of(",");
574
Davide Italiano07557fc2015-11-21 02:15:51 +0000575 if (ComaIdx == StringRef::npos)
576 report_fatal_error("Invalid section specification '" + Mapping +
577 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000578
Lang Hames78937c22015-07-04 01:35:26 +0000579 std::string FileName = SectionIDStr.substr(0, ComaIdx);
580 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000581 unsigned SectionID =
582 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000583
Lang Hames941f2472019-04-08 21:50:48 +0000584 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000585 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000586 uint64_t NewAddr;
587
Davide Italiano07557fc2015-11-21 02:15:51 +0000588 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
589 report_fatal_error("Invalid section address in mapping '" + Mapping +
590 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000591
Lang Hames941f2472019-04-08 21:50:48 +0000592 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000593 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000594}
595
Lang Hames9cb73532014-07-29 23:43:13 +0000596// Scatter sections in all directions!
597// Remaps section addresses for -verify mode. The following command line options
598// can be used to customize the layout of the memory within the phony target's
599// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000600// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000601// -target-addr-end <e> -- Specify where the phony target address range ends.
602// -target-section-sep <d> -- Specify how big a gap should be left between the
603// end of one section and the start of the next.
604// Defaults to zero. Set to something big
605// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
606//
Lang Hames78937c22015-07-04 01:35:26 +0000607static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000608 RuntimeDyld &Dyld,
609 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000610
611 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000612 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000613 WorklistT Worklist;
614
615 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000616 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000617 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000618 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000619
620 // Keep an "already allocated" mapping of section target addresses to sizes.
621 // Sections whose address mappings aren't specified on the command line will
622 // allocated around the explicitly mapped sections while maintaining the
623 // minimum separation.
624 std::map<uint64_t, uint64_t> AlreadyAllocated;
625
Lang Hamesff411502017-05-07 17:19:53 +0000626 // Move the previously applied mappings (whether explicitly specified on the
627 // command line, or implicitly set by RuntimeDyld) into the already-allocated
628 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000629 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
630 I != E;) {
631 WorklistT::iterator Tmp = I;
632 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000633
Lang Hames941f2472019-04-08 21:50:48 +0000634 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
635
636 if (LoadAddr != static_cast<uint64_t>(
637 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000638 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
639 // reason (e.g. zero byte COFF sections). Don't include those sections in
640 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000641 if (LoadAddr != 0)
642 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.size();
Lang Hames778ef5b2014-09-04 04:19:54 +0000643 Worklist.erase(Tmp);
644 }
645 }
Lang Hames9cb73532014-07-29 23:43:13 +0000646
647 // If the -target-addr-end option wasn't explicitly passed, then set it to a
648 // sensible default based on the target triple.
649 if (TargetAddrEnd.getNumOccurrences() == 0) {
650 if (TargetTriple.isArch16Bit())
651 TargetAddrEnd = (1ULL << 16) - 1;
652 else if (TargetTriple.isArch32Bit())
653 TargetAddrEnd = (1ULL << 32) - 1;
654 // TargetAddrEnd already has a sensible default for 64-bit systems, so
655 // there's nothing to do in the 64-bit case.
656 }
657
Lang Hames778ef5b2014-09-04 04:19:54 +0000658 // Process any elements remaining in the worklist.
659 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000660 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000661 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000662
Lang Hames778ef5b2014-09-04 04:19:54 +0000663 uint64_t NextSectionAddr = TargetAddrStart;
664
665 for (const auto &Alloc : AlreadyAllocated)
Lang Hames941f2472019-04-08 21:50:48 +0000666 if (NextSectionAddr + CurEntry->MB.size() + TargetSectionSep <= Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000667 break;
668 else
669 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
670
Lang Hames941f2472019-04-08 21:50:48 +0000671 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
672 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.size();
Lang Hames9cb73532014-07-29 23:43:13 +0000673 }
674
Lang Hames78937c22015-07-04 01:35:26 +0000675 // Add dummy symbols to the memory manager.
676 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000677 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000678
Davide Italiano07557fc2015-11-21 02:15:51 +0000679 if (EqualsIdx == StringRef::npos)
680 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
681 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000682
683 std::string Symbol = Mapping.substr(0, EqualsIdx);
684 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
685
686 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000687 if (StringRef(AddrStr).getAsInteger(0, Addr))
688 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000689
690 MemMgr.addDummySymbol(Symbol, Addr);
691 }
Lang Hames9cb73532014-07-29 23:43:13 +0000692}
693
694// Load and link the objects specified on the command line, but do not execute
695// anything. Instead, attach a RuntimeDyldChecker instance and call it to
696// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000697static int linkAndVerify() {
698
699 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000700 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000701 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000702
703 // Look up the target and build the disassembler.
704 Triple TheTriple(Triple::normalize(TripleName));
705 std::string ErrorStr;
706 const Target *TheTarget =
707 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000708 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000709 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000710
Lang Hamese1c11382014-06-27 20:20:57 +0000711 TripleName = TheTriple.getTriple();
712
713 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000714 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000715 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000716 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000717
718 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000719 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000720 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000721
722 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000723 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000724 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000725
726 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
727
728 std::unique_ptr<MCDisassembler> Disassembler(
729 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000730 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000731 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000732
733 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
734
Daniel Sanders50f17232015-09-15 16:17:27 +0000735 std::unique_ptr<MCInstPrinter> InstPrinter(
736 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000737
738 // Load any dylibs requested on the command line.
739 loadDylibs();
740
741 // Instantiate a dynamic linker.
742 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000743 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000744
745 using StubOffsets = StringMap<uint32_t>;
746 using SectionStubs = StringMap<StubOffsets>;
747 using FileStubs = StringMap<SectionStubs>;
748
749 FileStubs StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000750 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000751 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000752
753 Dyld.setNotifyStubEmitted(
754 [&StubMap](StringRef FilePath, StringRef SectionName,
755 StringRef SymbolName, uint32_t StubOffset) {
756 StubMap[sys::path::filename(FilePath)][SectionName][SymbolName] =
757 StubOffset;
758 });
759
760 auto GetSymbolAddress =
761 [&Dyld, &MemMgr](StringRef Symbol) -> Expected<JITTargetAddress> {
762 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
763 return InternalSymbol.getAddress();
764
765#ifdef _MSC_VER
766 using ExpectedLookupResult = MSVCPExpected<JITSymbolResolver::LookupResult>;
767#else
768 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
769#endif
770
771 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
772 auto ResultF = ResultP->get_future();
773
774 MemMgr.lookup(
775 JITSymbolResolver::LookupSet({Symbol}),
776 [=](Expected<JITSymbolResolver::LookupResult> Result) {
777 ResultP->set_value(std::move(Result));
778 });
779
780 auto Result = ResultF.get();
781 if (!Result)
782 return Result.takeError();
783
784 auto I = Result->find(Symbol);
785 assert(I != Result->end() &&
786 "Expected symbol address if no error occurred");
787 return I->second.getAddress();
788 };
789
790 auto IsSymbolValid =
791 [&Dyld, GetSymbolAddress](StringRef Symbol) {
792 if (Dyld.getSymbol(Symbol))
793 return true;
794 auto Addr = GetSymbolAddress(Symbol);
795 if (!Addr) {
796 logAllUnhandledErrors(Addr.takeError(), errs(), "RTDyldChecker: ");
797 return false;
798 }
799 return *Addr != 0;
800 };
801
802 FileToSectionIDMap FileToSecIDMap;
803
804 auto GetSectionAddress =
805 [&Dyld, &FileToSecIDMap](StringRef FileName, StringRef SectionName) {
806 unsigned SectionID =
807 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
808 return Dyld.getSectionLoadAddress(SectionID);
809 };
810
811 auto GetSectionContent =
812 [&Dyld, &FileToSecIDMap](StringRef FileName, StringRef SectionName) {
813 unsigned SectionID =
814 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
815 return Dyld.getSectionContent(SectionID);
816 };
817
818
819 auto GetSymbolContents =
820 [&Dyld](StringRef Symbol) {
821 auto *SymAddr = static_cast<char*>(Dyld.getSymbolLocalAddress(Symbol));
822 if (!SymAddr)
823 return StringRef();
824 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
825 if (SectionID == ~0U)
826 return StringRef();
827 StringRef SecContent = Dyld.getSectionContent(SectionID);
828 uint64_t SymSize = SecContent.size() - (SymAddr - SecContent.data());
829 return StringRef(SymAddr, SymSize);
830 };
831
832 auto GetStubOffset =
833 [&StubMap](StringRef FileName, StringRef SectionName, StringRef SymbolName) -> Expected<uint32_t> {
834 if (!StubMap.count(FileName))
835 return make_error<StringError>("File name not found", inconvertibleErrorCode());
836 if (!StubMap[FileName].count(SectionName))
837 return make_error<StringError>("Section name not found", inconvertibleErrorCode());
838 if (!StubMap[FileName][SectionName].count(SymbolName))
839 return make_error<StringError>("Symbol name not found", inconvertibleErrorCode());
840 return StubMap[FileName][SectionName][SymbolName];
841 };
842
843 // We will initialize this below once we have the first object file and can
844 // know the endianness.
845 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000846
847 // If we don't have any input files, read from stdin.
848 if (!InputFileList.size())
849 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000850 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000851 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000852 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000853 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000854
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000855 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000856 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000857
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000858 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000859 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
860
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000861 if (!MaybeObj) {
862 std::string Buf;
863 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000864 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000865 OS.flush();
866 ErrorAndExit("unable to create object file: '" + Buf + "'");
867 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000868
869 ObjectFile &Obj = **MaybeObj;
870
Lang Hames941f2472019-04-08 21:50:48 +0000871 if (!Checker)
872 Checker =
873 llvm::make_unique<RuntimeDyldChecker>(IsSymbolValid, GetSymbolAddress,
874 GetSymbolContents,
875 GetSectionAddress,
876 GetSectionContent, GetStubOffset,
877 Obj.isLittleEndian()
878 ? support::little
879 : support::big,
880 Disassembler.get(),
881 InstPrinter.get(), dbgs());
882
883 auto FileName = sys::path::filename(InputFile);
884 dbgs() << "In " << FileName << ":\n";
885 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
886
Lang Hamese1c11382014-06-27 20:20:57 +0000887 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000888 Dyld.loadObject(Obj);
889 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000890 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000891 }
892 }
893
Lang Hames78937c22015-07-04 01:35:26 +0000894 // Re-map the section addresses into the phony target address space and add
895 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000896 applySpecificSectionMappings(Dyld, FileToSecIDMap);
897 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000898
Lang Hamese1c11382014-06-27 20:20:57 +0000899 // Resolve all the relocations we can.
900 Dyld.resolveRelocations();
901
Lang Hames925e51b2014-09-03 05:42:52 +0000902 // Register EH frames.
903 Dyld.registerEHFrames();
904
Lang Hames941f2472019-04-08 21:50:48 +0000905 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000906 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000907 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000908 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000909
910 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000911}
912
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000913int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000914 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000915 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000916
Lang Hamese1c11382014-06-27 20:20:57 +0000917 llvm::InitializeAllTargetInfos();
918 llvm::InitializeAllTargetMCs();
919 llvm::InitializeAllDisassemblers();
920
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000921 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
922
Lang Hames941f2472019-04-08 21:50:48 +0000923 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
924
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000925 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000926 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000927 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000928 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000929 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000930 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000931 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
932 case AC_PrintObjectLineInfo:
933 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000934 case AC_Verify:
935 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000936 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000937}