Don't use 'using std::error_code' in include/llvm.
[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 #ifdef __APPLE__
36 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
37 #else
38 extern "C" void __clear_cache(void *, void*);
39 #endif
40 using std::error_code;
41
42 namespace {
43
44 int getPosixProtectionFlags(unsigned Flags) {
45   switch (Flags) {
46   case llvm::sys::Memory::MF_READ:
47     return PROT_READ;
48   case llvm::sys::Memory::MF_WRITE:
49     return PROT_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
66     // on FreeBSD.
67     return PROT_READ | PROT_EXEC;
68 #else
69     return PROT_EXEC;
70 #endif
71   default:
72     llvm_unreachable("Illegal memory protection flag specified!");
73   }
74   // Provide a default return value as required by some compilers.
75   return PROT_NONE;
76 }
77
78 } // namespace
79
80 namespace llvm {
81 namespace sys {
82
83 MemoryBlock
84 Memory::allocateMappedMemory(size_t NumBytes,
85                              const MemoryBlock *const NearBlock,
86                              unsigned PFlags,
87                              error_code &EC) {
88   EC = error_code();
89   if (NumBytes == 0)
90     return MemoryBlock();
91
92   static const size_t PageSize = process::get_self()->page_size();
93   const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
94
95   int fd = -1;
96 #ifdef NEED_DEV_ZERO_FOR_MMAP
97   static int zero_fd = open("/dev/zero", O_RDWR);
98   if (zero_fd == -1) {
99     EC = error_code(errno, std::generic_category());
100     return MemoryBlock();
101   }
102   fd = zero_fd;
103 #endif
104
105   int MMFlags = MAP_PRIVATE |
106 #ifdef HAVE_MMAP_ANONYMOUS
107   MAP_ANONYMOUS
108 #else
109   MAP_ANON
110 #endif
111   ; // Ends statement above
112
113   int Protect = getPosixProtectionFlags(PFlags);
114
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;
120
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);
126
127     EC = error_code(errno, std::generic_category());
128     return MemoryBlock();
129   }
130
131   MemoryBlock Result;
132   Result.Address = Addr;
133   Result.Size = NumPages*PageSize;
134
135   if (PFlags & MF_EXEC)
136     Memory::InvalidateInstructionCache(Result.Address, Result.Size);
137
138   return Result;
139 }
140
141 error_code
142 Memory::releaseMappedMemory(MemoryBlock &M) {
143   if (M.Address == nullptr || M.Size == 0)
144     return error_code();
145
146   if (0 != ::munmap(M.Address, M.Size))
147     return error_code(errno, std::generic_category());
148
149   M.Address = nullptr;
150   M.Size = 0;
151
152   return error_code();
153 }
154
155 error_code
156 Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
157   if (M.Address == nullptr || M.Size == 0)
158     return error_code();
159
160   if (!Flags)
161     return error_code(EINVAL, std::generic_category());
162
163   int Protect = getPosixProtectionFlags(Flags);
164
165   int Result = ::mprotect(M.Address, M.Size, Protect);
166   if (Result != 0)
167     return error_code(errno, std::generic_category());
168
169   if (Flags & MF_EXEC)
170     Memory::InvalidateInstructionCache(M.Address, M.Size);
171
172   return error_code();
173 }
174
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.
179 ///
180 MemoryBlock
181 Memory::AllocateRWX(size_t NumBytes, const MemoryBlock* NearBlock,
182                     std::string *ErrMsg) {
183   if (NumBytes == 0) return MemoryBlock();
184
185   size_t PageSize = process::get_self()->page_size();
186   size_t NumPages = (NumBytes+PageSize-1)/PageSize;
187
188   int fd = -1;
189 #ifdef NEED_DEV_ZERO_FOR_MMAP
190   static int zero_fd = open("/dev/zero", O_RDWR);
191   if (zero_fd == -1) {
192     MakeErrMsg(ErrMsg, "Can't open /dev/zero device");
193     return MemoryBlock();
194   }
195   fd = zero_fd;
196 #endif
197
198   int flags = MAP_PRIVATE |
199 #ifdef HAVE_MMAP_ANONYMOUS
200   MAP_ANONYMOUS
201 #else
202   MAP_ANON
203 #endif
204   ;
205
206   void* start = NearBlock ? (unsigned char*)NearBlock->base() +
207                             NearBlock->size() : nullptr;
208
209 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
210   void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_EXEC,
211                     flags, fd, 0);
212 #else
213   void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
214                     flags, fd, 0);
215 #endif
216   if (pa == MAP_FAILED) {
217     if (NearBlock) //Try again without a near hint
218       return AllocateRWX(NumBytes, nullptr);
219
220     MakeErrMsg(ErrMsg, "Can't allocate RWX Memory");
221     return MemoryBlock();
222   }
223
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();
231   }
232
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();
239   }
240 #endif
241
242   MemoryBlock result;
243   result.Address = pa;
244   result.Size = NumPages*PageSize;
245
246   return result;
247 }
248
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");
253   return false;
254 }
255
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;
263 #else
264   return true;
265 #endif
266 }
267
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);
277   return true;
278 #else
279   return true;
280 #endif
281 }
282
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,
286                                 (vm_size_t)Size, 0,
287                                 VM_PROT_READ | VM_PROT_WRITE);
288   return KERN_SUCCESS == kr;
289 #else
290   return true;
291 #endif
292 }
293
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,
297                                 (vm_size_t)Size, 0,
298                                 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
299   return KERN_SUCCESS == kr;
300 #else
301   return true;
302 #endif
303 }
304
305 /// InvalidateInstructionCache - Before the JIT can run a block of code
306 /// that has been emitted it must invalidate the instruction cache on some
307 /// platforms.
308 void Memory::InvalidateInstructionCache(const void *Addr,
309                                         size_t Len) {
310
311 // icache invalidation for PPC and ARM.
312 #if defined(__APPLE__)
313
314 #  if (defined(__POWERPC__) || defined (__ppc__) || \
315        defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
316        defined(__arm64__))
317   sys_icache_invalidate(const_cast<void *>(Addr), Len);
318 #  endif
319
320 #else
321
322 #  if (defined(__POWERPC__) || defined (__ppc__) || \
323        defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
324   const size_t LineSize = 32;
325
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;
329
330   for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
331     asm volatile("dcbf 0, %0" : : "r"(Line));
332   asm volatile("sync");
333
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);
351 #    else
352   cacheflush(const_cast<char *>(Start), Len, BCACHE);
353 #    endif
354 #  endif
355
356 #endif  // end apple
357
358   ValgrindDiscardTranslations(Addr, Len);
359 }
360
361 } // namespace sys
362 } // namespace llvm