Debian Codegraph @

Source/Core/Common/MemoryUtil.cpp

raw symbols SCIP
1 // Copyright 2008 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "Common/MemoryUtil.h"
5
6 #include <cstddef>
7 #include <cstdlib>
8
9 #include "Common/CommonFuncs.h"
10 #include "Common/Logging/Log.h"
11 #include "Common/MsgHandler.h"
12
13 #ifdef _WIN32
14 #include <windows.h>
15 #include "Common/StringUtil.h"
16 #else
17 #include <stdio.h>
18 #include <sys/mman.h>
19 #if defined(_M_ARM_64) && defined(__APPLE__)
20 #include <pthread.h>
21 #endif
22 #if defined __APPLE__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __NetBSD__
23 #include <sys/sysctl.h>
24 #elif defined __HAIKU__
25 #include <OS.h>
26 #else
27 #include <sys/sysinfo.h>
28 #endif
29 #endif
30
31 namespace Common
32 {
33 // This is purposely not a full wrapper for virtualalloc/mmap, but it
34 // provides exactly the primitive operations that Dolphin needs.
35
36 void* AllocateExecutableMemory(size_t size)
37 {
38 #if defined(_WIN32)
39 void* ptr = VirtualAlloc(nullptr, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
40 #else
41 int map_flags = MAP_ANON | MAP_PRIVATE;
42 #if defined(__APPLE__)
43 map_flags |= MAP_JIT;
44 #endif
45 void* ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, map_flags, -1, 0);
46 if (ptr == MAP_FAILED)
47 ptr = nullptr;
48 #endif
49
50 if (ptr == nullptr)
51 PanicAlertFmt("Failed to allocate executable memory");
52
53 return ptr;
54 }
55 // This function is used to provide a counter for the JITPageWrite*Execute*
56 // functions to enable nesting. The static variable is wrapped in a a function
57 // to allow those functions to be called inside of the constructor of a static
58 // variable portably.
59 //
60 // The variable is thread_local as the W^X mode is specific to each running thread.
61 static int& JITPageWriteNestCounter()
62 {
63 static thread_local int nest_counter = 0;
64 return nest_counter;
65 }
66
67 // Certain platforms (Mac OS on ARM) enforce that a single thread can only have write or
68 // execute permissions to pages at any given point of time. The two below functions
69 // are used to toggle between having write permissions or execute permissions.
70 //
71 // The default state of these allocations in Dolphin is for them to be executable,
72 // but not writeable. So, functions that are updating these pages should wrap their
73 // writes like below:
74
75 // JITPageWriteEnableExecuteDisable();
76 // PrepareInstructionStreamForJIT();
77 // JITPageWriteDisableExecuteEnable();
78
79 // These functions can be nested, in which case execution will only be enabled
80 // after the call to the JITPageWriteDisableExecuteEnable from the top most
81 // nesting level. Example:
82
83 // [JIT page is in execute mode for the thread]
84 // JITPageWriteEnableExecuteDisable();
85 // [JIT page is in write mode for the thread]
86 // JITPageWriteEnableExecuteDisable();
87 // [JIT page is in write mode for the thread]
88 // JITPageWriteDisableExecuteEnable();
89 // [JIT page is in write mode for the thread]
90 // JITPageWriteDisableExecuteEnable();
91 // [JIT page is in execute mode for the thread]
92
93 // Allows a thread to write to executable memory, but not execute the data.
94 void JITPageWriteEnableExecuteDisable()
95 {
96 #if defined(_M_ARM_64) && defined(__APPLE__)
97 if (JITPageWriteNestCounter() == 0)
98 {
99 pthread_jit_write_protect_np(0);
100 }
101 #endif
102 JITPageWriteNestCounter()++;
103 }
104 // Allows a thread to execute memory allocated for execution, but not write to it.
105 void JITPageWriteDisableExecuteEnable()
106 {
107 JITPageWriteNestCounter()--;
108
109 // Sanity check the NestCounter to identify underflow
110 // This can indicate the calls to JITPageWriteDisableExecuteEnable()
111 // are not matched with previous calls to JITPageWriteEnableExecuteDisable()
112 if (JITPageWriteNestCounter() < 0)
113 PanicAlertFmt("JITPageWriteNestCounter() underflowed");
114
115 #if defined(_M_ARM_64) && defined(__APPLE__)
116 if (JITPageWriteNestCounter() == 0)
117 {
118 pthread_jit_write_protect_np(1);
119 }
120 #endif
121 }
122
123 void* AllocateMemoryPages(size_t size)
124 {
125 #ifdef _WIN32
126 void* ptr = VirtualAlloc(nullptr, size, MEM_COMMIT, PAGE_READWRITE);
127 #else
128 void* ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
129
130 if (ptr == MAP_FAILED)
131 ptr = nullptr;
132 #endif
133
134 if (ptr == nullptr)
135 PanicAlertFmt("Failed to allocate raw memory");
136
137 return ptr;
138 }
139
140 void* AllocateAlignedMemory(size_t size, size_t alignment)
141 {
142 #ifdef _WIN32
143 void* ptr = _aligned_malloc(size, alignment);
144 #else
145 void* ptr = nullptr;
146 if (posix_memalign(&ptr, alignment, size) != 0)
147 ERROR_LOG_FMT(MEMMAP, "Failed to allocate aligned memory");
148 #endif
149
150 if (ptr == nullptr)
151 PanicAlertFmt("Failed to allocate aligned memory");
152
153 return ptr;
154 }
155
156 bool FreeMemoryPages(void* ptr, size_t size)
157 {
158 if (ptr)
159 {
160 #ifdef _WIN32
161 if (!VirtualFree(ptr, 0, MEM_RELEASE))
162 {
163 PanicAlertFmt("FreeMemoryPages failed!\nVirtualFree: {}", GetLastErrorString());
164 return false;
165 }
166 #else
167 if (munmap(ptr, size) != 0)
168 {
169 PanicAlertFmt("FreeMemoryPages failed!\nmunmap: {}", LastStrerrorString());
170 return false;
171 }
172 #endif
173 }
174 return true;
175 }
176
177 void FreeAlignedMemory(void* ptr)
178 {
179 if (ptr)
180 {
181 #ifdef _WIN32
182 _aligned_free(ptr);
183 #else
184 free(ptr);
185 #endif
186 }
187 }
188
189 bool ReadProtectMemory(void* ptr, size_t size)
190 {
191 #ifdef _WIN32
192 DWORD oldValue;
193 if (!VirtualProtect(ptr, size, PAGE_NOACCESS, &oldValue))
194 {
195 PanicAlertFmt("ReadProtectMemory failed!\nVirtualProtect: {}", GetLastErrorString());
196 return false;
197 }
198 #else
199 if (mprotect(ptr, size, PROT_NONE) != 0)
200 {
201 PanicAlertFmt("ReadProtectMemory failed!\nmprotect: {}", LastStrerrorString());
202 return false;
203 }
204 #endif
205 return true;
206 }
207
208 bool WriteProtectMemory(void* ptr, size_t size, bool allowExecute)
209 {
210 #ifdef _WIN32
211 DWORD oldValue;
212 if (!VirtualProtect(ptr, size, allowExecute ? PAGE_EXECUTE_READ : PAGE_READONLY, &oldValue))
213 {
214 PanicAlertFmt("WriteProtectMemory failed!\nVirtualProtect: {}", GetLastErrorString());
215 return false;
216 }
217 #elif !(defined(_M_ARM_64) && defined(__APPLE__))
218 // MacOS 11.2 on ARM does not allow for changing the access permissions of pages
219 // that were marked executable, instead it uses the protections offered by MAP_JIT
220 // for write protection.
221 if (mprotect(ptr, size, allowExecute ? (PROT_READ | PROT_EXEC) : PROT_READ) != 0)
222 {
223 PanicAlertFmt("WriteProtectMemory failed!\nmprotect: {}", LastStrerrorString());
224 return false;
225 }
226 #endif
227 return true;
228 }
229
230 bool UnWriteProtectMemory(void* ptr, size_t size, bool allowExecute)
231 {
232 #ifdef _WIN32
233 DWORD oldValue;
234 if (!VirtualProtect(ptr, size, allowExecute ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE, &oldValue))
235 {
236 PanicAlertFmt("UnWriteProtectMemory failed!\nVirtualProtect: {}", GetLastErrorString());
237 return false;
238 }
239 #elif !(defined(_M_ARM_64) && defined(__APPLE__))
240 // MacOS 11.2 on ARM does not allow for changing the access permissions of pages
241 // that were marked executable, instead it uses the protections offered by MAP_JIT
242 // for write protection.
243 if (mprotect(ptr, size,
244 allowExecute ? (PROT_READ | PROT_WRITE | PROT_EXEC) : PROT_WRITE | PROT_READ) != 0)
245 {
246 PanicAlertFmt("UnWriteProtectMemory failed!\nmprotect: {}", LastStrerrorString());
247 return false;
248 }
249 #endif
250 return true;
251 }
252
253 size_t MemPhysical()
254 {
255 #ifdef _WIN32
256 MEMORYSTATUSEX memInfo;
257 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
258 GlobalMemoryStatusEx(&memInfo);
259 return memInfo.ullTotalPhys;
260 #elif defined __APPLE__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __NetBSD__
261 int mib[2];
262 size_t physical_memory;
263 mib[0] = CTL_HW;
264 #ifdef __APPLE__
265 mib[1] = HW_MEMSIZE;
266 #elif defined __FreeBSD__
267 mib[1] = HW_REALMEM;
268 #elif defined __OpenBSD__ || defined __NetBSD__
269 mib[1] = HW_PHYSMEM64;
270 #endif
271 size_t length = sizeof(size_t);
272 sysctl(mib, 2, &physical_memory, &length, nullptr, 0);
273 return physical_memory;
274 #elif defined __HAIKU__
275 system_info sysinfo;
276 get_system_info(&sysinfo);
277 return static_cast<size_t>(sysinfo.max_pages * B_PAGE_SIZE);
278 #else
279 struct sysinfo memInfo;
280 sysinfo(&memInfo);
281 return (size_t)memInfo.totalram * memInfo.mem_unit;
282 #endif
283 }
284
285 } // namespace Common