xref: /llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkMemoryManager.cpp (revision 133f86e95492b2a00b944e070878424cfa73f87c)
1 //===--- JITLinkMemoryManager.cpp - JITLinkMemoryManager implementation ---===//
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 #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
10 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
11 #include "llvm/Support/FormatVariadic.h"
12 #include "llvm/Support/Process.h"
13 
14 #define DEBUG_TYPE "jitlink"
15 
16 using namespace llvm;
17 
18 namespace {
19 
20 // FIXME: Remove this copy of CWrapperFunctionResult as soon as JITLink can
21 // depend on shared utils from Orc.
22 
23 // Must be kept in-sync with compiler-rt/lib/orc/c-api.h.
24 union CWrapperFunctionResultDataUnion {
25   char *ValuePtr;
26   char Value[sizeof(ValuePtr)];
27 };
28 
29 // Must be kept in-sync with compiler-rt/lib/orc/c-api.h.
30 typedef struct {
31   CWrapperFunctionResultDataUnion Data;
32   size_t Size;
33 } CWrapperFunctionResult;
34 
35 Error toError(CWrapperFunctionResult R) {
36   bool HasError = false;
37   std::string ErrMsg;
38   if (R.Size) {
39     bool Large = R.Size > sizeof(CWrapperFunctionResultDataUnion);
40     char *Content = Large ? R.Data.ValuePtr : R.Data.Value;
41     if (Content[0]) {
42       HasError = true;
43       constexpr unsigned StrStart = 1 + sizeof(uint64_t);
44       ErrMsg.resize(R.Size - StrStart);
45       memcpy(&ErrMsg[0], Content + StrStart, R.Size - StrStart);
46     }
47     if (Large)
48       free(R.Data.ValuePtr);
49   } else if (R.Data.ValuePtr) {
50     HasError = true;
51     ErrMsg = R.Data.ValuePtr;
52     free(R.Data.ValuePtr);
53   }
54 
55   if (HasError)
56     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
57   return Error::success();
58 }
59 } // namespace
60 
61 namespace llvm {
62 namespace jitlink {
63 
64 JITLinkMemoryManager::~JITLinkMemoryManager() = default;
65 JITLinkMemoryManager::InFlightAlloc::~InFlightAlloc() = default;
66 
67 static Error runAllocAction(AllocActionCall &C) {
68   using WrapperFnTy = CWrapperFunctionResult (*)(const void *, size_t);
69   auto *Fn = C.FnAddr.toPtr<WrapperFnTy>();
70 
71   return toError(
72       Fn(C.CtxAddr.toPtr<const void *>(), static_cast<size_t>(C.CtxSize)));
73 }
74 
75 BasicLayout::BasicLayout(LinkGraph &G) : G(G) {
76 
77   for (auto &Sec : G.sections()) {
78     // Skip empty sections.
79     if (empty(Sec.blocks()))
80       continue;
81 
82     auto &Seg = Segments[{Sec.getMemProt(), Sec.getMemDeallocPolicy()}];
83     for (auto *B : Sec.blocks())
84       if (LLVM_LIKELY(!B->isZeroFill()))
85         Seg.ContentBlocks.push_back(B);
86       else
87         Seg.ZeroFillBlocks.push_back(B);
88   }
89 
90   // Build Segments map.
91   auto CompareBlocks = [](const Block *LHS, const Block *RHS) {
92     // Sort by section, address and size
93     if (LHS->getSection().getOrdinal() != RHS->getSection().getOrdinal())
94       return LHS->getSection().getOrdinal() < RHS->getSection().getOrdinal();
95     if (LHS->getAddress() != RHS->getAddress())
96       return LHS->getAddress() < RHS->getAddress();
97     return LHS->getSize() < RHS->getSize();
98   };
99 
100   LLVM_DEBUG(dbgs() << "Generated BasicLayout for " << G.getName() << ":\n");
101   for (auto &KV : Segments) {
102     auto &Seg = KV.second;
103 
104     llvm::sort(Seg.ContentBlocks, CompareBlocks);
105     llvm::sort(Seg.ZeroFillBlocks, CompareBlocks);
106 
107     for (auto *B : Seg.ContentBlocks) {
108       Seg.ContentSize = alignToBlock(Seg.ContentSize, *B);
109       Seg.ContentSize += B->getSize();
110       Seg.Alignment = std::max(Seg.Alignment, Align(B->getAlignment()));
111     }
112 
113     uint64_t SegEndOffset = Seg.ContentSize;
114     for (auto *B : Seg.ZeroFillBlocks) {
115       SegEndOffset = alignToBlock(SegEndOffset, *B);
116       SegEndOffset += B->getSize();
117       Seg.Alignment = std::max(Seg.Alignment, Align(B->getAlignment()));
118     }
119     Seg.ZeroFillSize = SegEndOffset - Seg.ContentSize;
120 
121     LLVM_DEBUG({
122       dbgs() << "  Seg " << KV.first
123              << ": content-size=" << formatv("{0:x}", Seg.ContentSize)
124              << ", zero-fill-size=" << formatv("{0:x}", Seg.ZeroFillSize)
125              << ", align=" << formatv("{0:x}", Seg.Alignment.value()) << "\n";
126     });
127   }
128 }
129 
130 Expected<BasicLayout::ContiguousPageBasedLayoutSizes>
131 BasicLayout::getContiguousPageBasedLayoutSizes(uint64_t PageSize) {
132   ContiguousPageBasedLayoutSizes SegsSizes;
133 
134   for (auto &KV : segments()) {
135     auto &AG = KV.first;
136     auto &Seg = KV.second;
137 
138     if (Seg.Alignment > PageSize)
139       return make_error<StringError>("Segment alignment greater than page size",
140                                      inconvertibleErrorCode());
141 
142     uint64_t SegSize = alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
143     if (AG.getMemDeallocPolicy() == MemDeallocPolicy::Standard)
144       SegsSizes.StandardSegs += SegSize;
145     else
146       SegsSizes.FinalizeSegs += SegSize;
147   }
148 
149   return SegsSizes;
150 }
151 
152 Error BasicLayout::apply() {
153   for (auto &KV : Segments) {
154     auto &Seg = KV.second;
155 
156     assert(!(Seg.ContentBlocks.empty() && Seg.ZeroFillBlocks.empty()) &&
157            "Empty section recorded?");
158 
159     for (auto *B : Seg.ContentBlocks) {
160       // Align addr and working-mem-offset.
161       Seg.Addr = alignToBlock(Seg.Addr, *B);
162       Seg.NextWorkingMemOffset = alignToBlock(Seg.NextWorkingMemOffset, *B);
163 
164       // Update block addr.
165       B->setAddress(Seg.Addr);
166       Seg.Addr += B->getSize();
167 
168       // Copy content to working memory, then update content to point at working
169       // memory.
170       memcpy(Seg.WorkingMem + Seg.NextWorkingMemOffset, B->getContent().data(),
171              B->getSize());
172       B->setMutableContent(
173           {Seg.WorkingMem + Seg.NextWorkingMemOffset, B->getSize()});
174       Seg.NextWorkingMemOffset += B->getSize();
175     }
176 
177     for (auto *B : Seg.ZeroFillBlocks) {
178       // Align addr.
179       Seg.Addr = alignToBlock(Seg.Addr, *B);
180       // Update block addr.
181       B->setAddress(Seg.Addr);
182       Seg.Addr += B->getSize();
183     }
184 
185     Seg.ContentBlocks.clear();
186     Seg.ZeroFillBlocks.clear();
187   }
188 
189   return Error::success();
190 }
191 
192 AllocActions &BasicLayout::graphAllocActions() { return G.allocActions(); }
193 
194 void SimpleSegmentAlloc::Create(JITLinkMemoryManager &MemMgr,
195                                 const JITLinkDylib *JD, SegmentMap Segments,
196                                 OnCreatedFunction OnCreated) {
197 
198   static_assert(AllocGroup::NumGroups == 16,
199                 "AllocGroup has changed. Section names below must be updated");
200   StringRef AGSectionNames[] = {
201       "__---.standard", "__R--.standard", "__-W-.standard", "__RW-.standard",
202       "__--X.standard", "__R-X.standard", "__-WX.standard", "__RWX.standard",
203       "__---.finalize", "__R--.finalize", "__-W-.finalize", "__RW-.finalize",
204       "__--X.finalize", "__R-X.finalize", "__-WX.finalize", "__RWX.finalize"};
205 
206   auto G =
207       std::make_unique<LinkGraph>("", Triple(), 0, support::native, nullptr);
208   AllocGroupSmallMap<Block *> ContentBlocks;
209 
210   orc::ExecutorAddr NextAddr(0x100000);
211   for (auto &KV : Segments) {
212     auto &AG = KV.first;
213     auto &Seg = KV.second;
214 
215     auto AGSectionName =
216         AGSectionNames[static_cast<unsigned>(AG.getMemProt()) |
217                        static_cast<bool>(AG.getMemDeallocPolicy()) << 3];
218 
219     auto &Sec = G->createSection(AGSectionName, AG.getMemProt());
220     Sec.setMemDeallocPolicy(AG.getMemDeallocPolicy());
221 
222     if (Seg.ContentSize != 0) {
223       NextAddr =
224           orc::ExecutorAddr(alignTo(NextAddr.getValue(), Seg.ContentAlign));
225       auto &B =
226           G->createMutableContentBlock(Sec, G->allocateBuffer(Seg.ContentSize),
227                                        NextAddr, Seg.ContentAlign.value(), 0);
228       ContentBlocks[AG] = &B;
229       NextAddr += Seg.ContentSize;
230     }
231   }
232 
233   // GRef declared separately since order-of-argument-eval isn't specified.
234   auto &GRef = *G;
235   MemMgr.allocate(JD, GRef,
236                   [G = std::move(G), ContentBlocks = std::move(ContentBlocks),
237                    OnCreated = std::move(OnCreated)](
238                       JITLinkMemoryManager::AllocResult Alloc) mutable {
239                     if (!Alloc)
240                       OnCreated(Alloc.takeError());
241                     else
242                       OnCreated(SimpleSegmentAlloc(std::move(G),
243                                                    std::move(ContentBlocks),
244                                                    std::move(*Alloc)));
245                   });
246 }
247 
248 Expected<SimpleSegmentAlloc>
249 SimpleSegmentAlloc::Create(JITLinkMemoryManager &MemMgr, const JITLinkDylib *JD,
250                            SegmentMap Segments) {
251   std::promise<MSVCPExpected<SimpleSegmentAlloc>> AllocP;
252   auto AllocF = AllocP.get_future();
253   Create(MemMgr, JD, std::move(Segments),
254          [&](Expected<SimpleSegmentAlloc> Result) {
255            AllocP.set_value(std::move(Result));
256          });
257   return AllocF.get();
258 }
259 
260 SimpleSegmentAlloc::SimpleSegmentAlloc(SimpleSegmentAlloc &&) = default;
261 SimpleSegmentAlloc &
262 SimpleSegmentAlloc::operator=(SimpleSegmentAlloc &&) = default;
263 SimpleSegmentAlloc::~SimpleSegmentAlloc() {}
264 
265 SimpleSegmentAlloc::SegmentInfo SimpleSegmentAlloc::getSegInfo(AllocGroup AG) {
266   auto I = ContentBlocks.find(AG);
267   if (I != ContentBlocks.end()) {
268     auto &B = *I->second;
269     return {B.getAddress(), B.getAlreadyMutableContent()};
270   }
271   return {};
272 }
273 
274 SimpleSegmentAlloc::SimpleSegmentAlloc(
275     std::unique_ptr<LinkGraph> G, AllocGroupSmallMap<Block *> ContentBlocks,
276     std::unique_ptr<JITLinkMemoryManager::InFlightAlloc> Alloc)
277     : G(std::move(G)), ContentBlocks(std::move(ContentBlocks)),
278       Alloc(std::move(Alloc)) {}
279 
280 class InProcessMemoryManager::IPInFlightAlloc
281     : public JITLinkMemoryManager::InFlightAlloc {
282 public:
283   IPInFlightAlloc(InProcessMemoryManager &MemMgr, LinkGraph &G, BasicLayout BL,
284                   sys::MemoryBlock StandardSegments,
285                   sys::MemoryBlock FinalizationSegments)
286       : MemMgr(MemMgr), G(G), BL(std::move(BL)),
287         StandardSegments(std::move(StandardSegments)),
288         FinalizationSegments(std::move(FinalizationSegments)) {}
289 
290   void finalize(OnFinalizedFunction OnFinalized) override {
291 
292     // Apply memory protections to all segments.
293     if (auto Err = applyProtections()) {
294       OnFinalized(std::move(Err));
295       return;
296     }
297 
298     // Run finalization actions.
299     // FIXME: Roll back previous successful actions on failure.
300     std::vector<AllocActionCall> DeallocActions;
301     DeallocActions.reserve(G.allocActions().size());
302     for (auto &ActPair : G.allocActions()) {
303       if (ActPair.Finalize.FnAddr)
304         if (auto Err = runAllocAction(ActPair.Finalize)) {
305           OnFinalized(std::move(Err));
306           return;
307         }
308       if (ActPair.Dealloc.FnAddr)
309         DeallocActions.push_back(ActPair.Dealloc);
310     }
311     G.allocActions().clear();
312 
313     // Release the finalize segments slab.
314     if (auto EC = sys::Memory::releaseMappedMemory(FinalizationSegments)) {
315       OnFinalized(errorCodeToError(EC));
316       return;
317     }
318 
319     // Continue with finalized allocation.
320     OnFinalized(MemMgr.createFinalizedAlloc(std::move(StandardSegments),
321                                             std::move(DeallocActions)));
322   }
323 
324   void abandon(OnAbandonedFunction OnAbandoned) override {
325     Error Err = Error::success();
326     if (auto EC = sys::Memory::releaseMappedMemory(FinalizationSegments))
327       Err = joinErrors(std::move(Err), errorCodeToError(EC));
328     if (auto EC = sys::Memory::releaseMappedMemory(StandardSegments))
329       Err = joinErrors(std::move(Err), errorCodeToError(EC));
330     OnAbandoned(std::move(Err));
331   }
332 
333 private:
334   Error applyProtections() {
335     for (auto &KV : BL.segments()) {
336       const auto &AG = KV.first;
337       auto &Seg = KV.second;
338 
339       auto Prot = toSysMemoryProtectionFlags(AG.getMemProt());
340 
341       uint64_t SegSize =
342           alignTo(Seg.ContentSize + Seg.ZeroFillSize, MemMgr.PageSize);
343       sys::MemoryBlock MB(Seg.WorkingMem, SegSize);
344       if (auto EC = sys::Memory::protectMappedMemory(MB, Prot))
345         return errorCodeToError(EC);
346       if (Prot & sys::Memory::MF_EXEC)
347         sys::Memory::InvalidateInstructionCache(MB.base(), MB.allocatedSize());
348     }
349     return Error::success();
350   }
351 
352   InProcessMemoryManager &MemMgr;
353   LinkGraph &G;
354   BasicLayout BL;
355   sys::MemoryBlock StandardSegments;
356   sys::MemoryBlock FinalizationSegments;
357 };
358 
359 Expected<std::unique_ptr<InProcessMemoryManager>>
360 InProcessMemoryManager::Create() {
361   if (auto PageSize = sys::Process::getPageSize())
362     return std::make_unique<InProcessMemoryManager>(*PageSize);
363   else
364     return PageSize.takeError();
365 }
366 
367 void InProcessMemoryManager::allocate(const JITLinkDylib *JD, LinkGraph &G,
368                                       OnAllocatedFunction OnAllocated) {
369 
370   // FIXME: Just check this once on startup.
371   if (!isPowerOf2_64((uint64_t)PageSize)) {
372     OnAllocated(make_error<StringError>("Page size is not a power of 2",
373                                         inconvertibleErrorCode()));
374     return;
375   }
376 
377   BasicLayout BL(G);
378 
379   /// Scan the request and calculate the group and total sizes.
380   /// Check that segment size is no larger than a page.
381   auto SegsSizes = BL.getContiguousPageBasedLayoutSizes(PageSize);
382   if (!SegsSizes) {
383     OnAllocated(SegsSizes.takeError());
384     return;
385   }
386 
387   /// Check that the total size requested (including zero fill) is not larger
388   /// than a size_t.
389   if (SegsSizes->total() > std::numeric_limits<size_t>::max()) {
390     OnAllocated(make_error<JITLinkError>(
391         "Total requested size " + formatv("{0:x}", SegsSizes->total()) +
392         " for graph " + G.getName() + " exceeds address space"));
393     return;
394   }
395 
396   // Allocate one slab for the whole thing (to make sure everything is
397   // in-range), then partition into standard and finalization blocks.
398   //
399   // FIXME: Make two separate allocations in the future to reduce
400   // fragmentation: finalization segments will usually be a single page, and
401   // standard segments are likely to be more than one page. Where multiple
402   // allocations are in-flight at once (likely) the current approach will leave
403   // a lot of single-page holes.
404   sys::MemoryBlock Slab;
405   sys::MemoryBlock StandardSegsMem;
406   sys::MemoryBlock FinalizeSegsMem;
407   {
408     const sys::Memory::ProtectionFlags ReadWrite =
409         static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
410                                                   sys::Memory::MF_WRITE);
411 
412     std::error_code EC;
413     Slab = sys::Memory::allocateMappedMemory(SegsSizes->total(), nullptr,
414                                              ReadWrite, EC);
415 
416     if (EC) {
417       OnAllocated(errorCodeToError(EC));
418       return;
419     }
420 
421     // Zero-fill the whole slab up-front.
422     memset(Slab.base(), 0, Slab.allocatedSize());
423 
424     StandardSegsMem = {Slab.base(),
425                        static_cast<size_t>(SegsSizes->StandardSegs)};
426     FinalizeSegsMem = {(void *)((char *)Slab.base() + SegsSizes->StandardSegs),
427                        static_cast<size_t>(SegsSizes->FinalizeSegs)};
428   }
429 
430   auto NextStandardSegAddr = orc::ExecutorAddr::fromPtr(StandardSegsMem.base());
431   auto NextFinalizeSegAddr = orc::ExecutorAddr::fromPtr(FinalizeSegsMem.base());
432 
433   LLVM_DEBUG({
434     dbgs() << "InProcessMemoryManager allocated:\n";
435     if (SegsSizes->StandardSegs)
436       dbgs() << formatv("  [ {0:x16} -- {1:x16} ]", NextStandardSegAddr,
437                         NextStandardSegAddr + StandardSegsMem.allocatedSize())
438              << " to stardard segs\n";
439     else
440       dbgs() << "  no standard segs\n";
441     if (SegsSizes->FinalizeSegs)
442       dbgs() << formatv("  [ {0:x16} -- {1:x16} ]", NextFinalizeSegAddr,
443                         NextFinalizeSegAddr + FinalizeSegsMem.allocatedSize())
444              << " to finalize segs\n";
445     else
446       dbgs() << "  no finalize segs\n";
447   });
448 
449   // Build ProtMap, assign addresses.
450   for (auto &KV : BL.segments()) {
451     auto &AG = KV.first;
452     auto &Seg = KV.second;
453 
454     auto &SegAddr = (AG.getMemDeallocPolicy() == MemDeallocPolicy::Standard)
455                         ? NextStandardSegAddr
456                         : NextFinalizeSegAddr;
457 
458     Seg.WorkingMem = SegAddr.toPtr<char *>();
459     Seg.Addr = SegAddr;
460 
461     SegAddr += alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
462   }
463 
464   if (auto Err = BL.apply()) {
465     OnAllocated(std::move(Err));
466     return;
467   }
468 
469   OnAllocated(std::make_unique<IPInFlightAlloc>(*this, G, std::move(BL),
470                                                 std::move(StandardSegsMem),
471                                                 std::move(FinalizeSegsMem)));
472 }
473 
474 void InProcessMemoryManager::deallocate(std::vector<FinalizedAlloc> Allocs,
475                                         OnDeallocatedFunction OnDeallocated) {
476   std::vector<sys::MemoryBlock> StandardSegmentsList;
477   std::vector<std::vector<AllocActionCall>> DeallocActionsList;
478 
479   {
480     std::lock_guard<std::mutex> Lock(FinalizedAllocsMutex);
481     for (auto &Alloc : Allocs) {
482       auto *FA = Alloc.release().toPtr<FinalizedAllocInfo *>();
483       StandardSegmentsList.push_back(std::move(FA->StandardSegments));
484       if (!FA->DeallocActions.empty())
485         DeallocActionsList.push_back(std::move(FA->DeallocActions));
486       FA->~FinalizedAllocInfo();
487       FinalizedAllocInfos.Deallocate(FA);
488     }
489   }
490 
491   Error DeallocErr = Error::success();
492 
493   while (!DeallocActionsList.empty()) {
494     auto &DeallocActions = DeallocActionsList.back();
495     auto &StandardSegments = StandardSegmentsList.back();
496 
497     /// Run any deallocate calls.
498     while (!DeallocActions.empty()) {
499       if (auto Err = runAllocAction(DeallocActions.back()))
500         DeallocErr = joinErrors(std::move(DeallocErr), std::move(Err));
501       DeallocActions.pop_back();
502     }
503 
504     /// Release the standard segments slab.
505     if (auto EC = sys::Memory::releaseMappedMemory(StandardSegments))
506       DeallocErr = joinErrors(std::move(DeallocErr), errorCodeToError(EC));
507 
508     DeallocActionsList.pop_back();
509     StandardSegmentsList.pop_back();
510   }
511 
512   OnDeallocated(std::move(DeallocErr));
513 }
514 
515 JITLinkMemoryManager::FinalizedAlloc
516 InProcessMemoryManager::createFinalizedAlloc(
517     sys::MemoryBlock StandardSegments,
518     std::vector<AllocActionCall> DeallocActions) {
519   std::lock_guard<std::mutex> Lock(FinalizedAllocsMutex);
520   auto *FA = FinalizedAllocInfos.Allocate<FinalizedAllocInfo>();
521   new (FA) FinalizedAllocInfo(
522       {std::move(StandardSegments), std::move(DeallocActions)});
523   return FinalizedAlloc(orc::ExecutorAddr::fromPtr(FA));
524 }
525 
526 } // end namespace jitlink
527 } // end namespace llvm
528