1 //===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines some functions for various memory management utilities.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/DataTypes.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include "llvm/Support/Process.h"
19 #ifdef HAVE_SYS_MMAN_H
24 #include <mach/mach.h>
28 # if defined(__OpenBSD__)
29 # include <mips64/sysarch.h>
31 # include <sys/cachectl.h>
36 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
38 extern "C" void __clear_cache(void *, void*);
43 int getPosixProtectionFlags(unsigned Flags) {
45 case llvm::sys::Memory::MF_READ:
47 case llvm::sys::Memory::MF_WRITE:
49 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
50 return PROT_READ | PROT_WRITE;
51 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
52 return PROT_READ | PROT_EXEC;
53 case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE |
54 llvm::sys::Memory::MF_EXEC:
55 return PROT_READ | PROT_WRITE | PROT_EXEC;
56 case llvm::sys::Memory::MF_EXEC:
57 #if defined(__FreeBSD__)
58 // On PowerPC, having an executable page that has no read permission
59 // can have unintended consequences. The function InvalidateInstruction-
60 // Cache uses instructions dcbf and icbi, both of which are treated by
61 // the processor as loads. If the page has no read permissions,
62 // executing these instructions will result in a segmentation fault.
63 // Somehow, this problem is not present on Linux, but it does happen
65 return PROT_READ | PROT_EXEC;
70 llvm_unreachable("Illegal memory protection flag specified!");
72 // Provide a default return value as required by some compilers.
76 } // anonymous namespace
82 Memory::allocateMappedMemory(size_t NumBytes,
83 const MemoryBlock *const NearBlock,
85 std::error_code &EC) {
86 EC = std::error_code();
90 static const size_t PageSize = Process::getPageSize();
91 const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
95 int MMFlags = MAP_PRIVATE |
101 ; // Ends statement above
103 int Protect = getPosixProtectionFlags(PFlags);
105 // Use any near hint and the page size to set a page-aligned starting address
106 uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
107 NearBlock->size() : 0;
108 if (Start && Start % PageSize)
109 Start += PageSize - Start % PageSize;
111 void *Addr = ::mmap(reinterpret_cast<void*>(Start), PageSize*NumPages,
112 Protect, MMFlags, fd, 0);
113 if (Addr == MAP_FAILED) {
114 if (NearBlock) //Try again without a near hint
115 return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
117 EC = std::error_code(errno, std::generic_category());
118 return MemoryBlock();
122 Result.Address = Addr;
123 Result.Size = NumPages*PageSize;
125 if (PFlags & MF_EXEC)
126 Memory::InvalidateInstructionCache(Result.Address, Result.Size);
132 Memory::releaseMappedMemory(MemoryBlock &M) {
133 if (M.Address == nullptr || M.Size == 0)
134 return std::error_code();
136 if (0 != ::munmap(M.Address, M.Size))
137 return std::error_code(errno, std::generic_category());
142 return std::error_code();
146 Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
147 static const size_t PageSize = Process::getPageSize();
148 if (M.Address == nullptr || M.Size == 0)
149 return std::error_code();
152 return std::error_code(EINVAL, std::generic_category());
154 int Protect = getPosixProtectionFlags(Flags);
156 uintptr_t Start = alignAddr((uint8_t *)M.Address - PageSize + 1, PageSize);
157 uintptr_t End = alignAddr((uint8_t *)M.Address + M.Size, PageSize);
158 int Result = ::mprotect((void *)Start, End - Start, Protect);
161 return std::error_code(errno, std::generic_category());
164 Memory::InvalidateInstructionCache(M.Address, M.Size);
166 return std::error_code();
169 /// AllocateRWX - Allocate a slab of memory with read/write/execute
170 /// permissions. This is typically used for JIT applications where we want
171 /// to emit code to the memory then jump to it. Getting this type of memory
172 /// is very OS specific.
175 Memory::AllocateRWX(size_t NumBytes, const MemoryBlock* NearBlock,
176 std::string *ErrMsg) {
177 if (NumBytes == 0) return MemoryBlock();
179 static const size_t PageSize = Process::getPageSize();
180 size_t NumPages = (NumBytes+PageSize-1)/PageSize;
184 int flags = MAP_PRIVATE |
192 void* start = NearBlock ? (unsigned char*)NearBlock->base() +
193 NearBlock->size() : nullptr;
195 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
196 void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_EXEC,
199 void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
202 if (pa == MAP_FAILED) {
203 if (NearBlock) //Try again without a near hint
204 return AllocateRWX(NumBytes, nullptr);
206 MakeErrMsg(ErrMsg, "Can't allocate RWX Memory");
207 return MemoryBlock();
210 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
211 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)pa,
212 (vm_size_t)(PageSize*NumPages), 0,
213 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
214 if (KERN_SUCCESS != kr) {
215 MakeErrMsg(ErrMsg, "vm_protect max RX failed");
216 return MemoryBlock();
219 kr = vm_protect(mach_task_self(), (vm_address_t)pa,
220 (vm_size_t)(PageSize*NumPages), 0,
221 VM_PROT_READ | VM_PROT_WRITE);
222 if (KERN_SUCCESS != kr) {
223 MakeErrMsg(ErrMsg, "vm_protect RW failed");
224 return MemoryBlock();
230 result.Size = NumPages*PageSize;
235 bool Memory::ReleaseRWX(MemoryBlock &M, std::string *ErrMsg) {
236 if (M.Address == nullptr || M.Size == 0) return false;
237 if (0 != ::munmap(M.Address, M.Size))
238 return MakeErrMsg(ErrMsg, "Can't release RWX Memory");
242 bool Memory::setWritable (MemoryBlock &M, std::string *ErrMsg) {
243 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
244 if (M.Address == 0 || M.Size == 0) return false;
245 Memory::InvalidateInstructionCache(M.Address, M.Size);
246 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
247 (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_WRITE);
248 return KERN_SUCCESS == kr;
254 bool Memory::setExecutable (MemoryBlock &M, std::string *ErrMsg) {
255 if (M.Address == nullptr || M.Size == 0) return false;
256 Memory::InvalidateInstructionCache(M.Address, M.Size);
257 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
258 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
259 (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
260 return KERN_SUCCESS == kr;
266 bool Memory::setRangeWritable(const void *Addr, size_t Size) {
267 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
268 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
270 VM_PROT_READ | VM_PROT_WRITE);
271 return KERN_SUCCESS == kr;
277 bool Memory::setRangeExecutable(const void *Addr, size_t Size) {
278 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
279 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
281 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
282 return KERN_SUCCESS == kr;
288 /// InvalidateInstructionCache - Before the JIT can run a block of code
289 /// that has been emitted it must invalidate the instruction cache on some
291 void Memory::InvalidateInstructionCache(const void *Addr,
294 // icache invalidation for PPC and ARM.
295 #if defined(__APPLE__)
297 # if (defined(__POWERPC__) || defined (__ppc__) || \
298 defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
300 sys_icache_invalidate(const_cast<void *>(Addr), Len);
305 # if (defined(__POWERPC__) || defined (__ppc__) || \
306 defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
307 const size_t LineSize = 32;
309 const intptr_t Mask = ~(LineSize - 1);
310 const intptr_t StartLine = ((intptr_t) Addr) & Mask;
311 const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
313 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
314 asm volatile("dcbf 0, %0" : : "r"(Line));
315 asm volatile("sync");
317 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
318 asm volatile("icbi 0, %0" : : "r"(Line));
319 asm volatile("isync");
320 # elif (defined(__arm__) || defined(__aarch64__) || defined(__mips__)) && \
322 // FIXME: Can we safely always call this for __GNUC__ everywhere?
323 const char *Start = static_cast<const char *>(Addr);
324 const char *End = Start + Len;
325 __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
330 ValgrindDiscardTranslations(Addr, Len);