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*);
40 using std::error_code;
44 int getPosixProtectionFlags(unsigned Flags) {
46 case llvm::sys::Memory::MF_READ:
48 case llvm::sys::Memory::MF_WRITE:
50 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
51 return PROT_READ | PROT_WRITE;
52 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
53 return PROT_READ | PROT_EXEC;
54 case llvm::sys::Memory::MF_READ |
55 llvm::sys::Memory::MF_WRITE |
56 llvm::sys::Memory::MF_EXEC:
57 return PROT_READ | PROT_WRITE | PROT_EXEC;
58 case llvm::sys::Memory::MF_EXEC:
59 #if defined(__FreeBSD__)
60 // On PowerPC, having an executable page that has no read permission
61 // can have unintended consequences. The function InvalidateInstruction-
62 // Cache uses instructions dcbf and icbi, both of which are treated by
63 // the processor as loads. If the page has no read permissions,
64 // executing these instructions will result in a segmentation fault.
65 // Somehow, this problem is not present on Linux, but it does happen
67 return PROT_READ | PROT_EXEC;
72 llvm_unreachable("Illegal memory protection flag specified!");
74 // Provide a default return value as required by some compilers.
84 Memory::allocateMappedMemory(size_t NumBytes,
85 const MemoryBlock *const NearBlock,
92 static const size_t PageSize = process::get_self()->page_size();
93 const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
96 #ifdef NEED_DEV_ZERO_FOR_MMAP
97 static int zero_fd = open("/dev/zero", O_RDWR);
99 EC = error_code(errno, std::generic_category());
100 return MemoryBlock();
105 int MMFlags = MAP_PRIVATE |
106 #ifdef HAVE_MMAP_ANONYMOUS
111 ; // Ends statement above
113 int Protect = getPosixProtectionFlags(PFlags);
115 // Use any near hint and the page size to set a page-aligned starting address
116 uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
117 NearBlock->size() : 0;
118 if (Start && Start % PageSize)
119 Start += PageSize - Start % PageSize;
121 void *Addr = ::mmap(reinterpret_cast<void*>(Start), PageSize*NumPages,
122 Protect, MMFlags, fd, 0);
123 if (Addr == MAP_FAILED) {
124 if (NearBlock) //Try again without a near hint
125 return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
127 EC = error_code(errno, std::generic_category());
128 return MemoryBlock();
132 Result.Address = Addr;
133 Result.Size = NumPages*PageSize;
135 if (PFlags & MF_EXEC)
136 Memory::InvalidateInstructionCache(Result.Address, Result.Size);
142 Memory::releaseMappedMemory(MemoryBlock &M) {
143 if (M.Address == nullptr || M.Size == 0)
146 if (0 != ::munmap(M.Address, M.Size))
147 return error_code(errno, std::generic_category());
156 Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
157 if (M.Address == nullptr || M.Size == 0)
161 return error_code(EINVAL, std::generic_category());
163 int Protect = getPosixProtectionFlags(Flags);
165 int Result = ::mprotect(M.Address, M.Size, Protect);
167 return error_code(errno, std::generic_category());
170 Memory::InvalidateInstructionCache(M.Address, M.Size);
175 /// AllocateRWX - Allocate a slab of memory with read/write/execute
176 /// permissions. This is typically used for JIT applications where we want
177 /// to emit code to the memory then jump to it. Getting this type of memory
178 /// is very OS specific.
181 Memory::AllocateRWX(size_t NumBytes, const MemoryBlock* NearBlock,
182 std::string *ErrMsg) {
183 if (NumBytes == 0) return MemoryBlock();
185 size_t PageSize = process::get_self()->page_size();
186 size_t NumPages = (NumBytes+PageSize-1)/PageSize;
189 #ifdef NEED_DEV_ZERO_FOR_MMAP
190 static int zero_fd = open("/dev/zero", O_RDWR);
192 MakeErrMsg(ErrMsg, "Can't open /dev/zero device");
193 return MemoryBlock();
198 int flags = MAP_PRIVATE |
199 #ifdef HAVE_MMAP_ANONYMOUS
206 void* start = NearBlock ? (unsigned char*)NearBlock->base() +
207 NearBlock->size() : nullptr;
209 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
210 void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_EXEC,
213 void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
216 if (pa == MAP_FAILED) {
217 if (NearBlock) //Try again without a near hint
218 return AllocateRWX(NumBytes, nullptr);
220 MakeErrMsg(ErrMsg, "Can't allocate RWX Memory");
221 return MemoryBlock();
224 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
225 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)pa,
226 (vm_size_t)(PageSize*NumPages), 0,
227 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
228 if (KERN_SUCCESS != kr) {
229 MakeErrMsg(ErrMsg, "vm_protect max RX failed");
230 return MemoryBlock();
233 kr = vm_protect(mach_task_self(), (vm_address_t)pa,
234 (vm_size_t)(PageSize*NumPages), 0,
235 VM_PROT_READ | VM_PROT_WRITE);
236 if (KERN_SUCCESS != kr) {
237 MakeErrMsg(ErrMsg, "vm_protect RW failed");
238 return MemoryBlock();
244 result.Size = NumPages*PageSize;
249 bool Memory::ReleaseRWX(MemoryBlock &M, std::string *ErrMsg) {
250 if (M.Address == nullptr || M.Size == 0) return false;
251 if (0 != ::munmap(M.Address, M.Size))
252 return MakeErrMsg(ErrMsg, "Can't release RWX Memory");
256 bool Memory::setWritable (MemoryBlock &M, std::string *ErrMsg) {
257 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
258 if (M.Address == 0 || M.Size == 0) return false;
259 Memory::InvalidateInstructionCache(M.Address, M.Size);
260 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
261 (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_WRITE);
262 return KERN_SUCCESS == kr;
268 bool Memory::setExecutable (MemoryBlock &M, std::string *ErrMsg) {
269 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
270 if (M.Address == 0 || M.Size == 0) return false;
271 Memory::InvalidateInstructionCache(M.Address, M.Size);
272 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
273 (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
274 return KERN_SUCCESS == kr;
275 #elif defined(__arm__) || defined(__aarch64__)
276 Memory::InvalidateInstructionCache(M.Address, M.Size);
283 bool Memory::setRangeWritable(const void *Addr, size_t Size) {
284 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
285 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
287 VM_PROT_READ | VM_PROT_WRITE);
288 return KERN_SUCCESS == kr;
294 bool Memory::setRangeExecutable(const void *Addr, size_t Size) {
295 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
296 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
298 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
299 return KERN_SUCCESS == kr;
305 /// InvalidateInstructionCache - Before the JIT can run a block of code
306 /// that has been emitted it must invalidate the instruction cache on some
308 void Memory::InvalidateInstructionCache(const void *Addr,
311 // icache invalidation for PPC and ARM.
312 #if defined(__APPLE__)
314 # if (defined(__POWERPC__) || defined (__ppc__) || \
315 defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
317 sys_icache_invalidate(const_cast<void *>(Addr), Len);
322 # if (defined(__POWERPC__) || defined (__ppc__) || \
323 defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
324 const size_t LineSize = 32;
326 const intptr_t Mask = ~(LineSize - 1);
327 const intptr_t StartLine = ((intptr_t) Addr) & Mask;
328 const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
330 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
331 asm volatile("dcbf 0, %0" : : "r"(Line));
332 asm volatile("sync");
334 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
335 asm volatile("icbi 0, %0" : : "r"(Line));
336 asm volatile("isync");
337 # elif (defined(__arm__) || defined(__aarch64__)) && defined(__GNUC__)
338 // FIXME: Can we safely always call this for __GNUC__ everywhere?
339 const char *Start = static_cast<const char *>(Addr);
340 const char *End = Start + Len;
341 __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
342 # elif defined(__mips__)
343 const char *Start = static_cast<const char *>(Addr);
344 # if defined(ANDROID)
345 // The declaration of "cacheflush" in Android bionic:
346 // extern int cacheflush(long start, long end, long flags);
347 const char *End = Start + Len;
348 long LStart = reinterpret_cast<long>(const_cast<char *>(Start));
349 long LEnd = reinterpret_cast<long>(const_cast<char *>(End));
350 cacheflush(LStart, LEnd, BCACHE);
352 cacheflush(const_cast<char *>(Start), Len, BCACHE);
358 ValgrindDiscardTranslations(Addr, Len);