1//===- SectionMemoryManager.cpp - Memory manager for MCJIT/RtDyld *- 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// This file implements the section-based memory manager used by the MCJIT 10// execution engine and RuntimeDyld 12//===----------------------------------------------------------------------===// 15#include "llvm/Config/config.h" 40uint8_t *SectionMemoryManager::allocateSection(
46assert(!(Alignment & (Alignment - 1)) &&
"Alignment must be a power of two.");
48 uintptr_t RequiredSize = Alignment * ((
Size + Alignment - 1) / Alignment + 1);
51 MemoryGroup &MemGroup = [&]() -> MemoryGroup & {
63// Look in the list of free memory regions and use a block there if one 65for (FreeMemBlock &FreeMB : MemGroup.FreeMem) {
66if (FreeMB.Free.allocatedSize() >= RequiredSize) {
67Addr = (uintptr_t)FreeMB.Free.base();
68 uintptr_t EndOfBlock =
Addr + FreeMB.Free.allocatedSize();
70Addr = (
Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
72if (FreeMB.PendingPrefixIndex == (
unsigned)-1) {
73// The part of the block we're giving out to the user is now pending 74 MemGroup.PendingMem.push_back(sys::MemoryBlock((
void *)
Addr,
Size));
76// Remember this pending block, such that future allocations can just 77// modify it rather than creating a new one 78 FreeMB.PendingPrefixIndex = MemGroup.PendingMem.size() - 1;
80 sys::MemoryBlock &PendingMB =
81 MemGroup.PendingMem[FreeMB.PendingPrefixIndex];
82 PendingMB = sys::MemoryBlock(PendingMB.base(),
83Addr +
Size - (uintptr_t)PendingMB.base());
86// Remember how much free space is now left in this block 93// No pre-allocated free block was large enough. Allocate a new memory region. 94// Note that all sections get allocated as read-write. The permissions will 95// be updated later based on memory group. 97// FIXME: It would be useful to define a default allocation size (or add 98// it as a constructor parameter) to minimize the number of allocations. 100// FIXME: Initialize the Near member for each memory group to avoid 104 Purpose, RequiredSize, &MemGroup.Near,
107// FIXME: Add error propagation to the interface. 111// Save this address as the basis for our next request 114// Copy the address to all the other groups, if they have not 116if (CodeMem.Near.base() ==
nullptr)
118if (RODataMem.Near.base() ==
nullptr)
120if (RWDataMem.Near.base() ==
nullptr)
123// Remember that we allocated this memory 124 MemGroup.AllocatedMem.push_back(MB);
125Addr = (uintptr_t)MB.base();
126 uintptr_t EndOfBlock =
Addr + MB.allocatedSize();
129Addr = (
Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
131// The part of the block we're giving out to the user is now pending 132 MemGroup.PendingMem.push_back(sys::MemoryBlock((
void *)
Addr,
Size));
134// The allocateMappedMemory may allocate much more memory than we need. In 135// this case, we store the unused memory as a free memory block. 136unsigned FreeSize = EndOfBlock -
Addr -
Size;
139 FreeMB.Free = sys::MemoryBlock((
void *)(
Addr +
Size), FreeSize);
140 FreeMB.PendingPrefixIndex = (
unsigned)-1;
141 MemGroup.FreeMem.push_back(FreeMB);
144// Return aligned address 149// FIXME: Should in-progress permissions be reverted if an error occurs? 152// Make code memory executable. 153 ec = applyMemoryGroupPermissions(CodeMem,
157 *ErrMsg = ec.message();
162// Make read-only data memory read-only. 166 *ErrMsg = ec.message();
171// Read-write data memory already has the correct permissions 173// Some platforms with separate data cache and instruction cache require 174// explicit cache flush, otherwise JIT code manipulations (like resolved 175// relocations) will get to the data cache but not to the instruction cache. 187size_t TrimmedSize = M.allocatedSize();
188 TrimmedSize -= StartOverlap;
189 TrimmedSize -= TrimmedSize %
PageSize;
203SectionMemoryManager::applyMemoryGroupPermissions(MemoryGroup &MemGroup,
204unsigned Permissions) {
205for (sys::MemoryBlock &MB : MemGroup.PendingMem)
209 MemGroup.PendingMem.clear();
211// Now go through free blocks and trim any of them that don't span the entire 212// page because one of the pending blocks may have overlapped it. 213for (FreeMemBlock &FreeMB : MemGroup.FreeMem) {
215// We cleared the PendingMem list, so all these pointers are now invalid 216 FreeMB.PendingPrefixIndex = (
unsigned)-1;
219// Remove all blocks which are now empty 220erase_if(MemGroup.FreeMem, [](FreeMemBlock &FreeMB) {
221 return FreeMB.Free.allocatedSize() == 0;
224return std::error_code();
230Block.allocatedSize());
234for (MemoryGroup *Group : {&CodeMem, &RWDataMem, &RODataMem}) {
242void SectionMemoryManager::anchor() {}
245// Trivial implementation of SectionMemoryManager::MemoryMapper that just calls 247classDefaultMMapper final :
public SectionMemoryManager::MemoryMapper {
251size_t NumBytes,
const sys::MemoryBlock *
const NearBlock,
252unsigned Flags, std::error_code &EC)
override{
256 std::error_code protectMappedMemory(
const sys::MemoryBlock &
Block,
257unsigned Flags)
override{
261 std::error_code releaseMappedMemory(sys::MemoryBlock &M)
override{
268 : MMapper(UnownedMM), OwnedMMapper(nullptr) {
270 OwnedMMapper = std::make_unique<DefaultMMapper>();
271 MMapper = OwnedMMapper.get();
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
Provides a library for accessing information about this process and other processes on the operating ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Implementations of this interface are used by SectionMemoryManager to request pages from the operatin...
virtual std::error_code protectMappedMemory(const sys::MemoryBlock &Block, unsigned Flags)=0
This method sets the protection flags for a block of memory to the state specified by Flags.
virtual std::error_code releaseMappedMemory(sys::MemoryBlock &M)=0
This method releases a block of memory that was allocated with the allocateMappedMemory method.
virtual sys::MemoryBlock allocateMappedMemory(AllocationPurpose Purpose, size_t NumBytes, const sys::MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)=0
This method attempts to allocate NumBytes bytes of virtual memory for Purpose.
AllocationPurpose
This enum describes the various reasons to allocate pages from allocateMappedMemory.
SectionMemoryManager(MemoryMapper *MM=nullptr)
Creates a SectionMemoryManager instance with MM as the associated memory mapper.
virtual void invalidateInstructionCache()
Invalidate instruction cache for code sections.
~SectionMemoryManager() override
uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool isReadOnly) override
Allocates a memory block of (at least) the given size suitable for executable code.
uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override
Allocates a memory block of (at least) the given size suitable for executable code.
bool finalizeMemory(std::string *ErrMsg=nullptr) override
Update section-specific memory permissions and other attributes.
StringRef - Represent a constant reference to a string, i.e.
This class encapsulates the notion of a memory block which has an address and a size.
size_t allocatedSize() const
The size as it was allocated.
static std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method.
static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e....
static void InvalidateInstructionCache(const void *Addr, size_t Len)
InvalidateInstructionCache - Before the JIT can run a block of code that has been emitted it must inv...
static std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags)
This method sets the protection flags for a block of memory to the state specified by /p Flags.
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
static sys::MemoryBlock trimBlockToPageSize(sys::MemoryBlock M)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...