On PowerPC, the cache-flush instructions dcbf and icbi are treated as
[oota-llvm.git] / lib / Support / Unix / Memory.inc
1 //===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines some functions for various memory management utilities.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Unix.h"
15 #include "llvm/Support/DataTypes.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include "llvm/Support/Process.h"
18
19 #ifdef HAVE_SYS_MMAN_H
20 #include <sys/mman.h>
21 #endif
22
23 #ifdef __APPLE__
24 #include <mach/mach.h>
25 #endif
26
27 #if defined(__mips__)
28 #  if defined(__OpenBSD__)
29 #    include <mips64/sysarch.h>
30 #  else
31 #    include <sys/cachectl.h>
32 #  endif
33 #endif
34
35 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
36
37 namespace {
38
39 int getPosixProtectionFlags(unsigned Flags) {
40   switch (Flags) {
41   case llvm::sys::Memory::MF_READ:
42     return PROT_READ;
43   case llvm::sys::Memory::MF_WRITE:
44     return PROT_WRITE;
45   case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
46     return PROT_READ | PROT_WRITE;
47   case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
48     return PROT_READ | PROT_EXEC;
49   case llvm::sys::Memory::MF_READ |
50          llvm::sys::Memory::MF_WRITE |
51          llvm::sys::Memory::MF_EXEC:
52     return PROT_READ | PROT_WRITE | PROT_EXEC;
53   case llvm::sys::Memory::MF_EXEC:
54 #if defined(__FreeBSD__)
55     return PROT_READ | PROT_EXEC;
56 #else
57     return PROT_EXEC;
58 #endif
59   default:
60     llvm_unreachable("Illegal memory protection flag specified!");
61   }
62   // Provide a default return value as required by some compilers.
63   return PROT_NONE;
64 }
65
66 } // namespace
67
68 namespace llvm {
69 namespace sys {
70
71 MemoryBlock
72 Memory::allocateMappedMemory(size_t NumBytes,
73                              const MemoryBlock *const NearBlock,
74                              unsigned PFlags,
75                              error_code &EC) {
76   EC = error_code::success();
77   if (NumBytes == 0)
78     return MemoryBlock();
79
80   static const size_t PageSize = process::get_self()->page_size();
81   const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
82
83   int fd = -1;
84 #ifdef NEED_DEV_ZERO_FOR_MMAP
85   static int zero_fd = open("/dev/zero", O_RDWR);
86   if (zero_fd == -1) {
87     EC = error_code(errno, system_category());
88     return MemoryBlock();
89   }
90   fd = zero_fd;
91 #endif
92
93   int MMFlags = MAP_PRIVATE |
94 #ifdef HAVE_MMAP_ANONYMOUS
95   MAP_ANONYMOUS
96 #else
97   MAP_ANON
98 #endif
99   ; // Ends statement above
100
101   int Protect = getPosixProtectionFlags(PFlags);
102
103   // Use any near hint and the page size to set a page-aligned starting address
104   uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
105                                       NearBlock->size() : 0;
106   if (Start && Start % PageSize)
107     Start += PageSize - Start % PageSize;
108
109   void *Addr = ::mmap(reinterpret_cast<void*>(Start), PageSize*NumPages,
110                       Protect, MMFlags, fd, 0);
111   if (Addr == MAP_FAILED) {
112     if (NearBlock) //Try again without a near hint
113       return allocateMappedMemory(NumBytes, 0, PFlags, EC);
114
115     EC = error_code(errno, system_category());
116     return MemoryBlock();
117   }
118
119   MemoryBlock Result;
120   Result.Address = Addr;
121   Result.Size = NumPages*PageSize;
122
123   if (PFlags & MF_EXEC)
124     Memory::InvalidateInstructionCache(Result.Address, Result.Size);
125
126   return Result;
127 }
128
129 error_code
130 Memory::releaseMappedMemory(MemoryBlock &M) {
131   if (M.Address == 0 || M.Size == 0)
132     return error_code::success();
133
134   if (0 != ::munmap(M.Address, M.Size))
135     return error_code(errno, system_category());
136
137   M.Address = 0;
138   M.Size = 0;
139
140   return error_code::success();
141 }
142
143 error_code
144 Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
145   if (M.Address == 0 || M.Size == 0)
146     return error_code::success();
147
148   if (!Flags)
149     return error_code(EINVAL, generic_category());
150
151   int Protect = getPosixProtectionFlags(Flags);
152
153   int Result = ::mprotect(M.Address, M.Size, Protect);
154   if (Result != 0)
155     return error_code(errno, system_category());
156
157   if (Flags & MF_EXEC)
158     Memory::InvalidateInstructionCache(M.Address, M.Size);
159
160   return error_code::success();
161 }
162
163 /// AllocateRWX - Allocate a slab of memory with read/write/execute
164 /// permissions.  This is typically used for JIT applications where we want
165 /// to emit code to the memory then jump to it.  Getting this type of memory
166 /// is very OS specific.
167 ///
168 MemoryBlock
169 Memory::AllocateRWX(size_t NumBytes, const MemoryBlock* NearBlock,
170                     std::string *ErrMsg) {
171   if (NumBytes == 0) return MemoryBlock();
172
173   size_t PageSize = process::get_self()->page_size();
174   size_t NumPages = (NumBytes+PageSize-1)/PageSize;
175
176   int fd = -1;
177 #ifdef NEED_DEV_ZERO_FOR_MMAP
178   static int zero_fd = open("/dev/zero", O_RDWR);
179   if (zero_fd == -1) {
180     MakeErrMsg(ErrMsg, "Can't open /dev/zero device");
181     return MemoryBlock();
182   }
183   fd = zero_fd;
184 #endif
185
186   int flags = MAP_PRIVATE |
187 #ifdef HAVE_MMAP_ANONYMOUS
188   MAP_ANONYMOUS
189 #else
190   MAP_ANON
191 #endif
192   ;
193
194   void* start = NearBlock ? (unsigned char*)NearBlock->base() +
195                             NearBlock->size() : 0;
196
197 #if defined(__APPLE__) && defined(__arm__)
198   void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_EXEC,
199                     flags, fd, 0);
200 #else
201   void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
202                     flags, fd, 0);
203 #endif
204   if (pa == MAP_FAILED) {
205     if (NearBlock) //Try again without a near hint
206       return AllocateRWX(NumBytes, 0);
207
208     MakeErrMsg(ErrMsg, "Can't allocate RWX Memory");
209     return MemoryBlock();
210   }
211
212 #if defined(__APPLE__) && defined(__arm__)
213   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)pa,
214                                 (vm_size_t)(PageSize*NumPages), 0,
215                                 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
216   if (KERN_SUCCESS != kr) {
217     MakeErrMsg(ErrMsg, "vm_protect max RX failed");
218     return MemoryBlock();
219   }
220
221   kr = vm_protect(mach_task_self(), (vm_address_t)pa,
222                   (vm_size_t)(PageSize*NumPages), 0,
223                   VM_PROT_READ | VM_PROT_WRITE);
224   if (KERN_SUCCESS != kr) {
225     MakeErrMsg(ErrMsg, "vm_protect RW failed");
226     return MemoryBlock();
227   }
228 #endif
229
230   MemoryBlock result;
231   result.Address = pa;
232   result.Size = NumPages*PageSize;
233
234   return result;
235 }
236
237 bool Memory::ReleaseRWX(MemoryBlock &M, std::string *ErrMsg) {
238   if (M.Address == 0 || M.Size == 0) return false;
239   if (0 != ::munmap(M.Address, M.Size))
240     return MakeErrMsg(ErrMsg, "Can't release RWX Memory");
241   return false;
242 }
243
244 bool Memory::setWritable (MemoryBlock &M, std::string *ErrMsg) {
245 #if defined(__APPLE__) && defined(__arm__)
246   if (M.Address == 0 || M.Size == 0) return false;
247   Memory::InvalidateInstructionCache(M.Address, M.Size);
248   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
249     (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_WRITE);
250   return KERN_SUCCESS == kr;
251 #else
252   return true;
253 #endif
254 }
255
256 bool Memory::setExecutable (MemoryBlock &M, std::string *ErrMsg) {
257 #if defined(__APPLE__) && defined(__arm__)
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_EXECUTE | VM_PROT_COPY);
262   return KERN_SUCCESS == kr;
263 #else
264   return true;
265 #endif
266 }
267
268 bool Memory::setRangeWritable(const void *Addr, size_t Size) {
269 #if defined(__APPLE__) && defined(__arm__)
270   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
271                                 (vm_size_t)Size, 0,
272                                 VM_PROT_READ | VM_PROT_WRITE);
273   return KERN_SUCCESS == kr;
274 #else
275   return true;
276 #endif
277 }
278
279 bool Memory::setRangeExecutable(const void *Addr, size_t Size) {
280 #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_EXECUTE | VM_PROT_COPY);
284   return KERN_SUCCESS == kr;
285 #else
286   return true;
287 #endif
288 }
289
290 /// InvalidateInstructionCache - Before the JIT can run a block of code
291 /// that has been emitted it must invalidate the instruction cache on some
292 /// platforms.
293 void Memory::InvalidateInstructionCache(const void *Addr,
294                                         size_t Len) {
295
296 // icache invalidation for PPC and ARM.
297 #if defined(__APPLE__)
298
299 #  if (defined(__POWERPC__) || defined (__ppc__) || \
300      defined(_POWER) || defined(_ARCH_PPC)) || defined(__arm__)
301   sys_icache_invalidate(const_cast<void *>(Addr), Len);
302 #  endif
303
304 #else
305
306 #  if (defined(__POWERPC__) || defined (__ppc__) || \
307        defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
308   const size_t LineSize = 32;
309
310   const intptr_t Mask = ~(LineSize - 1);
311   const intptr_t StartLine = ((intptr_t) Addr) & Mask;
312   const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
313
314   for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
315     asm volatile("dcbf 0, %0" : : "r"(Line));
316   asm volatile("sync");
317
318   for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
319     asm volatile("icbi 0, %0" : : "r"(Line));
320   asm volatile("isync");
321 #  elif defined(__arm__) && defined(__GNUC__)
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));
326 #  elif defined(__mips__)
327   const char *Start = static_cast<const char *>(Addr);
328   cacheflush(const_cast<char *>(Start), Len, BCACHE);
329 #  endif
330
331 #endif  // end apple
332
333   ValgrindDiscardTranslations(Addr, Len);
334 }
335
336 } // namespace sys
337 } // namespace llvm