blob: 1c6af7fa0f2ff8869ddc52ca97ec64d2813f8ea1 [file] [log] [blame]
Reid Spencer2896c952004-09-11 04:57:25 +00001//===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- C++ -*-===//
Michael J. Spencer447762d2010-11-29 18:16:10 +00002//
Reid Spencer2896c952004-09-11 04:57:25 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Michael J. Spencer447762d2010-11-29 18:16:10 +00007//
Reid Spencer2896c952004-09-11 04:57:25 +00008//===----------------------------------------------------------------------===//
9//
10// This file defines some functions for various memory management utilities.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Unix.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000015#include "llvm/Support/DataTypes.h"
Andrew Kaylor1f661002012-09-19 20:46:12 +000016#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000017#include "llvm/Support/Process.h"
Reid Spencer47cd6532004-12-27 06:17:03 +000018
19#ifdef HAVE_SYS_MMAN_H
20#include <sys/mman.h>
21#endif
Reid Spencer2896c952004-09-11 04:57:25 +000022
Evan Cheng5cc53c32008-09-18 07:54:21 +000023#ifdef __APPLE__
24#include <mach/mach.h>
25#endif
26
Chandler Carrutha699b6a2012-09-11 01:17:24 +000027#if defined(__mips__)
28# if defined(__OpenBSD__)
29# include <mips64/sysarch.h>
30# else
31# include <sys/cachectl.h>
32# endif
33#endif
34
Andrew Kaylor1f661002012-09-19 20:46:12 +000035extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
Rafael Espindolae16befb2013-05-14 18:06:14 +000036extern "C" void __clear_cache(void *, void*);
Andrew Kaylor1f661002012-09-19 20:46:12 +000037
38namespace {
39
40int getPosixProtectionFlags(unsigned Flags) {
41 switch (Flags) {
42 case llvm::sys::Memory::MF_READ:
43 return PROT_READ;
44 case llvm::sys::Memory::MF_WRITE:
45 return PROT_WRITE;
46 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
47 return PROT_READ | PROT_WRITE;
48 case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
49 return PROT_READ | PROT_EXEC;
50 case llvm::sys::Memory::MF_READ |
51 llvm::sys::Memory::MF_WRITE |
52 llvm::sys::Memory::MF_EXEC:
53 return PROT_READ | PROT_WRITE | PROT_EXEC;
54 case llvm::sys::Memory::MF_EXEC:
Krzysztof Parzyszek798679e2013-02-20 18:24:30 +000055#if defined(__FreeBSD__)
Krzysztof Parzyszek12ba7112013-02-20 19:25:09 +000056 // On PowerPC, having an executable page that has no read permission
57 // can have unintended consequences. The function InvalidateInstruction-
58 // Cache uses instructions dcbf and icbi, both of which are treated by
59 // the processor as loads. If the page has no read permissions,
60 // executing these instructions will result in a segmentation fault.
61 // Somehow, this problem is not present on Linux, but it does happen
62 // on FreeBSD.
Krzysztof Parzyszek798679e2013-02-20 18:24:30 +000063 return PROT_READ | PROT_EXEC;
64#else
Andrew Kaylor1f661002012-09-19 20:46:12 +000065 return PROT_EXEC;
Krzysztof Parzyszek798679e2013-02-20 18:24:30 +000066#endif
Andrew Kaylor1f661002012-09-19 20:46:12 +000067 default:
68 llvm_unreachable("Illegal memory protection flag specified!");
69 }
70 // Provide a default return value as required by some compilers.
71 return PROT_NONE;
72}
73
74} // namespace
75
76namespace llvm {
77namespace sys {
78
79MemoryBlock
80Memory::allocateMappedMemory(size_t NumBytes,
81 const MemoryBlock *const NearBlock,
82 unsigned PFlags,
83 error_code &EC) {
84 EC = error_code::success();
85 if (NumBytes == 0)
86 return MemoryBlock();
87
Chandler Carruthacd64be2012-12-31 23:31:56 +000088 static const size_t PageSize = process::get_self()->page_size();
Andrew Kaylor1f661002012-09-19 20:46:12 +000089 const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
90
91 int fd = -1;
92#ifdef NEED_DEV_ZERO_FOR_MMAP
93 static int zero_fd = open("/dev/zero", O_RDWR);
94 if (zero_fd == -1) {
95 EC = error_code(errno, system_category());
96 return MemoryBlock();
97 }
98 fd = zero_fd;
99#endif
100
101 int MMFlags = MAP_PRIVATE |
102#ifdef HAVE_MMAP_ANONYMOUS
103 MAP_ANONYMOUS
104#else
105 MAP_ANON
106#endif
107 ; // Ends statement above
108
109 int Protect = getPosixProtectionFlags(PFlags);
110
111 // Use any near hint and the page size to set a page-aligned starting address
112 uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
113 NearBlock->size() : 0;
114 if (Start && Start % PageSize)
115 Start += PageSize - Start % PageSize;
116
117 void *Addr = ::mmap(reinterpret_cast<void*>(Start), PageSize*NumPages,
118 Protect, MMFlags, fd, 0);
119 if (Addr == MAP_FAILED) {
120 if (NearBlock) //Try again without a near hint
121 return allocateMappedMemory(NumBytes, 0, PFlags, EC);
122
123 EC = error_code(errno, system_category());
124 return MemoryBlock();
125 }
126
127 MemoryBlock Result;
128 Result.Address = Addr;
129 Result.Size = NumPages*PageSize;
130
131 if (PFlags & MF_EXEC)
132 Memory::InvalidateInstructionCache(Result.Address, Result.Size);
133
134 return Result;
135}
136
137error_code
138Memory::releaseMappedMemory(MemoryBlock &M) {
139 if (M.Address == 0 || M.Size == 0)
140 return error_code::success();
141
142 if (0 != ::munmap(M.Address, M.Size))
143 return error_code(errno, system_category());
144
145 M.Address = 0;
146 M.Size = 0;
147
148 return error_code::success();
149}
150
151error_code
152Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
153 if (M.Address == 0 || M.Size == 0)
154 return error_code::success();
155
156 if (!Flags)
157 return error_code(EINVAL, generic_category());
158
159 int Protect = getPosixProtectionFlags(Flags);
160
161 int Result = ::mprotect(M.Address, M.Size, Protect);
162 if (Result != 0)
163 return error_code(errno, system_category());
164
165 if (Flags & MF_EXEC)
166 Memory::InvalidateInstructionCache(M.Address, M.Size);
167
168 return error_code::success();
169}
170
Evan Cheng7c5dbd92008-09-16 17:28:18 +0000171/// AllocateRWX - Allocate a slab of memory with read/write/execute
Reid Spencer47cd6532004-12-27 06:17:03 +0000172/// permissions. This is typically used for JIT applications where we want
173/// to emit code to the memory then jump to it. Getting this type of memory
174/// is very OS specific.
175///
Andrew Kaylor1f661002012-09-19 20:46:12 +0000176MemoryBlock
177Memory::AllocateRWX(size_t NumBytes, const MemoryBlock* NearBlock,
178 std::string *ErrMsg) {
Reid Spencer47cd6532004-12-27 06:17:03 +0000179 if (NumBytes == 0) return MemoryBlock();
180
Chandler Carruthacd64be2012-12-31 23:31:56 +0000181 size_t PageSize = process::get_self()->page_size();
182 size_t NumPages = (NumBytes+PageSize-1)/PageSize;
Reid Spencer47cd6532004-12-27 06:17:03 +0000183
184 int fd = -1;
185#ifdef NEED_DEV_ZERO_FOR_MMAP
186 static int zero_fd = open("/dev/zero", O_RDWR);
187 if (zero_fd == -1) {
Reid Spencere4ca7222006-08-23 20:34:57 +0000188 MakeErrMsg(ErrMsg, "Can't open /dev/zero device");
Chris Lattner5a9d2e52006-07-07 17:32:37 +0000189 return MemoryBlock();
Reid Spencer47cd6532004-12-27 06:17:03 +0000190 }
191 fd = zero_fd;
192#endif
193
194 int flags = MAP_PRIVATE |
195#ifdef HAVE_MMAP_ANONYMOUS
196 MAP_ANONYMOUS
197#else
198 MAP_ANON
199#endif
200 ;
Andrew Lenharth09402182005-07-29 23:40:16 +0000201
Michael J. Spencer447762d2010-11-29 18:16:10 +0000202 void* start = NearBlock ? (unsigned char*)NearBlock->base() +
Chris Lattner5a9d2e52006-07-07 17:32:37 +0000203 NearBlock->size() : 0;
Andrew Lenharth09402182005-07-29 23:40:16 +0000204
Evan Cheng5cc53c32008-09-18 07:54:21 +0000205#if defined(__APPLE__) && defined(__arm__)
Chandler Carruthacd64be2012-12-31 23:31:56 +0000206 void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_EXEC,
Evan Cheng5cc53c32008-09-18 07:54:21 +0000207 flags, fd, 0);
208#else
Chandler Carruthacd64be2012-12-31 23:31:56 +0000209 void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
Reid Spencer47cd6532004-12-27 06:17:03 +0000210 flags, fd, 0);
Evan Cheng5cc53c32008-09-18 07:54:21 +0000211#endif
Reid Spencer47cd6532004-12-27 06:17:03 +0000212 if (pa == MAP_FAILED) {
Andrew Lenharth09402182005-07-29 23:40:16 +0000213 if (NearBlock) //Try again without a near hint
214 return AllocateRWX(NumBytes, 0);
Chris Lattner5a9d2e52006-07-07 17:32:37 +0000215
Reid Spencere4ca7222006-08-23 20:34:57 +0000216 MakeErrMsg(ErrMsg, "Can't allocate RWX Memory");
Chris Lattner5a9d2e52006-07-07 17:32:37 +0000217 return MemoryBlock();
Reid Spencer47cd6532004-12-27 06:17:03 +0000218 }
Evan Cheng5cc53c32008-09-18 07:54:21 +0000219
220#if defined(__APPLE__) && defined(__arm__)
221 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)pa,
Chandler Carruthacd64be2012-12-31 23:31:56 +0000222 (vm_size_t)(PageSize*NumPages), 0,
Evan Cheng5cc53c32008-09-18 07:54:21 +0000223 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
224 if (KERN_SUCCESS != kr) {
Daniel Dunbar3222b9b2009-04-20 20:50:13 +0000225 MakeErrMsg(ErrMsg, "vm_protect max RX failed");
Andrew Kaylor1f661002012-09-19 20:46:12 +0000226 return MemoryBlock();
Evan Cheng5cc53c32008-09-18 07:54:21 +0000227 }
228
229 kr = vm_protect(mach_task_self(), (vm_address_t)pa,
Chandler Carruthacd64be2012-12-31 23:31:56 +0000230 (vm_size_t)(PageSize*NumPages), 0,
Evan Cheng5cc53c32008-09-18 07:54:21 +0000231 VM_PROT_READ | VM_PROT_WRITE);
232 if (KERN_SUCCESS != kr) {
Daniel Dunbar3222b9b2009-04-20 20:50:13 +0000233 MakeErrMsg(ErrMsg, "vm_protect RW failed");
Andrew Kaylor1f661002012-09-19 20:46:12 +0000234 return MemoryBlock();
Evan Cheng5cc53c32008-09-18 07:54:21 +0000235 }
236#endif
237
Reid Spencer47cd6532004-12-27 06:17:03 +0000238 MemoryBlock result;
239 result.Address = pa;
Chandler Carruthacd64be2012-12-31 23:31:56 +0000240 result.Size = NumPages*PageSize;
Evan Cheng5cc53c32008-09-18 07:54:21 +0000241
Reid Spencer47cd6532004-12-27 06:17:03 +0000242 return result;
243}
244
Andrew Kaylor1f661002012-09-19 20:46:12 +0000245bool Memory::ReleaseRWX(MemoryBlock &M, std::string *ErrMsg) {
Chris Lattner5a9d2e52006-07-07 17:32:37 +0000246 if (M.Address == 0 || M.Size == 0) return false;
247 if (0 != ::munmap(M.Address, M.Size))
Reid Spencere4ca7222006-08-23 20:34:57 +0000248 return MakeErrMsg(ErrMsg, "Can't release RWX Memory");
Chris Lattner5a9d2e52006-07-07 17:32:37 +0000249 return false;
Reid Spencer2896c952004-09-11 04:57:25 +0000250}
251
Andrew Kaylor1f661002012-09-19 20:46:12 +0000252bool Memory::setWritable (MemoryBlock &M, std::string *ErrMsg) {
Jim Grosbachb22ef712008-10-03 16:17:20 +0000253#if defined(__APPLE__) && defined(__arm__)
254 if (M.Address == 0 || M.Size == 0) return false;
Andrew Kaylor1f661002012-09-19 20:46:12 +0000255 Memory::InvalidateInstructionCache(M.Address, M.Size);
Jim Grosbachb22ef712008-10-03 16:17:20 +0000256 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
257 (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_WRITE);
258 return KERN_SUCCESS == kr;
259#else
260 return true;
261#endif
262}
263
Andrew Kaylor1f661002012-09-19 20:46:12 +0000264bool Memory::setExecutable (MemoryBlock &M, std::string *ErrMsg) {
Jim Grosbachb22ef712008-10-03 16:17:20 +0000265#if defined(__APPLE__) && defined(__arm__)
266 if (M.Address == 0 || M.Size == 0) return false;
Andrew Kaylor1f661002012-09-19 20:46:12 +0000267 Memory::InvalidateInstructionCache(M.Address, M.Size);
Jim Grosbachb22ef712008-10-03 16:17:20 +0000268 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
269 (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
270 return KERN_SUCCESS == kr;
Tim Northover77d0a4a2013-05-19 15:28:16 +0000271#elif defined(__arm__) || defined(__aarch64__)
272 Memory::InvalidateInstructionCache(M.Address, M.Size);
273 return true;
Jim Grosbachb22ef712008-10-03 16:17:20 +0000274#else
Jim Grosbach806d5072011-03-18 18:51:03 +0000275 return true;
Jim Grosbachb22ef712008-10-03 16:17:20 +0000276#endif
277}
278
Andrew Kaylor1f661002012-09-19 20:46:12 +0000279bool Memory::setRangeWritable(const void *Addr, size_t Size) {
Jim Grosbach93960512008-10-20 21:39:23 +0000280#if defined(__APPLE__) && defined(__arm__)
281 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
282 (vm_size_t)Size, 0,
283 VM_PROT_READ | VM_PROT_WRITE);
284 return KERN_SUCCESS == kr;
285#else
286 return true;
287#endif
288}
289
Andrew Kaylor1f661002012-09-19 20:46:12 +0000290bool Memory::setRangeExecutable(const void *Addr, size_t Size) {
Jim Grosbach93960512008-10-20 21:39:23 +0000291#if defined(__APPLE__) && defined(__arm__)
292 kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
293 (vm_size_t)Size, 0,
294 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
295 return KERN_SUCCESS == kr;
296#else
297 return true;
298#endif
299}
Andrew Kaylor1f661002012-09-19 20:46:12 +0000300
301/// InvalidateInstructionCache - Before the JIT can run a block of code
302/// that has been emitted it must invalidate the instruction cache on some
303/// platforms.
304void Memory::InvalidateInstructionCache(const void *Addr,
305 size_t Len) {
306
307// icache invalidation for PPC and ARM.
308#if defined(__APPLE__)
309
310# if (defined(__POWERPC__) || defined (__ppc__) || \
311 defined(_POWER) || defined(_ARCH_PPC)) || defined(__arm__)
312 sys_icache_invalidate(const_cast<void *>(Addr), Len);
313# endif
314
315#else
316
317# if (defined(__POWERPC__) || defined (__ppc__) || \
318 defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
319 const size_t LineSize = 32;
320
321 const intptr_t Mask = ~(LineSize - 1);
322 const intptr_t StartLine = ((intptr_t) Addr) & Mask;
323 const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
324
325 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
326 asm volatile("dcbf 0, %0" : : "r"(Line));
327 asm volatile("sync");
328
329 for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
330 asm volatile("icbi 0, %0" : : "r"(Line));
331 asm volatile("isync");
Tim Northover6c26b322013-05-04 18:52:44 +0000332# elif (defined(__arm__) || defined(__aarch64__)) && defined(__GNUC__)
Andrew Kaylor1f661002012-09-19 20:46:12 +0000333 // FIXME: Can we safely always call this for __GNUC__ everywhere?
334 const char *Start = static_cast<const char *>(Addr);
335 const char *End = Start + Len;
336 __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
337# elif defined(__mips__)
338 const char *Start = static_cast<const char *>(Addr);
Akira Hatanaka7239a602013-03-14 19:01:00 +0000339# if defined(ANDROID)
340 // The declaration of "cacheflush" in Android bionic:
341 // extern int cacheflush(long start, long end, long flags);
342 const char *End = Start + Len;
343 long LStart = reinterpret_cast<long>(const_cast<char *>(Start));
344 long LEnd = reinterpret_cast<long>(const_cast<char *>(End));
345 cacheflush(LStart, LEnd, BCACHE);
346# else
Andrew Kaylor1f661002012-09-19 20:46:12 +0000347 cacheflush(const_cast<char *>(Start), Len, BCACHE);
Akira Hatanaka7239a602013-03-14 19:01:00 +0000348# endif
Andrew Kaylor1f661002012-09-19 20:46:12 +0000349# endif
350
351#endif // end apple
352
353 ValgrindDiscardTranslations(Addr, Len);
354}
355
356} // namespace sys
357} // namespace llvm