1 //===-- llvm-rtdyld.cpp - MCJIT Testing Tool ------------------------------===//
3 // 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
7 //===----------------------------------------------------------------------===//
9 // This is a testing tool for use with the MC-JIT LLVM components.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/DebugInfo/DIContext.h"
15 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
16 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
17 #include "llvm/ExecutionEngine/RuntimeDyld.h"
18 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCTargetOptions.h"
27 #include "llvm/MC/TargetRegistry.h"
28 #include "llvm/Object/SymbolSize.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DynamicLibrary.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/InitLLVM.h"
33 #include "llvm/Support/MSVCErrorWorkarounds.h"
34 #include "llvm/Support/Memory.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/Timer.h"
39 #include "llvm/Support/raw_ostream.h"
45 using namespace llvm::object
;
47 static cl::OptionCategory
RTDyldCategory("RTDyld Options");
49 static cl::list
<std::string
> InputFileList(cl::Positional
,
50 cl::desc("<input files>"),
51 cl::cat(RTDyldCategory
));
55 AC_PrintObjectLineInfo
,
57 AC_PrintDebugLineInfo
,
61 static cl::opt
<ActionType
> Action(
62 cl::desc("Action to perform:"), cl::init(AC_Execute
),
64 clEnumValN(AC_Execute
, "execute",
65 "Load, link, and execute the inputs."),
66 clEnumValN(AC_PrintLineInfo
, "printline",
67 "Load, link, and print line information for each function."),
68 clEnumValN(AC_PrintDebugLineInfo
, "printdebugline",
69 "Load, link, and print line information for each function "
70 "using the debug object"),
71 clEnumValN(AC_PrintObjectLineInfo
, "printobjline",
72 "Like -printlineinfo but does not load the object first"),
73 clEnumValN(AC_Verify
, "verify",
74 "Load, link and verify the resulting memory image.")),
75 cl::cat(RTDyldCategory
));
77 static cl::opt
<std::string
>
78 EntryPoint("entry", cl::desc("Function to call as entry point."),
79 cl::init("_main"), cl::cat(RTDyldCategory
));
81 static cl::list
<std::string
> Dylibs("dylib", cl::desc("Add library."),
82 cl::cat(RTDyldCategory
));
84 static cl::list
<std::string
> InputArgv("args", cl::Positional
,
85 cl::desc("<program arguments>..."),
86 cl::PositionalEatsArgs
,
87 cl::cat(RTDyldCategory
));
89 static cl::opt
<std::string
>
90 TripleName("triple", cl::desc("Target triple for disassembler"),
91 cl::cat(RTDyldCategory
));
93 static cl::opt
<std::string
>
95 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
96 cl::value_desc("cpu-name"), cl::init(""), cl::cat(RTDyldCategory
));
98 static cl::list
<std::string
>
100 cl::desc("File containing RuntimeDyld verifier checks."),
101 cl::cat(RTDyldCategory
));
103 static cl::opt
<uint64_t>
104 PreallocMemory("preallocate",
105 cl::desc("Allocate memory upfront rather than on-demand"),
106 cl::init(0), cl::cat(RTDyldCategory
));
108 static cl::opt
<uint64_t> TargetAddrStart(
110 cl::desc("For -verify only: start of phony target address "
112 cl::init(4096), // Start at "page 1" - no allocating at "null".
113 cl::Hidden
, cl::cat(RTDyldCategory
));
115 static cl::opt
<uint64_t> TargetAddrEnd(
117 cl::desc("For -verify only: end of phony target address range."),
118 cl::init(~0ULL), cl::Hidden
, cl::cat(RTDyldCategory
));
120 static cl::opt
<uint64_t> TargetSectionSep(
121 "target-section-sep",
122 cl::desc("For -verify only: Separation between sections in "
123 "phony target address space."),
124 cl::init(0), cl::Hidden
, cl::cat(RTDyldCategory
));
126 static cl::list
<std::string
>
127 SpecificSectionMappings("map-section",
128 cl::desc("For -verify only: Map a section to a "
129 "specific address."),
130 cl::Hidden
, cl::cat(RTDyldCategory
));
132 static cl::list
<std::string
> DummySymbolMappings(
134 cl::desc("For -verify only: Inject a symbol into the extern "
136 cl::Hidden
, cl::cat(RTDyldCategory
));
138 static cl::opt
<bool> PrintAllocationRequests(
139 "print-alloc-requests",
140 cl::desc("Print allocation requests made to the memory "
141 "manager by RuntimeDyld"),
142 cl::Hidden
, cl::cat(RTDyldCategory
));
144 static cl::opt
<bool> ShowTimes("show-times",
145 cl::desc("Show times for llvm-rtdyld phases"),
146 cl::init(false), cl::cat(RTDyldCategory
));
148 ExitOnError ExitOnErr
;
150 struct RTDyldTimers
{
151 TimerGroup RTDyldTG
{"llvm-rtdyld timers", "timers for llvm-rtdyld phases"};
152 Timer LoadObjectsTimer
{"load", "time to load/add object files", RTDyldTG
};
153 Timer LinkTimer
{"link", "time to link object files", RTDyldTG
};
154 Timer RunTimer
{"run", "time to execute jitlink'd code", RTDyldTG
};
157 std::unique_ptr
<RTDyldTimers
> Timers
;
161 using SectionIDMap
= StringMap
<unsigned>;
162 using FileToSectionIDMap
= StringMap
<SectionIDMap
>;
164 void dumpFileToSectionIDMap(const FileToSectionIDMap
&FileToSecIDMap
) {
165 for (const auto &KV
: FileToSecIDMap
) {
166 llvm::dbgs() << "In " << KV
.first() << "\n";
167 for (auto &KV2
: KV
.second
)
168 llvm::dbgs() << " \"" << KV2
.first() << "\" -> " << KV2
.second
<< "\n";
172 Expected
<unsigned> getSectionId(const FileToSectionIDMap
&FileToSecIDMap
,
173 StringRef FileName
, StringRef SectionName
) {
174 auto I
= FileToSecIDMap
.find(FileName
);
175 if (I
== FileToSecIDMap
.end())
176 return make_error
<StringError
>("No file named " + FileName
,
177 inconvertibleErrorCode());
178 auto &SectionIDs
= I
->second
;
179 auto J
= SectionIDs
.find(SectionName
);
180 if (J
== SectionIDs
.end())
181 return make_error
<StringError
>("No section named \"" + SectionName
+
182 "\" in file " + FileName
,
183 inconvertibleErrorCode());
187 // A trivial memory manager that doesn't do anything fancy, just uses the
188 // support library allocation routines directly.
189 class TrivialMemoryManager
: public RTDyldMemoryManager
{
192 SectionInfo(StringRef Name
, sys::MemoryBlock MB
, unsigned SectionID
)
193 : Name(std::string(Name
)), MB(std::move(MB
)), SectionID(SectionID
) {}
196 unsigned SectionID
= ~0U;
199 SmallVector
<SectionInfo
, 16> FunctionMemory
;
200 SmallVector
<SectionInfo
, 16> DataMemory
;
202 uint8_t *allocateCodeSection(uintptr_t Size
, unsigned Alignment
,
204 StringRef SectionName
) override
;
205 uint8_t *allocateDataSection(uintptr_t Size
, unsigned Alignment
,
206 unsigned SectionID
, StringRef SectionName
,
207 bool IsReadOnly
) override
;
208 TrivialMemoryManager::TLSSection
209 allocateTLSSection(uintptr_t Size
, unsigned Alignment
, unsigned SectionID
,
210 StringRef SectionName
) override
;
212 /// If non null, records subsequent Name -> SectionID mappings.
213 void setSectionIDsMap(SectionIDMap
*SecIDMap
) {
214 this->SecIDMap
= SecIDMap
;
217 void *getPointerToNamedFunction(const std::string
&Name
,
218 bool AbortOnFailure
= true) override
{
222 bool finalizeMemory(std::string
*ErrMsg
) override
{ return false; }
224 void addDummySymbol(const std::string
&Name
, uint64_t Addr
) {
225 DummyExterns
[Name
] = Addr
;
228 JITSymbol
findSymbol(const std::string
&Name
) override
{
229 auto I
= DummyExterns
.find(Name
);
231 if (I
!= DummyExterns
.end())
232 return JITSymbol(I
->second
, JITSymbolFlags::Exported
);
234 if (auto Sym
= RTDyldMemoryManager::findSymbol(Name
))
236 else if (auto Err
= Sym
.takeError())
237 ExitOnErr(std::move(Err
));
239 ExitOnErr(make_error
<StringError
>("Could not find definition for \"" +
241 inconvertibleErrorCode()));
242 llvm_unreachable("Should have returned or exited by now");
245 void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
,
246 size_t Size
) override
{}
247 void deregisterEHFrames() override
{}
249 void preallocateSlab(uint64_t Size
) {
251 sys::MemoryBlock MB
=
252 sys::Memory::allocateMappedMemory(Size
, nullptr,
253 sys::Memory::MF_READ
|
254 sys::Memory::MF_WRITE
,
257 report_fatal_error(Twine("Can't allocate enough memory: ") +
261 UsePreallocation
= true;
265 uint8_t *allocateFromSlab(uintptr_t Size
, unsigned Alignment
, bool isCode
,
266 StringRef SectionName
, unsigned SectionID
) {
267 Size
= alignTo(Size
, Alignment
);
268 if (CurrentSlabOffset
+ Size
> SlabSize
)
269 report_fatal_error("Can't allocate enough memory. Tune --preallocate");
271 uintptr_t OldSlabOffset
= CurrentSlabOffset
;
272 sys::MemoryBlock
MB((void *)OldSlabOffset
, Size
);
274 FunctionMemory
.push_back(SectionInfo(SectionName
, MB
, SectionID
));
276 DataMemory
.push_back(SectionInfo(SectionName
, MB
, SectionID
));
277 CurrentSlabOffset
+= Size
;
278 return (uint8_t*)OldSlabOffset
;
282 std::map
<std::string
, uint64_t> DummyExterns
;
283 sys::MemoryBlock PreallocSlab
;
284 bool UsePreallocation
= false;
285 uintptr_t SlabSize
= 0;
286 uintptr_t CurrentSlabOffset
= 0;
287 SectionIDMap
*SecIDMap
= nullptr;
288 #if defined(__x86_64__) && defined(__ELF__) && defined(__linux__)
289 unsigned UsedTLSStorage
= 0;
293 uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size
,
296 StringRef SectionName
) {
297 if (PrintAllocationRequests
)
298 outs() << "allocateCodeSection(Size = " << Size
<< ", Alignment = "
299 << Alignment
<< ", SectionName = " << SectionName
<< ")\n";
302 (*SecIDMap
)[SectionName
] = SectionID
;
304 if (UsePreallocation
)
305 return allocateFromSlab(Size
, Alignment
, true /* isCode */,
306 SectionName
, SectionID
);
309 sys::MemoryBlock MB
=
310 sys::Memory::allocateMappedMemory(Size
, nullptr,
311 sys::Memory::MF_READ
|
312 sys::Memory::MF_WRITE
,
315 report_fatal_error(Twine("MemoryManager allocation failed: ") +
317 FunctionMemory
.push_back(SectionInfo(SectionName
, MB
, SectionID
));
318 return (uint8_t*)MB
.base();
321 uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size
,
324 StringRef SectionName
,
326 if (PrintAllocationRequests
)
327 outs() << "allocateDataSection(Size = " << Size
<< ", Alignment = "
328 << Alignment
<< ", SectionName = " << SectionName
<< ")\n";
331 (*SecIDMap
)[SectionName
] = SectionID
;
333 if (UsePreallocation
)
334 return allocateFromSlab(Size
, Alignment
, false /* isCode */, SectionName
,
338 sys::MemoryBlock MB
=
339 sys::Memory::allocateMappedMemory(Size
, nullptr,
340 sys::Memory::MF_READ
|
341 sys::Memory::MF_WRITE
,
344 report_fatal_error(Twine("MemoryManager allocation failed: ") +
346 DataMemory
.push_back(SectionInfo(SectionName
, MB
, SectionID
));
347 return (uint8_t*)MB
.base();
350 // In case the execution needs TLS storage, we define a very small TLS memory
351 // area here that will be used in allocateTLSSection().
352 #if defined(__x86_64__) && defined(__ELF__) && defined(__linux__)
354 alignas(16) __attribute__((visibility("hidden"), tls_model("initial-exec"),
355 used
)) thread_local
char LLVMRTDyldTLSSpace
[16];
359 TrivialMemoryManager::TLSSection
360 TrivialMemoryManager::allocateTLSSection(uintptr_t Size
, unsigned Alignment
,
362 StringRef SectionName
) {
363 #if defined(__x86_64__) && defined(__ELF__) && defined(__linux__)
364 if (Size
+ UsedTLSStorage
> sizeof(LLVMRTDyldTLSSpace
)) {
368 // Get the offset of the TLSSpace in the TLS block by using a tpoff
371 asm("leaq LLVMRTDyldTLSSpace@tpoff, %0" : "=r"(TLSOffset
));
374 // We use the storage directly as the initialization image. This means that
375 // when a new thread is spawned after this allocation, it will not be
376 // initialized correctly. This means, llvm-rtdyld will only support TLS in a
378 Section
.InitializationImage
=
379 reinterpret_cast<uint8_t *>(LLVMRTDyldTLSSpace
+ UsedTLSStorage
);
380 Section
.Offset
= TLSOffset
+ UsedTLSStorage
;
382 UsedTLSStorage
+= Size
;
390 static const char *ProgramName
;
392 static void ErrorAndExit(const Twine
&Msg
) {
393 errs() << ProgramName
<< ": error: " << Msg
<< "\n";
397 static void loadDylibs() {
398 for (const std::string
&Dylib
: Dylibs
) {
399 if (!sys::fs::is_regular_file(Dylib
))
400 report_fatal_error(Twine("Dylib not found: '") + Dylib
+ "'.");
402 if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib
.c_str(), &ErrMsg
))
403 report_fatal_error(Twine("Error loading '") + Dylib
+ "': " + ErrMsg
);
409 static int printLineInfoForInput(bool LoadObjects
, bool UseDebugObj
) {
410 assert(LoadObjects
|| !UseDebugObj
);
412 // Load any dylibs requested on the command line.
415 // If we don't have any input files, read from stdin.
416 if (!InputFileList
.size())
417 InputFileList
.push_back("-");
418 for (auto &File
: InputFileList
) {
419 // Instantiate a dynamic linker.
420 TrivialMemoryManager MemMgr
;
421 RuntimeDyld
Dyld(MemMgr
, MemMgr
);
423 // Load the input memory buffer.
425 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> InputBuffer
=
426 MemoryBuffer::getFileOrSTDIN(File
);
427 if (std::error_code EC
= InputBuffer
.getError())
428 ErrorAndExit("unable to read input: '" + EC
.message() + "'");
430 Expected
<std::unique_ptr
<ObjectFile
>> MaybeObj(
431 ObjectFile::createObjectFile((*InputBuffer
)->getMemBufferRef()));
435 raw_string_ostream
OS(Buf
);
436 logAllUnhandledErrors(MaybeObj
.takeError(), OS
);
438 ErrorAndExit("unable to create object file: '" + Buf
+ "'");
441 ObjectFile
&Obj
= **MaybeObj
;
443 OwningBinary
<ObjectFile
> DebugObj
;
444 std::unique_ptr
<RuntimeDyld::LoadedObjectInfo
> LoadedObjInfo
= nullptr;
445 ObjectFile
*SymbolObj
= &Obj
;
447 // Load the object file
449 Dyld
.loadObject(Obj
);
452 ErrorAndExit(Dyld
.getErrorString());
454 // Resolve all the relocations we can.
455 Dyld
.resolveRelocations();
458 DebugObj
= LoadedObjInfo
->getObjectForDebug(Obj
);
459 SymbolObj
= DebugObj
.getBinary();
460 LoadedObjInfo
.reset();
464 std::unique_ptr
<DIContext
> Context
= DWARFContext::create(
465 *SymbolObj
, DWARFContext::ProcessDebugRelocations::Process
,
466 LoadedObjInfo
.get());
468 std::vector
<std::pair
<SymbolRef
, uint64_t>> SymAddr
=
469 object::computeSymbolSizes(*SymbolObj
);
471 // Use symbol info to iterate functions in the object.
472 for (const auto &P
: SymAddr
) {
473 object::SymbolRef Sym
= P
.first
;
474 Expected
<SymbolRef::Type
> TypeOrErr
= Sym
.getType();
476 // TODO: Actually report errors helpfully.
477 consumeError(TypeOrErr
.takeError());
480 SymbolRef::Type Type
= *TypeOrErr
;
481 if (Type
== object::SymbolRef::ST_Function
) {
482 Expected
<StringRef
> Name
= Sym
.getName();
484 // TODO: Actually report errors helpfully.
485 consumeError(Name
.takeError());
488 Expected
<uint64_t> AddrOrErr
= Sym
.getAddress();
490 // TODO: Actually report errors helpfully.
491 consumeError(AddrOrErr
.takeError());
494 uint64_t Addr
= *AddrOrErr
;
496 object::SectionedAddress Address
;
498 uint64_t Size
= P
.second
;
499 // If we're not using the debug object, compute the address of the
500 // symbol in memory (rather than that in the unrelocated object file)
501 // and use that to query the DWARFContext.
502 if (!UseDebugObj
&& LoadObjects
) {
503 auto SecOrErr
= Sym
.getSection();
505 // TODO: Actually report errors helpfully.
506 consumeError(SecOrErr
.takeError());
509 object::section_iterator Sec
= *SecOrErr
;
510 Address
.SectionIndex
= Sec
->getIndex();
511 uint64_t SectionLoadAddress
=
512 LoadedObjInfo
->getSectionLoadAddress(*Sec
);
513 if (SectionLoadAddress
!= 0)
514 Addr
+= SectionLoadAddress
- Sec
->getAddress();
515 } else if (auto SecOrErr
= Sym
.getSection())
516 Address
.SectionIndex
= SecOrErr
.get()->getIndex();
518 outs() << "Function: " << *Name
<< ", Size = " << Size
519 << ", Addr = " << Addr
<< "\n";
521 Address
.Address
= Addr
;
522 DILineInfoTable Lines
=
523 Context
->getLineInfoForAddressRange(Address
, Size
);
524 for (auto &D
: Lines
) {
525 outs() << " Line info @ " << D
.first
- Addr
<< ": "
526 << D
.second
.FileName
<< ", line:" << D
.second
.Line
<< "\n";
535 static void doPreallocation(TrivialMemoryManager
&MemMgr
) {
536 // Allocate a slab of memory upfront, if required. This is used if
537 // we want to test small code models.
538 if (static_cast<intptr_t>(PreallocMemory
) < 0)
539 report_fatal_error("Pre-allocated bytes of memory must be a positive integer.");
541 // FIXME: Limit the amount of memory that can be preallocated?
542 if (PreallocMemory
!= 0)
543 MemMgr
.preallocateSlab(PreallocMemory
);
546 static int executeInput() {
547 // Load any dylibs requested on the command line.
550 // Instantiate a dynamic linker.
551 TrivialMemoryManager MemMgr
;
552 doPreallocation(MemMgr
);
553 RuntimeDyld
Dyld(MemMgr
, MemMgr
);
555 // If we don't have any input files, read from stdin.
556 if (!InputFileList
.size())
557 InputFileList
.push_back("-");
559 TimeRegion
TR(Timers
? &Timers
->LoadObjectsTimer
: nullptr);
560 for (auto &File
: InputFileList
) {
561 // Load the input memory buffer.
562 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> InputBuffer
=
563 MemoryBuffer::getFileOrSTDIN(File
);
564 if (std::error_code EC
= InputBuffer
.getError())
565 ErrorAndExit("unable to read input: '" + EC
.message() + "'");
566 Expected
<std::unique_ptr
<ObjectFile
>> MaybeObj(
567 ObjectFile::createObjectFile((*InputBuffer
)->getMemBufferRef()));
571 raw_string_ostream
OS(Buf
);
572 logAllUnhandledErrors(MaybeObj
.takeError(), OS
);
574 ErrorAndExit("unable to create object file: '" + Buf
+ "'");
577 ObjectFile
&Obj
= **MaybeObj
;
579 // Load the object file
580 Dyld
.loadObject(Obj
);
581 if (Dyld
.hasError()) {
582 ErrorAndExit(Dyld
.getErrorString());
588 TimeRegion
TR(Timers
? &Timers
->LinkTimer
: nullptr);
589 // Resove all the relocations we can.
590 // FIXME: Error out if there are unresolved relocations.
591 Dyld
.resolveRelocations();
594 // Get the address of the entry point (_main by default).
595 void *MainAddress
= Dyld
.getSymbolLocalAddress(EntryPoint
);
597 ErrorAndExit("no definition for '" + EntryPoint
+ "'");
599 // Invalidate the instruction cache for each loaded function.
600 for (auto &FM
: MemMgr
.FunctionMemory
) {
604 // Make sure the memory is executable.
605 // setExecutable will call InvalidateInstructionCache.
606 if (auto EC
= sys::Memory::protectMappedMemory(FM_MB
,
607 sys::Memory::MF_READ
|
608 sys::Memory::MF_EXEC
))
609 ErrorAndExit("unable to mark function executable: '" + EC
.message() +
613 // Dispatch to _main().
614 errs() << "loaded '" << EntryPoint
<< "' at: " << (void*)MainAddress
<< "\n";
616 int (*Main
)(int, const char**) =
617 (int(*)(int,const char**)) uintptr_t(MainAddress
);
618 std::vector
<const char *> Argv
;
619 // Use the name of the first input object module as argv[0] for the target.
620 Argv
.push_back(InputFileList
[0].data());
621 for (auto &Arg
: InputArgv
)
622 Argv
.push_back(Arg
.data());
623 Argv
.push_back(nullptr);
626 TimeRegion
TR(Timers
? &Timers
->RunTimer
: nullptr);
627 Result
= Main(Argv
.size() - 1, Argv
.data());
633 static int checkAllExpressions(RuntimeDyldChecker
&Checker
) {
634 for (const auto& CheckerFileName
: CheckFiles
) {
635 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> CheckerFileBuf
=
636 MemoryBuffer::getFileOrSTDIN(CheckerFileName
);
637 if (std::error_code EC
= CheckerFileBuf
.getError())
638 ErrorAndExit("unable to read input '" + CheckerFileName
+ "': " +
641 if (!Checker
.checkAllRulesInBuffer("# rtdyld-check:",
642 CheckerFileBuf
.get().get()))
643 ErrorAndExit("some checks in '" + CheckerFileName
+ "' failed");
648 void applySpecificSectionMappings(RuntimeDyld
&Dyld
,
649 const FileToSectionIDMap
&FileToSecIDMap
) {
651 for (StringRef Mapping
: SpecificSectionMappings
) {
652 size_t EqualsIdx
= Mapping
.find_first_of("=");
653 std::string SectionIDStr
= std::string(Mapping
.substr(0, EqualsIdx
));
654 size_t ComaIdx
= Mapping
.find_first_of(",");
656 if (ComaIdx
== StringRef::npos
)
657 report_fatal_error("Invalid section specification '" + Mapping
+
658 "'. Should be '<file name>,<section name>=<addr>'");
660 std::string FileName
= SectionIDStr
.substr(0, ComaIdx
);
661 std::string SectionName
= SectionIDStr
.substr(ComaIdx
+ 1);
663 ExitOnErr(getSectionId(FileToSecIDMap
, FileName
, SectionName
));
665 auto* OldAddr
= Dyld
.getSectionContent(SectionID
).data();
666 std::string NewAddrStr
= std::string(Mapping
.substr(EqualsIdx
+ 1));
669 if (StringRef(NewAddrStr
).getAsInteger(0, NewAddr
))
670 report_fatal_error("Invalid section address in mapping '" + Mapping
+
673 Dyld
.mapSectionAddress(OldAddr
, NewAddr
);
677 // Scatter sections in all directions!
678 // Remaps section addresses for -verify mode. The following command line options
679 // can be used to customize the layout of the memory within the phony target's
681 // -target-addr-start <s> -- Specify where the phony target address range starts.
682 // -target-addr-end <e> -- Specify where the phony target address range ends.
683 // -target-section-sep <d> -- Specify how big a gap should be left between the
684 // end of one section and the start of the next.
685 // Defaults to zero. Set to something big
686 // (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
688 static void remapSectionsAndSymbols(const llvm::Triple
&TargetTriple
,
690 TrivialMemoryManager
&MemMgr
) {
692 // Set up a work list (section addr/size pairs).
693 typedef std::list
<const TrivialMemoryManager::SectionInfo
*> WorklistT
;
696 for (const auto& CodeSection
: MemMgr
.FunctionMemory
)
697 Worklist
.push_back(&CodeSection
);
698 for (const auto& DataSection
: MemMgr
.DataMemory
)
699 Worklist
.push_back(&DataSection
);
701 // Keep an "already allocated" mapping of section target addresses to sizes.
702 // Sections whose address mappings aren't specified on the command line will
703 // allocated around the explicitly mapped sections while maintaining the
704 // minimum separation.
705 std::map
<uint64_t, uint64_t> AlreadyAllocated
;
707 // Move the previously applied mappings (whether explicitly specified on the
708 // command line, or implicitly set by RuntimeDyld) into the already-allocated
710 for (WorklistT::iterator I
= Worklist
.begin(), E
= Worklist
.end();
712 WorklistT::iterator Tmp
= I
;
715 auto LoadAddr
= Dyld
.getSectionLoadAddress((*Tmp
)->SectionID
);
717 if (LoadAddr
!= static_cast<uint64_t>(
718 reinterpret_cast<uintptr_t>((*Tmp
)->MB
.base()))) {
719 // A section will have a LoadAddr of 0 if it wasn't loaded for whatever
720 // reason (e.g. zero byte COFF sections). Don't include those sections in
721 // the allocation map.
723 AlreadyAllocated
[LoadAddr
] = (*Tmp
)->MB
.allocatedSize();
728 // If the -target-addr-end option wasn't explicitly passed, then set it to a
729 // sensible default based on the target triple.
730 if (TargetAddrEnd
.getNumOccurrences() == 0) {
731 if (TargetTriple
.isArch16Bit())
732 TargetAddrEnd
= (1ULL << 16) - 1;
733 else if (TargetTriple
.isArch32Bit())
734 TargetAddrEnd
= (1ULL << 32) - 1;
735 // TargetAddrEnd already has a sensible default for 64-bit systems, so
736 // there's nothing to do in the 64-bit case.
739 // Process any elements remaining in the worklist.
740 while (!Worklist
.empty()) {
741 auto *CurEntry
= Worklist
.front();
742 Worklist
.pop_front();
744 uint64_t NextSectionAddr
= TargetAddrStart
;
746 for (const auto &Alloc
: AlreadyAllocated
)
747 if (NextSectionAddr
+ CurEntry
->MB
.allocatedSize() + TargetSectionSep
<=
751 NextSectionAddr
= Alloc
.first
+ Alloc
.second
+ TargetSectionSep
;
753 Dyld
.mapSectionAddress(CurEntry
->MB
.base(), NextSectionAddr
);
754 AlreadyAllocated
[NextSectionAddr
] = CurEntry
->MB
.allocatedSize();
757 // Add dummy symbols to the memory manager.
758 for (const auto &Mapping
: DummySymbolMappings
) {
759 size_t EqualsIdx
= Mapping
.find_first_of('=');
761 if (EqualsIdx
== StringRef::npos
)
762 report_fatal_error(Twine("Invalid dummy symbol specification '") +
763 Mapping
+ "'. Should be '<symbol name>=<addr>'");
765 std::string Symbol
= Mapping
.substr(0, EqualsIdx
);
766 std::string AddrStr
= Mapping
.substr(EqualsIdx
+ 1);
769 if (StringRef(AddrStr
).getAsInteger(0, Addr
))
770 report_fatal_error(Twine("Invalid symbol mapping '") + Mapping
+ "'.");
772 MemMgr
.addDummySymbol(Symbol
, Addr
);
776 // Load and link the objects specified on the command line, but do not execute
777 // anything. Instead, attach a RuntimeDyldChecker instance and call it to
778 // verify the correctness of the linked memory.
779 static int linkAndVerify() {
781 // Check for missing triple.
782 if (TripleName
== "")
783 ErrorAndExit("-triple required when running in -verify mode.");
785 // Look up the target and build the disassembler.
786 Triple
TheTriple(Triple::normalize(TripleName
));
787 std::string ErrorStr
;
788 const Target
*TheTarget
=
789 TargetRegistry::lookupTarget("", TheTriple
, ErrorStr
);
791 ErrorAndExit("Error accessing target '" + TripleName
+ "': " + ErrorStr
);
793 TripleName
= TheTriple
.getTriple();
795 std::unique_ptr
<MCSubtargetInfo
> STI(
796 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, ""));
798 ErrorAndExit("Unable to create subtarget info!");
800 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
802 ErrorAndExit("Unable to create target register info!");
804 MCTargetOptions MCOptions
;
805 std::unique_ptr
<MCAsmInfo
> MAI(
806 TheTarget
->createMCAsmInfo(*MRI
, TripleName
, MCOptions
));
808 ErrorAndExit("Unable to create target asm info!");
810 MCContext
Ctx(Triple(TripleName
), MAI
.get(), MRI
.get(), STI
.get());
812 std::unique_ptr
<MCDisassembler
> Disassembler(
813 TheTarget
->createMCDisassembler(*STI
, Ctx
));
815 ErrorAndExit("Unable to create disassembler!");
817 std::unique_ptr
<MCInstrInfo
> MII(TheTarget
->createMCInstrInfo());
819 ErrorAndExit("Unable to create target instruction info!");
821 std::unique_ptr
<MCInstPrinter
> InstPrinter(
822 TheTarget
->createMCInstPrinter(Triple(TripleName
), 0, *MAI
, *MII
, *MRI
));
824 // Load any dylibs requested on the command line.
827 // Instantiate a dynamic linker.
828 TrivialMemoryManager MemMgr
;
829 doPreallocation(MemMgr
);
835 using StubInfos
= StringMap
<StubID
>;
836 using StubContainers
= StringMap
<StubInfos
>;
838 StubContainers StubMap
;
839 RuntimeDyld
Dyld(MemMgr
, MemMgr
);
840 Dyld
.setProcessAllSections(true);
842 Dyld
.setNotifyStubEmitted([&StubMap
](StringRef FilePath
,
843 StringRef SectionName
,
844 StringRef SymbolName
, unsigned SectionID
,
845 uint32_t StubOffset
) {
846 std::string ContainerName
=
847 (sys::path::filename(FilePath
) + "/" + SectionName
).str();
848 StubMap
[ContainerName
][SymbolName
] = {SectionID
, StubOffset
};
853 StringRef Symbol
) -> Expected
<RuntimeDyldChecker::MemoryRegionInfo
> {
854 RuntimeDyldChecker::MemoryRegionInfo SymInfo
;
856 // First get the target address.
857 if (auto InternalSymbol
= Dyld
.getSymbol(Symbol
))
858 SymInfo
.setTargetAddress(InternalSymbol
.getAddress());
860 // Symbol not found in RuntimeDyld. Fall back to external lookup.
862 using ExpectedLookupResult
=
863 MSVCPExpected
<JITSymbolResolver::LookupResult
>;
865 using ExpectedLookupResult
= Expected
<JITSymbolResolver::LookupResult
>;
868 auto ResultP
= std::make_shared
<std::promise
<ExpectedLookupResult
>>();
869 auto ResultF
= ResultP
->get_future();
871 MemMgr
.lookup(JITSymbolResolver::LookupSet({Symbol
}),
872 [=](Expected
<JITSymbolResolver::LookupResult
> Result
) {
873 ResultP
->set_value(std::move(Result
));
876 auto Result
= ResultF
.get();
878 return Result
.takeError();
880 auto I
= Result
->find(Symbol
);
881 assert(I
!= Result
->end() &&
882 "Expected symbol address if no error occurred");
883 SymInfo
.setTargetAddress(I
->second
.getAddress());
886 // Now find the symbol content if possible (otherwise leave content as a
887 // default-constructed StringRef).
888 if (auto *SymAddr
= Dyld
.getSymbolLocalAddress(Symbol
)) {
889 unsigned SectionID
= Dyld
.getSymbolSectionID(Symbol
);
890 if (SectionID
!= ~0U) {
891 char *CSymAddr
= static_cast<char *>(SymAddr
);
892 StringRef SecContent
= Dyld
.getSectionContent(SectionID
);
893 uint64_t SymSize
= SecContent
.size() - (CSymAddr
- SecContent
.data());
894 SymInfo
.setContent(ArrayRef
<char>(CSymAddr
, SymSize
));
895 SymInfo
.setTargetFlags(
896 Dyld
.getSymbol(Symbol
).getFlags().getTargetFlags());
902 auto IsSymbolValid
= [&Dyld
, GetSymbolInfo
](StringRef Symbol
) {
903 if (Dyld
.getSymbol(Symbol
))
905 auto SymInfo
= GetSymbolInfo(Symbol
);
907 logAllUnhandledErrors(SymInfo
.takeError(), errs(), "RTDyldChecker: ");
910 return SymInfo
->getTargetAddress() != 0;
913 FileToSectionIDMap FileToSecIDMap
;
915 auto GetSectionInfo
= [&Dyld
, &FileToSecIDMap
](StringRef FileName
,
916 StringRef SectionName
)
917 -> Expected
<RuntimeDyldChecker::MemoryRegionInfo
> {
918 auto SectionID
= getSectionId(FileToSecIDMap
, FileName
, SectionName
);
920 return SectionID
.takeError();
921 RuntimeDyldChecker::MemoryRegionInfo SecInfo
;
922 SecInfo
.setTargetAddress(Dyld
.getSectionLoadAddress(*SectionID
));
923 StringRef SecContent
= Dyld
.getSectionContent(*SectionID
);
924 SecInfo
.setContent(ArrayRef
<char>(SecContent
.data(), SecContent
.size()));
928 auto GetStubInfo
= [&Dyld
, &StubMap
](StringRef StubContainer
,
929 StringRef SymbolName
)
930 -> Expected
<RuntimeDyldChecker::MemoryRegionInfo
> {
931 if (!StubMap
.count(StubContainer
))
932 return make_error
<StringError
>("Stub container not found: " +
934 inconvertibleErrorCode());
935 if (!StubMap
[StubContainer
].count(SymbolName
))
936 return make_error
<StringError
>("Symbol name " + SymbolName
+
937 " in stub container " + StubContainer
,
938 inconvertibleErrorCode());
939 auto &SI
= StubMap
[StubContainer
][SymbolName
];
940 RuntimeDyldChecker::MemoryRegionInfo StubMemInfo
;
941 StubMemInfo
.setTargetAddress(Dyld
.getSectionLoadAddress(SI
.SectionID
) +
943 StringRef SecContent
=
944 Dyld
.getSectionContent(SI
.SectionID
).substr(SI
.Offset
);
945 StubMemInfo
.setContent(
946 ArrayRef
<char>(SecContent
.data(), SecContent
.size()));
950 // We will initialize this below once we have the first object file and can
951 // know the endianness.
952 std::unique_ptr
<RuntimeDyldChecker
> Checker
;
954 // If we don't have any input files, read from stdin.
955 if (!InputFileList
.size())
956 InputFileList
.push_back("-");
957 for (auto &InputFile
: InputFileList
) {
958 // Load the input memory buffer.
959 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> InputBuffer
=
960 MemoryBuffer::getFileOrSTDIN(InputFile
);
962 if (std::error_code EC
= InputBuffer
.getError())
963 ErrorAndExit("unable to read input: '" + EC
.message() + "'");
965 Expected
<std::unique_ptr
<ObjectFile
>> MaybeObj(
966 ObjectFile::createObjectFile((*InputBuffer
)->getMemBufferRef()));
970 raw_string_ostream
OS(Buf
);
971 logAllUnhandledErrors(MaybeObj
.takeError(), OS
);
973 ErrorAndExit("unable to create object file: '" + Buf
+ "'");
976 ObjectFile
&Obj
= **MaybeObj
;
979 Checker
= std::make_unique
<RuntimeDyldChecker
>(
980 IsSymbolValid
, GetSymbolInfo
, GetSectionInfo
, GetStubInfo
,
982 Obj
.isLittleEndian() ? llvm::endianness::little
983 : llvm::endianness::big
,
984 TheTriple
, MCPU
, SubtargetFeatures(), dbgs());
986 auto FileName
= sys::path::filename(InputFile
);
987 MemMgr
.setSectionIDsMap(&FileToSecIDMap
[FileName
]);
989 // Load the object file
990 Dyld
.loadObject(Obj
);
991 if (Dyld
.hasError()) {
992 ErrorAndExit(Dyld
.getErrorString());
996 // Re-map the section addresses into the phony target address space and add
998 applySpecificSectionMappings(Dyld
, FileToSecIDMap
);
999 remapSectionsAndSymbols(TheTriple
, Dyld
, MemMgr
);
1001 // Resolve all the relocations we can.
1002 Dyld
.resolveRelocations();
1004 // Register EH frames.
1005 Dyld
.registerEHFrames();
1007 int ErrorCode
= checkAllExpressions(*Checker
);
1008 if (Dyld
.hasError())
1009 ErrorAndExit("RTDyld reported an error applying relocations:\n " +
1010 Dyld
.getErrorString());
1015 int main(int argc
, char **argv
) {
1016 InitLLVM
X(argc
, argv
);
1017 ProgramName
= argv
[0];
1019 llvm::InitializeAllTargetInfos();
1020 llvm::InitializeAllTargetMCs();
1021 llvm::InitializeAllDisassemblers();
1023 cl::HideUnrelatedOptions({&RTDyldCategory
, &getColorCategory()});
1024 cl::ParseCommandLineOptions(argc
, argv
, "llvm MC-JIT tool\n");
1026 ExitOnErr
.setBanner(std::string(argv
[0]) + ": ");
1028 Timers
= ShowTimes
? std::make_unique
<RTDyldTimers
>() : nullptr;
1033 Result
= executeInput();
1035 case AC_PrintDebugLineInfo
:
1037 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ true);
1039 case AC_PrintLineInfo
:
1041 printLineInfoForInput(/* LoadObjects */ true, /* UseDebugObj */ false);
1043 case AC_PrintObjectLineInfo
:
1045 printLineInfoForInput(/* LoadObjects */ false, /* UseDebugObj */ false);
1048 Result
= linkAndVerify();