virtual_memory.cpp 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. #ifdef _WIN32
  28. #include <windows.h>
  29. #else
  30. #ifdef __APPLE__
  31. #include <mach/vm_statistics.h>
  32. #endif
  33. #include <sys/types.h>
  34. #include <sys/mman.h>
  35. #ifndef MAP_ANONYMOUS
  36. #define MAP_ANONYMOUS MAP_ANON
  37. #endif
  38. #endif
  39. #ifdef _WIN32
  40. std::string getErrorMessage(const char* function) {
  41. LPSTR messageBuffer = nullptr;
  42. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  43. NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
  44. std::string message(messageBuffer, size);
  45. LocalFree(messageBuffer);
  46. return std::string(function) + std::string(": ") + message;
  47. }
  48. void setPrivilege(const char* pszPrivilege, BOOL bEnable) {
  49. HANDLE hToken;
  50. TOKEN_PRIVILEGES tp;
  51. BOOL status;
  52. DWORD error;
  53. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  54. throw std::runtime_error(getErrorMessage("OpenProcessToken"));
  55. if (!LookupPrivilegeValue(NULL, pszPrivilege, &tp.Privileges[0].Luid))
  56. throw std::runtime_error(getErrorMessage("LookupPrivilegeValue"));
  57. tp.PrivilegeCount = 1;
  58. if (bEnable)
  59. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  60. else
  61. tp.Privileges[0].Attributes = 0;
  62. status = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  63. error = GetLastError();
  64. if (!status || (error != ERROR_SUCCESS))
  65. throw std::runtime_error(getErrorMessage("AdjustTokenPrivileges"));
  66. if (!CloseHandle(hToken))
  67. throw std::runtime_error(getErrorMessage("CloseHandle"));
  68. }
  69. #endif
  70. void* allocExecutableMemory(std::size_t bytes) {
  71. void* mem;
  72. #ifdef _WIN32
  73. mem = VirtualAlloc(nullptr, bytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  74. if (mem == nullptr)
  75. throw std::runtime_error(getErrorMessage("allocExecutableMemory - VirtualAlloc"));
  76. #else
  77. mem = mmap(nullptr, bytes, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  78. if (mem == MAP_FAILED)
  79. throw std::runtime_error("allocExecutableMemory - mmap failed");
  80. #endif
  81. return mem;
  82. }
  83. constexpr std::size_t align(std::size_t pos, std::size_t align) {
  84. return ((pos - 1) / align + 1) * align;
  85. }
  86. void* allocLargePagesMemory(std::size_t bytes) {
  87. void* mem;
  88. #ifdef _WIN32
  89. setPrivilege("SeLockMemoryPrivilege", 1);
  90. auto pageMinimum = GetLargePageMinimum();
  91. if (pageMinimum > 0)
  92. mem = VirtualAlloc(NULL, align(bytes, pageMinimum), MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE);
  93. else
  94. throw std::runtime_error("allocLargePagesMemory - Large pages are not supported");
  95. if (mem == nullptr)
  96. throw std::runtime_error(getErrorMessage("allocLargePagesMemory - VirtualAlloc"));
  97. #else
  98. #ifdef __APPLE__
  99. mem = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0);
  100. #else
  101. mem = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, -1, 0);
  102. #endif
  103. if (mem == MAP_FAILED)
  104. throw std::runtime_error("allocLargePagesMemory - mmap failed");
  105. #endif
  106. return mem;
  107. }
  108. void freePagedMemory(void* ptr, std::size_t bytes) {
  109. #ifdef _WIN32
  110. VirtualFree(ptr, 0, MEM_RELEASE);
  111. #else
  112. munmap(ptr, bytes);
  113. #endif
  114. }