18a6f3554SLang Hames //===- SectionMemoryManager.cpp - Memory manager for MCJIT/RtDyld *- C++ -*-==//
28a6f3554SLang Hames //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68a6f3554SLang Hames //
78a6f3554SLang Hames //===----------------------------------------------------------------------===//
88a6f3554SLang Hames //
98a6f3554SLang Hames // This file implements the section-based memory manager used by the MCJIT
108a6f3554SLang Hames // execution engine and RuntimeDyld
118a6f3554SLang Hames //
128a6f3554SLang Hames //===----------------------------------------------------------------------===//
138a6f3554SLang Hames 
148a6f3554SLang Hames #include "llvm/ExecutionEngine/SectionMemoryManager.h"
156bda14b3SChandler Carruth #include "llvm/Config/config.h"
168a6f3554SLang Hames #include "llvm/Support/MathExtras.h"
1794f181a4SKeno Fischer #include "llvm/Support/Process.h"
188a6f3554SLang Hames 
198a6f3554SLang Hames namespace llvm {
208a6f3554SLang Hames 
218a6f3554SLang Hames uint8_t *SectionMemoryManager::allocateDataSection(uintptr_t Size,
228a6f3554SLang Hames                                                    unsigned Alignment,
238a6f3554SLang Hames                                                    unsigned SectionID,
248a6f3554SLang Hames                                                    StringRef SectionName,
258a6f3554SLang Hames                                                    bool IsReadOnly) {
268a6f3554SLang Hames   if (IsReadOnly)
27e3992c63SSanjoy Das     return allocateSection(SectionMemoryManager::AllocationPurpose::ROData,
28e3992c63SSanjoy Das                            Size, Alignment);
29e3992c63SSanjoy Das   return allocateSection(SectionMemoryManager::AllocationPurpose::RWData, Size,
30e3992c63SSanjoy Das                          Alignment);
318a6f3554SLang Hames }
328a6f3554SLang Hames 
338a6f3554SLang Hames uint8_t *SectionMemoryManager::allocateCodeSection(uintptr_t Size,
348a6f3554SLang Hames                                                    unsigned Alignment,
358a6f3554SLang Hames                                                    unsigned SectionID,
368a6f3554SLang Hames                                                    StringRef SectionName) {
37e3992c63SSanjoy Das   return allocateSection(SectionMemoryManager::AllocationPurpose::Code, Size,
38e3992c63SSanjoy Das                          Alignment);
398a6f3554SLang Hames }
408a6f3554SLang Hames 
41e3992c63SSanjoy Das uint8_t *SectionMemoryManager::allocateSection(
42e3992c63SSanjoy Das     SectionMemoryManager::AllocationPurpose Purpose, uintptr_t Size,
438a6f3554SLang Hames     unsigned Alignment) {
448a6f3554SLang Hames   if (!Alignment)
458a6f3554SLang Hames     Alignment = 16;
468a6f3554SLang Hames 
478a6f3554SLang Hames   assert(!(Alignment & (Alignment - 1)) && "Alignment must be a power of two.");
488a6f3554SLang Hames 
498a6f3554SLang Hames   uintptr_t RequiredSize = Alignment * ((Size + Alignment - 1) / Alignment + 1);
508a6f3554SLang Hames   uintptr_t Addr = 0;
518a6f3554SLang Hames 
52e3992c63SSanjoy Das   MemoryGroup &MemGroup = [&]() -> MemoryGroup & {
53e3992c63SSanjoy Das     switch (Purpose) {
54e3992c63SSanjoy Das     case AllocationPurpose::Code:
55e3992c63SSanjoy Das       return CodeMem;
56e3992c63SSanjoy Das     case AllocationPurpose::ROData:
57e3992c63SSanjoy Das       return RODataMem;
58e3992c63SSanjoy Das     case AllocationPurpose::RWData:
59e3992c63SSanjoy Das       return RWDataMem;
60e3992c63SSanjoy Das     }
6189d31658SSimon Pilgrim     llvm_unreachable("Unknown SectionMemoryManager::AllocationPurpose");
62e3992c63SSanjoy Das   }();
63e3992c63SSanjoy Das 
648a6f3554SLang Hames   // Look in the list of free memory regions and use a block there if one
658a6f3554SLang Hames   // is available.
6694f181a4SKeno Fischer   for (FreeMemBlock &FreeMB : MemGroup.FreeMem) {
67*93d2bddaSLang Hames     if (FreeMB.Free.allocatedSize() >= RequiredSize) {
6894f181a4SKeno Fischer       Addr = (uintptr_t)FreeMB.Free.base();
69*93d2bddaSLang Hames       uintptr_t EndOfBlock = Addr + FreeMB.Free.allocatedSize();
708a6f3554SLang Hames       // Align the address.
718a6f3554SLang Hames       Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
7294f181a4SKeno Fischer 
7394f181a4SKeno Fischer       if (FreeMB.PendingPrefixIndex == (unsigned)-1) {
7494f181a4SKeno Fischer         // The part of the block we're giving out to the user is now pending
7594f181a4SKeno Fischer         MemGroup.PendingMem.push_back(sys::MemoryBlock((void *)Addr, Size));
7694f181a4SKeno Fischer 
7794f181a4SKeno Fischer         // Remember this pending block, such that future allocations can just
7894f181a4SKeno Fischer         // modify it rather than creating a new one
7994f181a4SKeno Fischer         FreeMB.PendingPrefixIndex = MemGroup.PendingMem.size() - 1;
8094f181a4SKeno Fischer       } else {
81e3992c63SSanjoy Das         sys::MemoryBlock &PendingMB =
82e3992c63SSanjoy Das             MemGroup.PendingMem[FreeMB.PendingPrefixIndex];
83e3992c63SSanjoy Das         PendingMB = sys::MemoryBlock(PendingMB.base(),
84e3992c63SSanjoy Das                                      Addr + Size - (uintptr_t)PendingMB.base());
8594f181a4SKeno Fischer       }
8694f181a4SKeno Fischer 
8794f181a4SKeno Fischer       // Remember how much free space is now left in this block
88e3992c63SSanjoy Das       FreeMB.Free =
89e3992c63SSanjoy Das           sys::MemoryBlock((void *)(Addr + Size), EndOfBlock - Addr - Size);
908a6f3554SLang Hames       return (uint8_t *)Addr;
918a6f3554SLang Hames     }
928a6f3554SLang Hames   }
938a6f3554SLang Hames 
948a6f3554SLang Hames   // No pre-allocated free block was large enough. Allocate a new memory region.
958a6f3554SLang Hames   // Note that all sections get allocated as read-write.  The permissions will
968a6f3554SLang Hames   // be updated later based on memory group.
978a6f3554SLang Hames   //
988a6f3554SLang Hames   // FIXME: It would be useful to define a default allocation size (or add
998a6f3554SLang Hames   // it as a constructor parameter) to minimize the number of allocations.
1008a6f3554SLang Hames   //
1018a6f3554SLang Hames   // FIXME: Initialize the Near member for each memory group to avoid
1028a6f3554SLang Hames   // interleaving.
1038a6f3554SLang Hames   std::error_code ec;
104e3992c63SSanjoy Das   sys::MemoryBlock MB = MMapper.allocateMappedMemory(
105e3992c63SSanjoy Das       Purpose, RequiredSize, &MemGroup.Near,
106e3992c63SSanjoy Das       sys::Memory::MF_READ | sys::Memory::MF_WRITE, ec);
1078a6f3554SLang Hames   if (ec) {
1088a6f3554SLang Hames     // FIXME: Add error propagation to the interface.
1098a6f3554SLang Hames     return nullptr;
1108a6f3554SLang Hames   }
1118a6f3554SLang Hames 
1128a6f3554SLang Hames   // Save this address as the basis for our next request
1138a6f3554SLang Hames   MemGroup.Near = MB;
1148a6f3554SLang Hames 
11594f181a4SKeno Fischer   // Remember that we allocated this memory
11694f181a4SKeno Fischer   MemGroup.AllocatedMem.push_back(MB);
1178a6f3554SLang Hames   Addr = (uintptr_t)MB.base();
118*93d2bddaSLang Hames   uintptr_t EndOfBlock = Addr + MB.allocatedSize();
1198a6f3554SLang Hames 
1208a6f3554SLang Hames   // Align the address.
1218a6f3554SLang Hames   Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
1228a6f3554SLang Hames 
12394f181a4SKeno Fischer   // The part of the block we're giving out to the user is now pending
12494f181a4SKeno Fischer   MemGroup.PendingMem.push_back(sys::MemoryBlock((void *)Addr, Size));
12594f181a4SKeno Fischer 
1268a6f3554SLang Hames   // The allocateMappedMemory may allocate much more memory than we need. In
1278a6f3554SLang Hames   // this case, we store the unused memory as a free memory block.
1288a6f3554SLang Hames   unsigned FreeSize = EndOfBlock - Addr - Size;
12994f181a4SKeno Fischer   if (FreeSize > 16) {
13094f181a4SKeno Fischer     FreeMemBlock FreeMB;
13194f181a4SKeno Fischer     FreeMB.Free = sys::MemoryBlock((void *)(Addr + Size), FreeSize);
13294f181a4SKeno Fischer     FreeMB.PendingPrefixIndex = (unsigned)-1;
13394f181a4SKeno Fischer     MemGroup.FreeMem.push_back(FreeMB);
13494f181a4SKeno Fischer   }
1358a6f3554SLang Hames 
1368a6f3554SLang Hames   // Return aligned address
1378a6f3554SLang Hames   return (uint8_t *)Addr;
1388a6f3554SLang Hames }
1398a6f3554SLang Hames 
140e3992c63SSanjoy Das bool SectionMemoryManager::finalizeMemory(std::string *ErrMsg) {
1418a6f3554SLang Hames   // FIXME: Should in-progress permissions be reverted if an error occurs?
1428a6f3554SLang Hames   std::error_code ec;
1438a6f3554SLang Hames 
1448a6f3554SLang Hames   // Make code memory executable.
1458a6f3554SLang Hames   ec = applyMemoryGroupPermissions(CodeMem,
1468a6f3554SLang Hames                                    sys::Memory::MF_READ | sys::Memory::MF_EXEC);
1478a6f3554SLang Hames   if (ec) {
1488a6f3554SLang Hames     if (ErrMsg) {
1498a6f3554SLang Hames       *ErrMsg = ec.message();
1508a6f3554SLang Hames     }
1518a6f3554SLang Hames     return true;
1528a6f3554SLang Hames   }
1538a6f3554SLang Hames 
1548a6f3554SLang Hames   // Make read-only data memory read-only.
1558a6f3554SLang Hames   ec = applyMemoryGroupPermissions(RODataMem,
1568a6f3554SLang Hames                                    sys::Memory::MF_READ | sys::Memory::MF_EXEC);
1578a6f3554SLang Hames   if (ec) {
1588a6f3554SLang Hames     if (ErrMsg) {
1598a6f3554SLang Hames       *ErrMsg = ec.message();
1608a6f3554SLang Hames     }
1618a6f3554SLang Hames     return true;
1628a6f3554SLang Hames   }
1638a6f3554SLang Hames 
1648a6f3554SLang Hames   // Read-write data memory already has the correct permissions
1658a6f3554SLang Hames 
1668a6f3554SLang Hames   // Some platforms with separate data cache and instruction cache require
1678a6f3554SLang Hames   // explicit cache flush, otherwise JIT code manipulations (like resolved
1688a6f3554SLang Hames   // relocations) will get to the data cache but not to the instruction cache.
1698a6f3554SLang Hames   invalidateInstructionCache();
1708a6f3554SLang Hames 
1718a6f3554SLang Hames   return false;
1728a6f3554SLang Hames }
1738a6f3554SLang Hames 
17494f181a4SKeno Fischer static sys::MemoryBlock trimBlockToPageSize(sys::MemoryBlock M) {
175e4b4ab6dSLang Hames   static const size_t PageSize = sys::Process::getPageSizeEstimate();
17694f181a4SKeno Fischer 
17794f181a4SKeno Fischer   size_t StartOverlap =
17894f181a4SKeno Fischer       (PageSize - ((uintptr_t)M.base() % PageSize)) % PageSize;
17994f181a4SKeno Fischer 
180*93d2bddaSLang Hames   size_t TrimmedSize = M.allocatedSize();
18194f181a4SKeno Fischer   TrimmedSize -= StartOverlap;
18294f181a4SKeno Fischer   TrimmedSize -= TrimmedSize % PageSize;
18394f181a4SKeno Fischer 
184e3992c63SSanjoy Das   sys::MemoryBlock Trimmed((void *)((uintptr_t)M.base() + StartOverlap),
185e3992c63SSanjoy Das                            TrimmedSize);
18694f181a4SKeno Fischer 
18794f181a4SKeno Fischer   assert(((uintptr_t)Trimmed.base() % PageSize) == 0);
188*93d2bddaSLang Hames   assert((Trimmed.allocatedSize() % PageSize) == 0);
189*93d2bddaSLang Hames   assert(M.base() <= Trimmed.base() &&
190*93d2bddaSLang Hames          Trimmed.allocatedSize() <= M.allocatedSize());
19194f181a4SKeno Fischer 
19294f181a4SKeno Fischer   return Trimmed;
19394f181a4SKeno Fischer }
19494f181a4SKeno Fischer 
1958a6f3554SLang Hames std::error_code
1968a6f3554SLang Hames SectionMemoryManager::applyMemoryGroupPermissions(MemoryGroup &MemGroup,
1978a6f3554SLang Hames                                                   unsigned Permissions) {
19817433bd1SKeno Fischer   for (sys::MemoryBlock &MB : MemGroup.PendingMem)
199e3992c63SSanjoy Das     if (std::error_code EC = MMapper.protectMappedMemory(MB, Permissions))
200efeddcc5SBenjamin Kramer       return EC;
2018a6f3554SLang Hames 
20294f181a4SKeno Fischer   MemGroup.PendingMem.clear();
20394f181a4SKeno Fischer 
20494f181a4SKeno Fischer   // Now go through free blocks and trim any of them that don't span the entire
20594f181a4SKeno Fischer   // page because one of the pending blocks may have overlapped it.
20694f181a4SKeno Fischer   for (FreeMemBlock &FreeMB : MemGroup.FreeMem) {
20794f181a4SKeno Fischer     FreeMB.Free = trimBlockToPageSize(FreeMB.Free);
20894f181a4SKeno Fischer     // We cleared the PendingMem list, so all these pointers are now invalid
20994f181a4SKeno Fischer     FreeMB.PendingPrefixIndex = (unsigned)-1;
21094f181a4SKeno Fischer   }
21194f181a4SKeno Fischer 
21294f181a4SKeno Fischer   // Remove all blocks which are now empty
213*93d2bddaSLang Hames   MemGroup.FreeMem.erase(remove_if(MemGroup.FreeMem,
214*93d2bddaSLang Hames                                    [](FreeMemBlock &FreeMB) {
215*93d2bddaSLang Hames                                      return FreeMB.Free.allocatedSize() == 0;
216*93d2bddaSLang Hames                                    }),
21794f181a4SKeno Fischer                          MemGroup.FreeMem.end());
21894f181a4SKeno Fischer 
2198a6f3554SLang Hames   return std::error_code();
2208a6f3554SLang Hames }
2218a6f3554SLang Hames 
2228a6f3554SLang Hames void SectionMemoryManager::invalidateInstructionCache() {
22317433bd1SKeno Fischer   for (sys::MemoryBlock &Block : CodeMem.PendingMem)
224*93d2bddaSLang Hames     sys::Memory::InvalidateInstructionCache(Block.base(),
225*93d2bddaSLang Hames                                             Block.allocatedSize());
2268a6f3554SLang Hames }
2278a6f3554SLang Hames 
2288a6f3554SLang Hames SectionMemoryManager::~SectionMemoryManager() {
22917433bd1SKeno Fischer   for (MemoryGroup *Group : {&CodeMem, &RWDataMem, &RODataMem}) {
230efeddcc5SBenjamin Kramer     for (sys::MemoryBlock &Block : Group->AllocatedMem)
231e3992c63SSanjoy Das       MMapper.releaseMappedMemory(Block);
23217433bd1SKeno Fischer   }
2338a6f3554SLang Hames }
2348a6f3554SLang Hames 
235e3992c63SSanjoy Das SectionMemoryManager::MemoryMapper::~MemoryMapper() {}
236e3992c63SSanjoy Das 
2371bd40005SWeiming Zhao void SectionMemoryManager::anchor() {}
2381bd40005SWeiming Zhao 
239e3992c63SSanjoy Das namespace {
240e3992c63SSanjoy Das // Trivial implementation of SectionMemoryManager::MemoryMapper that just calls
241e3992c63SSanjoy Das // into sys::Memory.
242e3992c63SSanjoy Das class DefaultMMapper final : public SectionMemoryManager::MemoryMapper {
243e3992c63SSanjoy Das public:
244e3992c63SSanjoy Das   sys::MemoryBlock
245e3992c63SSanjoy Das   allocateMappedMemory(SectionMemoryManager::AllocationPurpose Purpose,
246e3992c63SSanjoy Das                        size_t NumBytes, const sys::MemoryBlock *const NearBlock,
247e3992c63SSanjoy Das                        unsigned Flags, std::error_code &EC) override {
248*93d2bddaSLang Hames     return sys::Memory::allocateMappedMemory(NumBytes, NearBlock, Flags, EC);
249e3992c63SSanjoy Das   }
250e3992c63SSanjoy Das 
251e3992c63SSanjoy Das   std::error_code protectMappedMemory(const sys::MemoryBlock &Block,
252e3992c63SSanjoy Das                                       unsigned Flags) override {
253e3992c63SSanjoy Das     return sys::Memory::protectMappedMemory(Block, Flags);
254e3992c63SSanjoy Das   }
255e3992c63SSanjoy Das 
256e3992c63SSanjoy Das   std::error_code releaseMappedMemory(sys::MemoryBlock &M) override {
257e3992c63SSanjoy Das     return sys::Memory::releaseMappedMemory(M);
258e3992c63SSanjoy Das   }
259e3992c63SSanjoy Das };
260e3992c63SSanjoy Das 
261e3992c63SSanjoy Das DefaultMMapper DefaultMMapperInstance;
262e3992c63SSanjoy Das } // namespace
263e3992c63SSanjoy Das 
264e3992c63SSanjoy Das SectionMemoryManager::SectionMemoryManager(MemoryMapper *MM)
265e3992c63SSanjoy Das     : MMapper(MM ? *MM : DefaultMMapperInstance) {}
266e3992c63SSanjoy Das 
2678a6f3554SLang Hames } // namespace llvm
268