1 //===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- 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 defines some functions for various memory management utilities.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/Config/config.h"
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 #include <zircon/syscalls.h>
32 # if defined(__OpenBSD__)
33 # include <mips64/sysarch.h>
34 # elif !defined(__FreeBSD__)
35 # include <sys/cachectl.h>
39 #if defined(__APPLE__)
40 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
42 extern "C" void __clear_cache(void *, void*);
47 int getPosixProtectionFlags(unsigned Flags) {
49 case llvm::sys::Memory::MF_READ:
51 case llvm::sys::Memory::MF_WRITE:
53 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
54 return PROT_READ | PROT_WRITE;
55 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
56 return PROT_READ | PROT_EXEC;
57 case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE |
58 llvm::sys::Memory::MF_EXEC:
59 return PROT_READ | PROT_WRITE | PROT_EXEC;
60 case llvm::sys::Memory::MF_EXEC:
61 #if defined(__FreeBSD__)
62 // On PowerPC, having an executable page that has no read permission
63 // can have unintended consequences. The function InvalidateInstruction-
64 // Cache uses instructions dcbf and icbi, both of which are treated by
65 // the processor as loads. If the page has no read permissions,
66 // executing these instructions will result in a segmentation fault.
67 // Somehow, this problem is not present on Linux, but it does happen
69 return PROT_READ | PROT_EXEC;
74 llvm_unreachable("Illegal memory protection flag specified!");
76 // Provide a default return value as required by some compilers.
80 } // anonymous namespace
86 Memory::allocateMappedMemory(size_t NumBytes,
87 const MemoryBlock *const NearBlock,
89 std::error_code &EC) {
90 EC = std::error_code();
96 int MMFlags = MAP_PRIVATE |
102 ; // Ends statement above
104 int Protect = getPosixProtectionFlags(PFlags);
106 #if defined(__NetBSD__) && defined(PROT_MPROTECT)
107 Protect |= PROT_MPROTECT(PROT_READ | PROT_WRITE | PROT_EXEC);
110 // Use any near hint and the page size to set a page-aligned starting address
111 uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
112 NearBlock->size() : 0;
113 static const size_t PageSize = Process::getPageSize();
114 if (Start && Start % PageSize)
115 Start += PageSize - Start % PageSize;
117 void *Addr = ::mmap(reinterpret_cast<void *>(Start), NumBytes, Protect,
119 if (Addr == MAP_FAILED) {
120 if (NearBlock) //Try again without a near hint
121 return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
123 EC = std::error_code(errno, std::generic_category());
124 return MemoryBlock();
128 Result.Address = Addr;
129 Result.Size = NumBytes;
131 // Rely on protectMappedMemory to invalidate instruction cache.
132 if (PFlags & MF_EXEC) {
133 EC = Memory::protectMappedMemory (Result, PFlags);
134 if (EC != std::error_code())
135 return MemoryBlock();
142 Memory::releaseMappedMemory(MemoryBlock &M) {
143 if (M.Address == nullptr || M.Size == 0)
144 return std::error_code();
146 if (0 != ::munmap(M.Address, M.Size))
147 return std::error_code(errno, std::generic_category());
152 return std::error_code();
156 Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
157 static const size_t PageSize = Process::getPageSize();
158 if (M.Address == nullptr || M.Size == 0)
159 return std::error_code();
162 return std::error_code(EINVAL, std::generic_category());
164 int Protect = getPosixProtectionFlags(Flags);
165 uintptr_t Start = alignAddr((uint8_t *)M.Address - PageSize + 1, PageSize);
166 uintptr_t End = alignAddr((uint8_t *)M.Address + M.Size, PageSize);
168 bool InvalidateCache = (Flags & MF_EXEC);
170 #if defined(__arm__) || defined(__aarch64__)
171 // Certain ARM implementations treat icache clear instruction as a memory read,
172 // and CPU segfaults on trying to clear cache on !PROT_READ page. Therefore we need
173 // to temporarily add PROT_READ for the sake of flushing the instruction caches.
174 if (InvalidateCache && !(Protect & PROT_READ)) {
175 int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
177 return std::error_code(errno, std::generic_category());
179 Memory::InvalidateInstructionCache(M.Address, M.Size);
180 InvalidateCache = false;
184 int Result = ::mprotect((void *)Start, End - Start, Protect);
187 return std::error_code(errno, std::generic_category());
190 Memory::InvalidateInstructionCache(M.Address, M.Size);
192 return std::error_code();
195 /// InvalidateInstructionCache - Before the JIT can run a block of code
196 /// that has been emitted it must invalidate the instruction cache on some
198 void Memory::InvalidateInstructionCache(const void *Addr,
201 // icache invalidation for PPC and ARM.
202 #if defined(__APPLE__)
204 # if (defined(__POWERPC__) || defined (__ppc__) || \
205 defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
207 sys_icache_invalidate(const_cast<void *>(Addr), Len);
210 #elif defined(__Fuchsia__)
212 zx_status_t Status = zx_cache_flush(Addr, Len, ZX_CACHE_FLUSH_INSN);
213 assert(Status == ZX_OK && "cannot invalidate instruction cache");
217 # if (defined(__POWERPC__) || defined (__ppc__) || \
218 defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
219 const size_t LineSize = 32;
221 const intptr_t Mask = ~(LineSize - 1);
222 const intptr_t StartLine = ((intptr_t) Addr) & Mask;
223 const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
225 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
226 asm volatile("dcbf 0, %0" : : "r"(Line));
227 asm volatile("sync");
229 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
230 asm volatile("icbi 0, %0" : : "r"(Line));
231 asm volatile("isync");
232 # elif (defined(__arm__) || defined(__aarch64__) || defined(__mips__)) && \
234 // FIXME: Can we safely always call this for __GNUC__ everywhere?
235 const char *Start = static_cast<const char *>(Addr);
236 const char *End = Start + Len;
237 __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
242 ValgrindDiscardTranslations(Addr, Len);