Memory.inc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. //===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines some functions for various memory management utilities.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "Unix.h"
  13. #include "llvm/Config/config.h"
  14. #include "llvm/Support/Alignment.h"
  15. #include "llvm/Support/DataTypes.h"
  16. #include "llvm/Support/ErrorHandling.h"
  17. #include "llvm/Support/Process.h"
  18. #ifdef HAVE_SYS_MMAN_H
  19. #include <sys/mman.h>
  20. #endif
  21. #ifdef __APPLE__
  22. #include <mach/mach.h>
  23. #endif
  24. #ifdef __Fuchsia__
  25. #include <zircon/syscalls.h>
  26. #endif
  27. #if defined(__APPLE__)
  28. extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
  29. #else
  30. extern "C" void __clear_cache(void *, void*);
  31. #endif
  32. static int getPosixProtectionFlags(unsigned Flags) {
  33. switch (Flags & llvm::sys::Memory::MF_RWE_MASK) {
  34. case llvm::sys::Memory::MF_READ:
  35. return PROT_READ;
  36. case llvm::sys::Memory::MF_WRITE:
  37. return PROT_WRITE;
  38. case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
  39. return PROT_READ | PROT_WRITE;
  40. case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
  41. return PROT_READ | PROT_EXEC;
  42. case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE |
  43. llvm::sys::Memory::MF_EXEC:
  44. return PROT_READ | PROT_WRITE | PROT_EXEC;
  45. case llvm::sys::Memory::MF_EXEC:
  46. #if (defined(__FreeBSD__) || defined(__POWERPC__) || defined (__ppc__) || \
  47. defined(_POWER) || defined(_ARCH_PPC))
  48. // On PowerPC, having an executable page that has no read permission
  49. // can have unintended consequences. The function InvalidateInstruction-
  50. // Cache uses instructions dcbf and icbi, both of which are treated by
  51. // the processor as loads. If the page has no read permissions,
  52. // executing these instructions will result in a segmentation fault.
  53. return PROT_READ | PROT_EXEC;
  54. #else
  55. return PROT_EXEC;
  56. #endif
  57. default:
  58. llvm_unreachable("Illegal memory protection flag specified!");
  59. }
  60. // Provide a default return value as required by some compilers.
  61. return PROT_NONE;
  62. }
  63. namespace llvm {
  64. namespace sys {
  65. MemoryBlock
  66. Memory::allocateMappedMemory(size_t NumBytes,
  67. const MemoryBlock *const NearBlock,
  68. unsigned PFlags,
  69. std::error_code &EC) {
  70. EC = std::error_code();
  71. if (NumBytes == 0)
  72. return MemoryBlock();
  73. // On platforms that have it, we can use MAP_ANON to get a memory-mapped
  74. // page without file backing, but we need a fallback of opening /dev/zero
  75. // for strictly POSIX platforms instead.
  76. int fd;
  77. #if defined(MAP_ANON)
  78. fd = -1;
  79. #else
  80. fd = open("/dev/zero", O_RDWR);
  81. if (fd == -1) {
  82. EC = std::error_code(errno, std::generic_category());
  83. return MemoryBlock();
  84. }
  85. #endif
  86. int MMFlags = MAP_PRIVATE;
  87. #if defined(MAP_ANON)
  88. MMFlags |= MAP_ANON;
  89. #endif
  90. int Protect = getPosixProtectionFlags(PFlags);
  91. #if defined(__NetBSD__) && defined(PROT_MPROTECT)
  92. Protect |= PROT_MPROTECT(PROT_READ | PROT_WRITE | PROT_EXEC);
  93. #endif
  94. // Use any near hint and the page size to set a page-aligned starting address
  95. uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
  96. NearBlock->allocatedSize() : 0;
  97. static const size_t PageSize = Process::getPageSizeEstimate();
  98. const size_t NumPages = (NumBytes+PageSize-1)/PageSize;
  99. if (Start && Start % PageSize)
  100. Start += PageSize - Start % PageSize;
  101. // FIXME: Handle huge page requests (MF_HUGE_HINT).
  102. void *Addr = ::mmap(reinterpret_cast<void *>(Start), PageSize*NumPages, Protect,
  103. MMFlags, fd, 0);
  104. if (Addr == MAP_FAILED) {
  105. if (NearBlock) { //Try again without a near hint
  106. #if !defined(MAP_ANON)
  107. close(fd);
  108. #endif
  109. return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
  110. }
  111. EC = std::error_code(errno, std::generic_category());
  112. #if !defined(MAP_ANON)
  113. close(fd);
  114. #endif
  115. return MemoryBlock();
  116. }
  117. #if !defined(MAP_ANON)
  118. close(fd);
  119. #endif
  120. MemoryBlock Result;
  121. Result.Address = Addr;
  122. Result.AllocatedSize = PageSize*NumPages;
  123. Result.Flags = PFlags;
  124. // Rely on protectMappedMemory to invalidate instruction cache.
  125. if (PFlags & MF_EXEC) {
  126. EC = Memory::protectMappedMemory (Result, PFlags);
  127. if (EC != std::error_code())
  128. return MemoryBlock();
  129. }
  130. return Result;
  131. }
  132. std::error_code
  133. Memory::releaseMappedMemory(MemoryBlock &M) {
  134. if (M.Address == nullptr || M.AllocatedSize == 0)
  135. return std::error_code();
  136. if (0 != ::munmap(M.Address, M.AllocatedSize))
  137. return std::error_code(errno, std::generic_category());
  138. M.Address = nullptr;
  139. M.AllocatedSize = 0;
  140. return std::error_code();
  141. }
  142. std::error_code
  143. Memory::protectMappedMemory(const MemoryBlock &M, unsigned Flags) {
  144. static const Align PageSize = Align(Process::getPageSizeEstimate());
  145. if (M.Address == nullptr || M.AllocatedSize == 0)
  146. return std::error_code();
  147. if (!Flags)
  148. return std::error_code(EINVAL, std::generic_category());
  149. int Protect = getPosixProtectionFlags(Flags);
  150. uintptr_t Start = alignAddr((const uint8_t *)M.Address - PageSize.value() + 1, PageSize);
  151. uintptr_t End = alignAddr((const uint8_t *)M.Address + M.AllocatedSize, PageSize);
  152. bool InvalidateCache = (Flags & MF_EXEC);
  153. #if defined(__arm__) || defined(__aarch64__)
  154. // Certain ARM implementations treat icache clear instruction as a memory read,
  155. // and CPU segfaults on trying to clear cache on !PROT_READ page. Therefore we need
  156. // to temporarily add PROT_READ for the sake of flushing the instruction caches.
  157. if (InvalidateCache && !(Protect & PROT_READ)) {
  158. int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
  159. if (Result != 0)
  160. return std::error_code(errno, std::generic_category());
  161. Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
  162. InvalidateCache = false;
  163. }
  164. #endif
  165. int Result = ::mprotect((void *)Start, End - Start, Protect);
  166. if (Result != 0)
  167. return std::error_code(errno, std::generic_category());
  168. if (InvalidateCache)
  169. Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
  170. return std::error_code();
  171. }
  172. /// InvalidateInstructionCache - Before the JIT can run a block of code
  173. /// that has been emitted it must invalidate the instruction cache on some
  174. /// platforms.
  175. void Memory::InvalidateInstructionCache(const void *Addr,
  176. size_t Len) {
  177. // icache invalidation for PPC and ARM.
  178. #if defined(__APPLE__)
  179. # if (defined(__POWERPC__) || defined (__ppc__) || \
  180. defined(_POWER) || defined(_ARCH_PPC) || defined(__arm__) || \
  181. defined(__arm64__))
  182. sys_icache_invalidate(const_cast<void *>(Addr), Len);
  183. # endif
  184. #elif defined(__Fuchsia__)
  185. zx_status_t Status = zx_cache_flush(Addr, Len, ZX_CACHE_FLUSH_INSN);
  186. assert(Status == ZX_OK && "cannot invalidate instruction cache");
  187. #else
  188. # if (defined(__POWERPC__) || defined (__ppc__) || \
  189. defined(_POWER) || defined(_ARCH_PPC)) && defined(__GNUC__)
  190. const size_t LineSize = 32;
  191. const intptr_t Mask = ~(LineSize - 1);
  192. const intptr_t StartLine = ((intptr_t) Addr) & Mask;
  193. const intptr_t EndLine = ((intptr_t) Addr + Len + LineSize - 1) & Mask;
  194. for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
  195. asm volatile("dcbf 0, %0" : : "r"(Line));
  196. asm volatile("sync");
  197. for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
  198. asm volatile("icbi 0, %0" : : "r"(Line));
  199. asm volatile("isync");
  200. # elif (defined(__arm__) || defined(__aarch64__) || defined(__mips__)) && \
  201. defined(__GNUC__)
  202. // FIXME: Can we safely always call this for __GNUC__ everywhere?
  203. const char *Start = static_cast<const char *>(Addr);
  204. const char *End = Start + Len;
  205. __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
  206. # endif
  207. #endif // end apple
  208. ValgrindDiscardTranslations(Addr, Len);
  209. }
  210. } // namespace sys
  211. } // namespace llvm