virtual_memory.c 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. #if defined(_WIN32) || defined(__CYGWIN__)
  26. #include <windows.h>
  27. #else
  28. #define _GNU_SOURCE 1 /* needed for MAP_ANONYMOUS on older platforms */
  29. #ifdef __APPLE__
  30. #include <mach/vm_statistics.h>
  31. #include <TargetConditionals.h>
  32. #include <AvailabilityMacros.h>
  33. # if TARGET_OS_OSX
  34. # define USE_PTHREAD_JIT_WP 1
  35. # include <pthread.h>
  36. # include <sys/utsname.h>
  37. # include <stdio.h>
  38. # endif
  39. #endif
  40. #include <sys/types.h>
  41. #include <sys/mman.h>
  42. #include <errno.h>
  43. #ifndef MAP_ANONYMOUS
  44. #define MAP_ANONYMOUS MAP_ANON
  45. #endif
  46. #define PAGE_READONLY PROT_READ
  47. #define PAGE_READWRITE (PROT_READ | PROT_WRITE)
  48. #define PAGE_EXECUTE_READ (PROT_READ | PROT_EXEC)
  49. #define PAGE_EXECUTE_READWRITE (PROT_READ | PROT_WRITE | PROT_EXEC)
  50. #endif
  51. #include "virtual_memory.h"
  52. #if defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  53. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  54. static int MacOSchecked, MacOSver;
  55. /* This function is used implicitly by clang's __builtin_available() checker.
  56. * When cross-compiling, the library containing this function doesn't exist,
  57. * and linking will fail because the symbol is unresolved. The function here
  58. * is a quick and dirty hack to get close enough to identify MacOSX 11.0.
  59. */
  60. static int32_t __isOSVersionAtLeast(int32_t major, int32_t minor, int32_t subminor) {
  61. if (!MacOSchecked) {
  62. struct utsname ut;
  63. int mmaj, mmin;
  64. uname(&ut);
  65. sscanf(ut.release, "%d.%d", &mmaj, &mmin);
  66. // The utsname release version is 9 greater than the canonical OS version
  67. mmaj -= 9;
  68. MacOSver = (mmaj << 8) | mmin;
  69. MacOSchecked = 1;
  70. }
  71. return MacOSver >= ((major << 8) | minor);
  72. }
  73. #endif
  74. #if defined(_WIN32) || defined(__CYGWIN__)
  75. #define Fail(func) do {*errfunc = func; return GetLastError();} while(0)
  76. int setPrivilege(const char* pszPrivilege, BOOL bEnable, char **errfunc) {
  77. HANDLE hToken;
  78. TOKEN_PRIVILEGES tp;
  79. BOOL status;
  80. DWORD error = 0;
  81. *errfunc = NULL;
  82. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  83. Fail("OpenProcessToken");
  84. if (!LookupPrivilegeValue(NULL, pszPrivilege, &tp.Privileges[0].Luid)) {
  85. *errfunc = "LookupPrivilegeValue";
  86. error = GetLastError();
  87. goto out;
  88. }
  89. tp.PrivilegeCount = 1;
  90. if (bEnable)
  91. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  92. else
  93. tp.Privileges[0].Attributes = 0;
  94. status = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  95. error = GetLastError();
  96. if (!status || (error != ERROR_SUCCESS)) {
  97. *errfunc = "AdjustTokenPrivileges";
  98. goto out;
  99. }
  100. out:
  101. if (!CloseHandle(hToken)) {
  102. if (*errfunc == NULL) {
  103. *errfunc = "CloseHandle";
  104. error = GetLastError();
  105. }
  106. }
  107. return error;
  108. }
  109. #else
  110. #define Fail(func) do {*errfunc = func; return errno;} while(0)
  111. #endif
  112. void* allocMemoryPages(size_t bytes) {
  113. void* mem;
  114. #if defined(_WIN32) || defined(__CYGWIN__)
  115. mem = VirtualAlloc(NULL, bytes, MEM_COMMIT, PAGE_READWRITE);
  116. #else
  117. #if defined(__NetBSD__)
  118. #define RESERVED_FLAGS PROT_MPROTECT(PROT_EXEC)
  119. #else
  120. #define RESERVED_FLAGS 0
  121. #endif
  122. #ifdef USE_PTHREAD_JIT_WP
  123. #define MEXTRA MAP_JIT
  124. #define PEXTRA PROT_EXEC
  125. #else
  126. #define MEXTRA 0
  127. #define PEXTRA 0
  128. #endif
  129. mem = mmap(NULL, bytes, PAGE_READWRITE | RESERVED_FLAGS | PEXTRA, MAP_ANONYMOUS | MAP_PRIVATE | MEXTRA, -1, 0);
  130. if (mem == MAP_FAILED)
  131. mem = NULL;
  132. #if defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  133. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  134. if (__builtin_available(macOS 11.0, *)) {
  135. pthread_jit_write_protect_np(0);
  136. }
  137. #endif
  138. #endif
  139. return mem;
  140. }
  141. static inline int pageProtect(void* ptr, size_t bytes, int rules, char **errfunc) {
  142. #if defined(_WIN32) || defined(__CYGWIN__)
  143. DWORD oldp;
  144. if (!VirtualProtect(ptr, bytes, (DWORD)rules, &oldp)) {
  145. Fail("VirtualProtect");
  146. }
  147. #else
  148. if (-1 == mprotect(ptr, bytes, rules))
  149. Fail("mprotect");
  150. #endif
  151. return 0;
  152. }
  153. void setPagesRW(void* ptr, size_t bytes) {
  154. char *errfunc;
  155. #if defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  156. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  157. if (__builtin_available(macOS 11.0, *)) {
  158. pthread_jit_write_protect_np(0);
  159. } else {
  160. pageProtect(ptr, bytes, PAGE_READWRITE, &errfunc);
  161. }
  162. #else
  163. pageProtect(ptr, bytes, PAGE_READWRITE, &errfunc);
  164. #endif
  165. }
  166. void setPagesRX(void* ptr, size_t bytes) {
  167. char *errfunc;
  168. #if defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  169. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  170. if (__builtin_available(macOS 11.0, *)) {
  171. pthread_jit_write_protect_np(1);
  172. __builtin___clear_cache((char*)ptr, ((char*)ptr) + bytes);
  173. } else {
  174. pageProtect(ptr, bytes, PAGE_EXECUTE_READ, &errfunc);
  175. }
  176. #else
  177. pageProtect(ptr, bytes, PAGE_EXECUTE_READ, &errfunc);
  178. #endif
  179. }
  180. void setPagesRWX(void* ptr, size_t bytes) {
  181. char *errfunc;
  182. pageProtect(ptr, bytes, PAGE_EXECUTE_READWRITE, &errfunc);
  183. }
  184. void* allocLargePagesMemory(size_t bytes) {
  185. void* mem;
  186. char *errfunc;
  187. #if defined(_WIN32) || defined(__CYGWIN__)
  188. if (setPrivilege("SeLockMemoryPrivilege", 1, &errfunc))
  189. return NULL;
  190. size_t pageMinimum = GetLargePageMinimum();
  191. if (!pageMinimum) {
  192. errfunc = "No large pages";
  193. return NULL;
  194. }
  195. mem = VirtualAlloc(NULL, alignSize(bytes, pageMinimum), MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE);
  196. #else
  197. #ifdef __APPLE__
  198. mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0);
  199. #elif defined(__FreeBSD__)
  200. mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER, -1, 0);
  201. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  202. mem = MAP_FAILED; // OpenBSD does not support huge pages
  203. #else
  204. mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, -1, 0);
  205. #endif
  206. if (mem == MAP_FAILED)
  207. mem = NULL;
  208. #endif
  209. return mem;
  210. }
  211. void freePagedMemory(void* ptr, size_t bytes) {
  212. #if defined(_WIN32) || defined(__CYGWIN__)
  213. VirtualFree(ptr, 0, MEM_RELEASE);
  214. #else
  215. // some munmap implementations can crash on null pointer, despite what the manpage says
  216. if (ptr) {
  217. munmap(ptr, bytes);
  218. }
  219. #endif
  220. }