Untabify.
[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
41 namespace {
42
43 int getPosixProtectionFlags(unsigned Flags) {
44   switch (Flags) {
45   case llvm::sys::Memory::MF_READ:
46     return PROT_READ;
47   case llvm::sys::Memory::MF_WRITE:
48     return PROT_WRITE;
49   case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
50     return PROT_READ | PROT_WRITE;
51   case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
52     return PROT_READ | PROT_EXEC;
53   case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE |
54       llvm::sys::Memory::MF_EXEC:
55     return PROT_READ | PROT_WRITE | PROT_EXEC;
56   case llvm::sys::Memory::MF_EXEC:
57 #if defined(__FreeBSD__)
58     // On PowerPC, having an executable page that has no read permission
59     // can have unintended consequences.  The function InvalidateInstruction-
60     // Cache uses instructions dcbf and icbi, both of which are treated by
61     // the processor as loads.  If the page has no read permissions,
62     // executing these instructions will result in a segmentation fault.
63     // Somehow, this problem is not present on Linux, but it does happen
64     // on FreeBSD.
65     return PROT_READ | PROT_EXEC;
66 #else
67     return PROT_EXEC;
68 #endif
69   default:
70     llvm_unreachable("Illegal memory protection flag specified!");
71   }
72   // Provide a default return value as required by some compilers.
73   return PROT_NONE;
74 }
75
76 } // namespace
77
78 namespace llvm {
79 namespace sys {
80
81 MemoryBlock
82 Memory::allocateMappedMemory(size_t NumBytes,
83                              const MemoryBlock *const NearBlock,
84                              unsigned PFlags,
85                              std::error_code &EC) {
86   EC = std::error_code();
87   if (NumBytes == 0)
88     return MemoryBlock();
89
90   static const size_t PageSize = Process::getPageSize();
91   const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
92
93   int fd = -1;
94 #ifdef NEED_DEV_ZERO_FOR_MMAP
95   static int zero_fd = open("/dev/zero", O_RDWR);
96   if (zero_fd == -1) {
97     EC = std::error_code(errno, std::generic_category());
98     return MemoryBlock();
99   }
100   fd = zero_fd;
101 #endif
102
103   int MMFlags = MAP_PRIVATE |
104 #ifdef HAVE_MMAP_ANONYMOUS
105   MAP_ANONYMOUS
106 #else
107   MAP_ANON
108 #endif
109   ; // Ends statement above
110
111   int Protect = getPosixProtectionFlags(PFlags);
112
113   // Use any near hint and the page size to set a page-aligned starting address
114   uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
115                                       NearBlock->size() : 0;
116   if (Start && Start % PageSize)
117     Start += PageSize - Start % PageSize;
118
119   void *Addr = ::mmap(reinterpret_cast<void*>(Start), PageSize*NumPages,
120                       Protect, MMFlags, fd, 0);
121   if (Addr == MAP_FAILED) {
122     if (NearBlock) //Try again without a near hint
123       return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
124
125     EC = std::error_code(errno, std::generic_category());
126     return MemoryBlock();
127   }
128
129   MemoryBlock Result;
130   Result.Address = Addr;
131   Result.Size = NumPages*PageSize;
132
133   if (PFlags & MF_EXEC)
134     Memory::InvalidateInstructionCache(Result.Address, Result.Size);
135
136   return Result;
137 }
138
139 std::error_code
140 Memory::releaseMappedMemory(MemoryBlock &M) {
141   if (M.Address == nullptr || M.Size == 0)
142     return std::error_code();
143
144   if (0 != ::munmap(M.Address, M.Size))
145     return std::error_code(errno, std::generic_category());
146
147   M.Address = nullptr;
148   M.Size = 0;
149
150   return std::error_code();
151 }
152
153 std::error_code
154 Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
155   if (M.Address == nullptr || M.Size == 0)
156     return std::error_code();
157
158   if (!Flags)
159     return std::error_code(EINVAL, std::generic_category());
160
161   int Protect = getPosixProtectionFlags(Flags);
162
163   int Result = ::mprotect(M.Address, M.Size, Protect);
164   if (Result != 0)
165     return std::error_code(errno, std::generic_category());
166
167   if (Flags & MF_EXEC)
168     Memory::InvalidateInstructionCache(M.Address, M.Size);
169
170   return std::error_code();
171 }
172
173 /// AllocateRWX - Allocate a slab of memory with read/write/execute
174 /// permissions.  This is typically used for JIT applications where we want
175 /// to emit code to the memory then jump to it.  Getting this type of memory
176 /// is very OS specific.
177 ///
178 MemoryBlock
179 Memory::AllocateRWX(size_t NumBytes, const MemoryBlock* NearBlock,
180                     std::string *ErrMsg) {
181   if (NumBytes == 0) return MemoryBlock();
182
183   size_t PageSize = Process::getPageSize();
184   size_t NumPages = (NumBytes+PageSize-1)/PageSize;
185
186   int fd = -1;
187 #ifdef NEED_DEV_ZERO_FOR_MMAP
188   static int zero_fd = open("/dev/zero", O_RDWR);
189   if (zero_fd == -1) {
190     MakeErrMsg(ErrMsg, "Can't open /dev/zero device");
191     return MemoryBlock();
192   }
193   fd = zero_fd;
194 #endif
195
196   int flags = MAP_PRIVATE |
197 #ifdef HAVE_MMAP_ANONYMOUS
198   MAP_ANONYMOUS
199 #else
200   MAP_ANON
201 #endif
202   ;
203
204   void* start = NearBlock ? (unsigned char*)NearBlock->base() +
205                             NearBlock->size() : nullptr;
206
207 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
208   void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_EXEC,
209                     flags, fd, 0);
210 #else
211   void *pa = ::mmap(start, PageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
212                     flags, fd, 0);
213 #endif
214   if (pa == MAP_FAILED) {
215     if (NearBlock) //Try again without a near hint
216       return AllocateRWX(NumBytes, nullptr);
217
218     MakeErrMsg(ErrMsg, "Can't allocate RWX Memory");
219     return MemoryBlock();
220   }
221
222 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
223   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)pa,
224                                 (vm_size_t)(PageSize*NumPages), 0,
225                                 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
226   if (KERN_SUCCESS != kr) {
227     MakeErrMsg(ErrMsg, "vm_protect max RX failed");
228     return MemoryBlock();
229   }
230
231   kr = vm_protect(mach_task_self(), (vm_address_t)pa,
232                   (vm_size_t)(PageSize*NumPages), 0,
233                   VM_PROT_READ | VM_PROT_WRITE);
234   if (KERN_SUCCESS != kr) {
235     MakeErrMsg(ErrMsg, "vm_protect RW failed");
236     return MemoryBlock();
237   }
238 #endif
239
240   MemoryBlock result;
241   result.Address = pa;
242   result.Size = NumPages*PageSize;
243
244   return result;
245 }
246
247 bool Memory::ReleaseRWX(MemoryBlock &M, std::string *ErrMsg) {
248   if (M.Address == nullptr || M.Size == 0) return false;
249   if (0 != ::munmap(M.Address, M.Size))
250     return MakeErrMsg(ErrMsg, "Can't release RWX Memory");
251   return false;
252 }
253
254 bool Memory::setWritable (MemoryBlock &M, std::string *ErrMsg) {
255 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
256   if (M.Address == 0 || M.Size == 0) return false;
257   Memory::InvalidateInstructionCache(M.Address, M.Size);
258   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
259     (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_WRITE);
260   return KERN_SUCCESS == kr;
261 #else
262   return true;
263 #endif
264 }
265
266 bool Memory::setExecutable (MemoryBlock &M, std::string *ErrMsg) {
267 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
268   if (M.Address == 0 || M.Size == 0) return false;
269   Memory::InvalidateInstructionCache(M.Address, M.Size);
270   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)M.Address,
271     (vm_size_t)M.Size, 0, VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
272   return KERN_SUCCESS == kr;
273 #elif defined(__arm__) || defined(__aarch64__)
274   Memory::InvalidateInstructionCache(M.Address, M.Size);
275   return true;
276 #else
277   return true;
278 #endif
279 }
280
281 bool Memory::setRangeWritable(const void *Addr, size_t Size) {
282 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
283   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
284                                 (vm_size_t)Size, 0,
285                                 VM_PROT_READ | VM_PROT_WRITE);
286   return KERN_SUCCESS == kr;
287 #else
288   return true;
289 #endif
290 }
291
292 bool Memory::setRangeExecutable(const void *Addr, size_t Size) {
293 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
294   kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)Addr,
295                                 (vm_size_t)Size, 0,
296                                 VM_PROT_READ | VM_PROT_EXECUTE | VM_PROT_COPY);
297   return KERN_SUCCESS == kr;
298 #else
299   return true;
300 #endif
301 }
302
303 /// InvalidateInstructionCache - Before the JIT can run a block of code
304 /// that has been emitted it must invalidate the instruction cache on some
305 /// platforms.
306 void Memory::InvalidateInstructionCache(const void *Addr,
307                                         size_t Len) {
308
309 // icache invalidation for PPC and ARM.
310 #if defined(__APPLE__)
311
312 #  if (defined(__POWERPC__) || defined (__ppc__) || \
313        defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
314        defined(__arm64__))
315   sys_icache_invalidate(const_cast<void *>(Addr), Len);
316 #  endif
317
318 #else
319
320 #  if (defined(__POWERPC__) || defined (__ppc__) || \
321        defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
322   const size_t LineSize = 32;
323
324   const intptr_t Mask = ~(LineSize - 1);
325   const intptr_t StartLine = ((intptr_t) Addr) & Mask;
326   const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
327
328   for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
329     asm volatile("dcbf 0, %0" : : "r"(Line));
330   asm volatile("sync");
331
332   for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
333     asm volatile("icbi 0, %0" : : "r"(Line));
334   asm volatile("isync");
335 #  elif (defined(__arm__) || defined(__aarch64__) || defined(__mips__)) && \
336         defined(__GNUC__)
337   // FIXME: Can we safely always call this for __GNUC__ everywhere?
338   const char *Start = static_cast<const char *>(Addr);
339   const char *End = Start + Len;
340   __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
341 #  endif
342
343 #endif  // end apple
344
345   ValgrindDiscardTranslations(Addr, Len);
346 }
347
348 } // namespace sys
349 } // namespace llvm