1 //===------ JITLinkGeneric.h - Generic JIT linker utilities -----*- C++ -*-===//
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 // Generic JITLinker utilities. E.g. graph pruning, eh-frame parsing.
11 //===----------------------------------------------------------------------===//
13 #ifndef LIB_EXECUTIONENGINE_JITLINK_JITLINKGENERIC_H
14 #define LIB_EXECUTIONENGINE_JITLINK_JITLINKGENERIC_H
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
19 #define DEBUG_TYPE "jitlink"
23 class MemoryBufferRef
;
27 /// Base class for a JIT linker.
29 /// A JITLinkerBase instance links one object file into an ongoing JIT
30 /// session. Symbol resolution and finalization operations are pluggable,
31 /// and called using continuation passing (passing a continuation for the
32 /// remaining linker work) to allow them to be performed asynchronously.
35 JITLinkerBase(std::unique_ptr
<JITLinkContext
> Ctx
, PassConfiguration Passes
)
36 : Ctx(std::move(Ctx
)), Passes(std::move(Passes
)) {
37 assert(this->Ctx
&& "Ctx can not be null");
40 virtual ~JITLinkerBase();
43 struct SegmentLayout
{
44 using BlocksList
= std::vector
<Block
*>;
46 BlocksList ContentBlocks
;
47 BlocksList ZeroFillBlocks
;
50 using SegmentLayoutMap
= DenseMap
<unsigned, SegmentLayout
>;
53 // 1.1: Build link graph
54 // 1.2: Run pre-prune passes
56 // 1.3: Run post-prune passes
57 // 1.4: Sort blocks into segments
58 // 1.5: Allocate segment memory
59 // 1.6: Identify externals and make an async call to resolve function
60 void linkPhase1(std::unique_ptr
<JITLinkerBase
> Self
);
63 // 2.1: Apply resolution results
64 // 2.2: Fix up block contents
65 // 2.3: Call OnResolved callback
66 // 2.3: Make an async call to transfer and finalize memory.
67 void linkPhase2(std::unique_ptr
<JITLinkerBase
> Self
,
68 Expected
<AsyncLookupResult
> LookupResult
,
69 SegmentLayoutMap Layout
);
72 // 3.1: Call OnFinalized callback, handing off allocation.
73 void linkPhase3(std::unique_ptr
<JITLinkerBase
> Self
, Error Err
);
75 // Build a graph from the given object buffer.
76 // To be implemented by the client.
77 virtual Expected
<std::unique_ptr
<LinkGraph
>>
78 buildGraph(MemoryBufferRef ObjBuffer
) = 0;
80 // For debug dumping of the link graph.
81 virtual StringRef
getEdgeKindName(Edge::Kind K
) const = 0;
83 // Alight a JITTargetAddress to conform with block alignment requirements.
84 static JITTargetAddress
alignToBlock(JITTargetAddress Addr
, Block
&B
) {
85 uint64_t Delta
= (B
.getAlignmentOffset() - Addr
) % B
.getAlignment();
89 // Alight a pointer to conform with block alignment requirements.
90 static char *alignToBlock(char *P
, Block
&B
) {
91 uint64_t PAddr
= static_cast<uint64_t>(reinterpret_cast<uintptr_t>(P
));
92 uint64_t Delta
= (B
.getAlignmentOffset() - PAddr
) % B
.getAlignment();
97 // Run all passes in the given pass list, bailing out immediately if any pass
99 Error
runPasses(LinkGraphPassList
&Passes
);
101 // Copy block contents and apply relocations.
102 // Implemented in JITLinker.
104 copyAndFixUpBlocks(const SegmentLayoutMap
&Layout
,
105 JITLinkMemoryManager::Allocation
&Alloc
) const = 0;
107 SegmentLayoutMap
layOutBlocks();
108 Error
allocateSegments(const SegmentLayoutMap
&Layout
);
109 DenseSet
<StringRef
> getExternalSymbolNames() const;
110 void applyLookupResult(AsyncLookupResult LR
);
111 void deallocateAndBailOut(Error Err
);
113 void dumpGraph(raw_ostream
&OS
);
115 std::unique_ptr
<JITLinkContext
> Ctx
;
116 PassConfiguration Passes
;
117 std::unique_ptr
<LinkGraph
> G
;
118 std::unique_ptr
<JITLinkMemoryManager::Allocation
> Alloc
;
121 template <typename LinkerImpl
> class JITLinker
: public JITLinkerBase
{
123 using JITLinkerBase::JITLinkerBase
;
125 /// Link constructs a LinkerImpl instance and calls linkPhase1.
126 /// Link should be called with the constructor arguments for LinkerImpl, which
127 /// will be forwarded to the constructor.
128 template <typename
... ArgTs
> static void link(ArgTs
&&... Args
) {
129 auto L
= std::make_unique
<LinkerImpl
>(std::forward
<ArgTs
>(Args
)...);
131 // Ownership of the linker is passed into the linker's doLink function to
132 // allow it to be passed on to async continuations.
134 // FIXME: Remove LTmp once we have c++17.
135 // C++17 sequencing rules guarantee that function name expressions are
136 // sequenced before arguments, so L->linkPhase1(std::move(L), ...) will be
139 LTmp
.linkPhase1(std::move(L
));
143 const LinkerImpl
&impl() const {
144 return static_cast<const LinkerImpl
&>(*this);
148 copyAndFixUpBlocks(const SegmentLayoutMap
&Layout
,
149 JITLinkMemoryManager::Allocation
&Alloc
) const override
{
150 LLVM_DEBUG(dbgs() << "Copying and fixing up blocks:\n");
151 for (auto &KV
: Layout
) {
152 auto &Prot
= KV
.first
;
153 auto &SegLayout
= KV
.second
;
155 auto SegMem
= Alloc
.getWorkingMemory(
156 static_cast<sys::Memory::ProtectionFlags
>(Prot
));
157 char *LastBlockEnd
= SegMem
.data();
158 char *BlockDataPtr
= LastBlockEnd
;
161 dbgs() << " Processing segment "
162 << static_cast<sys::Memory::ProtectionFlags
>(Prot
) << " [ "
163 << (const void *)SegMem
.data() << " .. "
164 << (const void *)((char *)SegMem
.data() + SegMem
.size())
165 << " ]\n Processing content sections:\n";
168 for (auto *B
: SegLayout
.ContentBlocks
) {
169 LLVM_DEBUG(dbgs() << " " << *B
<< ":\n");
171 // Pad to alignment/alignment-offset.
172 BlockDataPtr
= alignToBlock(BlockDataPtr
, *B
);
175 dbgs() << " Bumped block pointer to "
176 << (const void *)BlockDataPtr
<< " to meet block alignment "
177 << B
->getAlignment() << " and alignment offset "
178 << B
->getAlignmentOffset() << "\n";
181 // Zero pad up to alignment.
183 if (LastBlockEnd
!= BlockDataPtr
)
184 dbgs() << " Zero padding from " << (const void *)LastBlockEnd
185 << " to " << (const void *)BlockDataPtr
<< "\n";
188 while (LastBlockEnd
!= BlockDataPtr
)
191 // Copy initial block content.
193 dbgs() << " Copying block " << *B
<< " content, "
194 << B
->getContent().size() << " bytes, from "
195 << (const void *)B
->getContent().data() << " to "
196 << (const void *)BlockDataPtr
<< "\n";
198 memcpy(BlockDataPtr
, B
->getContent().data(), B
->getContent().size());
200 // Copy Block data and apply fixups.
201 LLVM_DEBUG(dbgs() << " Applying fixups.\n");
202 for (auto &E
: B
->edges()) {
204 // Skip non-relocation edges.
205 if (!E
.isRelocation())
208 // Dispatch to LinkerImpl for fixup.
209 if (auto Err
= impl().applyFixup(*B
, E
, BlockDataPtr
))
213 // Point the block's content to the fixed up buffer.
214 B
->setContent(StringRef(BlockDataPtr
, B
->getContent().size()));
216 // Update block end pointer.
217 LastBlockEnd
= BlockDataPtr
+ B
->getContent().size();
218 BlockDataPtr
= LastBlockEnd
;
221 // Zero pad the rest of the segment.
223 dbgs() << " Zero padding end of segment from "
224 << (const void *)LastBlockEnd
<< " to "
225 << (const void *)((char *)SegMem
.data() + SegMem
.size()) << "\n";
227 while (LastBlockEnd
!= SegMem
.data() + SegMem
.size())
231 return Error::success();
235 /// Removes dead symbols/blocks/addressables.
237 /// Finds the set of symbols and addressables reachable from any symbol
238 /// initially marked live. All symbols/addressables not marked live at the end
239 /// of this process are removed.
240 void prune(LinkGraph
&G
);
242 } // end namespace jitlink
243 } // end namespace llvm
245 #undef DEBUG_TYPE // "jitlink"
247 #endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINKGENERIC_H