virtual_memory.c 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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 defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  131. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  132. if (__builtin_available(macOS 11.0, *)) {
  133. pthread_jit_write_protect_np(0);
  134. }
  135. #endif
  136. #endif
  137. return mem;
  138. }
  139. static inline int pageProtect(void* ptr, size_t bytes, int rules, char **errfunc) {
  140. #if defined(_WIN32) || defined(__CYGWIN__)
  141. DWORD oldp;
  142. if (!VirtualProtect(ptr, bytes, (DWORD)rules, &oldp)) {
  143. Fail("VirtualProtect");
  144. }
  145. #else
  146. if (-1 == mprotect(ptr, bytes, rules))
  147. Fail("mprotect");
  148. #endif
  149. return 0;
  150. }
  151. void setPagesRW(void* ptr, size_t bytes) {
  152. char *errfunc;
  153. #if defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  154. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  155. if (__builtin_available(macOS 11.0, *)) {
  156. pthread_jit_write_protect_np(0);
  157. } else {
  158. pageProtect(ptr, bytes, PAGE_READWRITE, &errfunc);
  159. }
  160. #else
  161. pageProtect(ptr, bytes, PAGE_READWRITE, &errfunc);
  162. #endif
  163. }
  164. void setPagesRX(void* ptr, size_t bytes) {
  165. char *errfunc;
  166. #if defined(USE_PTHREAD_JIT_WP) && defined(MAC_OS_VERSION_11_0) \
  167. && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_11_0
  168. if (__builtin_available(macOS 11.0, *)) {
  169. pthread_jit_write_protect_np(1);
  170. } else {
  171. pageProtect(ptr, bytes, PAGE_EXECUTE_READ, &errfunc);
  172. }
  173. #else
  174. pageProtect(ptr, bytes, PAGE_EXECUTE_READ, &errfunc);
  175. #endif
  176. }
  177. void setPagesRWX(void* ptr, size_t bytes) {
  178. char *errfunc;
  179. pageProtect(ptr, bytes, PAGE_EXECUTE_READWRITE, &errfunc);
  180. }
  181. void* allocLargePagesMemory(size_t bytes) {
  182. void* mem;
  183. char *errfunc;
  184. #if defined(_WIN32) || defined(__CYGWIN__)
  185. if (setPrivilege("SeLockMemoryPrivilege", 1, &errfunc))
  186. return NULL;
  187. size_t pageMinimum = GetLargePageMinimum();
  188. if (!pageMinimum) {
  189. errfunc = "No large pages";
  190. return NULL;
  191. }
  192. mem = VirtualAlloc(NULL, alignSize(bytes, pageMinimum), MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE);
  193. #else
  194. #ifdef __APPLE__
  195. mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0);
  196. #elif defined(__FreeBSD__)
  197. mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER, -1, 0);
  198. #elif defined(__OpenBSD__) || defined(__NetBSD__)
  199. mem = MAP_FAILED; // OpenBSD does not support huge pages
  200. #else
  201. mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, -1, 0);
  202. #endif
  203. if (mem == MAP_FAILED)
  204. mem = NULL;
  205. #endif
  206. return mem;
  207. }
  208. void freePagedMemory(void* ptr, size_t bytes) {
  209. #if defined(_WIN32) || defined(__CYGWIN__)
  210. VirtualFree(ptr, 0, MEM_RELEASE);
  211. #else
  212. munmap(ptr, bytes);
  213. #endif
  214. }