blob: af83ea1227b91926bb120a0ee0485cb0c97a6d99 [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;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000444 Address.SectionIndex = Sec->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000445 uint64_t SectionLoadAddress =
Lang Hames2e88f4f2015-07-28 17:52:11 +0000446 LoadedObjInfo->getSectionLoadAddress(*Sec);
Keno Fischerc780e8e2015-05-21 21:24:32 +0000447 if (SectionLoadAddress != 0)
448 Addr += SectionLoadAddress - Sec->getAddress();
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000449 } else if (auto SecOrErr = Sym.getSection())
450 Address.SectionIndex = SecOrErr.get()->getIndex();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000451
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000452 outs() << "Function: " << *Name << ", Size = " << Size
453 << ", Addr = " << Addr << "\n";
Andrew Kaylord55d7012013-01-25 22:50:58 +0000454
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000455 Address.Address = Addr;
456 DILineInfoTable Lines =
457 Context->getLineInfoForAddressRange(Address, Size);
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000458 for (auto &D : Lines) {
459 outs() << " Line info @ " << D.first - Addr << ": "
460 << D.second.FileName << ", line:" << D.second.Line << "\n";
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000461 }
Andrew Kaylord55d7012013-01-25 22:50:58 +0000462 }
463 }
464 }
465
466 return 0;
467}
468
Davide Italianob59ea902015-10-21 22:12:03 +0000469static void doPreallocation(TrivialMemoryManager &MemMgr) {
470 // Allocate a slab of memory upfront, if required. This is used if
471 // we want to test small code models.
472 if (static_cast<intptr_t>(PreallocMemory) < 0)
473 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
474
475 // FIXME: Limit the amount of memory that can be preallocated?
476 if (PreallocMemory != 0)
477 MemMgr.preallocateSlab(PreallocMemory);
478}
479
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000480static int executeInput() {
Lang Hamesd311c0e2014-05-13 22:37:41 +0000481 // Load any dylibs requested on the command line.
482 loadDylibs();
483
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000484 // Instantiate a dynamic linker.
Benjamin Kramer9ce77082013-08-03 22:16:31 +0000485 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000486 doPreallocation(MemMgr);
Lang Hames633fe142015-03-30 03:37:06 +0000487 RuntimeDyld Dyld(MemMgr, MemMgr);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000488
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000489 // If we don't have any input files, read from stdin.
490 if (!InputFileList.size())
491 InputFileList.push_back("-");
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000492 for (auto &File : InputFileList) {
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000493 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000494 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000495 MemoryBuffer::getFileOrSTDIN(File);
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000496 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000497 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000498 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000499 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
500
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000501 if (!MaybeObj) {
502 std::string Buf;
503 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000504 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000505 OS.flush();
506 ErrorAndExit("unable to create object file: '" + Buf + "'");
507 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000508
509 ObjectFile &Obj = **MaybeObj;
510
Andrew Kayloradc70562012-10-02 21:18:39 +0000511 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000512 Dyld.loadObject(Obj);
513 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000514 ErrorAndExit(Dyld.getErrorString());
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000515 }
Jim Grosbach40411cc2011-03-22 18:19:42 +0000516 }
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000517
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000518 // Resove all the relocations we can.
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000519 // FIXME: Error out if there are unresolved relocations.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000520 Dyld.resolveRelocations();
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000521
Jim Grosbachd35159a2011-04-13 15:38:30 +0000522 // Get the address of the entry point (_main by default).
Lang Hamesb1186032015-03-11 00:43:26 +0000523 void *MainAddress = Dyld.getSymbolLocalAddress(EntryPoint);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000524 if (!MainAddress)
Lang Hames9e964f32016-03-25 17:25:34 +0000525 ErrorAndExit("no definition for '" + EntryPoint + "'");
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000526
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000527 // Invalidate the instruction cache for each loaded function.
Davide Italiano5d7e8fd2015-10-12 00:57:29 +0000528 for (auto &FM : MemMgr.FunctionMemory) {
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000529
Lang Hames941f2472019-04-08 21:50:48 +0000530 auto &FM_MB = FM.MB;
531
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000532 // Make sure the memory is executable.
Davide Italianoaf08e1b2015-11-17 16:37:52 +0000533 // setExecutable will call InvalidateInstructionCache.
Lang Hames941f2472019-04-08 21:50:48 +0000534 if (auto EC = sys::Memory::protectMappedMemory(FM_MB,
Lang Hamesafcb70d2017-11-16 23:04:44 +0000535 sys::Memory::MF_READ |
536 sys::Memory::MF_EXEC))
537 ErrorAndExit("unable to mark function executable: '" + EC.message() +
538 "'");
Jim Grosbach3ed03f12011-04-12 00:23:32 +0000539 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000540
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000541 // Dispatch to _main().
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000542 errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000543
544 int (*Main)(int, const char**) =
545 (int(*)(int,const char**)) uintptr_t(MainAddress);
Lang Hamescf49aa32019-04-25 05:02:10 +0000546 std::vector<const char *> Argv;
Jim Grosbach7cb41d72011-04-13 15:49:40 +0000547 // Use the name of the first input object module as argv[0] for the target.
Lang Hamescf49aa32019-04-25 05:02:10 +0000548 Argv.push_back(InputFileList[0].data());
549 for (auto &Arg : InputArgv)
550 Argv.push_back(Arg.data());
551 Argv.push_back(nullptr);
552 return Main(Argv.size() - 1, Argv.data());
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000553}
554
Lang Hamese1c11382014-06-27 20:20:57 +0000555static int checkAllExpressions(RuntimeDyldChecker &Checker) {
556 for (const auto& CheckerFileName : CheckFiles) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000557 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
558 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
559 if (std::error_code EC = CheckerFileBuf.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000560 ErrorAndExit("unable to read input '" + CheckerFileName + "': " +
Lang Hamese1c11382014-06-27 20:20:57 +0000561 EC.message());
562
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000563 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
564 CheckerFileBuf.get().get()))
Lang Hames9e964f32016-03-25 17:25:34 +0000565 ErrorAndExit("some checks in '" + CheckerFileName + "' failed");
Lang Hamese1c11382014-06-27 20:20:57 +0000566 }
567 return 0;
568}
569
Lang Hames941f2472019-04-08 21:50:48 +0000570void applySpecificSectionMappings(RuntimeDyld &Dyld,
571 const FileToSectionIDMap &FileToSecIDMap) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000572
573 for (StringRef Mapping : SpecificSectionMappings) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000574 size_t EqualsIdx = Mapping.find_first_of("=");
Lang Hames78937c22015-07-04 01:35:26 +0000575 std::string SectionIDStr = Mapping.substr(0, EqualsIdx);
Lang Hames778ef5b2014-09-04 04:19:54 +0000576 size_t ComaIdx = Mapping.find_first_of(",");
577
Davide Italiano07557fc2015-11-21 02:15:51 +0000578 if (ComaIdx == StringRef::npos)
579 report_fatal_error("Invalid section specification '" + Mapping +
580 "'. Should be '<file name>,<section name>=<addr>'");
Lang Hames778ef5b2014-09-04 04:19:54 +0000581
Lang Hames78937c22015-07-04 01:35:26 +0000582 std::string FileName = SectionIDStr.substr(0, ComaIdx);
583 std::string SectionName = SectionIDStr.substr(ComaIdx + 1);
Lang Hames941f2472019-04-08 21:50:48 +0000584 unsigned SectionID =
585 ExitOnErr(getSectionId(FileToSecIDMap, FileName, SectionName));
Lang Hames778ef5b2014-09-04 04:19:54 +0000586
Lang Hames941f2472019-04-08 21:50:48 +0000587 auto* OldAddr = Dyld.getSectionContent(SectionID).data();
Lang Hames78937c22015-07-04 01:35:26 +0000588 std::string NewAddrStr = Mapping.substr(EqualsIdx + 1);
Lang Hames778ef5b2014-09-04 04:19:54 +0000589 uint64_t NewAddr;
590
Davide Italiano07557fc2015-11-21 02:15:51 +0000591 if (StringRef(NewAddrStr).getAsInteger(0, NewAddr))
592 report_fatal_error("Invalid section address in mapping '" + Mapping +
593 "'.");
Lang Hames778ef5b2014-09-04 04:19:54 +0000594
Lang Hames941f2472019-04-08 21:50:48 +0000595 Dyld.mapSectionAddress(OldAddr, NewAddr);
Lang Hames778ef5b2014-09-04 04:19:54 +0000596 }
Lang Hames778ef5b2014-09-04 04:19:54 +0000597}
598
Lang Hames9cb73532014-07-29 23:43:13 +0000599// Scatter sections in all directions!
600// Remaps section addresses for -verify mode. The following command line options
601// can be used to customize the layout of the memory within the phony target's
602// address space:
Simon Pilgrimdae11f72016-11-20 13:31:13 +0000603// -target-addr-start <s> -- Specify where the phony target address range starts.
Lang Hames9cb73532014-07-29 23:43:13 +0000604// -target-addr-end <e> -- Specify where the phony target address range ends.
605// -target-section-sep <d> -- Specify how big a gap should be left between the
606// end of one section and the start of the next.
607// Defaults to zero. Set to something big
608// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
609//
Lang Hames78937c22015-07-04 01:35:26 +0000610static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
Lang Hames941f2472019-04-08 21:50:48 +0000611 RuntimeDyld &Dyld,
612 TrivialMemoryManager &MemMgr) {
Lang Hames778ef5b2014-09-04 04:19:54 +0000613
614 // Set up a work list (section addr/size pairs).
Lang Hames941f2472019-04-08 21:50:48 +0000615 typedef std::list<const TrivialMemoryManager::SectionInfo*> WorklistT;
Lang Hames778ef5b2014-09-04 04:19:54 +0000616 WorklistT Worklist;
617
618 for (const auto& CodeSection : MemMgr.FunctionMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000619 Worklist.push_back(&CodeSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000620 for (const auto& DataSection : MemMgr.DataMemory)
Lang Hames941f2472019-04-08 21:50:48 +0000621 Worklist.push_back(&DataSection);
Lang Hames778ef5b2014-09-04 04:19:54 +0000622
623 // Keep an "already allocated" mapping of section target addresses to sizes.
624 // Sections whose address mappings aren't specified on the command line will
625 // allocated around the explicitly mapped sections while maintaining the
626 // minimum separation.
627 std::map<uint64_t, uint64_t> AlreadyAllocated;
628
Lang Hamesff411502017-05-07 17:19:53 +0000629 // Move the previously applied mappings (whether explicitly specified on the
630 // command line, or implicitly set by RuntimeDyld) into the already-allocated
631 // map.
Lang Hames778ef5b2014-09-04 04:19:54 +0000632 for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
633 I != E;) {
634 WorklistT::iterator Tmp = I;
635 ++I;
Lang Hames778ef5b2014-09-04 04:19:54 +0000636
Lang Hames941f2472019-04-08 21:50:48 +0000637 auto LoadAddr = Dyld.getSectionLoadAddress((*Tmp)->SectionID);
638
639 if (LoadAddr != static_cast<uint64_t>(
640 reinterpret_cast<uintptr_t>((*Tmp)->MB.base()))) {
Lang Hames776f1d52018-10-23 01:36:33 +0000641 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
642 // reason (e.g. zero byte COFF sections). Don't include those sections in
643 // the allocation map.
Lang Hames941f2472019-04-08 21:50:48 +0000644 if (LoadAddr != 0)
Lang Hames93d2bdd2019-05-20 20:53:05 +0000645 AlreadyAllocated[LoadAddr] = (*Tmp)->MB.allocatedSize();
Lang Hames778ef5b2014-09-04 04:19:54 +0000646 Worklist.erase(Tmp);
647 }
648 }
Lang Hames9cb73532014-07-29 23:43:13 +0000649
650 // If the -target-addr-end option wasn't explicitly passed, then set it to a
651 // sensible default based on the target triple.
652 if (TargetAddrEnd.getNumOccurrences() == 0) {
653 if (TargetTriple.isArch16Bit())
654 TargetAddrEnd = (1ULL << 16) - 1;
655 else if (TargetTriple.isArch32Bit())
656 TargetAddrEnd = (1ULL << 32) - 1;
657 // TargetAddrEnd already has a sensible default for 64-bit systems, so
658 // there's nothing to do in the 64-bit case.
659 }
660
Lang Hames778ef5b2014-09-04 04:19:54 +0000661 // Process any elements remaining in the worklist.
662 while (!Worklist.empty()) {
Lang Hames941f2472019-04-08 21:50:48 +0000663 auto *CurEntry = Worklist.front();
Lang Hames778ef5b2014-09-04 04:19:54 +0000664 Worklist.pop_front();
Lang Hames9cb73532014-07-29 23:43:13 +0000665
Lang Hames778ef5b2014-09-04 04:19:54 +0000666 uint64_t NextSectionAddr = TargetAddrStart;
667
668 for (const auto &Alloc : AlreadyAllocated)
Lang Hames93d2bdd2019-05-20 20:53:05 +0000669 if (NextSectionAddr + CurEntry->MB.allocatedSize() + TargetSectionSep <=
670 Alloc.first)
Lang Hames778ef5b2014-09-04 04:19:54 +0000671 break;
672 else
673 NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
674
Lang Hames941f2472019-04-08 21:50:48 +0000675 Dyld.mapSectionAddress(CurEntry->MB.base(), NextSectionAddr);
Lang Hames93d2bdd2019-05-20 20:53:05 +0000676 AlreadyAllocated[NextSectionAddr] = CurEntry->MB.allocatedSize();
Lang Hames9cb73532014-07-29 23:43:13 +0000677 }
678
Lang Hames78937c22015-07-04 01:35:26 +0000679 // Add dummy symbols to the memory manager.
680 for (const auto &Mapping : DummySymbolMappings) {
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000681 size_t EqualsIdx = Mapping.find_first_of('=');
Lang Hames78937c22015-07-04 01:35:26 +0000682
Davide Italiano07557fc2015-11-21 02:15:51 +0000683 if (EqualsIdx == StringRef::npos)
684 report_fatal_error("Invalid dummy symbol specification '" + Mapping +
685 "'. Should be '<symbol name>=<addr>'");
Lang Hames78937c22015-07-04 01:35:26 +0000686
687 std::string Symbol = Mapping.substr(0, EqualsIdx);
688 std::string AddrStr = Mapping.substr(EqualsIdx + 1);
689
690 uint64_t Addr;
Davide Italiano07557fc2015-11-21 02:15:51 +0000691 if (StringRef(AddrStr).getAsInteger(0, Addr))
692 report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
Lang Hames78937c22015-07-04 01:35:26 +0000693
694 MemMgr.addDummySymbol(Symbol, Addr);
695 }
Lang Hames9cb73532014-07-29 23:43:13 +0000696}
697
698// Load and link the objects specified on the command line, but do not execute
699// anything. Instead, attach a RuntimeDyldChecker instance and call it to
700// verify the correctness of the linked memory.
Lang Hamese1c11382014-06-27 20:20:57 +0000701static int linkAndVerify() {
702
703 // Check for missing triple.
Davide Italiano78da7592015-11-21 05:44:41 +0000704 if (TripleName == "")
Lang Hames9e964f32016-03-25 17:25:34 +0000705 ErrorAndExit("-triple required when running in -verify mode.");
Lang Hamese1c11382014-06-27 20:20:57 +0000706
707 // Look up the target and build the disassembler.
708 Triple TheTriple(Triple::normalize(TripleName));
709 std::string ErrorStr;
710 const Target *TheTarget =
711 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000712 if (!TheTarget)
Lang Hames9e964f32016-03-25 17:25:34 +0000713 ErrorAndExit("Error accessing target '" + TripleName + "': " + ErrorStr);
Davide Italiano78da7592015-11-21 05:44:41 +0000714
Lang Hamese1c11382014-06-27 20:20:57 +0000715 TripleName = TheTriple.getTriple();
716
717 std::unique_ptr<MCSubtargetInfo> STI(
Petar Jovanovic280e5622015-06-23 22:52:19 +0000718 TheTarget->createMCSubtargetInfo(TripleName, MCPU, ""));
Davide Italianoebb27af2015-11-21 05:49:07 +0000719 if (!STI)
Lang Hames9e964f32016-03-25 17:25:34 +0000720 ErrorAndExit("Unable to create subtarget info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000721
722 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000723 if (!MRI)
Lang Hames9e964f32016-03-25 17:25:34 +0000724 ErrorAndExit("Unable to create target register info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000725
726 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italianoebb27af2015-11-21 05:49:07 +0000727 if (!MAI)
Lang Hames9e964f32016-03-25 17:25:34 +0000728 ErrorAndExit("Unable to create target asm info!");
Lang Hamese1c11382014-06-27 20:20:57 +0000729
730 MCContext Ctx(MAI.get(), MRI.get(), nullptr);
731
732 std::unique_ptr<MCDisassembler> Disassembler(
733 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italianoebb27af2015-11-21 05:49:07 +0000734 if (!Disassembler)
Lang Hames9e964f32016-03-25 17:25:34 +0000735 ErrorAndExit("Unable to create disassembler!");
Lang Hamese1c11382014-06-27 20:20:57 +0000736
737 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
738
Daniel Sanders50f17232015-09-15 16:17:27 +0000739 std::unique_ptr<MCInstPrinter> InstPrinter(
740 TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
Lang Hamese1c11382014-06-27 20:20:57 +0000741
742 // Load any dylibs requested on the command line.
743 loadDylibs();
744
745 // Instantiate a dynamic linker.
746 TrivialMemoryManager MemMgr;
Davide Italianob59ea902015-10-21 22:12:03 +0000747 doPreallocation(MemMgr);
Lang Hames941f2472019-04-08 21:50:48 +0000748
Lang Hamesc7c1f212019-04-12 18:07:28 +0000749 struct StubID {
750 unsigned SectionID;
751 uint32_t Offset;
752 };
753 using StubInfos = StringMap<StubID>;
754 using StubContainers = StringMap<StubInfos>;
Lang Hames941f2472019-04-08 21:50:48 +0000755
Lang Hamesc7c1f212019-04-12 18:07:28 +0000756 StubContainers StubMap;
Lang Hames633fe142015-03-30 03:37:06 +0000757 RuntimeDyld Dyld(MemMgr, MemMgr);
Lang Hames925e51b2014-09-03 05:42:52 +0000758 Dyld.setProcessAllSections(true);
Lang Hames941f2472019-04-08 21:50:48 +0000759
Lang Hamesc7c1f212019-04-12 18:07:28 +0000760 Dyld.setNotifyStubEmitted([&StubMap](StringRef FilePath,
761 StringRef SectionName,
762 StringRef SymbolName, unsigned SectionID,
763 uint32_t StubOffset) {
764 std::string ContainerName =
765 (sys::path::filename(FilePath) + "/" + SectionName).str();
766 StubMap[ContainerName][SymbolName] = {SectionID, StubOffset};
767 });
Lang Hames941f2472019-04-08 21:50:48 +0000768
Lang Hamesc7c1f212019-04-12 18:07:28 +0000769 auto GetSymbolInfo =
770 [&Dyld, &MemMgr](
771 StringRef Symbol) -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
772 RuntimeDyldChecker::MemoryRegionInfo SymInfo;
Lang Hames941f2472019-04-08 21:50:48 +0000773
Lang Hamesc7c1f212019-04-12 18:07:28 +0000774 // First get the target address.
775 if (auto InternalSymbol = Dyld.getSymbol(Symbol))
Lang Hames23085ec2019-05-12 22:26:33 +0000776 SymInfo.setTargetAddress(InternalSymbol.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000777 else {
778 // Symbol not found in RuntimeDyld. Fall back to external lookup.
Lang Hames941f2472019-04-08 21:50:48 +0000779#ifdef _MSC_VER
Lang Hamesc7c1f212019-04-12 18:07:28 +0000780 using ExpectedLookupResult =
781 MSVCPExpected<JITSymbolResolver::LookupResult>;
Lang Hames941f2472019-04-08 21:50:48 +0000782#else
783 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
784#endif
785
786 auto ResultP = std::make_shared<std::promise<ExpectedLookupResult>>();
787 auto ResultF = ResultP->get_future();
788
Lang Hamesc7c1f212019-04-12 18:07:28 +0000789 MemMgr.lookup(JITSymbolResolver::LookupSet({Symbol}),
790 [=](Expected<JITSymbolResolver::LookupResult> Result) {
791 ResultP->set_value(std::move(Result));
792 });
Lang Hames941f2472019-04-08 21:50:48 +0000793
794 auto Result = ResultF.get();
795 if (!Result)
796 return Result.takeError();
797
798 auto I = Result->find(Symbol);
799 assert(I != Result->end() &&
800 "Expected symbol address if no error occurred");
Lang Hames23085ec2019-05-12 22:26:33 +0000801 SymInfo.setTargetAddress(I->second.getAddress());
Lang Hamesc7c1f212019-04-12 18:07:28 +0000802 }
Lang Hames941f2472019-04-08 21:50:48 +0000803
Lang Hamesc7c1f212019-04-12 18:07:28 +0000804 // Now find the symbol content if possible (otherwise leave content as a
805 // default-constructed StringRef).
806 if (auto *SymAddr = Dyld.getSymbolLocalAddress(Symbol)) {
807 unsigned SectionID = Dyld.getSymbolSectionID(Symbol);
808 if (SectionID != ~0U) {
809 char *CSymAddr = static_cast<char *>(SymAddr);
810 StringRef SecContent = Dyld.getSectionContent(SectionID);
811 uint64_t SymSize = SecContent.size() - (CSymAddr - SecContent.data());
Lang Hames23085ec2019-05-12 22:26:33 +0000812 SymInfo.setContent(StringRef(CSymAddr, SymSize));
Lang Hames941f2472019-04-08 21:50:48 +0000813 }
Lang Hamesc7c1f212019-04-12 18:07:28 +0000814 }
815 return SymInfo;
816 };
817
818 auto IsSymbolValid = [&Dyld, GetSymbolInfo](StringRef Symbol) {
819 if (Dyld.getSymbol(Symbol))
820 return true;
821 auto SymInfo = GetSymbolInfo(Symbol);
822 if (!SymInfo) {
823 logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
824 return false;
825 }
Lang Hames23085ec2019-05-12 22:26:33 +0000826 return SymInfo->getTargetAddress() != 0;
Lang Hamesc7c1f212019-04-12 18:07:28 +0000827 };
Lang Hames941f2472019-04-08 21:50:48 +0000828
829 FileToSectionIDMap FileToSecIDMap;
830
Lang Hamesc7c1f212019-04-12 18:07:28 +0000831 auto GetSectionInfo = [&Dyld, &FileToSecIDMap](StringRef FileName,
832 StringRef SectionName)
833 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
834 auto SectionID = getSectionId(FileToSecIDMap, FileName, SectionName);
835 if (!SectionID)
836 return SectionID.takeError();
837 RuntimeDyldChecker::MemoryRegionInfo SecInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000838 SecInfo.setTargetAddress(Dyld.getSectionLoadAddress(*SectionID));
839 SecInfo.setContent(Dyld.getSectionContent(*SectionID));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000840 return SecInfo;
841 };
Lang Hames941f2472019-04-08 21:50:48 +0000842
Lang Hamesc7c1f212019-04-12 18:07:28 +0000843 auto GetStubInfo = [&Dyld, &StubMap](StringRef StubContainer,
844 StringRef SymbolName)
845 -> Expected<RuntimeDyldChecker::MemoryRegionInfo> {
846 if (!StubMap.count(StubContainer))
847 return make_error<StringError>("Stub container not found: " +
848 StubContainer,
849 inconvertibleErrorCode());
850 if (!StubMap[StubContainer].count(SymbolName))
851 return make_error<StringError>("Symbol name " + SymbolName +
852 " in stub container " + StubContainer,
853 inconvertibleErrorCode());
854 auto &SI = StubMap[StubContainer][SymbolName];
855 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo;
Lang Hames23085ec2019-05-12 22:26:33 +0000856 StubMemInfo.setTargetAddress(Dyld.getSectionLoadAddress(SI.SectionID) +
857 SI.Offset);
858 StubMemInfo.setContent(
859 Dyld.getSectionContent(SI.SectionID).substr(SI.Offset));
Lang Hamesc7c1f212019-04-12 18:07:28 +0000860 return StubMemInfo;
861 };
Lang Hames941f2472019-04-08 21:50:48 +0000862
863 // We will initialize this below once we have the first object file and can
864 // know the endianness.
865 std::unique_ptr<RuntimeDyldChecker> Checker;
Lang Hamese1c11382014-06-27 20:20:57 +0000866
867 // If we don't have any input files, read from stdin.
868 if (!InputFileList.size())
869 InputFileList.push_back("-");
Lang Hames941f2472019-04-08 21:50:48 +0000870 for (auto &InputFile : InputFileList) {
Lang Hamese1c11382014-06-27 20:20:57 +0000871 // Load the input memory buffer.
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000872 ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
Lang Hames941f2472019-04-08 21:50:48 +0000873 MemoryBuffer::getFileOrSTDIN(InputFile);
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000874
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000875 if (std::error_code EC = InputBuffer.getError())
Lang Hames9e964f32016-03-25 17:25:34 +0000876 ErrorAndExit("unable to read input: '" + EC.message() + "'");
Lang Hamese1c11382014-06-27 20:20:57 +0000877
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000878 Expected<std::unique_ptr<ObjectFile>> MaybeObj(
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000879 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
880
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000881 if (!MaybeObj) {
882 std::string Buf;
883 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000884 logAllUnhandledErrors(MaybeObj.takeError(), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000885 OS.flush();
886 ErrorAndExit("unable to create object file: '" + Buf + "'");
887 }
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000888
889 ObjectFile &Obj = **MaybeObj;
890
Lang Hames941f2472019-04-08 21:50:48 +0000891 if (!Checker)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000892 Checker = std::make_unique<RuntimeDyldChecker>(
Lang Hamesc7c1f212019-04-12 18:07:28 +0000893 IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo,
894 GetStubInfo, Obj.isLittleEndian() ? support::little : support::big,
895 Disassembler.get(), InstPrinter.get(), dbgs());
Lang Hames941f2472019-04-08 21:50:48 +0000896
897 auto FileName = sys::path::filename(InputFile);
Lang Hames941f2472019-04-08 21:50:48 +0000898 MemMgr.setSectionIDsMap(&FileToSecIDMap[FileName]);
899
Lang Hamese1c11382014-06-27 20:20:57 +0000900 // Load the object file
Lang Hamesb5c7b1f2014-11-26 16:54:40 +0000901 Dyld.loadObject(Obj);
902 if (Dyld.hasError()) {
Lang Hames9e964f32016-03-25 17:25:34 +0000903 ErrorAndExit(Dyld.getErrorString());
Lang Hamese1c11382014-06-27 20:20:57 +0000904 }
905 }
906
Lang Hames78937c22015-07-04 01:35:26 +0000907 // Re-map the section addresses into the phony target address space and add
908 // dummy symbols.
Lang Hames941f2472019-04-08 21:50:48 +0000909 applySpecificSectionMappings(Dyld, FileToSecIDMap);
910 remapSectionsAndSymbols(TheTriple, Dyld, MemMgr);
Lang Hames375385f2014-07-30 03:12:41 +0000911
Lang Hamese1c11382014-06-27 20:20:57 +0000912 // Resolve all the relocations we can.
913 Dyld.resolveRelocations();
914
Lang Hames925e51b2014-09-03 05:42:52 +0000915 // Register EH frames.
916 Dyld.registerEHFrames();
917
Lang Hames941f2472019-04-08 21:50:48 +0000918 int ErrorCode = checkAllExpressions(*Checker);
Davide Italiano78da7592015-11-21 05:44:41 +0000919 if (Dyld.hasError())
Lang Hames9e964f32016-03-25 17:25:34 +0000920 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
Davide Italiano78da7592015-11-21 05:44:41 +0000921 Dyld.getErrorString());
Lang Hamesae172682014-08-05 20:51:46 +0000922
923 return ErrorCode;
Lang Hamese1c11382014-06-27 20:20:57 +0000924}
925
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000926int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000927 InitLLVM X(argc, argv);
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000928 ProgramName = argv[0];
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000929
Lang Hamese1c11382014-06-27 20:20:57 +0000930 llvm::InitializeAllTargetInfos();
931 llvm::InitializeAllTargetMCs();
932 llvm::InitializeAllDisassemblers();
933
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000934 cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
935
Lang Hames941f2472019-04-08 21:50:48 +0000936 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
937
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000938 switch (Action) {
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000939 case AC_Execute:
Jim Grosbach4d5284b2011-03-18 17:24:21 +0000940 return executeInput();
Keno Fischerc780e8e2015-05-21 21:24:32 +0000941 case AC_PrintDebugLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000942 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */ true);
Andrew Kaylord55d7012013-01-25 22:50:58 +0000943 case AC_PrintLineInfo:
Keno Fischer281b6942015-05-30 19:44:53 +0000944 return printLineInfoForInput(/* LoadObjects */ true,/* UseDebugObj */false);
945 case AC_PrintObjectLineInfo:
946 return printLineInfoForInput(/* LoadObjects */false,/* UseDebugObj */false);
Lang Hamese1c11382014-06-27 20:20:57 +0000947 case AC_Verify:
948 return linkAndVerify();
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000949 }
Jim Grosbach0072cdb2011-03-18 17:11:39 +0000950}