Memory.inc 10 KB

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