Memory.inc 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. #include "llvm/Support/Valgrind.h"
  19. #ifdef HAVE_SYS_MMAN_H
  20. #include <sys/mman.h>
  21. #endif
  22. #ifdef __APPLE__
  23. #include <mach/mach.h>
  24. #endif
  25. #ifdef __Fuchsia__
  26. #include <zircon/syscalls.h>
  27. #endif
  28. #if defined(__APPLE__)
  29. extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
  30. #else
  31. extern "C" void __clear_cache(void *, void *);
  32. #endif
  33. static int getPosixProtectionFlags(unsigned Flags) {
  34. switch (Flags & llvm::sys::Memory::MF_RWE_MASK) {
  35. case llvm::sys::Memory::MF_READ:
  36. return PROT_READ;
  37. case llvm::sys::Memory::MF_WRITE:
  38. return PROT_WRITE;
  39. case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE:
  40. return PROT_READ | PROT_WRITE;
  41. case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_EXEC:
  42. return PROT_READ | PROT_EXEC;
  43. case llvm::sys::Memory::MF_READ | llvm::sys::Memory::MF_WRITE |
  44. llvm::sys::Memory::MF_EXEC:
  45. return PROT_READ | PROT_WRITE | PROT_EXEC;
  46. case llvm::sys::Memory::MF_EXEC:
  47. #if defined(__FreeBSD__) || defined(__powerpc__)
  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 Memory::allocateMappedMemory(size_t NumBytes,
  66. const MemoryBlock *const NearBlock,
  67. unsigned PFlags, std::error_code &EC) {
  68. EC = std::error_code();
  69. if (NumBytes == 0)
  70. return MemoryBlock();
  71. // On platforms that have it, we can use MAP_ANON to get a memory-mapped
  72. // page without file backing, but we need a fallback of opening /dev/zero
  73. // for strictly POSIX platforms instead.
  74. int fd;
  75. #if defined(MAP_ANON)
  76. fd = -1;
  77. #else
  78. fd = open("/dev/zero", O_RDWR);
  79. if (fd == -1) {
  80. EC = std::error_code(errno, std::generic_category());
  81. return MemoryBlock();
  82. }
  83. #endif
  84. int MMFlags = MAP_PRIVATE;
  85. #if defined(MAP_ANON)
  86. MMFlags |= MAP_ANON;
  87. #endif
  88. int Protect = getPosixProtectionFlags(PFlags);
  89. #if defined(__NetBSD__) && defined(PROT_MPROTECT)
  90. Protect |= PROT_MPROTECT(PROT_READ | PROT_WRITE | PROT_EXEC);
  91. #endif
  92. // Use any near hint and the page size to set a page-aligned starting address
  93. uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
  94. NearBlock->allocatedSize()
  95. : 0;
  96. static const size_t PageSize = Process::getPageSizeEstimate();
  97. const size_t NumPages = (NumBytes + PageSize - 1) / PageSize;
  98. if (Start && Start % PageSize)
  99. Start += PageSize - Start % PageSize;
  100. // FIXME: Handle huge page requests (MF_HUGE_HINT).
  101. void *Addr = ::mmap(reinterpret_cast<void *>(Start), PageSize * NumPages,
  102. Protect, MMFlags, fd, 0);
  103. if (Addr == MAP_FAILED) {
  104. if (NearBlock) { // Try again without a near hint
  105. #if !defined(MAP_ANON)
  106. close(fd);
  107. #endif
  108. return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
  109. }
  110. EC = std::error_code(errno, std::generic_category());
  111. #if !defined(MAP_ANON)
  112. close(fd);
  113. #endif
  114. return MemoryBlock();
  115. }
  116. #if !defined(MAP_ANON)
  117. close(fd);
  118. #endif
  119. MemoryBlock Result;
  120. Result.Address = Addr;
  121. Result.AllocatedSize = PageSize * NumPages;
  122. Result.Flags = PFlags;
  123. // Rely on protectMappedMemory to invalidate instruction cache.
  124. if (PFlags & MF_EXEC) {
  125. EC = Memory::protectMappedMemory(Result, PFlags);
  126. if (EC != std::error_code())
  127. return MemoryBlock();
  128. }
  129. return Result;
  130. }
  131. std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {
  132. if (M.Address == nullptr || M.AllocatedSize == 0)
  133. return std::error_code();
  134. if (0 != ::munmap(M.Address, M.AllocatedSize))
  135. return std::error_code(errno, std::generic_category());
  136. M.Address = nullptr;
  137. M.AllocatedSize = 0;
  138. return std::error_code();
  139. }
  140. std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
  141. unsigned Flags) {
  142. static const Align PageSize = Align(Process::getPageSizeEstimate());
  143. if (M.Address == nullptr || M.AllocatedSize == 0)
  144. return std::error_code();
  145. if (!Flags)
  146. return std::error_code(EINVAL, std::generic_category());
  147. int Protect = getPosixProtectionFlags(Flags);
  148. uintptr_t Start =
  149. alignAddr((const uint8_t *)M.Address - PageSize.value() + 1, PageSize);
  150. uintptr_t End =
  151. 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
  155. // read, and CPU segfaults on trying to clear cache on !PROT_READ page.
  156. // Therefore we need to temporarily add PROT_READ for the sake of flushing the
  157. // instruction caches.
  158. if (InvalidateCache && !(Protect & PROT_READ)) {
  159. int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
  160. if (Result != 0)
  161. return std::error_code(errno, std::generic_category());
  162. Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
  163. InvalidateCache = false;
  164. }
  165. #endif
  166. int Result = ::mprotect((void *)Start, End - Start, Protect);
  167. if (Result != 0)
  168. return std::error_code(errno, std::generic_category());
  169. if (InvalidateCache)
  170. Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
  171. return std::error_code();
  172. }
  173. /// InvalidateInstructionCache - Before the JIT can run a block of code
  174. /// that has been emitted it must invalidate the instruction cache on some
  175. /// platforms.
  176. void Memory::InvalidateInstructionCache(const void *Addr, size_t Len) {
  177. // icache invalidation for PPC and ARM.
  178. #if defined(__APPLE__)
  179. #if (defined(__powerpc__) || defined(__arm__) || defined(__arm64__))
  180. sys_icache_invalidate(const_cast<void *>(Addr), Len);
  181. #endif
  182. #elif defined(__Fuchsia__)
  183. zx_status_t Status = zx_cache_flush(Addr, Len, ZX_CACHE_FLUSH_INSN);
  184. assert(Status == ZX_OK && "cannot invalidate instruction cache");
  185. #else
  186. #if defined(__powerpc__) && defined(__GNUC__)
  187. const size_t LineSize = 32;
  188. const intptr_t Mask = ~(LineSize - 1);
  189. const intptr_t StartLine = ((intptr_t)Addr) & Mask;
  190. const intptr_t EndLine = ((intptr_t)Addr + Len + LineSize - 1) & Mask;
  191. for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
  192. asm volatile("dcbf 0, %0" : : "r"(Line));
  193. asm volatile("sync");
  194. for (intptr_t Line = StartLine; Line < EndLine; Line += LineSize)
  195. asm volatile("icbi 0, %0" : : "r"(Line));
  196. asm volatile("isync");
  197. #elif (defined(__arm__) || defined(__aarch64__) || defined(__mips__)) && \
  198. defined(__GNUC__)
  199. // FIXME: Can we safely always call this for __GNUC__ everywhere?
  200. const char *Start = static_cast<const char *>(Addr);
  201. const char *End = Start + Len;
  202. __clear_cache(const_cast<char *>(Start), const_cast<char *>(End));
  203. #endif
  204. #endif // end apple
  205. ValgrindDiscardTranslations(Addr, Len);
  206. }
  207. } // namespace sys
  208. } // namespace llvm