blob: d8382a1d29fa7e458ae158fbf45f491d00928880 [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 Hamescf49aa32019-04-25 05:02:10 +000080static cl::list<std::string> InputArgv("args", cl::Positional,
81 cl::desc("<program arguments>..."),
82 cl::ZeroOrMore, cl::PositionalEatsArgs);
83
Lang Hamese1c11382014-06-27 20:20:57 +000084static cl::opt<std::string>
85TripleName("triple", cl::desc("Target triple for disassembler"));
86
Petar Jovanovic280e5622015-06-23 22:52:19 +000087static cl::opt<std::string>
88MCPU("mcpu",
89 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
90 cl::value_desc("cpu-name"),
91 cl::init(""));
92
Lang Hamese1c11382014-06-27 20:20:57 +000093static cl::list<std::string>
94CheckFiles("check",
95 cl::desc("File containing RuntimeDyld verifier checks."),
96 cl::ZeroOrMore);
97
Fangrui Songb5f39842019-04-24 02:40:20 +000098static cl::opt<uint64_t>
99 PreallocMemory("preallocate",
100 cl::desc("Allocate memory upfront rather than on-demand"),
101 cl::init(0));
Davide Italianob59ea902015-10-21 22:12:03 +0000102
Fangrui Songb5f39842019-04-24 02:40:20 +0000103static cl::opt<uint64_t> TargetAddrStart(
104 "target-addr-start",
105 cl::desc("For -verify only: start of phony target address "
106 "range."),
107 cl::init(4096), // Start at "page 1" - no allocating at "null".
108 cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000109
Fangrui Songb5f39842019-04-24 02:40:20 +0000110static cl::opt<uint64_t> TargetAddrEnd(
111 "target-addr-end",
112 cl::desc("For -verify only: end of phony target address range."),
113 cl::init(~0ULL), cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000114
Fangrui Songb5f39842019-04-24 02:40:20 +0000115static cl::opt<uint64_t> TargetSectionSep(
116 "target-section-sep",
117 cl::desc("For -verify only: Separation between sections in "
118 "phony target address space."),
119 cl::init(0), cl::Hidden);
Lang Hames9cb73532014-07-29 23:43:13 +0000120
Lang Hames778ef5b2014-09-04 04:19:54 +0000121static cl::list<std::string>
122SpecificSectionMappings("map-section",
Lang Hames78937c22015-07-04 01:35:26 +0000123 cl::desc("For -verify only: Map a section to a "
124 "specific address."),
125 cl::ZeroOrMore,
126 cl::Hidden);
127
128static cl::list<std::string>
129DummySymbolMappings("dummy-extern",
130 cl::desc("For -verify only: Inject a symbol into the extern "
131 "symbol table."),
132 cl::ZeroOrMore,
133 cl::Hidden);
Lang Hames778ef5b2014-09-04 04:19:54 +0000134
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000135static cl::opt<bool>
136PrintAllocationRequests("print-alloc-requests",
137 cl::desc("Print allocation requests made to the memory "
138 "manager by RuntimeDyld"),
139 cl::Hidden);
140
Lang Hames941f2472019-04-08 21:50:48 +0000141ExitOnError ExitOnErr;
142
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000143/* *** */
144
Lang Hames941f2472019-04-08 21:50:48 +0000145using SectionIDMap = StringMap<unsigned>;
146using FileToSectionIDMap = StringMap<SectionIDMap>;
147
148void dumpFileToSectionIDMap(const FileToSectionIDMap &FileToSecIDMap) {
149 for (const auto &KV : FileToSecIDMap) {
150 llvm::dbgs() << "In " << KV.first() << "\n";
151 for (auto &KV2 : KV.second)
152 llvm::dbgs() << " \"" << KV2.first() << "\" -> " << KV2.second << "\n";
153 }
154}
155
156Expected<unsigned> getSectionId(const FileToSectionIDMap &FileToSecIDMap,
157 StringRef FileName, StringRef SectionName) {
158 auto I = FileToSecIDMap.find(FileName);
159 if (I == FileToSecIDMap.end())
160 return make_error<StringError>("No file named " + FileName,
161 inconvertibleErrorCode());
162 auto &SectionIDs = I->second;
163 auto J = SectionIDs.find(SectionName);
164 if (J == SectionIDs.end())
165 return make_error<StringError>("No section named \"" + SectionName +
166 "\" in file " + FileName,
167 inconvertibleErrorCode());
168 return J->second;
169}
170
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000171// A trivial memory manager that doesn't do anything fancy, just uses the
172// support library allocation routines directly.
173class TrivialMemoryManager : public RTDyldMemoryManager {
174public:
Lang Hames941f2472019-04-08 21:50:48 +0000175 struct SectionInfo {
176 SectionInfo(StringRef Name, sys::MemoryBlock MB, unsigned SectionID)
177 : Name(Name), MB(std::move(MB)), SectionID(SectionID) {}
178 std::string Name;
179 sys::MemoryBlock MB;
180 unsigned SectionID = ~0U;
181 };
182
183 SmallVector<SectionInfo, 16> FunctionMemory;
184 SmallVector<SectionInfo, 16> DataMemory;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000185
186 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
Craig Toppere56917c2014-03-08 08:27:28 +0000187 unsigned SectionID,
188 StringRef SectionName) override;
Jim Grosbacheff0a402012-01-16 22:26:39 +0000189 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000190 unsigned SectionID, StringRef SectionName,
Craig Toppere56917c2014-03-08 08:27:28 +0000191 bool IsReadOnly) override;
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000192
Lang Hames941f2472019-04-08 21:50:48 +0000193 /// If non null, records subsequent Name -> SectionID mappings.
194 void setSectionIDsMap(SectionIDMap *SecIDMap) {
195 this->SecIDMap = SecIDMap;
196 }
197
Craig Toppere56917c2014-03-08 08:27:28 +0000198 void *getPointerToNamedFunction(const std::string &Name,
199 bool AbortOnFailure = true) override {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000200 return nullptr;
Danil Malyshevbfee5422012-03-28 21:46:36 +0000201 }
202
Craig Toppere56917c2014-03-08 08:27:28 +0000203 bool finalizeMemory(std::string *ErrMsg) override { return false; }
Andrew Kaylora342cb92012-11-15 23:50:01 +0000204
Lang Hames78937c22015-07-04 01:35:26 +0000205 void addDummySymbol(const std::string &Name, uint64_t Addr) {
206 DummyExterns[Name] = Addr;
207 }
208
Lang Hamesad4a9112016-08-01 20:49:11 +0000209 JITSymbol findSymbol(const std::string &Name) override {
Lang Hames78937c22015-07-04 01:35:26 +0000210 auto I = DummyExterns.find(Name);
211
212 if (I != DummyExterns.end())
Lang Hamesad4a9112016-08-01 20:49:11 +0000213 return JITSymbol(I->second, JITSymbolFlags::Exported);
Lang Hames78937c22015-07-04 01:35:26 +0000214
Lang Hamescf49aa32019-04-25 05:02:10 +0000215 if (auto Sym = RTDyldMemoryManager::findSymbol(Name))
216 return Sym;
217 else if (auto Err = Sym.takeError())
218 ExitOnErr(std::move(Err));
219 else
220 ExitOnErr(make_error<StringError>("Could not find definition for \"" +
221 Name + "\"",
222 inconvertibleErrorCode()));
223 llvm_unreachable("Should have returned or exited by now");
Lang Hames78937c22015-07-04 01:35:26 +0000224 }
225
Tim Northover5af339a2015-06-03 18:26:52 +0000226 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
227 size_t Size) override {}
Lang Hamesc936ac72017-05-09 21:32:18 +0000228 void deregisterEHFrames() override {}
Davide Italianob59ea902015-10-21 22:12:03 +0000229
230 void preallocateSlab(uint64_t Size) {
Lang Hamesafcb70d2017-11-16 23:04:44 +0000231 std::error_code EC;
232 sys::MemoryBlock MB =
233 sys::Memory::allocateMappedMemory(Size, nullptr,
234 sys::Memory::MF_READ |
235 sys::Memory::MF_WRITE,
236 EC);
Davide Italianob59ea902015-10-21 22:12:03 +0000237 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000238 report_fatal_error("Can't allocate enough memory: " + EC.message());
Davide Italianob59ea902015-10-21 22:12:03 +0000239
240 PreallocSlab = MB;
241 UsePreallocation = true;
242 SlabSize = Size;
243 }
244
Lang Hames941f2472019-04-08 21:50:48 +0000245 uint8_t *allocateFromSlab(uintptr_t Size, unsigned Alignment, bool isCode,
246 StringRef SectionName, unsigned SectionID) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000247 Size = alignTo(Size, Alignment);
Davide Italianob59ea902015-10-21 22:12:03 +0000248 if (CurrentSlabOffset + Size > SlabSize)
249 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
250
251 uintptr_t OldSlabOffset = CurrentSlabOffset;
252 sys::MemoryBlock MB((void *)OldSlabOffset, Size);
253 if (isCode)
Lang Hames941f2472019-04-08 21:50:48 +0000254 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000255 else
Lang Hames941f2472019-04-08 21:50:48 +0000256 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Davide Italianob59ea902015-10-21 22:12:03 +0000257 CurrentSlabOffset += Size;
258 return (uint8_t*)OldSlabOffset;
259 }
260
Lang Hames78937c22015-07-04 01:35:26 +0000261private:
262 std::map<std::string, uint64_t> DummyExterns;
Davide Italianob59ea902015-10-21 22:12:03 +0000263 sys::MemoryBlock PreallocSlab;
264 bool UsePreallocation = false;
265 uintptr_t SlabSize = 0;
266 uintptr_t CurrentSlabOffset = 0;
Lang Hames941f2472019-04-08 21:50:48 +0000267 SectionIDMap *SecIDMap = nullptr;
Jim Grosbach2dcef0502011-04-04 23:04:39 +0000268};
269
Jim Grosbacheff0a402012-01-16 22:26:39 +0000270uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
271 unsigned Alignment,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000272 unsigned SectionID,
273 StringRef SectionName) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000274 if (PrintAllocationRequests)
275 outs() << "allocateCodeSection(Size = " << Size << ", Alignment = "
276 << Alignment << ", SectionName = " << SectionName << ")\n";
277
Lang Hames941f2472019-04-08 21:50:48 +0000278 if (SecIDMap)
279 (*SecIDMap)[SectionName] = SectionID;
280
Davide Italianob59ea902015-10-21 22:12:03 +0000281 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000282 return allocateFromSlab(Size, Alignment, true /* isCode */,
283 SectionName, SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000284
Lang Hamesafcb70d2017-11-16 23:04:44 +0000285 std::error_code EC;
286 sys::MemoryBlock MB =
287 sys::Memory::allocateMappedMemory(Size, nullptr,
288 sys::Memory::MF_READ |
289 sys::Memory::MF_WRITE,
290 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000291 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000292 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000293 FunctionMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000294 return (uint8_t*)MB.base();
Jim Grosbacheff0a402012-01-16 22:26:39 +0000295}
296
297uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
298 unsigned Alignment,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000299 unsigned SectionID,
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000300 StringRef SectionName,
Andrew Kaylora342cb92012-11-15 23:50:01 +0000301 bool IsReadOnly) {
Sanjoy Dasd5658b02015-11-23 21:47:51 +0000302 if (PrintAllocationRequests)
303 outs() << "allocateDataSection(Size = " << Size << ", Alignment = "
304 << Alignment << ", SectionName = " << SectionName << ")\n";
305
Lang Hames941f2472019-04-08 21:50:48 +0000306 if (SecIDMap)
307 (*SecIDMap)[SectionName] = SectionID;
308
Davide Italianob59ea902015-10-21 22:12:03 +0000309 if (UsePreallocation)
Lang Hames941f2472019-04-08 21:50:48 +0000310 return allocateFromSlab(Size, Alignment, false /* isCode */, SectionName,
311 SectionID);
Davide Italianob59ea902015-10-21 22:12:03 +0000312
Lang Hamesafcb70d2017-11-16 23:04:44 +0000313 std::error_code EC;
314 sys::MemoryBlock MB =
315 sys::Memory::allocateMappedMemory(Size, nullptr,
316 sys::Memory::MF_READ |
317 sys::Memory::MF_WRITE,
318 EC);
Davide Italiano89151a02015-10-15 00:05:32 +0000319 if (!MB.base())
Lang Hamesafcb70d2017-11-16 23:04:44 +0000320 report_fatal_error("MemoryManager allocation failed: " + EC.message());
Lang Hames941f2472019-04-08 21:50:48 +0000321 DataMemory.push_back(SectionInfo(SectionName, MB, SectionID));
Danil Malyshev8c17fbd2012-05-16 18:50:11 +0000322 return (uint8_t*)MB.base();
323}
324
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000325static const char *ProgramName;
326
Lang Hamesee5417d2016-04-05 20:11:24 +0000327static void ErrorAndExit(const Twine &Msg) {
Davide Italianoc2e910d2015-11-20 23:12:15 +0000328 errs() << ProgramName << ": error: " << Msg << "\n";
Lang Hames9e964f32016-03-25 17:25:34 +0000329 exit(1);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000330}
331
Lang Hamesd311c0e2014-05-13 22:37:41 +0000332static void loadDylibs() {
333 for (const std::string &Dylib : Dylibs) {
Davide Italiano5cdf9362015-11-22 01:58:33 +0000334 if (!sys::fs::is_regular_file(Dylib))
Davide Italiano41d0fa72015-11-21 05:58:19 +0000335 report_fatal_error("Dylib not found: '" + Dylib + "'.");
Davide Italiano5cdf9362015-11-22 01:58:33 +0000336 std::string ErrMsg;
337 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg))
338 report_fatal_error("Error loading '" + Dylib + "': " + ErrMsg);
Lang Hamesd311c0e2014-05-13 22:37:41 +0000339 }
340}
341
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000342/* *** */
343
Keno Fischerc780e8e2015-05-21 21:24:32 +0000344static int printLineInfoForInput(bool LoadObjects, bool UseDebugObj) {
345 assert(LoadObjects || !UseDebugObj);
346
Lang Hamesd311c0e2014-05-13 22:37:41 +0000347 // Load any dylibs requested on the command line.
348 loadDylibs();
349
Andrew Kaylord55d7012013-01-25 22:50:58 +0000350 // If we don't have any input files, read from stdin.
351 if (!InputFileList.size())
352 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000353 for (auto &File : InputFileList) {
Andrew Kaylord55d7012013-01-25 22:50:58 +0000354 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000355 TrivialMemoryManager MemMgr;
Lang Hames633fe142015-03-30 03:37:06 +0000356 RuntimeDyld Dyld(MemMgr, MemMgr);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000357
358 // Load the input memory buffer.
Andrew Kaylord55d7012013-01-25 22:50:58 +0000359
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000360 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000361 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000362 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000363 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000364
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000365 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000366 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
367
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000368 if (!MaybeObj) {
369 std::string Buf;
370 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000371 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000372 OS.flush();
373 ErrorAndExit("unable to create object file: '" + Buf + "'");
374 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000375
376 ObjectFile &Obj = **MaybeObj;
377
Keno Fischerc780e8e2015-05-21 21:24:32 +0000378 OwningBinary<ObjectFile> DebugObj;
379 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo = nullptr;
380 ObjectFile *SymbolObj = &Obj;
381 if (LoadObjects) {
382 // Load the object file
383 LoadedObjInfo =
384 Dyld.loadObject(Obj);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000385
Keno Fischerc780e8e2015-05-21 21:24:32 +0000386 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000387 ErrorAndExit(Dyld.getErrorString());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000388
Keno Fischerc780e8e2015-05-21 21:24:32 +0000389 // Resolve all the relocations we can.
390 Dyld.resolveRelocations();
Andrew Kaylord55d7012013-01-25 22:50:58 +0000391
Keno Fischerc780e8e2015-05-21 21:24:32 +0000392 if (UseDebugObj) {
393 DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
394 SymbolObj = DebugObj.getBinary();
Lang Hames5c969332015-07-28 20:51:53 +0000395 LoadedObjInfo.reset();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000396 }
397 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000398
Rafael Espindolac398e672017-07-19 22:27:28 +0000399 std::unique_ptr<DIContext> Context =
400 DWARFContext::create(*SymbolObj, LoadedObjInfo.get());
Andrew Kaylord55d7012013-01-25 22:50:58 +0000401
Rafael Espindola6bf32212015-06-24 19:57:32 +0000402 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
Rafael Espindolab109c032015-06-23 02:08:48 +0000403 object::computeSymbolSizes(*SymbolObj);
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000404
Andrew Kaylord55d7012013-01-25 22:50:58 +0000405 // Use symbol info to iterate functions in the object.
Rafael Espindola6bf32212015-06-24 19:57:32 +0000406 for (const auto &P : SymAddr) {
Rafael Espindolab109c032015-06-23 02:08:48 +0000407 object::SymbolRef Sym = P.first;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000408 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
409 if (!TypeOrErr) {
410 // TODO: Actually report errors helpfully.
411 consumeError(TypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000412 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000413 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000414 SymbolRef::Type Type = *TypeOrErr;
415 if (Type == object::SymbolRef::ST_Function) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000416 Expected<StringRef> Name = Sym.getName();
417 if (!Name) {
418 // TODO: Actually report errors helpfully.
419 consumeError(Name.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000420 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000421 }
Kevin Enderby931cb652016-06-24 18:24:42 +0000422 Expected<uint64_t> AddrOrErr = Sym.getAddress();
423 if (!AddrOrErr) {
424 // TODO: Actually report errors helpfully.
425 consumeError(AddrOrErr.takeError());
Rafael Espindolada176272015-05-31 22:13:51 +0000426 continue;
Kevin Enderby931cb652016-06-24 18:24:42 +0000427 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000428 uint64_t Addr = *AddrOrErr;
Rafael Espindolaa82ce1d2015-05-31 23:15:35 +0000429
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000430 object::SectionedAddress Address;
431
Rafael Espindolab109c032015-06-23 02:08:48 +0000432 uint64_t Size = P.second;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000433 // If we're not using the debug object, compute the address of the
434 // symbol in memory (rather than that in the unrelocated object file)
435 // and use that to query the DWARFContext.
436 if (!UseDebugObj && LoadObjects) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000437 auto SecOrErr = Sym.getSection();
438 if (!SecOrErr) {
439 // TODO: Actually report errors helpfully.
440 consumeError(SecOrErr.takeError());
441 continue;
442 }
443 object::section_iterator Sec = *SecOrErr;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000444 StringRef SecName;
445 Sec->getName(SecName);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000446 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000447 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000448 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000449 if (SectionLoadAddress != 0)
450 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000451 } else if (auto SecOrErr = Sym.getSection())
452 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000453
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000454 outs() << "Function: " << *Name << ", Size = " << Size
455 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000456
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000457 Address.Address = Addr;
458 DILineInfoTable Lines =
459 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000460 for (auto &D : Lines) {
461 outs() << " Line info @ " << D.first - Addr << ": "
462 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000463 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000464 }
465 }
466 }
467
468 return 0;
469}
470
Davide Italianob59ea902015-10-21 22:12:03 +0000471static void doPreallocation(TrivialMemoryManager &MemMgr) {
472 // Allocate a slab of memory upfront, if required. This is used if
473 // we want to test small code models.
474 if (static_cast<intptr_t>(PreallocMemory) < 0)
475 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
476
477 // FIXME: Limit the amount of memory that can be preallocated?
478 if (PreallocMemory != 0)
479 MemMgr.preallocateSlab(PreallocMemory);
480}
481
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000482static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000483 // Load any dylibs requested on the command line.
484 loadDylibs();
485
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000486 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000487 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000488 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000489 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000490
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000491 // If we don't have any input files, read from stdin.
492 if (!InputFileList.size())
493 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000494 for (auto &File : InputFileList) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000495 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000496 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000497 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000498 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000499 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000500 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000501 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
502
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000503 if (!MaybeObj) {
504 std::string Buf;
505 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000506 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000507 OS.flush();
508 ErrorAndExit("unable to create object file: '" + Buf + "'");
509 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000510
511 ObjectFile &Obj = **MaybeObj;
512
Andrew Kayloradc70562012-10-02 21:18:39 +0000513 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000514 Dyld.loadObject(Obj);
515 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000516 ErrorAndExit(Dyld.getErrorString());
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000517 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000518 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000519
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000520 // Resove all the relocations we can.
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000521 // FIXME: Error out if there are unresolved relocations.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000522 Dyld.resolveRelocations();
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000523
Jim Grosbachd35159a2011-04-13 15:38:30 +0000524 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000525 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000526 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000527 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000528
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000529 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000530 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000531
Lang Hames941f2472019-04-08 21:50:48 +0000532 auto &FM_MB = FM.MB;
533
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000534 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000535 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000536 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000537 sys::Memory::MF_READ |
538 sys::Memory::MF_EXEC))
539 ErrorAndExit("unable to mark function executable: '" + EC.message() +
540 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000541 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000542
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000543 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000544 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000545
546 int (*Main)(int, const char**) =
547 (int(*)(int,const char**)) uintptr_t(MainAddress);
Lang Hamescf49aa32019-04-25 05:02:10 +0000548 std::vector<const char *> Argv;
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000549 // Use the name of the first input object module as argv[0] for the target.
Lang Hamescf49aa32019-04-25 05:02:10 +0000550 Argv.push_back(InputFileList[0].data());
551 for (auto &Arg : InputArgv)
552 Argv.push_back(Arg.data());
553 Argv.push_back(nullptr);
554 return Main(Argv.size() - 1, Argv.data());
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000555}
556
Lang Hamese1c11382014-06-27 20:20:57 +0000557static int checkAllExpressions(RuntimeDyldChecker &Checker) {
558 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000559 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
560 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
561 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000562 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000563 EC.message());
564
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000565 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
566 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000567 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000568 }
569 return 0;
570}
571
Lang Hames941f2472019-04-08 21:50:48 +0000572void applySpecificSectionMappings(RuntimeDyld &Dyld,
573 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000574
575 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000576 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000577 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000578 size_t ComaIdx = Mapping.find_first_of(",");
579
Davide Italiano07557fc2015-11-21 02:15:51 +0000580 if (ComaIdx == StringRef::npos)
581 report_fatal_error("Invalid section specification '" + Mapping +
582 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000583
Lang Hames78937c22015-07-04 01:35:26 +0000584 std::string FileName = SectionIDStr.substr(0, ComaIdx);
585 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000586 unsigned SectionID =
587 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000588
Lang Hames941f2472019-04-08 21:50:48 +0000589 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000590 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000591 uint64_t NewAddr;
592
Davide Italiano07557fc2015-11-21 02:15:51 +0000593 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
594 report_fatal_error("Invalid section address in mapping '" + Mapping +
595 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000596
Lang Hames941f2472019-04-08 21:50:48 +0000597 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000598 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000599}
600
Lang Hames9cb73532014-07-29 23:43:13 +0000601// Scatter sections in all directions!
602// Remaps section addresses for -verify mode. The following command line options
603// can be used to customize the layout of the memory within the phony target's
604// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000605// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000606// -target-addr-end <e> -- Specify where the phony target address range ends.
607// -target-section-sep <d> -- Specify how big a gap should be left between the
608// end of one section and the start of the next.
609// Defaults to zero. Set to something big
610// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
611//
Lang Hames78937c22015-07-04 01:35:26 +0000612static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000613 RuntimeDyld &Dyld,
614 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000615
616 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000617 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000618 WorklistT Worklist;
619
620 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000621 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000622 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000623 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000624
625 // Keep an "already allocated" mapping of section target addresses to sizes.
626 // Sections whose address mappings aren't specified on the command line will
627 // allocated around the explicitly mapped sections while maintaining the
628 // minimum separation.
629 std::map<uint64_t, uint64_t> AlreadyAllocated;
630
Lang Hamesff411502017-05-07 17:19:53 +0000631 // Move the previously applied mappings (whether explicitly specified on the
632 // command line, or implicitly set by RuntimeDyld) into the already-allocated
633 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000634 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
635 I != E;) {
636 WorklistT::iterator Tmp = I;
637 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000638
Lang Hames941f2472019-04-08 21:50:48 +0000639 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
640
641 if (LoadAddr != static_cast<uint64_t>(
642 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000643 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
644 // reason (e.g. zero byte COFF sections). Don't include those sections in
645 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000646 if (LoadAddr != 0)
647 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.size();
Lang Hames778ef5b2014-09-04 04:19:54 +0000648 Worklist.erase(Tmp);
649 }
650 }
Lang Hames9cb73532014-07-29 23:43:13 +0000651
652 // If the -target-addr-end option wasn't explicitly passed, then set it to a
653 // sensible default based on the target triple.
654 if (TargetAddrEnd.getNumOccurrences() == 0) {
655 if (TargetTriple.isArch16Bit())
656 TargetAddrEnd = (1ULL << 16) - 1;
657 else if (TargetTriple.isArch32Bit())
658 TargetAddrEnd = (1ULL << 32) - 1;
659 // TargetAddrEnd already has a sensible default for 64-bit systems, so
660 // there's nothing to do in the 64-bit case.
661 }
662
Lang Hames778ef5b2014-09-04 04:19:54 +0000663 // Process any elements remaining in the worklist.
664 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000665 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000666 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000667
Lang Hames778ef5b2014-09-04 04:19:54 +0000668 uint64_t NextSectionAddr = TargetAddrStart;
669
670 for (const auto &Alloc : AlreadyAllocated)
Lang Hames941f2472019-04-08 21:50:48 +0000671 if (NextSectionAddr + CurEntry->MB.size() + TargetSectionSep <= Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000672 break;
673 else
674 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
675
Lang Hames941f2472019-04-08 21:50:48 +0000676 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
677 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.size();
Lang Hames9cb73532014-07-29 23:43:13 +0000678 }
679
Lang Hames78937c22015-07-04 01:35:26 +0000680 // Add dummy symbols to the memory manager.
681 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000682 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000683
Davide Italiano07557fc2015-11-21 02:15:51 +0000684 if (EqualsIdx == StringRef::npos)
685 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
686 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000687
688 std::string Symbol = Mapping.substr(0, EqualsIdx);
689 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
690
691 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000692 if (StringRef(AddrStr).getAsInteger(0, Addr))
693 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000694
695 MemMgr.addDummySymbol(Symbol, Addr);
696 }
Lang Hames9cb73532014-07-29 23:43:13 +0000697}
698
699// Load and link the objects specified on the command line, but do not execute
700// anything. Instead, attach a RuntimeDyldChecker instance and call it to
701// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000702static int linkAndVerify() {
703
704 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000705 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000706 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000707
708 // Look up the target and build the disassembler.
709 Triple TheTriple(Triple::normalize(TripleName));
710 std::string ErrorStr;
711 const Target *TheTarget =
712 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000713 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000714 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000715
Lang Hamese1c11382014-06-27 20:20:57 +0000716 TripleName = TheTriple.getTriple();
717
718 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000719 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000720 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000721 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000722
723 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000724 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000725 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000726
727 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000728 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000729 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000730
731 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
732
733 std::unique_ptr<MCDisassembler> Disassembler(
734 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000735 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000736 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000737
738 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
739
Daniel Sanders50f17232015-09-15 16:17:27 +0000740 std::unique_ptr<MCInstPrinter> InstPrinter(
741 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000742
743 // Load any dylibs requested on the command line.
744 loadDylibs();
745
746 // Instantiate a dynamic linker.
747 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000748 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000749
Lang Hamesc7c1f212019-04-12 18:07:28 +0000750 struct StubID {
751 unsigned SectionID;
752 uint32_t Offset;
753 };
754 using StubInfos = StringMap<StubID>;
755 using StubContainers = StringMap<StubInfos>;
Lang Hames941f2472019-04-08 21:50:48 +0000756
Lang Hamesc7c1f212019-04-12 18:07:28 +0000757 StubContainers StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000758 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000759 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000760
Lang Hamesc7c1f212019-04-12 18:07:28 +0000761 Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
762 StringRef SectionName,
763 StringRef SymbolName, unsigned SectionID,
764 uint32_t StubOffset) {
765 std::string ContainerName =
766 (sys::path::filename(FilePath) + "/" + SectionName).str();
767 StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
768 });
Lang Hames941f2472019-04-08 21:50:48 +0000769
Lang Hamesc7c1f212019-04-12 18:07:28 +0000770 auto GetSymbolInfo =
771 [&Dyld, &MemMgr](
772 StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
773 RuntimeDyldChecker::MemoryRegionInfo SymInfo;
Lang Hames941f2472019-04-08 21:50:48 +0000774
Lang Hamesc7c1f212019-04-12 18:07:28 +0000775 // First get the target address.
776 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
777 SymInfo.TargetAddress = InternalSymbol.getAddress();
778 else {
779 // Symbol not found in RuntimeDyld. Fall back to external lookup.
Lang Hames941f2472019-04-08 21:50:48 +0000780#ifdef _MSC_VER
Lang Hamesc7c1f212019-04-12 18:07:28 +0000781 using ExpectedLookupResult =
782 MSVCPExpected<JITSymbolResolver::LookupResult>;
Lang Hames941f2472019-04-08 21:50:48 +0000783#else
784 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
785#endif
786
787 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
788 auto ResultF = ResultP->get_future();
789
Lang Hamesc7c1f212019-04-12 18:07:28 +0000790 MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
791 [=](Expected<JITSymbolResolver::LookupResult> Result) {
792 ResultP->set_value(std::move(Result));
793 });
Lang Hames941f2472019-04-08 21:50:48 +0000794
795 auto Result = ResultF.get();
796 if (!Result)
797 return Result.takeError();
798
799 auto I = Result->find(Symbol);
800 assert(I != Result->end() &&
801 "Expected symbol address if no error occurred");
Lang Hamesc7c1f212019-04-12 18:07:28 +0000802 SymInfo.TargetAddress = I->second.getAddress();
803 }
Lang Hames941f2472019-04-08 21:50:48 +0000804
Lang Hamesc7c1f212019-04-12 18:07:28 +0000805 // Now find the symbol content if possible (otherwise leave content as a
806 // default-constructed StringRef).
807 if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
808 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
809 if (SectionID != ~0U) {
810 char *CSymAddr = static_cast<char *>(SymAddr);
811 StringRef SecContent = Dyld.getSectionContent(SectionID);
812 uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
813 SymInfo.Content = StringRef(CSymAddr, SymSize);
Lang Hames941f2472019-04-08 21:50:48 +0000814 }
Lang Hamesc7c1f212019-04-12 18:07:28 +0000815 }
816 return SymInfo;
817 };
818
819 auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
820 if (Dyld.getSymbol(Symbol))
821 return true;
822 auto SymInfo = GetSymbolInfo(Symbol);
823 if (!SymInfo) {
824 logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
825 return false;
826 }
827 return SymInfo->TargetAddress != 0;
828 };
Lang Hames941f2472019-04-08 21:50:48 +0000829
830 FileToSectionIDMap FileToSecIDMap;
831
Lang Hamesc7c1f212019-04-12 18:07:28 +0000832 auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
833 StringRef SectionName)
834 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
835 auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
836 if (!SectionID)
837 return SectionID.takeError();
838 RuntimeDyldChecker::MemoryRegionInfo SecInfo;
839 SecInfo.TargetAddress = Dyld.getSectionLoadAddress(*SectionID);
840 SecInfo.Content = Dyld.getSectionContent(*SectionID);
841 return SecInfo;
842 };
Lang Hames941f2472019-04-08 21:50:48 +0000843
Lang Hamesc7c1f212019-04-12 18:07:28 +0000844 auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
845 StringRef SymbolName)
846 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
847 if (!StubMap.count(StubContainer))
848 return make_error<StringError>("Stub container not found: " +
849 StubContainer,
850 inconvertibleErrorCode());
851 if (!StubMap[StubContainer].count(SymbolName))
852 return make_error<StringError>("Symbol name " + SymbolName +
853 " in stub container " + StubContainer,
854 inconvertibleErrorCode());
855 auto &SI = StubMap[StubContainer][SymbolName];
856 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
857 StubMemInfo.TargetAddress =
858 Dyld.getSectionLoadAddress(SI.SectionID) + SI.Offset;
859 StubMemInfo.Content =
860 Dyld.getSectionContent(SI.SectionID).substr(SI.Offset);
861 return StubMemInfo;
862 };
Lang Hames941f2472019-04-08 21:50:48 +0000863
864 // We will initialize this below once we have the first object file and can
865 // know the endianness.
866 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000867
868 // If we don't have any input files, read from stdin.
869 if (!InputFileList.size())
870 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000871 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000872 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000873 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000874 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000875
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000876 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000877 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000878
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000879 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000880 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
881
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000882 if (!MaybeObj) {
883 std::string Buf;
884 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000885 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000886 OS.flush();
887 ErrorAndExit("unable to create object file: '" + Buf + "'");
888 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000889
890 ObjectFile &Obj = **MaybeObj;
891
Lang Hames941f2472019-04-08 21:50:48 +0000892 if (!Checker)
Lang Hamesc7c1f212019-04-12 18:07:28 +0000893 Checker = llvm::make_unique<RuntimeDyldChecker>(
894 IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
895 GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
896 Disassembler.get(), InstPrinter.get(), dbgs());
Lang Hames941f2472019-04-08 21:50:48 +0000897
898 auto FileName = sys::path::filename(InputFile);
Lang Hames941f2472019-04-08 21:50:48 +0000899 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
900
Lang Hamese1c11382014-06-27 20:20:57 +0000901 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000902 Dyld.loadObject(Obj);
903 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000904 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000905 }
906 }
907
Lang Hames78937c22015-07-04 01:35:26 +0000908 // Re-map the section addresses into the phony target address space and add
909 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000910 applySpecificSectionMappings(Dyld, FileToSecIDMap);
911 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000912
Lang Hamese1c11382014-06-27 20:20:57 +0000913 // Resolve all the relocations we can.
914 Dyld.resolveRelocations();
915
Lang Hames925e51b2014-09-03 05:42:52 +0000916 // Register EH frames.
917 Dyld.registerEHFrames();
918
Lang Hames941f2472019-04-08 21:50:48 +0000919 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000920 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000921 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000922 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000923
924 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000925}
926
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000927int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000928 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000929 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000930
Lang Hamese1c11382014-06-27 20:20:57 +0000931 llvm::InitializeAllTargetInfos();
932 llvm::InitializeAllTargetMCs();
933 llvm::InitializeAllDisassemblers();
934
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000935 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
936
Lang Hames941f2472019-04-08 21:50:48 +0000937 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
938
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000939 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000940 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000941 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000942 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000943 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000944 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000945 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
946 case AC_PrintObjectLineInfo:
947 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000948 case AC_Verify:
949 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000950 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000951}