Memory.inc 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. //===- Win32/Memory.cpp - Win32 Memory Implementation -----------*- 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 provides the Win32 specific implementation of various Memory
  10. // management utilities
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Support/DataTypes.h"
  14. #include "llvm/Support/ErrorHandling.h"
  15. #include "llvm/Support/Process.h"
  16. #include "llvm/Support/WindowsError.h"
  17. // The Windows.h header must be the last one included.
  18. #include "llvm/Support/Windows/WindowsSupport.h"
  19. static DWORD getWindowsProtectionFlags(unsigned Flags) {
  20. switch (Flags & llvm::sys::Memory::MF_RWE_MASK) {
  21. // Contrary to what you might expect, the Windows page protection flags
  22. // are not a bitwise combination of RWX values
  23. case llvm::sys::Memory::MF_READ:
  24. return PAGE_READONLY;
  25. case llvm::sys::Memory::MF_WRITE:
  26. // Note: PAGE_WRITE is not supported by VirtualProtect
  27. return PAGE_READWRITE;
  28. case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_WRITE:
  29. return PAGE_READWRITE;
  30. case llvm::sys::Memory::MF_READ|llvm::sys::Memory::MF_EXEC:
  31. return PAGE_EXECUTE_READ;
  32. case llvm::sys::Memory::MF_READ |
  33. llvm::sys::Memory::MF_WRITE |
  34. llvm::sys::Memory::MF_EXEC:
  35. return PAGE_EXECUTE_READWRITE;
  36. case llvm::sys::Memory::MF_EXEC:
  37. return PAGE_EXECUTE;
  38. default:
  39. llvm_unreachable("Illegal memory protection flag specified!");
  40. }
  41. // Provide a default return value as required by some compilers.
  42. return PAGE_NOACCESS;
  43. }
  44. // While we'd be happy to allocate single pages, the Windows allocation
  45. // granularity may be larger than a single page (in practice, it is 64K)
  46. // so mapping less than that will create an unreachable fragment of memory.
  47. static size_t getAllocationGranularity() {
  48. SYSTEM_INFO Info;
  49. ::GetSystemInfo(&Info);
  50. if (Info.dwPageSize > Info.dwAllocationGranularity)
  51. return Info.dwPageSize;
  52. else
  53. return Info.dwAllocationGranularity;
  54. }
  55. // Large/huge memory pages need explicit process permissions in order to be
  56. // used. See https://blogs.msdn.microsoft.com/oldnewthing/20110128-00/?p=11643
  57. // Also large pages need to be manually enabled on your OS. If all this is
  58. // sucessfull, we return the minimal large memory page size.
  59. static size_t enableProcessLargePages() {
  60. HANDLE Token = 0;
  61. size_t LargePageMin = GetLargePageMinimum();
  62. if (LargePageMin)
  63. OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
  64. &Token);
  65. if (!Token)
  66. return 0;
  67. LUID Luid;
  68. if (!LookupPrivilegeValue(0, SE_LOCK_MEMORY_NAME, &Luid)) {
  69. CloseHandle(Token);
  70. return 0;
  71. }
  72. TOKEN_PRIVILEGES TP{};
  73. TP.PrivilegeCount = 1;
  74. TP.Privileges[0].Luid = Luid;
  75. TP.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  76. if (!AdjustTokenPrivileges(Token, FALSE, &TP, 0, 0, 0)) {
  77. CloseHandle(Token);
  78. return 0;
  79. }
  80. DWORD E = GetLastError();
  81. CloseHandle(Token);
  82. if (E == ERROR_SUCCESS)
  83. return LargePageMin;
  84. return 0;
  85. }
  86. namespace llvm {
  87. namespace sys {
  88. //===----------------------------------------------------------------------===//
  89. //=== WARNING: Implementation here must contain only Win32 specific code
  90. //=== and must not be UNIX code
  91. //===----------------------------------------------------------------------===//
  92. MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
  93. const MemoryBlock *const NearBlock,
  94. unsigned Flags,
  95. std::error_code &EC) {
  96. EC = std::error_code();
  97. if (NumBytes == 0)
  98. return MemoryBlock();
  99. static size_t DefaultGranularity = getAllocationGranularity();
  100. static size_t LargePageGranularity = enableProcessLargePages();
  101. DWORD AllocType = MEM_RESERVE | MEM_COMMIT;
  102. bool HugePages = false;
  103. size_t Granularity = DefaultGranularity;
  104. if ((Flags & MF_HUGE_HINT) && LargePageGranularity > 0) {
  105. AllocType |= MEM_LARGE_PAGES;
  106. HugePages = true;
  107. Granularity = LargePageGranularity;
  108. }
  109. size_t NumBlocks = (NumBytes + Granularity - 1) / Granularity;
  110. uintptr_t Start = NearBlock ? reinterpret_cast<uintptr_t>(NearBlock->base()) +
  111. NearBlock->allocatedSize()
  112. : 0;
  113. // If the requested address is not aligned to the allocation granularity,
  114. // round up to get beyond NearBlock. VirtualAlloc would have rounded down.
  115. if (Start && Start % Granularity != 0)
  116. Start += Granularity - Start % Granularity;
  117. DWORD Protect = getWindowsProtectionFlags(Flags);
  118. size_t AllocSize = NumBlocks * Granularity;
  119. void *PA = ::VirtualAlloc(reinterpret_cast<void *>(Start),
  120. AllocSize, AllocType, Protect);
  121. if (PA == NULL) {
  122. if (NearBlock || HugePages) {
  123. // Try again without the NearBlock hint and without large memory pages
  124. return allocateMappedMemory(NumBytes, NULL, Flags & ~MF_HUGE_HINT, EC);
  125. }
  126. EC = mapWindowsError(::GetLastError());
  127. return MemoryBlock();
  128. }
  129. MemoryBlock Result;
  130. Result.Address = PA;
  131. Result.AllocatedSize = AllocSize;
  132. Result.Flags = (Flags & ~MF_HUGE_HINT) | (HugePages ? MF_HUGE_HINT : 0);
  133. if (Flags & MF_EXEC)
  134. Memory::InvalidateInstructionCache(Result.Address, AllocSize);
  135. return Result;
  136. }
  137. std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {
  138. if (M.Address == 0 || M.AllocatedSize == 0)
  139. return std::error_code();
  140. if (!VirtualFree(M.Address, 0, MEM_RELEASE))
  141. return mapWindowsError(::GetLastError());
  142. M.Address = 0;
  143. M.AllocatedSize = 0;
  144. return std::error_code();
  145. }
  146. std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
  147. unsigned Flags) {
  148. if (M.Address == 0 || M.AllocatedSize == 0)
  149. return std::error_code();
  150. DWORD Protect = getWindowsProtectionFlags(Flags);
  151. DWORD OldFlags;
  152. if (!VirtualProtect(M.Address, M.AllocatedSize, Protect, &OldFlags))
  153. return mapWindowsError(::GetLastError());
  154. if (Flags & MF_EXEC)
  155. Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
  156. return std::error_code();
  157. }
  158. /// InvalidateInstructionCache - Before the JIT can run a block of code
  159. /// that has been emitted it must invalidate the instruction cache on some
  160. /// platforms.
  161. void Memory::InvalidateInstructionCache(
  162. const void *Addr, size_t Len) {
  163. FlushInstructionCache(GetCurrentProcess(), Addr, Len);
  164. }
  165. } // namespace sys
  166. } // namespace llvm