virtual_memory.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /*
  2. Copyright (c) 2018-2019, tevador <tevador@gmail.com>
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of the copyright holder nor the
  12. names of its contributors may be used to endorse or promote products
  13. derived from this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  18. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  21. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  22. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  23. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include "virtual_memory.hpp"
  26. #include <stdexcept>
  27. #if defined(_WIN32) || defined(__CYGWIN__)
  28. #include <windows.h>
  29. #else
  30. #ifdef __APPLE__
  31. #include <mach/vm_statistics.h>
  32. #include <TargetConditionals.h>
  33. # if defined(__aarch64__) && TARGET_OS_OSX
  34. # define USE_PTHREAD_JIT_WP 1
  35. # include <pthread.h>
  36. # endif
  37. #endif
  38. #include <sys/types.h>
  39. #include <sys/mman.h>
  40. #ifndef MAP_ANONYMOUS
  41. #define MAP_ANONYMOUS MAP_ANON
  42. #endif
  43. #define PAGE_READONLY PROT_READ
  44. #define PAGE_READWRITE (PROT_READ | PROT_WRITE)
  45. #define PAGE_EXECUTE_READ (PROT_READ | PROT_EXEC)
  46. #define PAGE_EXECUTE_READWRITE (PROT_READ | PROT_WRITE | PROT_EXEC)
  47. #endif
  48. #if defined(_WIN32) || defined(__CYGWIN__)
  49. std::string getErrorMessage(const char* function) {
  50. LPSTR messageBuffer = nullptr;
  51. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  52. NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
  53. std::string message(messageBuffer, size);
  54. LocalFree(messageBuffer);
  55. return std::string(function) + std::string(": ") + message;
  56. }
  57. void setPrivilege(const char* pszPrivilege, BOOL bEnable) {
  58. HANDLE hToken;
  59. TOKEN_PRIVILEGES tp;
  60. BOOL status;
  61. DWORD error;
  62. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  63. throw std::runtime_error(getErrorMessage("OpenProcessToken"));
  64. if (!LookupPrivilegeValue(NULL, pszPrivilege, &tp.Privileges[0].Luid))
  65. throw std::runtime_error(getErrorMessage("LookupPrivilegeValue"));
  66. tp.PrivilegeCount = 1;
  67. if (bEnable)
  68. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  69. else
  70. tp.Privileges[0].Attributes = 0;
  71. status = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  72. error = GetLastError();
  73. if (!status || (error != ERROR_SUCCESS))
  74. throw std::runtime_error(getErrorMessage("AdjustTokenPrivileges"));
  75. if (!CloseHandle(hToken))
  76. throw std::runtime_error(getErrorMessage("CloseHandle"));
  77. }
  78. #endif
  79. void* allocMemoryPages(std::size_t bytes) {
  80. void* mem;
  81. #if defined(_WIN32) || defined(__CYGWIN__)
  82. mem = VirtualAlloc(nullptr, bytes, MEM_COMMIT, PAGE_READWRITE);
  83. if (mem == nullptr)
  84. throw std::runtime_error(getErrorMessage("allocMemoryPages - VirtualAlloc"));
  85. #else
  86. #if defined(__NetBSD__)
  87. #define RESERVED_FLAGS PROT_MPROTECT(PROT_EXEC)
  88. #else
  89. #define RESERVED_FLAGS 0
  90. #endif
  91. #ifdef __APPLE__
  92. #include <TargetConditionals.h>
  93. #ifdef TARGET_OS_OSX
  94. #define MEXTRA MAP_JIT
  95. #else
  96. #define MEXTRA 0
  97. #endif
  98. #else
  99. #define MEXTRA 0
  100. #endif
  101. #ifdef USE_PTHREAD_JIT_WP
  102. #define PEXTRA PROT_EXEC
  103. #else
  104. #define PEXTRA 0
  105. #endif
  106. mem = mmap(nullptr, bytes, PAGE_READWRITE | RESERVED_FLAGS | PEXTRA, MAP_ANONYMOUS | MAP_PRIVATE | MEXTRA, -1, 0);
  107. if (mem == MAP_FAILED)
  108. throw std::runtime_error("allocMemoryPages - mmap failed");
  109. #ifdef USE_PTHREAD_JIT_WP
  110. pthread_jit_write_protect_np(false);
  111. #endif
  112. #endif
  113. return mem;
  114. }
  115. static inline void pageProtect(void* ptr, std::size_t bytes, int rules) {
  116. #if defined(_WIN32) || defined(__CYGWIN__)
  117. DWORD oldp;
  118. if (!VirtualProtect(ptr, bytes, (DWORD)rules, &oldp)) {
  119. throw std::runtime_error(getErrorMessage("VirtualProtect"));
  120. }
  121. #else
  122. if (-1 == mprotect(ptr, bytes, rules))
  123. throw std::runtime_error("mprotect failed");
  124. #endif
  125. }
  126. void setPagesRW(void* ptr, std::size_t bytes) {
  127. #ifdef USE_PTHREAD_JIT_WP
  128. pthread_jit_write_protect_np(false);
  129. #else
  130. pageProtect(ptr, bytes, PAGE_READWRITE);
  131. #endif
  132. }
  133. void setPagesRX(void* ptr, std::size_t bytes) {
  134. #ifdef USE_PTHREAD_JIT_WP
  135. pthread_jit_write_protect_np(true);
  136. #else
  137. pageProtect(ptr, bytes, PAGE_EXECUTE_READ);
  138. #endif
  139. }
  140. void setPagesRWX(void* ptr, std::size_t bytes) {
  141. pageProtect(ptr, bytes, PAGE_EXECUTE_READWRITE);
  142. }
  143. void* allocLargePagesMemory(std::size_t bytes) {
  144. void* mem;
  145. #if defined(_WIN32) || defined(__CYGWIN__)
  146. setPrivilege("SeLockMemoryPrivilege", 1);
  147. auto pageMinimum = GetLargePageMinimum();
  148. if (pageMinimum > 0)
  149. mem = VirtualAlloc(NULL, alignSize(bytes, pageMinimum), MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE);
  150. else
  151. throw std::runtime_error("allocLargePagesMemory - Large pages are not supported");
  152. if (mem == nullptr)
  153. throw std::runtime_error(getErrorMessage("allocLargePagesMemory - VirtualAlloc"));
  154. #else
  155. #ifdef __APPLE__
  156. mem = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0);
  157. #elif defined(__FreeBSD__)
  158. mem = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER, -1, 0);
  159. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  160. mem = MAP_FAILED; // OpenBSD does not support huge pages
  161. #else
  162. mem = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, -1, 0);
  163. #endif
  164. if (mem == MAP_FAILED)
  165. throw std::runtime_error("allocLargePagesMemory - mmap failed");
  166. #endif
  167. return mem;
  168. }
  169. void freePagedMemory(void* ptr, std::size_t bytes) {
  170. #if defined(_WIN32) || defined(__CYGWIN__)
  171. VirtualFree(ptr, 0, MEM_RELEASE);
  172. #else
  173. munmap(ptr, bytes);
  174. #endif
  175. }