LLVM 24.0.0git
RuntimeDyld.cpp
Go to the documentation of this file.
1//===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of the MC-JIT runtime dynamic linker.
10//
11//===----------------------------------------------------------------------===//
12
14#include "RuntimeDyldCOFF.h"
15#include "RuntimeDyldELF.h"
16#include "RuntimeDyldImpl.h"
17#include "RuntimeDyldMachO.h"
18#include "llvm/Object/COFF.h"
23#include <mutex>
24
25#include <future>
26
27using namespace llvm;
28using namespace llvm::object;
29
30#define DEBUG_TYPE "dyld"
31
32namespace {
33
34enum RuntimeDyldErrorCode {
35 GenericRTDyldError = 1
36};
37
38// FIXME: This class is only here to support the transition to llvm::Error. It
39// will be removed once this transition is complete. Clients should prefer to
40// deal with the Error value directly, rather than converting to error_code.
41class RuntimeDyldErrorCategory : public std::error_category {
42public:
43 const char *name() const noexcept override { return "runtimedyld"; }
44
45 std::string message(int Condition) const override {
46 switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
47 case GenericRTDyldError: return "Generic RuntimeDyld error";
48 }
49 llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
50 }
51};
52
53}
54
56
58 OS << ErrMsg << "\n";
59}
60
61std::error_code RuntimeDyldError::convertToErrorCode() const {
62 static RuntimeDyldErrorCategory RTDyldErrorCategory;
63 return std::error_code(GenericRTDyldError, RTDyldErrorCategory);
64}
65
66// Empty out-of-line virtual destructor as the key function.
68
69// Pin LoadedObjectInfo's vtables to this file.
71
72namespace llvm {
73
75
77 MemMgr.deregisterEHFrames();
78}
79
80#ifndef NDEBUG
81static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
82 dbgs() << "----- Contents of section " << S.getName() << " " << State
83 << " -----";
84
85 if (S.getAddress() == nullptr) {
86 dbgs() << "\n <section not emitted>\n";
87 return;
88 }
89
90 const unsigned ColsPerRow = 16;
91
92 uint8_t *DataAddr = S.getAddress();
93 uint64_t LoadAddr = S.getLoadAddress();
94
95 unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
96 unsigned BytesRemaining = S.getSize();
97
98 if (StartPadding) {
99 dbgs() << "\n" << format("0x%016" PRIx64,
100 LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
101 while (StartPadding--)
102 dbgs() << " ";
103 }
104
105 while (BytesRemaining > 0) {
106 if ((LoadAddr & (ColsPerRow - 1)) == 0)
107 dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
108
109 dbgs() << " " << format("%02x", *DataAddr);
110
111 ++DataAddr;
112 ++LoadAddr;
113 --BytesRemaining;
114 }
115
116 dbgs() << "\n";
117}
118#endif
119
120// Resolve the relocations for all symbols we currently know about.
122 std::lock_guard<sys::Mutex> locked(lock);
123
124 // Print out the sections prior to relocation.
125 LLVM_DEBUG({
126 for (SectionEntry &S : Sections)
127 dumpSectionMemory(S, "before relocations");
128 });
129
130 // First, resolve relocations associated with external symbols.
131 if (auto Err = resolveExternalSymbols()) {
132 HasError = true;
133 ErrorStr = toString(std::move(Err));
134 }
135
137
138 // Print out sections after relocation.
139 LLVM_DEBUG({
140 for (SectionEntry &S : Sections)
141 dumpSectionMemory(S, "after relocations");
142 });
143}
144
146 // Iterate over all outstanding relocations
147 for (const auto &Rel : Relocations) {
148 // The Section here (Sections[i]) refers to the section in which the
149 // symbol for the relocation is located. The SectionID in the relocation
150 // entry provides the section to which the relocation will be applied.
151 unsigned Idx = Rel.first;
152 uint64_t Addr = getSectionLoadAddress(Idx);
153 LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
154 << format("%p", (uintptr_t)Addr) << "\n");
155 resolveRelocationList(Rel.second, Addr);
156 }
157 Relocations.clear();
158}
159
160void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
161 uint64_t TargetAddress) {
162 std::lock_guard<sys::Mutex> locked(lock);
163 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
164 if (Sections[i].getAddress() == LocalAddress) {
165 reassignSectionAddress(i, TargetAddress);
166 return;
167 }
168 }
169 llvm_unreachable("Attempting to remap address of unknown section!");
170}
171
172static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
173 uint64_t &Result) {
174 Expected<uint64_t> AddressOrErr = Sym.getAddress();
175 if (!AddressOrErr)
176 return AddressOrErr.takeError();
177 Result = *AddressOrErr - Sec.getAddress();
178 return Error::success();
179}
180
183 std::lock_guard<sys::Mutex> locked(lock);
184
185 // Save information about our target
186 Arch = Obj.getArch();
187 IsTargetLittleEndian = Obj.isLittleEndian();
188 setMipsABI(Obj);
189
190 // Compute the memory size required to load all sections to be loaded
191 // and pass this information to the memory manager
192 if (MemMgr.needsToReserveAllocationSpace()) {
193 uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
194 Align CodeAlign, RODataAlign, RWDataAlign;
195 if (auto Err = computeTotalAllocSize(Obj, CodeSize, CodeAlign, RODataSize,
196 RODataAlign, RWDataSize, RWDataAlign))
197 return std::move(Err);
198 MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
199 RWDataSize, RWDataAlign);
200 }
201
202 // Used sections from the object file
203 ObjSectionToIDMap LocalSections;
204
205 // Common symbols requiring allocation, with their sizes and alignments
206 CommonSymbolList CommonSymbolsToAllocate;
207
208 uint64_t CommonSize = 0;
209 uint32_t CommonAlign = 0;
210
211 // First, collect all weak and common symbols. We need to know if stronger
212 // definitions occur elsewhere.
213 JITSymbolResolver::LookupSet ResponsibilitySet;
214 {
216 for (auto &Sym : Obj.symbols()) {
217 Expected<uint32_t> FlagsOrErr = Sym.getFlags();
218 if (!FlagsOrErr)
219 // TODO: Test this error.
220 return FlagsOrErr.takeError();
221 if ((*FlagsOrErr & SymbolRef::SF_Common) ||
222 (*FlagsOrErr & SymbolRef::SF_Weak)) {
223 // Get symbol name.
224 if (auto NameOrErr = Sym.getName())
225 Symbols.insert(*NameOrErr);
226 else
227 return NameOrErr.takeError();
228 }
229 }
230
231 if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))
232 ResponsibilitySet = std::move(*ResultOrErr);
233 else
234 return ResultOrErr.takeError();
235 }
236
237 // Parse symbols
238 LLVM_DEBUG(dbgs() << "Parse symbols:\n");
239 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
240 ++I) {
241 Expected<uint32_t> FlagsOrErr = I->getFlags();
242 if (!FlagsOrErr)
243 // TODO: Test this error.
244 return FlagsOrErr.takeError();
245
246 // Skip undefined symbols.
247 if (*FlagsOrErr & SymbolRef::SF_Undefined)
248 continue;
249
250 // Get the symbol type.
252 if (auto SymTypeOrErr = I->getType())
253 SymType = *SymTypeOrErr;
254 else
255 return SymTypeOrErr.takeError();
256
257 // Get symbol name.
258 StringRef Name;
259 if (auto NameOrErr = I->getName())
260 Name = *NameOrErr;
261 else
262 return NameOrErr.takeError();
263
264 // Compute JIT symbol flags.
265 auto JITSymFlags = getJITSymbolFlags(*I);
266 if (!JITSymFlags)
267 return JITSymFlags.takeError();
268
269 // If this is a weak definition, check to see if there's a strong one.
270 // If there is, skip this symbol (we won't be providing it: the strong
271 // definition will). If there's no strong definition, make this definition
272 // strong.
273 if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
274 // First check whether there's already a definition in this instance.
275 if (GlobalSymbolTable.count(Name))
276 continue;
277
278 // If we're not responsible for this symbol, skip it.
279 if (!ResponsibilitySet.count(Name))
280 continue;
281
282 // Otherwise update the flags on the symbol to make this definition
283 // strong.
284 if (JITSymFlags->isWeak())
285 *JITSymFlags &= ~JITSymbolFlags::Weak;
286 if (JITSymFlags->isCommon()) {
287 *JITSymFlags &= ~JITSymbolFlags::Common;
288 uint32_t Align = I->getAlignment();
289 uint64_t Size = I->getCommonSize();
290 if (!CommonAlign)
291 CommonAlign = Align;
292 CommonSize = alignTo(CommonSize, Align) + Size;
293 CommonSymbolsToAllocate.push_back(*I);
294 }
295 }
296
297 if (*FlagsOrErr & SymbolRef::SF_Absolute &&
298 SymType != object::SymbolRef::ST_File) {
299 uint64_t Addr = 0;
300 if (auto AddrOrErr = I->getAddress())
301 Addr = *AddrOrErr;
302 else
303 return AddrOrErr.takeError();
304
305 unsigned SectionID = AbsoluteSymbolSection;
306
307 LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
308 << " SID: " << SectionID
309 << " Offset: " << format("%p", (uintptr_t)Addr)
310 << " flags: " << *FlagsOrErr << "\n");
311 // Skip absolute symbol relocations.
312 if (!Name.empty()) {
313 auto Result = GlobalSymbolTable.insert_or_assign(
314 Name, SymbolTableEntry(SectionID, Addr, *JITSymFlags));
315 processNewSymbol(*I, Result.first->getValue());
316 }
317 } else if (SymType == object::SymbolRef::ST_Function ||
318 SymType == object::SymbolRef::ST_Data ||
320 SymType == object::SymbolRef::ST_Other) {
321
322 section_iterator SI = Obj.section_end();
323 if (auto SIOrErr = I->getSection())
324 SI = *SIOrErr;
325 else
326 return SIOrErr.takeError();
327
328 if (SI == Obj.section_end())
329 continue;
330
331 // Get symbol offset.
332 uint64_t SectOffset;
333 if (auto Err = getOffset(*I, *SI, SectOffset))
334 return std::move(Err);
335
336 bool IsCode = SI->isText();
337 unsigned SectionID;
338 if (auto SectionIDOrErr =
339 findOrEmitSection(Obj, *SI, IsCode, LocalSections))
340 SectionID = *SectionIDOrErr;
341 else
342 return SectionIDOrErr.takeError();
343
344 LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
345 << " SID: " << SectionID
346 << " Offset: " << format("%p", (uintptr_t)SectOffset)
347 << " flags: " << *FlagsOrErr << "\n");
348 // Skip absolute symbol relocations.
349 if (!Name.empty()) {
350 auto Result = GlobalSymbolTable.insert_or_assign(
351 Name, SymbolTableEntry(SectionID, SectOffset, *JITSymFlags));
352 processNewSymbol(*I, Result.first->getValue());
353 }
354 }
355 }
356
357 // Allocate common symbols
358 if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
359 CommonAlign))
360 return std::move(Err);
361
362 // Parse and process relocations
363 LLVM_DEBUG(dbgs() << "Parse relocations:\n");
364 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
365 SI != SE; ++SI) {
366 StubMap Stubs;
367
368 Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
369 if (!RelSecOrErr)
370 return RelSecOrErr.takeError();
371
372 section_iterator RelocatedSection = *RelSecOrErr;
373 if (RelocatedSection == SE)
374 continue;
375
376 relocation_iterator I = SI->relocation_begin();
377 relocation_iterator E = SI->relocation_end();
378
379 if (I == E && !ProcessAllSections)
380 continue;
381
382 bool IsCode = RelocatedSection->isText();
383 unsigned SectionID = 0;
384 if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
385 LocalSections))
386 SectionID = *SectionIDOrErr;
387 else
388 return SectionIDOrErr.takeError();
389
390 LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
391
392 for (; I != E;)
393 if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
394 I = *IOrErr;
395 else
396 return IOrErr.takeError();
397
398 // If there is a NotifyStubEmitted callback set, call it to register any
399 // stubs created for this section.
400 if (NotifyStubEmitted) {
401 StringRef FileName = Obj.getFileName();
402 StringRef SectionName = Sections[SectionID].getName();
403 for (auto &KV : Stubs) {
404
405 auto &VR = KV.first;
406 uint64_t StubAddr = KV.second;
407
408 // If this is a named stub, just call NotifyStubEmitted.
409 if (VR.SymbolName) {
410 NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,
411 StubAddr);
412 continue;
413 }
414
415 // Otherwise we will have to try a reverse lookup on the globla symbol table.
416 for (auto &GSTMapEntry : GlobalSymbolTable) {
417 StringRef SymbolName = GSTMapEntry.first();
418 auto &GSTEntry = GSTMapEntry.second;
419 if (GSTEntry.getSectionID() == VR.SectionID &&
420 GSTEntry.getOffset() == VR.Offset) {
421 NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,
422 StubAddr);
423 break;
424 }
425 }
426 }
427 }
428 }
429
430 // Process remaining sections
431 if (ProcessAllSections) {
432 LLVM_DEBUG(dbgs() << "Process remaining sections:\n");
433 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
434 SI != SE; ++SI) {
435
436 /* Ignore already loaded sections */
437 if (LocalSections.find(*SI) != LocalSections.end())
438 continue;
439
440 bool IsCode = SI->isText();
441 if (auto SectionIDOrErr =
442 findOrEmitSection(Obj, *SI, IsCode, LocalSections))
443 LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");
444 else
445 return SectionIDOrErr.takeError();
446 }
447 }
448
449 // Give the subclasses a chance to tie-up any loose ends.
450 if (auto Err = finalizeLoad(Obj, LocalSections))
451 return std::move(Err);
452
453// for (auto E : LocalSections)
454// llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
455
456 return LocalSections;
457}
458
459// A helper method for computeTotalAllocSize.
460// Computes the memory size required to allocate sections with the given sizes,
461// assuming that all sections are allocated with the given alignment
462static uint64_t
463computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
464 Align Alignment) {
465 uint64_t TotalSize = 0;
466 for (uint64_t SectionSize : SectionSizes)
467 TotalSize += alignTo(SectionSize, Alignment);
468 return TotalSize;
469}
470
471static bool isRequiredForExecution(const SectionRef Section) {
472 const ObjectFile *Obj = Section.getObject();
474 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
475 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
476 const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
477 // Zero-sized sections must still be loaded: symbols may be defined in
478 // them (e.g. a zero-sized object, like an empty struct in C, in .bss),
479 // and references to such symbols need a valid address. Sections are only
480 // emitted on demand, and a zero-sized section gets a minimal allocation.
481 bool IsDiscardable =
482 CoffSection->Characteristics &
484 return !IsDiscardable;
485 }
486
488 return true;
489}
490
491static bool isReadOnlyData(const SectionRef Section) {
492 const ObjectFile *Obj = Section.getObject();
494 return !(ELFSectionRef(Section).getFlags() &
496 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
497 return ((COFFObj->getCOFFSection(Section)->Characteristics &
501 ==
504
506 return false;
507}
508
509static bool isZeroInit(const SectionRef Section) {
510 const ObjectFile *Obj = Section.getObject();
512 return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
513 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
514 return COFFObj->getCOFFSection(Section)->Characteristics &
516
517 auto *MachO = cast<MachOObjectFile>(Obj);
518 unsigned SectionType = MachO->getSectionType(Section);
519 return SectionType == MachO::S_ZEROFILL ||
520 SectionType == MachO::S_GB_ZEROFILL;
521}
522
523static bool isTLS(const SectionRef Section) {
524 const ObjectFile *Obj = Section.getObject();
526 return ELFSectionRef(Section).getFlags() & ELF::SHF_TLS;
527 return false;
528}
529
530// Compute an upper bound of the memory size that is required to load all
531// sections
533 const ObjectFile &Obj, uint64_t &CodeSize, Align &CodeAlign,
534 uint64_t &RODataSize, Align &RODataAlign, uint64_t &RWDataSize,
535 Align &RWDataAlign) {
536 // Compute the size of all sections required for execution
537 std::vector<uint64_t> CodeSectionSizes;
538 std::vector<uint64_t> ROSectionSizes;
539 std::vector<uint64_t> RWSectionSizes;
540
541 // Collect sizes of all sections to be loaded;
542 // also determine the max alignment of all sections
543 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
544 SI != SE; ++SI) {
545 const SectionRef &Section = *SI;
546
547 bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
548
549 // Consider only the sections that are required to be loaded for execution
550 if (IsRequired) {
551 uint64_t DataSize = Section.getSize();
552 Align Alignment = Section.getAlignment();
553 bool IsCode = Section.isText();
554 bool IsReadOnly = isReadOnlyData(Section);
555 bool IsTLS = isTLS(Section);
556
557 Expected<StringRef> NameOrErr = Section.getName();
558 if (!NameOrErr)
559 return NameOrErr.takeError();
560 StringRef Name = *NameOrErr;
561
562 uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
563
564 uint64_t PaddingSize = 0;
565 if (Name == ".eh_frame")
566 PaddingSize += 4;
567 if (StubBufSize != 0)
568 PaddingSize += getStubAlignment().value() - 1;
569
570 uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;
571
572 // The .eh_frame section (at least on Linux) needs an extra four bytes
573 // padded
574 // with zeroes added at the end. For MachO objects, this section has a
575 // slightly different name, so this won't have any effect for MachO
576 // objects.
577 if (Name == ".eh_frame")
578 SectionSize += 4;
579
580 if (!SectionSize)
581 SectionSize = 1;
582
583 if (IsCode) {
584 CodeAlign = std::max(CodeAlign, Alignment);
585 CodeSectionSizes.push_back(SectionSize);
586 } else if (IsReadOnly) {
587 RODataAlign = std::max(RODataAlign, Alignment);
588 ROSectionSizes.push_back(SectionSize);
589 } else if (!IsTLS) {
590 RWDataAlign = std::max(RWDataAlign, Alignment);
591 RWSectionSizes.push_back(SectionSize);
592 }
593 }
594 }
595
596 // Compute Global Offset Table size. If it is not zero we
597 // also update alignment, which is equal to a size of a
598 // single GOT entry.
599 if (unsigned GotSize = computeGOTSize(Obj)) {
600 RWSectionSizes.push_back(GotSize);
601 RWDataAlign = std::max(RWDataAlign, Align(getGOTEntrySize()));
602 }
603
604 // Compute the size of all common symbols
605 uint64_t CommonSize = 0;
606 Align CommonAlign;
607 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
608 ++I) {
609 Expected<uint32_t> FlagsOrErr = I->getFlags();
610 if (!FlagsOrErr)
611 // TODO: Test this error.
612 return FlagsOrErr.takeError();
613 if (*FlagsOrErr & SymbolRef::SF_Common) {
614 // Add the common symbols to a list. We'll allocate them all below.
615 uint64_t Size = I->getCommonSize();
616 Align Alignment = Align(I->getAlignment());
617 // If this is the first common symbol, use its alignment as the alignment
618 // for the common symbols section.
619 if (CommonSize == 0)
620 CommonAlign = Alignment;
621 CommonSize = alignTo(CommonSize, Alignment) + Size;
622 }
623 }
624 if (CommonSize != 0) {
625 RWSectionSizes.push_back(CommonSize);
626 RWDataAlign = std::max(RWDataAlign, CommonAlign);
627 }
628
629 if (!CodeSectionSizes.empty()) {
630 // Add 64 bytes for a potential IFunc resolver stub
631 CodeSectionSizes.push_back(64);
632 }
633
634 // Compute the required allocation space for each different type of sections
635 // (code, read-only data, read-write data) assuming that all sections are
636 // allocated with the max alignment. Note that we cannot compute with the
637 // individual alignments of the sections, because then the required size
638 // depends on the order, in which the sections are allocated.
639 CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
640 RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
641 RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
642
643 return Error::success();
644}
645
646// compute GOT size
648 size_t GotEntrySize = getGOTEntrySize();
649 if (!GotEntrySize)
650 return 0;
651
652 size_t GotSize = 0;
653 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
654 SI != SE; ++SI) {
655
656 for (const RelocationRef &Reloc : SI->relocations())
658 GotSize += GotEntrySize;
659 }
660
661 return GotSize;
662}
663
664// compute stub buffer size for the given section
666 const SectionRef &Section) {
667 if (!MemMgr.allowStubAllocation()) {
668 return 0;
669 }
670
671 unsigned StubSize = getMaxStubSize();
672 if (StubSize == 0) {
673 return 0;
674 }
675 // FIXME: this is an inefficient way to handle this. We should computed the
676 // necessary section allocation size in loadObject by walking all the sections
677 // once.
678 unsigned StubBufSize = 0;
679 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
680 SI != SE; ++SI) {
681
682 Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
683 if (!RelSecOrErr)
685
686 section_iterator RelSecI = *RelSecOrErr;
687 if (!(RelSecI == Section))
688 continue;
689
690 for (const RelocationRef &Reloc : SI->relocations()) {
692 StubBufSize += StubSize;
694 StubBufSize = sizeAfterAddingDLLImportStub(StubBufSize);
695 }
696 }
697
698 // Get section data size and alignment
699 uint64_t DataSize = Section.getSize();
700 Align Alignment = Section.getAlignment();
701
702 // Add stubbuf size alignment
703 Align StubAlignment = getStubAlignment();
704 Align EndAlignment = commonAlignment(Alignment, DataSize);
705 if (StubAlignment > EndAlignment)
706 StubBufSize += StubAlignment.value() - EndAlignment.value();
707 return StubBufSize;
708}
709
711 unsigned Size) const {
712 uint64_t Result = 0;
714 Src += Size - 1;
715 while (Size--)
716 Result = (Result << 8) | *Src--;
717 } else
718 while (Size--)
719 Result = (Result << 8) | *Src++;
720
721 return Result;
722}
723
725 unsigned Size) const {
727 while (Size--) {
728 *Dst++ = Value & 0xFF;
729 Value >>= 8;
730 }
731 } else {
732 Dst += Size - 1;
733 while (Size--) {
734 *Dst-- = Value & 0xFF;
735 Value >>= 8;
736 }
737 }
738}
739
744
746 CommonSymbolList &SymbolsToAllocate,
747 uint64_t CommonSize,
748 uint32_t CommonAlign) {
749 if (SymbolsToAllocate.empty())
750 return Error::success();
751
752 // Allocate memory for the section
753 unsigned SectionID = Sections.size();
754 uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
755 "<common symbols>", false);
756 if (!Addr)
757 report_fatal_error("Unable to allocate memory for common symbols!");
758 uint64_t Offset = 0;
759 Sections.push_back(
760 SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
761 memset(Addr, 0, CommonSize);
762
763 LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
764 << " new addr: " << format("%p", Addr)
765 << " DataSize: " << CommonSize << "\n");
766
767 // Assign the address of each symbol
768 for (auto &Sym : SymbolsToAllocate) {
769 uint32_t Alignment = Sym.getAlignment();
770 uint64_t Size = Sym.getCommonSize();
771 StringRef Name;
772 if (auto NameOrErr = Sym.getName())
773 Name = *NameOrErr;
774 else
775 return NameOrErr.takeError();
776 if (Alignment) {
777 // This symbol has an alignment requirement.
778 uint64_t AlignOffset =
779 offsetToAlignment((uint64_t)Addr, Align(Alignment));
780 Addr += AlignOffset;
781 Offset += AlignOffset;
782 }
783 auto JITSymFlags = getJITSymbolFlags(Sym);
784
785 if (!JITSymFlags)
786 return JITSymFlags.takeError();
787
788 LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
789 << format("%p", Addr) << "\n");
790 if (!Name.empty()) // Skip absolute symbol relocations.
791 GlobalSymbolTable[Name] =
792 SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
793 Offset += Size;
794 Addr += Size;
795 }
796
797 return Error::success();
798}
799
802 const SectionRef &Section,
803 bool IsCode) {
805 Align Alignment = Section.getAlignment();
806
807 unsigned PaddingSize = 0;
808 unsigned StubBufSize = 0;
809 bool IsRequired = isRequiredForExecution(Section);
810 bool IsVirtual = Section.isVirtual();
811 bool IsZeroInit = isZeroInit(Section);
812 bool IsReadOnly = isReadOnlyData(Section);
813 bool IsTLS = isTLS(Section);
814 uint64_t DataSize = Section.getSize();
815
816 Expected<StringRef> NameOrErr = Section.getName();
817 if (!NameOrErr)
818 return NameOrErr.takeError();
819 StringRef Name = *NameOrErr;
820
821 StubBufSize = computeSectionStubBufSize(Obj, Section);
822
823 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
824 // with zeroes added at the end. For MachO objects, this section has a
825 // slightly different name, so this won't have any effect for MachO objects.
826 if (Name == ".eh_frame")
827 PaddingSize = 4;
828
829 uintptr_t Allocate;
830 unsigned SectionID = Sections.size();
831 uint8_t *Addr;
832 uint64_t LoadAddress = 0;
833 const char *pData = nullptr;
834
835 // If this section contains any bits (i.e. isn't a virtual or bss section),
836 // grab a reference to them.
837 if (!IsVirtual && !IsZeroInit) {
838 // In either case, set the location of the unrelocated section in memory,
839 // since we still process relocations for it even if we're not applying them.
840 if (Expected<StringRef> E = Section.getContents())
841 data = *E;
842 else
843 return E.takeError();
844 pData = data.data();
845 }
846
847 // If there are any stubs then the section alignment needs to be at least as
848 // high as stub alignment or padding calculations may by incorrect when the
849 // section is remapped.
850 if (StubBufSize != 0) {
851 Alignment = std::max(Alignment, getStubAlignment());
852 PaddingSize += getStubAlignment().value() - 1;
853 }
854
855 // Some sections, such as debug info, don't need to be loaded for execution.
856 // Process those only if explicitly requested.
857 if (IsRequired || ProcessAllSections) {
858 Allocate = DataSize + PaddingSize + StubBufSize;
859 if (!Allocate)
860 Allocate = 1;
861 if (IsTLS) {
862 auto TLSSection = MemMgr.allocateTLSSection(Allocate, Alignment.value(),
863 SectionID, Name);
864 if (!TLSSection.InitializationImage)
866 "Unable to allocate TLS section memory");
867 Addr = TLSSection.InitializationImage;
868 LoadAddress = TLSSection.Offset;
869 } else if (IsCode) {
870 Addr = MemMgr.allocateCodeSection(Allocate, Alignment.value(), SectionID,
871 Name);
872 } else {
873 Addr = MemMgr.allocateDataSection(Allocate, Alignment.value(), SectionID,
874 Name, IsReadOnly);
875 }
876 if (!Addr)
877 report_fatal_error("Unable to allocate section memory!");
878
879 // Zero-initialize or copy the data from the image
880 if (IsZeroInit || IsVirtual)
881 memset(Addr, 0, DataSize);
882 else
883 memcpy(Addr, pData, DataSize);
884
885 // Fill in any extra bytes we allocated for padding
886 if (PaddingSize != 0) {
887 memset(Addr + DataSize, 0, PaddingSize);
888 // Update the DataSize variable to include padding.
889 DataSize += PaddingSize;
890
891 // Align DataSize to stub alignment if we have any stubs (PaddingSize will
892 // have been increased above to account for this).
893 if (StubBufSize > 0)
894 DataSize &= -getStubAlignment().value();
895 }
896
897 LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
898 << Name << " obj addr: " << format("%p", pData)
899 << " new addr: " << format("%p", Addr) << " DataSize: "
900 << DataSize << " StubBufSize: " << StubBufSize
901 << " Allocate: " << Allocate << "\n");
902 } else {
903 // Even if we didn't load the section, we need to record an entry for it
904 // to handle later processing (and by 'handle' I mean don't do anything
905 // with these sections).
906 Allocate = 0;
907 Addr = nullptr;
909 dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
910 << " obj addr: " << format("%p", data.data()) << " new addr: 0"
911 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
912 << " Allocate: " << Allocate << "\n");
913 }
914
915 Sections.push_back(
916 SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
917
918 // The load address of a TLS section is not equal to the address of its
919 // initialization image
920 if (IsTLS)
921 Sections.back().setLoadAddress(LoadAddress);
922 // Debug info sections are linked as if their load address was zero
923 if (!IsRequired)
924 Sections.back().setLoadAddress(0);
925
926 return SectionID;
927}
928
931 const SectionRef &Section,
932 bool IsCode,
933 ObjSectionToIDMap &LocalSections) {
934
935 unsigned SectionID = 0;
936 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
937 if (i != LocalSections.end())
938 SectionID = i->second;
939 else {
940 if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
941 SectionID = *SectionIDOrErr;
942 else
943 return SectionIDOrErr.takeError();
944 LocalSections[Section] = SectionID;
945 }
946 return SectionID;
947}
948
950 unsigned SectionID) {
951 Relocations[SectionID].push_back(RE);
952}
953
955 StringRef SymbolName) {
956 // Relocation by symbol. If the symbol is found in the global symbol table,
957 // create an appropriate section relocation. Otherwise, add it to
958 // ExternalSymbolRelocations.
960 if (Loc == GlobalSymbolTable.end()) {
961 ExternalSymbolRelocations[SymbolName].push_back(RE);
962 } else {
963 assert(!SymbolName.empty() &&
964 "Empty symbol should not be in GlobalSymbolTable");
965 // Copy the RE since we want to modify its addend.
966 RelocationEntry RECopy = RE;
967 const auto &SymInfo = Loc->second;
968 RECopy.Addend += SymInfo.getOffset();
969 Relocations[SymInfo.getSectionID()].push_back(RECopy);
970 }
971}
972
974 unsigned AbiVariant) {
977 // This stub has to be able to access the full address space,
978 // since symbol lookup won't necessarily find a handy, in-range,
979 // PLT stub for functions which could be anywhere.
980 // Stub can use ip0 (== x16) to calculate address
981 writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
982 writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
983 writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
984 writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
985 writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
986
987 return Addr;
988 } else if (Arch == Triple::arm || Arch == Triple::armeb) {
989 // TODO: There is only ARM far stub now. We should add the Thumb stub,
990 // and stubs for branches Thumb - ARM and ARM - Thumb.
991 writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]
992 return Addr + 4;
993 } else if (Arch == Triple::loongarch64) {
994 // lu12i.w $t0, %abs_hi20(addr)
995 // ori $t0, $t0, %abs_lo12(addr)
996 // lu32i.d $t0, %abs64_lo20(addr)
997 // lu52i.d $t0, $t0, %abs64_lo12(addr)
998 // jr $t0
999 writeBytesUnaligned(0x1400000c, Addr, 4);
1000 writeBytesUnaligned(0x0380018c, Addr + 4, 4);
1001 writeBytesUnaligned(0x1600000c, Addr + 8, 4);
1002 writeBytesUnaligned(0x0300018c, Addr + 12, 4);
1003 writeBytesUnaligned(0x4c000180, Addr + 16, 4);
1004 return Addr;
1005 } else if (IsMipsO32ABI || IsMipsN32ABI) {
1006 // 0: 3c190000 lui t9,%hi(addr).
1007 // 4: 27390000 addiu t9,t9,%lo(addr).
1008 // 8: 03200008 jr t9.
1009 // c: 00000000 nop.
1010 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
1011 const unsigned NopInstr = 0x0;
1012 unsigned JrT9Instr = 0x03200008;
1013 if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
1014 (AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
1015 JrT9Instr = 0x03200009;
1016
1017 writeBytesUnaligned(LuiT9Instr, Addr, 4);
1018 writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
1019 writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
1020 writeBytesUnaligned(NopInstr, Addr + 12, 4);
1021 return Addr;
1022 } else if (IsMipsN64ABI) {
1023 // 0: 3c190000 lui t9,%highest(addr).
1024 // 4: 67390000 daddiu t9,t9,%higher(addr).
1025 // 8: 0019CC38 dsll t9,t9,16.
1026 // c: 67390000 daddiu t9,t9,%hi(addr).
1027 // 10: 0019CC38 dsll t9,t9,16.
1028 // 14: 67390000 daddiu t9,t9,%lo(addr).
1029 // 18: 03200008 jr t9.
1030 // 1c: 00000000 nop.
1031 const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
1032 DsllT9Instr = 0x19CC38;
1033 const unsigned NopInstr = 0x0;
1034 unsigned JrT9Instr = 0x03200008;
1035 if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
1036 JrT9Instr = 0x03200009;
1037
1038 writeBytesUnaligned(LuiT9Instr, Addr, 4);
1039 writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
1040 writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
1041 writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
1042 writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
1043 writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
1044 writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
1045 writeBytesUnaligned(NopInstr, Addr + 28, 4);
1046 return Addr;
1047 } else if (Arch == Triple::ppc) {
1048 // Load the target address into r12 and branch to it. r12 is volatile
1049 // and is not used to pass arguments.
1050 writeInt32BE(Addr, 0x3D800000); // lis r12, hi(addr)
1051 writeInt32BE(Addr + 4, 0x618C0000); // ori r12, r12, lo(addr)
1052 writeInt32BE(Addr + 8, 0x7D8903A6); // mtctr r12
1053 writeInt32BE(Addr + 12, 0x4E800420); // bctr
1054 return Addr;
1055 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1056 // Depending on which version of the ELF ABI is in use, we need to
1057 // generate one of two variants of the stub. They both start with
1058 // the same sequence to load the target address into r12.
1059 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
1060 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
1061 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
1062 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
1063 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
1064 if (AbiVariant == 2) {
1065 // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
1066 // The address is already in r12 as required by the ABI. Branch to it.
1067 writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
1068 writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
1069 writeInt32BE(Addr+28, 0x4E800420); // bctr
1070 } else {
1071 // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
1072 // Load the function address on r11 and sets it to control register. Also
1073 // loads the function TOC in r2 and environment pointer to r11.
1074 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
1075 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
1076 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
1077 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
1078 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
1079 writeInt32BE(Addr+40, 0x4E800420); // bctr
1080 }
1081 return Addr;
1082 } else if (Arch == Triple::systemz) {
1083 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
1084 writeInt16BE(Addr+2, 0x0000);
1085 writeInt16BE(Addr+4, 0x0004);
1086 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
1087 // 8-byte address stored at Addr + 8
1088 return Addr;
1089 } else if (Arch == Triple::x86_64) {
1090 *Addr = 0xFF; // jmp
1091 *(Addr+1) = 0x25; // rip
1092 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
1093 } else if (Arch == Triple::x86) {
1094 *Addr = 0xE9; // 32-bit pc-relative jump.
1095 }
1096 return Addr;
1097}
1098
1099// Assign an address to a symbol name and resolve all the relocations
1100// associated with it.
1102 uint64_t Addr) {
1103 // The address to use for relocation resolution is not
1104 // the address of the local section buffer. We must be doing
1105 // a remote execution environment of some sort. Relocations can't
1106 // be applied until all the sections have been moved. The client must
1107 // trigger this with a call to MCJIT::finalize() or
1108 // RuntimeDyld::resolveRelocations().
1109 //
1110 // Addr is a uint64_t because we can't assume the pointer width
1111 // of the target is the same as that of the host. Just use a generic
1112 // "big enough" type.
1113 LLVM_DEBUG(
1114 dbgs() << "Reassigning address for section " << SectionID << " ("
1115 << Sections[SectionID].getName() << "): "
1116 << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
1117 << " -> " << format("0x%016" PRIx64, Addr) << "\n");
1118 Sections[SectionID].setLoadAddress(Addr);
1119}
1120
1122 uint64_t Value) {
1123 for (const RelocationEntry &RE : Relocs) {
1124 // Ignore relocations for sections that were not loaded
1125 if (RE.SectionID != AbsoluteSymbolSection &&
1126 Sections[RE.SectionID].getAddress() == nullptr)
1127 continue;
1129 }
1130}
1131
1133 const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {
1134 for (auto &RelocKV : ExternalSymbolRelocations) {
1135 StringRef Name = RelocKV.first();
1136 RelocationList &Relocs = RelocKV.second;
1137 if (Name.size() == 0) {
1138 // This is an absolute symbol, use an address of zero.
1139 LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
1140 << "\n");
1141 resolveRelocationList(Relocs, 0);
1142 } else {
1143 uint64_t Addr = 0;
1144 JITSymbolFlags Flags;
1146 if (Loc == GlobalSymbolTable.end()) {
1147 auto RRI = ExternalSymbolMap.find(Name);
1148 assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
1149 Addr = RRI->second.getAddress();
1150 Flags = RRI->second.getFlags();
1151 } else {
1152 // We found the symbol in our global table. It was probably in a
1153 // Module that we loaded previously.
1154 const auto &SymInfo = Loc->second;
1155 Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
1156 SymInfo.getOffset();
1157 Flags = SymInfo.getFlags();
1158 }
1159
1160 // FIXME: Implement error handling that doesn't kill the host program!
1161 if (!Addr && !Resolver.allowsZeroSymbols())
1162 report_fatal_error(Twine("Program used external function '") + Name +
1163 "' which could not be resolved!");
1164
1165 // If Resolver returned UINT64_MAX, the client wants to handle this symbol
1166 // manually and we shouldn't resolve its relocations.
1167 if (Addr != UINT64_MAX) {
1168
1169 // Tweak the address based on the symbol flags if necessary.
1170 // For example, this is used by RuntimeDyldMachOARM to toggle the low bit
1171 // if the target symbol is Thumb.
1172 Addr = modifyAddressBasedOnFlags(Addr, Flags);
1173
1174 LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
1175 << format("0x%lx", Addr) << "\n");
1176 resolveRelocationList(Relocs, Addr);
1177 }
1178 }
1179 }
1181}
1182
1184 StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
1185
1186 // Resolution can trigger emission of more symbols, so iterate until
1187 // we've resolved *everything*.
1188 {
1189 JITSymbolResolver::LookupSet ResolvedSymbols;
1190
1191 while (true) {
1193
1194 for (auto &RelocKV : ExternalSymbolRelocations) {
1195 StringRef Name = RelocKV.first();
1196 if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
1197 !ResolvedSymbols.count(Name))
1198 NewSymbols.insert(Name);
1199 }
1200
1201 if (NewSymbols.empty())
1202 break;
1203
1204#ifdef _MSC_VER
1205 using ExpectedLookupResult =
1207#else
1208 using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
1209#endif
1210
1211 auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();
1212 auto NewSymbolsF = NewSymbolsP->get_future();
1213 Resolver.lookup(NewSymbols,
1215 NewSymbolsP->set_value(std::move(Result));
1216 });
1217
1218 auto NewResolverResults = NewSymbolsF.get();
1219
1220 if (!NewResolverResults)
1221 return NewResolverResults.takeError();
1222
1223 assert(NewResolverResults->size() == NewSymbols.size() &&
1224 "Should have errored on unresolved symbols");
1225
1226 for (auto &RRKV : *NewResolverResults) {
1227 assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
1228 ExternalSymbolMap.insert(RRKV);
1229 ResolvedSymbols.insert(RRKV.first);
1230 }
1231 }
1232 }
1233
1234 applyExternalSymbolRelocations(ExternalSymbolMap);
1235
1236 return Error::success();
1237}
1238
1240 std::unique_ptr<RuntimeDyldImpl> This,
1242 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
1243 OnEmitted,
1245 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info) {
1246
1247 auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));
1248 auto PostResolveContinuation =
1249 [SharedThis, OnEmitted = std::move(OnEmitted), O = std::move(O),
1250 Info = std::move(Info)](
1252 if (!Result) {
1253 OnEmitted(std::move(O), std::move(Info), Result.takeError());
1254 return;
1255 }
1256
1257 /// Copy the result into a StringMap, where the keys are held by value.
1259 for (auto &KV : *Result)
1260 Resolved[KV.first] = KV.second;
1261
1262 SharedThis->applyExternalSymbolRelocations(Resolved);
1263 SharedThis->resolveLocalRelocations();
1264 SharedThis->registerEHFrames();
1265 std::string ErrMsg;
1266 if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))
1267 OnEmitted(std::move(O), std::move(Info),
1268 make_error<StringError>(std::move(ErrMsg),
1270 else
1271 OnEmitted(std::move(O), std::move(Info), Error::success());
1272 };
1273
1275
1276 for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {
1277 StringRef Name = RelocKV.first();
1278 if (Name.empty()) // Skip absolute symbol relocations.
1279 continue;
1280 assert(!SharedThis->GlobalSymbolTable.count(Name) &&
1281 "Name already processed. RuntimeDyld instances can not be re-used "
1282 "when finalizing with finalizeAsync.");
1283 Symbols.insert(Name);
1284 }
1285
1286 if (!Symbols.empty()) {
1287 SharedThis->Resolver.lookup(Symbols, std::move(PostResolveContinuation));
1288 } else
1289 PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());
1290}
1291
1292//===----------------------------------------------------------------------===//
1293// RuntimeDyld class implementation
1294
1296 const object::SectionRef &Sec) const {
1297
1298 auto I = ObjSecToIDMap.find(Sec);
1299 if (I != ObjSecToIDMap.end())
1300 return RTDyld.Sections[I->second].getLoadAddress();
1301
1302 return 0;
1303}
1304
1307 unsigned Alignment,
1308 unsigned SectionID,
1310 return {};
1311}
1312
1313void RuntimeDyld::MemoryManager::anchor() {}
1314void JITSymbolResolver::anchor() {}
1315void LegacyJITSymbolResolver::anchor() {}
1316
1318 JITSymbolResolver &Resolver)
1319 : MemMgr(MemMgr), Resolver(Resolver) {
1320 // FIXME: There's a potential issue lurking here if a single instance of
1321 // RuntimeDyld is used to load multiple objects. The current implementation
1322 // associates a single memory manager with a RuntimeDyld instance. Even
1323 // though the public class spawns a new 'impl' instance for each load,
1324 // they share a single memory manager. This can become a problem when page
1325 // permissions are applied.
1326 Dyld = nullptr;
1327 ProcessAllSections = false;
1328}
1329
1330RuntimeDyld::~RuntimeDyld() = default;
1331
1332static std::unique_ptr<RuntimeDyldCOFF>
1335 JITSymbolResolver &Resolver, bool ProcessAllSections,
1336 RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
1337 std::unique_ptr<RuntimeDyldCOFF> Dyld =
1339 Dyld->setProcessAllSections(ProcessAllSections);
1340 Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
1341 return Dyld;
1342}
1343
1344static std::unique_ptr<RuntimeDyldELF>
1346 JITSymbolResolver &Resolver, bool ProcessAllSections,
1347 RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
1348 std::unique_ptr<RuntimeDyldELF> Dyld =
1350 Dyld->setProcessAllSections(ProcessAllSections);
1351 Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
1352 return Dyld;
1353}
1354
1355static std::unique_ptr<RuntimeDyldMachO>
1359 bool ProcessAllSections,
1360 RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
1361 std::unique_ptr<RuntimeDyldMachO> Dyld =
1363 Dyld->setProcessAllSections(ProcessAllSections);
1364 Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
1365 return Dyld;
1366}
1367
1368std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
1370 if (!Dyld) {
1371 if (Obj.isELF())
1372 Dyld = createRuntimeDyldELF(Obj.getArch(), MemMgr, Resolver,
1373 ProcessAllSections,
1374 std::move(NotifyStubEmitted));
1375 else if (Obj.isMachO())
1376 Dyld = createRuntimeDyldMachO(Obj.getArch(), MemMgr, Resolver,
1377 ProcessAllSections,
1378 std::move(NotifyStubEmitted));
1379 else if (Obj.isCOFF())
1380 Dyld = createRuntimeDyldCOFF(Obj.getArch(), MemMgr, Resolver,
1381 ProcessAllSections,
1382 std::move(NotifyStubEmitted));
1383 else
1384 report_fatal_error("Incompatible object format!");
1385 }
1386
1387 if (!Dyld->isCompatibleFile(Obj))
1388 report_fatal_error("Incompatible object format!");
1389
1390 auto LoadedObjInfo = Dyld->loadObject(Obj);
1391 MemMgr.notifyObjectLoaded(*this, Obj);
1392 return LoadedObjInfo;
1393}
1394
1396 if (!Dyld)
1397 return nullptr;
1398 return Dyld->getSymbolLocalAddress(Name);
1399}
1400
1402 assert(Dyld && "No RuntimeDyld instance attached");
1403 return Dyld->getSymbolSectionID(Name);
1404}
1405
1407 if (!Dyld)
1408 return nullptr;
1409 return Dyld->getSymbol(Name);
1410}
1411
1412std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
1413 if (!Dyld)
1414 return std::map<StringRef, JITEvaluatedSymbol>();
1415 return Dyld->getSymbolTable();
1416}
1417
1418void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
1419
1420void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
1421 Dyld->reassignSectionAddress(SectionID, Addr);
1422}
1423
1424void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
1425 uint64_t TargetAddress) {
1426 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
1427}
1428
1429bool RuntimeDyld::hasError() { return Dyld->hasError(); }
1430
1431StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
1432
1434 bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
1435 MemMgr.FinalizationLocked = true;
1438 if (!MemoryFinalizationLocked) {
1439 MemMgr.finalizeMemory();
1440 MemMgr.FinalizationLocked = false;
1441 }
1442}
1443
1445 assert(Dyld && "No Dyld instance attached");
1446 return Dyld->getSectionContent(SectionID);
1447}
1448
1449uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {
1450 assert(Dyld && "No Dyld instance attached");
1451 return Dyld->getSectionLoadAddress(SectionID);
1452}
1453
1455 if (Dyld)
1456 Dyld->registerEHFrames();
1457}
1458
1460 if (Dyld)
1461 Dyld->deregisterEHFrames();
1462}
1463// FIXME: Kill this with fire once we have a new JIT linker: this is only here
1464// so that we can re-use RuntimeDyld's implementation without twisting the
1465// interface any further for ORC's purposes.
1469 bool ProcessAllSections,
1472 std::map<StringRef, JITEvaluatedSymbol>)>
1473 OnLoaded,
1475 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
1476 OnEmitted) {
1477
1478 RuntimeDyld RTDyld(MemMgr, Resolver);
1479 RTDyld.setProcessAllSections(ProcessAllSections);
1480
1481 auto Info = RTDyld.loadObject(*O.getBinary());
1482
1483 if (RTDyld.hasError()) {
1484 OnEmitted(std::move(O), std::move(Info),
1487 return;
1488 }
1489
1490 if (auto Err = OnLoaded(*O.getBinary(), *Info, RTDyld.getSymbolTable())) {
1491 OnEmitted(std::move(O), std::move(Info), std::move(Err));
1492 return;
1493 }
1494
1495 RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),
1496 std::move(O), std::move(Info));
1497}
1498
1499} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define I(x, y, z)
Definition MD5.cpp:57
static StringRef getName(Value *V)
static const char * name
static Split data
#define LLVM_DEBUG(...)
Definition Debug.h:119
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
Represents a symbol that has been evaluated to an address already.
Definition JITSymbol.h:231
Flags for symbols in the JIT.
Definition JITSymbol.h:75
static LLVM_ABI Expected< JITSymbolFlags > fromObjectSymbol(const object::SymbolRef &Symbol)
Construct a JITSymbolFlags value based on the flags of the given libobject symbol.
Definition JITSymbol.cpp:69
Symbol resolution interface.
Definition JITSymbol.h:373
std::set< StringRef > LookupSet
Definition JITSymbol.h:375
RelocationEntry - used to represent relocations internally in the dynamic linker.
int64_t Addend
Addend - the relocation addend encoded in the instruction itself.
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2295
static std::unique_ptr< RuntimeDyldCOFF > create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
static std::unique_ptr< RuntimeDyldELF > create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
virtual bool relocationNeedsGot(const RelocationRef &R) const
void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
virtual void processNewSymbol(const SymbolRef &ObjSymbol, SymbolTableEntry &Entry)
StringMap< RelocationList > ExternalSymbolRelocations
void reassignSectionAddress(unsigned SectionID, uint64_t Addr)
NotifyStubEmittedFunction NotifyStubEmitted
virtual uint64_t modifyAddressBasedOnFlags(uint64_t Addr, JITSymbolFlags Flags) const
Modify the given target address based on the given symbol flags.
virtual Expected< relocation_iterator > processRelocationRef(unsigned SectionID, relocation_iterator RelI, const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs)=0
Parses one or more object file relocations (some object files use relocation pairs) and stores it to ...
std::map< SectionRef, unsigned > ObjSectionToIDMap
virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value)=0
A object file specific relocation resolver.
virtual Align getStubAlignment()=0
void writeInt32BE(uint8_t *Addr, uint32_t Value)
virtual Error finalizeLoad(const ObjectFile &ObjImg, ObjSectionToIDMap &SectionMap)
void applyExternalSymbolRelocations(const StringMap< JITEvaluatedSymbol > ExternalSymbolMap)
void resolveRelocationList(const RelocationList &Relocs, uint64_t Value)
Resolves relocations from Relocs list with address from Value.
SmallVector< RelocationEntry, 64 > RelocationList
std::map< RelocationValueRef, uintptr_t > StubMap
void writeInt16BE(uint8_t *Addr, uint16_t Value)
static const unsigned AbsoluteSymbolSection
void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName)
virtual void registerEHFrames()
JITSymbolResolver & Resolver
virtual ~RuntimeDyldImpl()
static void finalizeAsync(std::unique_ptr< RuntimeDyldImpl > This, unique_function< void(object::OwningBinary< object::ObjectFile >, std::unique_ptr< RuntimeDyld::LoadedObjectInfo >, Error)> OnEmitted, object::OwningBinary< object::ObjectFile > O, std::unique_ptr< RuntimeDyld::LoadedObjectInfo > Info)
Error emitCommonSymbols(const ObjectFile &Obj, CommonSymbolList &CommonSymbols, uint64_t CommonSize, uint32_t CommonAlign)
Given the common symbols discovered in the object file, emit a new section for them and update the sy...
Expected< unsigned > emitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode)
Emits section data from the object file to the MemoryManager.
virtual unsigned sizeAfterAddingDLLImportStub(unsigned Size) const
DenseMap< unsigned, RelocationList > Relocations
std::vector< SymbolRef > CommonSymbolList
RuntimeDyld::MemoryManager & MemMgr
void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID)
Expected< unsigned > findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode, ObjSectionToIDMap &LocalSections)
Find Section in LocalSections.
virtual bool relocationNeedsStub(const RelocationRef &R) const
Triple::ArchType Arch
unsigned computeGOTSize(const ObjectFile &Obj)
virtual void setMipsABI(const ObjectFile &Obj)
void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const
Endian-aware write.
virtual size_t getGOTEntrySize()
uint8_t * createStubFunction(uint8_t *Addr, unsigned AbiVariant=0)
Emits long jump instruction to Addr.
uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const
Endian-aware read Read the least significant Size bytes from Src.
virtual bool relocationNeedsDLLImportStub(const RelocationRef &R) const
uint64_t getSectionLoadAddress(unsigned SectionID) const
virtual unsigned getMaxStubSize() const =0
Error computeTotalAllocSize(const ObjectFile &Obj, uint64_t &CodeSize, Align &CodeAlign, uint64_t &RODataSize, Align &RODataAlign, uint64_t &RWDataSize, Align &RWDataAlign)
unsigned computeSectionStubBufSize(const ObjectFile &Obj, const SectionRef &Section)
RTDyldSymbolTable GlobalSymbolTable
virtual Expected< JITSymbolFlags > getJITSymbolFlags(const SymbolRef &Sym)
Generate JITSymbolFlags from a libObject symbol.
Expected< ObjSectionToIDMap > loadObjectImpl(const object::ObjectFile &Obj)
Error resolveExternalSymbols()
Resolve relocations to external symbols.
static std::unique_ptr< RuntimeDyldMachO > create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Create a RuntimeDyldMachO instance for the given target architecture.
Information about the loaded object.
Definition RuntimeDyld.h:70
uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override
Obtain the Load Address of a section by SectionRef.
virtual TLSSection allocateTLSSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName)
Allocate a memory block of (at least) the given size to be used for thread-local storage (TLS).
LLVM_ABI void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
Map a section to its target address space value.
void setProcessAllSections(bool ProcessAllSections)
By default, only sections that are "required for execution" are passed to the RTDyldMemoryManager,...
LLVM_ABI void reassignSectionAddress(unsigned SectionID, uint64_t Addr)
LLVM_ABI uint64_t getSectionLoadAddress(unsigned SectionID) const
If the section was loaded, return the section's load address, otherwise return std::nullopt.
LLVM_ABI void * getSymbolLocalAddress(StringRef Name) const
Get the address of our local copy of the symbol.
LLVM_ABI std::map< StringRef, JITEvaluatedSymbol > getSymbolTable() const
Returns a copy of the symbol table.
LLVM_ABI void resolveRelocations()
Resolve the relocations for all symbols we currently know about.
LLVM_ABI void finalizeWithMemoryManagerLocking()
Perform all actions needed to make the code owned by this RuntimeDyld instance executable:
std::function< void( StringRef FileName, StringRef SectionName, StringRef SymbolName, unsigned SectionID, uint32_t StubOffset)> NotifyStubEmittedFunction
Definition RuntimeDyld.h:65
LLVM_ABI void deregisterEHFrames()
LLVM_ABI void registerEHFrames()
Register any EH frame sections that have been loaded but not previously registered with the memory ma...
LLVM_ABI ~RuntimeDyld()
LLVM_ABI StringRef getSectionContent(unsigned SectionID) const
Returns the section's working memory.
LLVM_ABI JITEvaluatedSymbol getSymbol(StringRef Name) const
Get the target address and flags for the named symbol.
LLVM_ABI RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Construct a RuntimeDyld instance.
LLVM_ABI bool hasError()
LLVM_ABI std::unique_ptr< LoadedObjectInfo > loadObject(const object::ObjectFile &O)
Add the referenced object file to the list of objects to be loaded and relocated.
LLVM_ABI StringRef getErrorString()
LLVM_ABI unsigned getSymbolSectionID(StringRef Name) const
Get the section ID for the section containing the given symbol.
SectionEntry - represents a section emitted into memory by the dynamic linker.
StringRef getName() const
uint8_t * getAddress() const
size_t getSize() const
uint64_t getLoadAddress() const
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
StringMapIterBase< SymbolTableEntry, true > const_iterator
Definition StringMap.h:208
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:311
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Symbol info for RuntimeDyld.
@ loongarch64
Definition Triple.h:66
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
This class is the base class for all object file types.
Definition ObjectFile.h:231
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition ObjectFile.h:54
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
uint64_t getAddress() const
Definition ObjectFile.h:526
bool isText() const
Whether this section contains instructions.
Definition ObjectFile.h:555
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition ObjectFile.h:170
Expected< uint64_t > getAddress() const
Returns the symbol virtual address (i.e.
Definition ObjectFile.h:469
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_SCN_MEM_READ
Definition COFF.h:336
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition COFF.h:305
@ IMAGE_SCN_MEM_DISCARDABLE
Definition COFF.h:331
@ IMAGE_SCN_LNK_INFO
Definition COFF.h:307
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition COFF.h:304
@ IMAGE_SCN_MEM_WRITE
Definition COFF.h:337
@ EF_MIPS_ARCH
Definition ELF.h:388
@ EF_MIPS_ARCH_32R6
Definition ELF.h:386
@ EF_MIPS_ARCH_64R6
Definition ELF.h:387
@ SHF_ALLOC
Definition ELF.h:1098
@ SHF_WRITE
Definition ELF.h:1095
@ SHF_TLS
Definition ELF.h:1123
@ SHF_EXECINSTR
Definition ELF.h:1101
@ SHT_NOBITS
Definition ELF.h:1003
@ S_GB_ZEROFILL
S_GB_ZEROFILL - Zero fill on demand section (that can be larger than 4 gigabytes).
Definition MachO.h:155
@ S_ZEROFILL
S_ZEROFILL - Zero fill on demand section.
Definition MachO.h:129
content_iterator< SectionRef > section_iterator
Definition ObjectFile.h:49
content_iterator< RelocationRef > relocation_iterator
Definition ObjectFile.h:79
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
static std::unique_ptr< RuntimeDyldMachO > createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM, JITSymbolResolver &Resolver, bool ProcessAllSections, RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted)
static bool isTLS(const SectionRef Section)
static void dumpSectionMemory(const SectionEntry &S, StringRef State)
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
static std::unique_ptr< RuntimeDyldCOFF > createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM, JITSymbolResolver &Resolver, bool ProcessAllSections, RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
static bool isReadOnlyData(const SectionRef Section)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:191
LLVM_ABI void jitLinkForORC(object::OwningBinary< object::ObjectFile > O, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver, bool ProcessAllSections, unique_function< Error(const object::ObjectFile &Obj, RuntimeDyld::LoadedObjectInfo &, std::map< StringRef, JITEvaluatedSymbol >)> OnLoaded, unique_function< void(object::OwningBinary< object::ObjectFile >, std::unique_ptr< RuntimeDyld::LoadedObjectInfo >, Error)> OnEmitted)
static std::unique_ptr< RuntimeDyldELF > createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM, JITSymbolResolver &Resolver, bool ProcessAllSections, RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted)
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
static bool isZeroInit(const SectionRef Section)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
static uint64_t computeAllocationSizeForSections(std::vector< uint64_t > &SectionSizes, Align Alignment)
static bool isRequiredForExecution(const SectionRef Section)
SymInfo contains information about symbol: it's address and section index which is -1LL for absolute ...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
support::ulittle32_t Characteristics
Definition COFF.h:459