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
allocateDataSection(uintptr_t Size,unsigned Alignment,unsigned SectionID,StringRef SectionName,bool IsReadOnly)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
allocateCodeSection(uintptr_t Size,unsigned Alignment,unsigned SectionID,StringRef SectionName)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
allocateSection(SectionMemoryManager::AllocationPurpose Purpose,uintptr_t Size,unsigned Alignment)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) {
6793d2bddaSLang Hames if (FreeMB.Free.allocatedSize() >= RequiredSize) {
6894f181a4SKeno Fischer Addr = (uintptr_t)FreeMB.Free.base();
6993d2bddaSLang 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
115574713c3SLang Hames // Copy the address to all the other groups, if they have not
116574713c3SLang Hames // been initialized.
1175a667c0eSKazu Hirata if (CodeMem.Near.base() == nullptr)
118574713c3SLang Hames CodeMem.Near = MB;
1195a667c0eSKazu Hirata if (RODataMem.Near.base() == nullptr)
120574713c3SLang Hames RODataMem.Near = MB;
1215a667c0eSKazu Hirata if (RWDataMem.Near.base() == nullptr)
122574713c3SLang Hames RWDataMem.Near = MB;
123574713c3SLang Hames
12494f181a4SKeno Fischer // Remember that we allocated this memory
12594f181a4SKeno Fischer MemGroup.AllocatedMem.push_back(MB);
1268a6f3554SLang Hames Addr = (uintptr_t)MB.base();
12793d2bddaSLang Hames uintptr_t EndOfBlock = Addr + MB.allocatedSize();
1288a6f3554SLang Hames
1298a6f3554SLang Hames // Align the address.
1308a6f3554SLang Hames Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
1318a6f3554SLang Hames
13294f181a4SKeno Fischer // The part of the block we're giving out to the user is now pending
13394f181a4SKeno Fischer MemGroup.PendingMem.push_back(sys::MemoryBlock((void *)Addr, Size));
13494f181a4SKeno Fischer
1358a6f3554SLang Hames // The allocateMappedMemory may allocate much more memory than we need. In
1368a6f3554SLang Hames // this case, we store the unused memory as a free memory block.
1378a6f3554SLang Hames unsigned FreeSize = EndOfBlock - Addr - Size;
13894f181a4SKeno Fischer if (FreeSize > 16) {
13994f181a4SKeno Fischer FreeMemBlock FreeMB;
14094f181a4SKeno Fischer FreeMB.Free = sys::MemoryBlock((void *)(Addr + Size), FreeSize);
14194f181a4SKeno Fischer FreeMB.PendingPrefixIndex = (unsigned)-1;
14294f181a4SKeno Fischer MemGroup.FreeMem.push_back(FreeMB);
14394f181a4SKeno Fischer }
1448a6f3554SLang Hames
1458a6f3554SLang Hames // Return aligned address
1468a6f3554SLang Hames return (uint8_t *)Addr;
1478a6f3554SLang Hames }
1488a6f3554SLang Hames
finalizeMemory(std::string * ErrMsg)149e3992c63SSanjoy Das bool SectionMemoryManager::finalizeMemory(std::string *ErrMsg) {
1508a6f3554SLang Hames // FIXME: Should in-progress permissions be reverted if an error occurs?
1518a6f3554SLang Hames std::error_code ec;
1528a6f3554SLang Hames
1538a6f3554SLang Hames // Make code memory executable.
1548a6f3554SLang Hames ec = applyMemoryGroupPermissions(CodeMem,
1558a6f3554SLang Hames sys::Memory::MF_READ | sys::Memory::MF_EXEC);
1568a6f3554SLang Hames if (ec) {
1578a6f3554SLang Hames if (ErrMsg) {
1588a6f3554SLang Hames *ErrMsg = ec.message();
1598a6f3554SLang Hames }
1608a6f3554SLang Hames return true;
1618a6f3554SLang Hames }
1628a6f3554SLang Hames
1638a6f3554SLang Hames // Make read-only data memory read-only.
164ba0e7143SDavid Turner ec = applyMemoryGroupPermissions(RODataMem, sys::Memory::MF_READ);
1658a6f3554SLang Hames if (ec) {
1668a6f3554SLang Hames if (ErrMsg) {
1678a6f3554SLang Hames *ErrMsg = ec.message();
1688a6f3554SLang Hames }
1698a6f3554SLang Hames return true;
1708a6f3554SLang Hames }
1718a6f3554SLang Hames
1728a6f3554SLang Hames // Read-write data memory already has the correct permissions
1738a6f3554SLang Hames
1748a6f3554SLang Hames // Some platforms with separate data cache and instruction cache require
1758a6f3554SLang Hames // explicit cache flush, otherwise JIT code manipulations (like resolved
1768a6f3554SLang Hames // relocations) will get to the data cache but not to the instruction cache.
1778a6f3554SLang Hames invalidateInstructionCache();
1788a6f3554SLang Hames
1798a6f3554SLang Hames return false;
1808a6f3554SLang Hames }
1818a6f3554SLang Hames
trimBlockToPageSize(sys::MemoryBlock M)18294f181a4SKeno Fischer static sys::MemoryBlock trimBlockToPageSize(sys::MemoryBlock M) {
183e4b4ab6dSLang Hames static const size_t PageSize = sys::Process::getPageSizeEstimate();
18494f181a4SKeno Fischer
18594f181a4SKeno Fischer size_t StartOverlap =
18694f181a4SKeno Fischer (PageSize - ((uintptr_t)M.base() % PageSize)) % PageSize;
18794f181a4SKeno Fischer
18893d2bddaSLang Hames size_t TrimmedSize = M.allocatedSize();
18994f181a4SKeno Fischer TrimmedSize -= StartOverlap;
19094f181a4SKeno Fischer TrimmedSize -= TrimmedSize % PageSize;
19194f181a4SKeno Fischer
192e3992c63SSanjoy Das sys::MemoryBlock Trimmed((void *)((uintptr_t)M.base() + StartOverlap),
193e3992c63SSanjoy Das TrimmedSize);
19494f181a4SKeno Fischer
19594f181a4SKeno Fischer assert(((uintptr_t)Trimmed.base() % PageSize) == 0);
19693d2bddaSLang Hames assert((Trimmed.allocatedSize() % PageSize) == 0);
19793d2bddaSLang Hames assert(M.base() <= Trimmed.base() &&
19893d2bddaSLang Hames Trimmed.allocatedSize() <= M.allocatedSize());
19994f181a4SKeno Fischer
20094f181a4SKeno Fischer return Trimmed;
20194f181a4SKeno Fischer }
20294f181a4SKeno Fischer
2038a6f3554SLang Hames std::error_code
applyMemoryGroupPermissions(MemoryGroup & MemGroup,unsigned Permissions)2048a6f3554SLang Hames SectionMemoryManager::applyMemoryGroupPermissions(MemoryGroup &MemGroup,
2058a6f3554SLang Hames unsigned Permissions) {
20617433bd1SKeno Fischer for (sys::MemoryBlock &MB : MemGroup.PendingMem)
207e3992c63SSanjoy Das if (std::error_code EC = MMapper.protectMappedMemory(MB, Permissions))
208efeddcc5SBenjamin Kramer return EC;
2098a6f3554SLang Hames
21094f181a4SKeno Fischer MemGroup.PendingMem.clear();
21194f181a4SKeno Fischer
21294f181a4SKeno Fischer // Now go through free blocks and trim any of them that don't span the entire
21394f181a4SKeno Fischer // page because one of the pending blocks may have overlapped it.
21494f181a4SKeno Fischer for (FreeMemBlock &FreeMB : MemGroup.FreeMem) {
21594f181a4SKeno Fischer FreeMB.Free = trimBlockToPageSize(FreeMB.Free);
21694f181a4SKeno Fischer // We cleared the PendingMem list, so all these pointers are now invalid
21794f181a4SKeno Fischer FreeMB.PendingPrefixIndex = (unsigned)-1;
21894f181a4SKeno Fischer }
21994f181a4SKeno Fischer
22094f181a4SKeno Fischer // Remove all blocks which are now empty
2219939cf5aSKazu Hirata erase_if(MemGroup.FreeMem, [](FreeMemBlock &FreeMB) {
22293d2bddaSLang Hames return FreeMB.Free.allocatedSize() == 0;
2239939cf5aSKazu Hirata });
22494f181a4SKeno Fischer
2258a6f3554SLang Hames return std::error_code();
2268a6f3554SLang Hames }
2278a6f3554SLang Hames
invalidateInstructionCache()2288a6f3554SLang Hames void SectionMemoryManager::invalidateInstructionCache() {
22917433bd1SKeno Fischer for (sys::MemoryBlock &Block : CodeMem.PendingMem)
23093d2bddaSLang Hames sys::Memory::InvalidateInstructionCache(Block.base(),
23193d2bddaSLang Hames Block.allocatedSize());
2328a6f3554SLang Hames }
2338a6f3554SLang Hames
~SectionMemoryManager()2348a6f3554SLang Hames SectionMemoryManager::~SectionMemoryManager() {
23517433bd1SKeno Fischer for (MemoryGroup *Group : {&CodeMem, &RWDataMem, &RODataMem}) {
236efeddcc5SBenjamin Kramer for (sys::MemoryBlock &Block : Group->AllocatedMem)
237e3992c63SSanjoy Das MMapper.releaseMappedMemory(Block);
23817433bd1SKeno Fischer }
2398a6f3554SLang Hames }
2408a6f3554SLang Hames
241*3a3cb929SKazu Hirata SectionMemoryManager::MemoryMapper::~MemoryMapper() = default;
242e3992c63SSanjoy Das
anchor()2431bd40005SWeiming Zhao void SectionMemoryManager::anchor() {}
2441bd40005SWeiming Zhao
245e3992c63SSanjoy Das namespace {
246e3992c63SSanjoy Das // Trivial implementation of SectionMemoryManager::MemoryMapper that just calls
247e3992c63SSanjoy Das // into sys::Memory.
248e3992c63SSanjoy Das class DefaultMMapper final : public SectionMemoryManager::MemoryMapper {
249e3992c63SSanjoy Das public:
250e3992c63SSanjoy Das sys::MemoryBlock
allocateMappedMemory(SectionMemoryManager::AllocationPurpose Purpose,size_t NumBytes,const sys::MemoryBlock * const NearBlock,unsigned Flags,std::error_code & EC)251e3992c63SSanjoy Das allocateMappedMemory(SectionMemoryManager::AllocationPurpose Purpose,
252e3992c63SSanjoy Das size_t NumBytes, const sys::MemoryBlock *const NearBlock,
253e3992c63SSanjoy Das unsigned Flags, std::error_code &EC) override {
25493d2bddaSLang Hames return sys::Memory::allocateMappedMemory(NumBytes, NearBlock, Flags, EC);
255e3992c63SSanjoy Das }
256e3992c63SSanjoy Das
protectMappedMemory(const sys::MemoryBlock & Block,unsigned Flags)257e3992c63SSanjoy Das std::error_code protectMappedMemory(const sys::MemoryBlock &Block,
258e3992c63SSanjoy Das unsigned Flags) override {
259e3992c63SSanjoy Das return sys::Memory::protectMappedMemory(Block, Flags);
260e3992c63SSanjoy Das }
261e3992c63SSanjoy Das
releaseMappedMemory(sys::MemoryBlock & M)262e3992c63SSanjoy Das std::error_code releaseMappedMemory(sys::MemoryBlock &M) override {
263e3992c63SSanjoy Das return sys::Memory::releaseMappedMemory(M);
264e3992c63SSanjoy Das }
265e3992c63SSanjoy Das };
266e3992c63SSanjoy Das
2677e8babebSLang Hames DefaultMMapper DefaultMMapperInstance;
268e3992c63SSanjoy Das } // namespace
269e3992c63SSanjoy Das
SectionMemoryManager(MemoryMapper * MM)270e3992c63SSanjoy Das SectionMemoryManager::SectionMemoryManager(MemoryMapper *MM)
2717e8babebSLang Hames : MMapper(MM ? *MM : DefaultMMapperInstance) {}
272e3992c63SSanjoy Das
2738a6f3554SLang Hames } // namespace llvm
274