MemoryUtil.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // Copyright 2008 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #include <cstddef>
  5. #include <cstdlib>
  6. #include <string>
  7. #include "Common/CommonFuncs.h"
  8. #include "Common/CommonTypes.h"
  9. #include "Common/MemoryUtil.h"
  10. #include "Common/MsgHandler.h"
  11. #include "Common/Logging/Log.h"
  12. #ifdef _WIN32
  13. #include <windows.h>
  14. #include <psapi.h>
  15. #include "Common/StringUtil.h"
  16. #else
  17. #include <stdio.h>
  18. #include <sys/mman.h>
  19. #include <sys/types.h>
  20. #if defined __APPLE__ || defined __FreeBSD__
  21. #include <sys/sysctl.h>
  22. #else
  23. #include <sys/sysinfo.h>
  24. #endif
  25. #endif
  26. // Valgrind doesn't support MAP_32BIT.
  27. // Uncomment the following line to be able to run Dolphin in Valgrind.
  28. //#undef MAP_32BIT
  29. #if !defined(_WIN32) && defined(_M_X86_64) && !defined(MAP_32BIT)
  30. #include <unistd.h>
  31. #define PAGE_MASK (getpagesize() - 1)
  32. #define round_page(x) ((((unsigned long)(x)) + PAGE_MASK) & ~(PAGE_MASK))
  33. #endif
  34. // This is purposely not a full wrapper for virtualalloc/mmap, but it
  35. // provides exactly the primitive operations that Dolphin needs.
  36. void* AllocateExecutableMemory(size_t size, bool low)
  37. {
  38. #if defined(_WIN32)
  39. void* ptr = VirtualAlloc(0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  40. #else
  41. static char *map_hint = nullptr;
  42. #if defined(_M_X86_64) && !defined(MAP_32BIT)
  43. // This OS has no flag to enforce allocation below the 4 GB boundary,
  44. // but if we hint that we want a low address it is very likely we will
  45. // get one.
  46. // An older version of this code used MAP_FIXED, but that has the side
  47. // effect of discarding already mapped pages that happen to be in the
  48. // requested virtual memory range (such as the emulated RAM, sometimes).
  49. if (low && (!map_hint))
  50. map_hint = (char*)round_page(512*1024*1024); /* 0.5 GB rounded up to the next page */
  51. #endif
  52. void* ptr = mmap(map_hint, size, PROT_READ | PROT_WRITE | PROT_EXEC,
  53. MAP_ANON | MAP_PRIVATE
  54. #if defined(_M_X86_64) && defined(MAP_32BIT)
  55. | (low ? MAP_32BIT : 0)
  56. #endif
  57. , -1, 0);
  58. #endif /* defined(_WIN32) */
  59. // printf("Mapped executable memory at %p (size %ld)\n", ptr,
  60. // (unsigned long)size);
  61. #ifdef _WIN32
  62. if (ptr == nullptr)
  63. {
  64. #else
  65. if (ptr == MAP_FAILED)
  66. {
  67. ptr = nullptr;
  68. #endif
  69. PanicAlert("Failed to allocate executable memory. If you are running Dolphin in Valgrind, try '#undef MAP_32BIT'.");
  70. }
  71. #if !defined(_WIN32) && defined(_M_X86_64) && !defined(MAP_32BIT)
  72. else
  73. {
  74. if (low)
  75. {
  76. map_hint += size;
  77. map_hint = (char*)round_page(map_hint); /* round up to the next page */
  78. // printf("Next map will (hopefully) be at %p\n", map_hint);
  79. }
  80. }
  81. #endif
  82. #if _M_X86_64
  83. if ((u64)ptr >= 0x80000000 && low == true)
  84. PanicAlert("Executable memory ended up above 2GB!");
  85. #endif
  86. return ptr;
  87. }
  88. void* AllocateMemoryPages(size_t size)
  89. {
  90. #ifdef _WIN32
  91. void* ptr = VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
  92. #else
  93. void* ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE,
  94. MAP_ANON | MAP_PRIVATE, -1, 0);
  95. if (ptr == MAP_FAILED)
  96. ptr = nullptr;
  97. #endif
  98. if (ptr == nullptr)
  99. PanicAlert("Failed to allocate raw memory");
  100. return ptr;
  101. }
  102. void* AllocateAlignedMemory(size_t size, size_t alignment)
  103. {
  104. #ifdef _WIN32
  105. void* ptr = _aligned_malloc(size, alignment);
  106. #else
  107. void* ptr = nullptr;
  108. if (posix_memalign(&ptr, alignment, size) != 0)
  109. ERROR_LOG(MEMMAP, "Failed to allocate aligned memory");
  110. #endif
  111. // printf("Mapped memory at %p (size %ld)\n", ptr,
  112. // (unsigned long)size);
  113. if (ptr == nullptr)
  114. PanicAlert("Failed to allocate aligned memory");
  115. return ptr;
  116. }
  117. void FreeMemoryPages(void* ptr, size_t size)
  118. {
  119. if (ptr)
  120. {
  121. bool error_occurred = false;
  122. #ifdef _WIN32
  123. if (!VirtualFree(ptr, 0, MEM_RELEASE))
  124. error_occurred = true;
  125. #else
  126. int retval = munmap(ptr, size);
  127. if (retval != 0)
  128. error_occurred = true;
  129. #endif
  130. if (error_occurred)
  131. PanicAlert("FreeMemoryPages failed!\n%s", GetLastErrorMsg().c_str());
  132. }
  133. }
  134. void FreeAlignedMemory(void* ptr)
  135. {
  136. if (ptr)
  137. {
  138. #ifdef _WIN32
  139. _aligned_free(ptr);
  140. #else
  141. free(ptr);
  142. #endif
  143. }
  144. }
  145. void ReadProtectMemory(void* ptr, size_t size)
  146. {
  147. bool error_occurred = false;
  148. #ifdef _WIN32
  149. DWORD oldValue;
  150. if (!VirtualProtect(ptr, size, PAGE_NOACCESS, &oldValue))
  151. error_occurred = true;
  152. #else
  153. int retval = mprotect(ptr, size, PROT_NONE);
  154. if (retval != 0)
  155. error_occurred = true;
  156. #endif
  157. if (error_occurred)
  158. PanicAlert("ReadProtectMemory failed!\n%s", GetLastErrorMsg().c_str());
  159. }
  160. void WriteProtectMemory(void* ptr, size_t size, bool allowExecute)
  161. {
  162. bool error_occurred = false;
  163. #ifdef _WIN32
  164. DWORD oldValue;
  165. if (!VirtualProtect(ptr, size, allowExecute ? PAGE_EXECUTE_READ : PAGE_READONLY, &oldValue))
  166. error_occurred = true;
  167. #else
  168. int retval = mprotect(ptr, size, allowExecute ? (PROT_READ | PROT_EXEC) : PROT_READ);
  169. if (retval != 0)
  170. error_occurred = true;
  171. #endif
  172. if (error_occurred)
  173. PanicAlert("WriteProtectMemory failed!\n%s", GetLastErrorMsg().c_str());
  174. }
  175. void UnWriteProtectMemory(void* ptr, size_t size, bool allowExecute)
  176. {
  177. bool error_occurred = false;
  178. #ifdef _WIN32
  179. DWORD oldValue;
  180. if (!VirtualProtect(ptr, size, allowExecute ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE, &oldValue))
  181. error_occurred = true;
  182. #else
  183. int retval = mprotect(ptr, size, allowExecute ? (PROT_READ | PROT_WRITE | PROT_EXEC) : PROT_WRITE | PROT_READ);
  184. if (retval != 0)
  185. error_occurred = true;
  186. #endif
  187. if (error_occurred)
  188. PanicAlert("UnWriteProtectMemory failed!\n%s", GetLastErrorMsg().c_str());
  189. }
  190. std::string MemUsage()
  191. {
  192. #ifdef _WIN32
  193. #pragma comment(lib, "psapi")
  194. DWORD processID = GetCurrentProcessId();
  195. HANDLE hProcess;
  196. PROCESS_MEMORY_COUNTERS pmc;
  197. std::string Ret;
  198. // Print information about the memory usage of the process.
  199. hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
  200. if (nullptr == hProcess) return "MemUsage Error";
  201. if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)))
  202. Ret = StringFromFormat("%s K", ThousandSeparate(pmc.WorkingSetSize / 1024, 7).c_str());
  203. CloseHandle(hProcess);
  204. return Ret;
  205. #else
  206. return "";
  207. #endif
  208. }
  209. size_t MemPhysical()
  210. {
  211. #ifdef _WIN32
  212. MEMORYSTATUSEX memInfo;
  213. memInfo.dwLength = sizeof(MEMORYSTATUSEX);
  214. GlobalMemoryStatusEx(&memInfo);
  215. return memInfo.ullTotalPhys;
  216. #elif defined __APPLE__ || defined __FreeBSD__
  217. int mib[2];
  218. size_t physical_memory;
  219. mib[0] = CTL_HW;
  220. #ifdef __APPLE__
  221. mib[1] = HW_MEMSIZE;
  222. #elif defined __FreeBSD__
  223. mib[1] = HW_REALMEM;
  224. #endif
  225. size_t length = sizeof(size_t);
  226. sysctl(mib, 2, &physical_memory, &length, NULL, 0);
  227. return physical_memory;
  228. #else
  229. struct sysinfo memInfo;
  230. sysinfo (&memInfo);
  231. return (size_t)memInfo.totalram * memInfo.mem_unit;
  232. #endif
  233. }