Memory.inc 6.5 KB

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