| 1 | // Copyright 2008 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/MemArena.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <cstddef> |
| 8 | #include <cstdlib> |
| 9 | #include <string> |
| 10 | |
| 11 | #include <fmt/format.h> |
| 12 | |
| 13 | #include <windows.h> |
| 14 | |
| 15 | #include "Common/Align.h" |
| 16 | #include "Common/Assert.h" |
| 17 | #include "Common/CommonFuncs.h" |
| 18 | #include "Common/CommonTypes.h" |
| 19 | #include "Common/DynamicLibrary.h" |
| 20 | #include "Common/Logging/Log.h" |
| 21 | #include "Common/MsgHandler.h" |
| 22 | #include "Common/StringUtil.h" |
| 23 | |
| 24 | using PVirtualAlloc2 = PVOID(WINAPI*)(HANDLE Process, PVOID BaseAddress, SIZE_T Size, |
| 25 | ULONG AllocationType, ULONG PageProtection, |
| 26 | MEM_EXTENDED_PARAMETER* ExtendedParameters, |
| 27 | ULONG ParameterCount); |
| 28 | |
| 29 | using PMapViewOfFile3 = PVOID(WINAPI*)(HANDLE FileMapping, HANDLE Process, PVOID BaseAddress, |
| 30 | ULONG64 Offset, SIZE_T ViewSize, ULONG AllocationType, |
| 31 | ULONG PageProtection, |
| 32 | MEM_EXTENDED_PARAMETER* ExtendedParameters, |
| 33 | ULONG ParameterCount); |
| 34 | |
| 35 | using PUnmapViewOfFileEx = BOOL(WINAPI*)(PVOID BaseAddress, ULONG UnmapFlags); |
| 36 | |
| 37 | using PIsApiSetImplemented = BOOL(APIENTRY*)(PCSTR Contract); |
| 38 | |
| 39 | namespace Common |
| 40 | { |
| 41 | struct WindowsMemoryRegion |
| 42 | { |
| 43 | u8* m_start; |
| 44 | size_t m_size; |
| 45 | bool m_is_mapped; |
| 46 | |
| 47 | WindowsMemoryRegion(u8* start, size_t size, bool is_mapped) |
| 48 | : m_start(start), m_size(size), m_is_mapped(is_mapped) |
| 49 | { |
| 50 | } |
| 51 | }; |
| 52 | |
| 53 | static bool InitWindowsMemoryFunctions(WindowsMemoryFunctions* functions) |
| 54 | { |
| 55 | DynamicLibrary kernelBase{"KernelBase.dll"}; |
| 56 | if (!kernelBase.IsOpen()) |
| 57 | return false; |
| 58 | |
| 59 | void* const ptr_IsApiSetImplemented = kernelBase.GetSymbolAddress("IsApiSetImplemented"); |
| 60 | if (!ptr_IsApiSetImplemented) |
| 61 | return false; |
| 62 | if (!reinterpret_cast<PIsApiSetImplemented>(ptr_IsApiSetImplemented)( |
| 63 | "api-ms-win-core-memory-l1-1-6")) |
| 64 | return false; |
| 65 | |
| 66 | functions->m_api_ms_win_core_memory_l1_1_6_handle.Open("api-ms-win-core-memory-l1-1-6.dll"); |
| 67 | functions->m_kernel32_handle.Open("Kernel32.dll"); |
| 68 | if (!functions->m_api_ms_win_core_memory_l1_1_6_handle.IsOpen() || |
| 69 | !functions->m_kernel32_handle.IsOpen()) |
| 70 | { |
| 71 | functions->m_api_ms_win_core_memory_l1_1_6_handle.Close(); |
| 72 | functions->m_kernel32_handle.Close(); |
| 73 | return false; |
| 74 | } |
| 75 | |
| 76 | void* const address_VirtualAlloc2 = |
| 77 | functions->m_api_ms_win_core_memory_l1_1_6_handle.GetSymbolAddress("VirtualAlloc2FromApp"); |
| 78 | void* const address_MapViewOfFile3 = |
| 79 | functions->m_api_ms_win_core_memory_l1_1_6_handle.GetSymbolAddress("MapViewOfFile3FromApp"); |
| 80 | void* const address_UnmapViewOfFileEx = |
| 81 | functions->m_kernel32_handle.GetSymbolAddress("UnmapViewOfFileEx"); |
| 82 | if (address_VirtualAlloc2 && address_MapViewOfFile3 && address_UnmapViewOfFileEx) |
| 83 | { |
| 84 | functions->m_address_VirtualAlloc2 = address_VirtualAlloc2; |
| 85 | functions->m_address_MapViewOfFile3 = address_MapViewOfFile3; |
| 86 | functions->m_address_UnmapViewOfFileEx = address_UnmapViewOfFileEx; |
| 87 | return true; |
| 88 | } |
| 89 | |
| 90 | // at least one function is not available, use legacy logic |
| 91 | functions->m_api_ms_win_core_memory_l1_1_6_handle.Close(); |
| 92 | functions->m_kernel32_handle.Close(); |
| 93 | return false; |
| 94 | } |
| 95 | |
| 96 | MemArena::MemArena() |
| 97 | { |
| 98 | // Check if VirtualAlloc2 and MapViewOfFile3 are available, which provide functionality to reserve |
| 99 | // a memory region no other allocation may occupy while still allowing us to allocate and map |
| 100 | // stuff within it. If they're not available we'll instead fall back to the 'legacy' logic and |
| 101 | // just hope that nothing allocates in our address range. |
| 102 | InitWindowsMemoryFunctions(&m_memory_functions); |
| 103 | } |
| 104 | |
| 105 | MemArena::~MemArena() |
| 106 | { |
| 107 | ReleaseMemoryRegion(); |
| 108 | ReleaseSHMSegment(); |
| 109 | } |
| 110 | |
| 111 | static DWORD GetHighDWORD(u64 value) |
| 112 | { |
| 113 | return static_cast<DWORD>(value >> 32); |
| 114 | } |
| 115 | |
| 116 | static DWORD GetLowDWORD(u64 value) |
| 117 | { |
| 118 | return static_cast<DWORD>(value); |
| 119 | } |
| 120 | |
| 121 | void MemArena::GrabSHMSegment(size_t size, std::string_view base_name) |
| 122 | { |
| 123 | const std::string name = fmt::format("{}.{}", base_name, GetCurrentProcessId()); |
| 124 | m_memory_handle = |
| 125 | CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, GetHighDWORD(size), |
| 126 | GetLowDWORD(size), UTF8ToTStr(name).c_str()); |
| 127 | } |
| 128 | |
| 129 | void MemArena::ReleaseSHMSegment() |
| 130 | { |
| 131 | if (!m_memory_handle) |
| 132 | return; |
| 133 | CloseHandle(m_memory_handle); |
| 134 | m_memory_handle = nullptr; |
| 135 | } |
| 136 | |
| 137 | void* MemArena::CreateView(s64 offset, size_t size) |
| 138 | { |
| 139 | const u64 off = static_cast<u64>(offset); |
| 140 | return MapViewOfFileEx(m_memory_handle, FILE_MAP_ALL_ACCESS, GetHighDWORD(off), GetLowDWORD(off), |
| 141 | size, nullptr); |
| 142 | } |
| 143 | |
| 144 | void MemArena::ReleaseView(void* view, size_t size) |
| 145 | { |
| 146 | UnmapViewOfFile(view); |
| 147 | } |
| 148 | |
| 149 | u8* MemArena::ReserveMemoryRegion(size_t memory_size) |
| 150 | { |
| 151 | if (m_reserved_region) |
| 152 | { |
| 153 | PanicAlertFmt("Tried to reserve a second memory region from the same MemArena."); |
| 154 | return nullptr; |
| 155 | } |
| 156 | |
| 157 | u8* base; |
| 158 | if (m_memory_functions.m_api_ms_win_core_memory_l1_1_6_handle.IsOpen()) |
| 159 | { |
| 160 | base = static_cast<u8*>(reinterpret_cast<PVirtualAlloc2>( |
| 161 | m_memory_functions.m_address_VirtualAlloc2)(nullptr, nullptr, memory_size, |
| 162 | MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, |
| 163 | PAGE_NOACCESS, nullptr, 0)); |
| 164 | if (base) |
| 165 | { |
| 166 | m_reserved_region = base; |
| 167 | m_regions.emplace_back(base, memory_size, false); |
| 168 | } |
| 169 | else |
| 170 | { |
| 171 | PanicAlertFmt("Failed to map enough memory space: {}", GetLastErrorString()); |
| 172 | } |
| 173 | } |
| 174 | else |
| 175 | { |
| 176 | NOTICE_LOG_FMT(MEMMAP, "VirtualAlloc2 and/or MapViewFromFile3 unavailable. " |
| 177 | "Falling back to legacy memory mapping."); |
| 178 | base = static_cast<u8*>(VirtualAlloc(nullptr, memory_size, MEM_RESERVE, PAGE_READWRITE)); |
| 179 | if (base) |
| 180 | VirtualFree(base, 0, MEM_RELEASE); |
| 181 | else |
| 182 | PanicAlertFmt("Failed to find enough memory space: {}", GetLastErrorString()); |
| 183 | } |
| 184 | |
| 185 | return base; |
| 186 | } |
| 187 | |
| 188 | void MemArena::ReleaseMemoryRegion() |
| 189 | { |
| 190 | if (m_memory_functions.m_api_ms_win_core_memory_l1_1_6_handle.IsOpen() && m_reserved_region) |
| 191 | { |
| 192 | // user should have unmapped everything by this point, check if that's true and yell if not |
| 193 | // (it indicates a bug in the emulated memory mapping logic) |
| 194 | size_t mapped_region_count = 0; |
| 195 | for (const auto& r : m_regions) |
| 196 | { |
| 197 | if (r.m_is_mapped) |
| 198 | ++mapped_region_count; |
| 199 | } |
| 200 | |
| 201 | if (mapped_region_count > 0) |
| 202 | { |
| 203 | PanicAlertFmt("Error while releasing fastmem region: {} regions are still mapped!", |
| 204 | mapped_region_count); |
| 205 | } |
| 206 | |
| 207 | // then free memory |
| 208 | VirtualFree(m_reserved_region, 0, MEM_RELEASE); |
| 209 | m_reserved_region = nullptr; |
| 210 | m_regions.clear(); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | WindowsMemoryRegion* MemArena::EnsureSplitRegionForMapping(void* start_address, size_t size) |
| 215 | { |
| 216 | u8* const address = static_cast<u8*>(start_address); |
| 217 | auto& regions = m_regions; |
| 218 | if (regions.empty()) |
| 219 | { |
| 220 | NOTICE_LOG_FMT(MEMMAP, "Tried to map a memory region without reserving a memory block first."); |
| 221 | return nullptr; |
| 222 | } |
| 223 | |
| 224 | // find closest region that is <= the given address by using upper bound and decrementing |
| 225 | auto it = std::ranges::upper_bound(regions, address, {}, &WindowsMemoryRegion::m_start); |
| 226 | if (it == regions.begin()) |
| 227 | { |
| 228 | // this should never happen, implies that the given address is before the start of the |
| 229 | // reserved memory block |
| 230 | NOTICE_LOG_FMT(MEMMAP, "Invalid address {} given to map.", fmt::ptr(address)); |
| 231 | return nullptr; |
| 232 | } |
| 233 | --it; |
| 234 | |
| 235 | if (it->m_is_mapped) |
| 236 | { |
| 237 | NOTICE_LOG_FMT(MEMMAP, |
| 238 | "Address to map {} with a size of 0x{:x} overlaps with existing mapping " |
| 239 | "at {}.", |
| 240 | fmt::ptr(address), size, fmt::ptr(it->m_start)); |
| 241 | return nullptr; |
| 242 | } |
| 243 | |
| 244 | const size_t mapping_index = it - regions.begin(); |
| 245 | u8* const mapping_address = it->m_start; |
| 246 | const size_t mapping_size = it->m_size; |
| 247 | if (mapping_address == address) |
| 248 | { |
| 249 | // if this region is already split up correctly we don't have to do anything |
| 250 | if (mapping_size == size) |
| 251 | return &*it; |
| 252 | |
| 253 | // if this region is smaller than the requested size we can't map |
| 254 | if (mapping_size < size) |
| 255 | { |
| 256 | NOTICE_LOG_FMT(MEMMAP, |
| 257 | "Not enough free space at address {} to map 0x{:x} bytes (0x{:x} available).", |
| 258 | fmt::ptr(mapping_address), size, mapping_size); |
| 259 | return nullptr; |
| 260 | } |
| 261 | |
| 262 | // split region |
| 263 | if (!VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) |
| 264 | { |
| 265 | NOTICE_LOG_FMT(MEMMAP, "Region splitting failed: {}", GetLastErrorString()); |
| 266 | return nullptr; |
| 267 | } |
| 268 | |
| 269 | // update tracked mappings and return the first of the two |
| 270 | it->m_size = size; |
| 271 | u8* const new_mapping_start = address + size; |
| 272 | const size_t new_mapping_size = mapping_size - size; |
| 273 | regions.insert(it + 1, WindowsMemoryRegion(new_mapping_start, new_mapping_size, false)); |
| 274 | return ®ions[mapping_index]; |
| 275 | } |
| 276 | |
| 277 | ASSERT(mapping_address < address); |
| 278 | |
| 279 | // is there enough space to map this? |
| 280 | const size_t size_before = static_cast<size_t>(address - mapping_address); |
| 281 | const size_t minimum_size = size + size_before; |
| 282 | if (mapping_size < minimum_size) |
| 283 | { |
| 284 | NOTICE_LOG_FMT(MEMMAP, |
| 285 | "Not enough free space at address {} to map memory region (need 0x{:x} " |
| 286 | "bytes, but only 0x{:x} available).", |
| 287 | fmt::ptr(address), minimum_size, mapping_size); |
| 288 | return nullptr; |
| 289 | } |
| 290 | |
| 291 | // split region |
| 292 | if (!VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) |
| 293 | { |
| 294 | NOTICE_LOG_FMT(MEMMAP, "Region splitting failed: {}", GetLastErrorString()); |
| 295 | return nullptr; |
| 296 | } |
| 297 | |
| 298 | // do we now have two regions or three regions? |
| 299 | if (mapping_size == minimum_size) |
| 300 | { |
| 301 | // split into two; update tracked mappings and return the second one |
| 302 | it->m_size = size_before; |
| 303 | u8* const new_mapping_start = address; |
| 304 | const size_t new_mapping_size = size; |
| 305 | regions.insert(it + 1, WindowsMemoryRegion(new_mapping_start, new_mapping_size, false)); |
| 306 | return ®ions[mapping_index + 1]; |
| 307 | } |
| 308 | else |
| 309 | { |
| 310 | // split into three; update tracked mappings and return the middle one |
| 311 | it->m_size = size_before; |
| 312 | u8* const middle_mapping_start = address; |
| 313 | const size_t middle_mapping_size = size; |
| 314 | u8* const after_mapping_start = address + size; |
| 315 | const size_t after_mapping_size = mapping_size - minimum_size; |
| 316 | regions.insert(it + 1, WindowsMemoryRegion(after_mapping_start, after_mapping_size, false)); |
| 317 | regions.insert(regions.begin() + mapping_index + 1, |
| 318 | WindowsMemoryRegion(middle_mapping_start, middle_mapping_size, false)); |
| 319 | return ®ions[mapping_index + 1]; |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | void* MemArena::MapInMemoryRegion(s64 offset, size_t size, void* base, bool writeable) |
| 324 | { |
| 325 | void* result; |
| 326 | |
| 327 | if (m_memory_functions.m_api_ms_win_core_memory_l1_1_6_handle.IsOpen()) |
| 328 | { |
| 329 | WindowsMemoryRegion* const region = EnsureSplitRegionForMapping(base, size); |
| 330 | if (!region) |
| 331 | { |
| 332 | PanicAlertFmt("Splitting memory region failed."); |
| 333 | return nullptr; |
| 334 | } |
| 335 | |
| 336 | result = reinterpret_cast<PMapViewOfFile3>(m_memory_functions.m_address_MapViewOfFile3)( |
| 337 | m_memory_handle, nullptr, base, offset, size, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, |
| 338 | nullptr, 0); |
| 339 | if (result) |
| 340 | { |
| 341 | region->m_is_mapped = true; |
| 342 | } |
| 343 | else |
| 344 | { |
| 345 | PanicAlertFmt("Mapping memory region failed: {}", GetLastErrorString()); |
| 346 | |
| 347 | // revert the split, if any |
| 348 | JoinRegionsAfterUnmap(base, size); |
| 349 | |
| 350 | return nullptr; |
| 351 | } |
| 352 | } |
| 353 | else |
| 354 | { |
| 355 | result = |
| 356 | MapViewOfFileEx(m_memory_handle, FILE_MAP_ALL_ACCESS, 0, (DWORD)((u64)offset), size, base); |
| 357 | |
| 358 | if (!result) |
| 359 | return nullptr; |
| 360 | } |
| 361 | |
| 362 | if (!writeable) |
| 363 | { |
| 364 | // If we want to use PAGE_READONLY for now while still being able to switch to PAGE_READWRITE |
| 365 | // later, we have to call MapViewOfFile with PAGE_READWRITE and then switch to PAGE_READONLY. |
| 366 | ChangeMappingProtection(base, size, writeable); |
| 367 | } |
| 368 | |
| 369 | return result; |
| 370 | } |
| 371 | |
| 372 | bool MemArena::ChangeMappingProtection(void* view, size_t size, bool writeable) |
| 373 | { |
| 374 | DWORD old_protect; |
| 375 | const int retval = |
| 376 | VirtualProtect(view, size, writeable ? PAGE_READWRITE : PAGE_READONLY, &old_protect); |
| 377 | if (retval == 0) |
| 378 | PanicAlertFmt("VirtualProtect failed: {}", GetLastErrorString()); |
| 379 | return retval != 0; |
| 380 | } |
| 381 | |
| 382 | bool MemArena::JoinRegionsAfterUnmap(void* start_address, size_t size) |
| 383 | { |
| 384 | u8* const address = static_cast<u8*>(start_address); |
| 385 | auto& regions = m_regions; |
| 386 | if (regions.empty()) |
| 387 | { |
| 388 | NOTICE_LOG_FMT(MEMMAP, |
| 389 | "Tried to unmap a memory region without reserving a memory block first."); |
| 390 | return false; |
| 391 | } |
| 392 | |
| 393 | // there should be a mapping that matches the request exactly, find it |
| 394 | auto it = std::ranges::lower_bound(regions, address, {}, &WindowsMemoryRegion::m_start); |
| 395 | if (it == regions.end() || it->m_start != address || it->m_size != size) |
| 396 | { |
| 397 | // didn't find it, we were given bogus input |
| 398 | NOTICE_LOG_FMT(MEMMAP, "Invalid address/size given to unmap."); |
| 399 | return false; |
| 400 | } |
| 401 | it->m_is_mapped = false; |
| 402 | |
| 403 | const bool can_join_with_preceding = it != regions.begin() && !(it - 1)->m_is_mapped; |
| 404 | const bool can_join_with_succeeding = (it + 1) != regions.end() && !(it + 1)->m_is_mapped; |
| 405 | if (can_join_with_preceding && can_join_with_succeeding) |
| 406 | { |
| 407 | // join three mappings to one |
| 408 | auto it_preceding = it - 1; |
| 409 | auto it_succeeding = it + 1; |
| 410 | const size_t total_size = it_preceding->m_size + size + it_succeeding->m_size; |
| 411 | if (!VirtualFree(it_preceding->m_start, total_size, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) |
| 412 | { |
| 413 | NOTICE_LOG_FMT(MEMMAP, "Region coalescing failed: {}", GetLastErrorString()); |
| 414 | return false; |
| 415 | } |
| 416 | |
| 417 | it_preceding->m_size = total_size; |
| 418 | regions.erase(it, it + 2); |
| 419 | } |
| 420 | else if (can_join_with_preceding && !can_join_with_succeeding) |
| 421 | { |
| 422 | // join two mappings to one |
| 423 | auto it_preceding = it - 1; |
| 424 | const size_t total_size = it_preceding->m_size + size; |
| 425 | if (!VirtualFree(it_preceding->m_start, total_size, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) |
| 426 | { |
| 427 | NOTICE_LOG_FMT(MEMMAP, "Region coalescing failed: {}", GetLastErrorString()); |
| 428 | return false; |
| 429 | } |
| 430 | |
| 431 | it_preceding->m_size = total_size; |
| 432 | regions.erase(it); |
| 433 | } |
| 434 | else if (!can_join_with_preceding && can_join_with_succeeding) |
| 435 | { |
| 436 | // join two mappings to one |
| 437 | auto it_succeeding = it + 1; |
| 438 | const size_t total_size = size + it_succeeding->m_size; |
| 439 | if (!VirtualFree(it->m_start, total_size, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) |
| 440 | { |
| 441 | NOTICE_LOG_FMT(MEMMAP, "Region coalescing failed: {}", GetLastErrorString()); |
| 442 | return false; |
| 443 | } |
| 444 | |
| 445 | it->m_size = total_size; |
| 446 | regions.erase(it_succeeding); |
| 447 | } |
| 448 | return true; |
| 449 | } |
| 450 | |
| 451 | void MemArena::UnmapFromMemoryRegion(void* view, size_t size) |
| 452 | { |
| 453 | if (m_memory_functions.m_api_ms_win_core_memory_l1_1_6_handle.IsOpen()) |
| 454 | { |
| 455 | if (reinterpret_cast<PUnmapViewOfFileEx>(m_memory_functions.m_address_UnmapViewOfFileEx)( |
| 456 | view, MEM_PRESERVE_PLACEHOLDER)) |
| 457 | { |
| 458 | if (!JoinRegionsAfterUnmap(view, size)) |
| 459 | PanicAlertFmt("Joining memory region failed."); |
| 460 | } |
| 461 | else |
| 462 | { |
| 463 | PanicAlertFmt("Unmapping memory region failed: {}", GetLastErrorString()); |
| 464 | } |
| 465 | return; |
| 466 | } |
| 467 | |
| 468 | UnmapViewOfFile(view); |
| 469 | } |
| 470 | |
| 471 | size_t MemArena::GetPageSize() const |
| 472 | { |
| 473 | SYSTEM_INFO si; |
| 474 | GetSystemInfo(&si); |
| 475 | |
| 476 | if (!m_memory_functions.m_address_MapViewOfFile3) |
| 477 | { |
| 478 | // In this case, we can only map pages that are 64K aligned. |
| 479 | // See https://devblogs.microsoft.com/oldnewthing/20031008-00/?p=42223 |
| 480 | return std::max<size_t>(si.dwPageSize, 64 * 1024); |
| 481 | } |
| 482 | |
| 483 | return si.dwPageSize; |
| 484 | } |
| 485 | |
| 486 | LazyMemoryRegion::LazyMemoryRegion() |
| 487 | { |
| 488 | InitWindowsMemoryFunctions(&m_memory_functions); |
| 489 | } |
| 490 | |
| 491 | LazyMemoryRegion::~LazyMemoryRegion() |
| 492 | { |
| 493 | Release(); |
| 494 | } |
| 495 | |
| 496 | void* LazyMemoryRegion::Create(size_t size) |
| 497 | { |
| 498 | ASSERT(!m_memory); |
| 499 | |
| 500 | if (size == 0) |
| 501 | return nullptr; |
| 502 | |
| 503 | if (!m_memory_functions.m_api_ms_win_core_memory_l1_1_6_handle.IsOpen()) |
| 504 | return nullptr; |
| 505 | |
| 506 | // reserve block of memory |
| 507 | const size_t memory_size = Common::AlignUp(size, BLOCK_SIZE); |
| 508 | const size_t block_count = memory_size / BLOCK_SIZE; |
| 509 | u8* memory = |
| 510 | static_cast<u8*>(reinterpret_cast<PVirtualAlloc2>(m_memory_functions.m_address_VirtualAlloc2)( |
| 511 | nullptr, nullptr, memory_size, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, |
| 512 | nullptr, 0)); |
| 513 | if (!memory) |
| 514 | { |
| 515 | NOTICE_LOG_FMT(MEMMAP, "Memory reservation of {} bytes failed.", size); |
| 516 | return nullptr; |
| 517 | } |
| 518 | |
| 519 | // split into individual block-sized regions |
| 520 | for (size_t i = 0; i < block_count - 1; ++i) |
| 521 | { |
| 522 | if (!VirtualFree(memory + i * BLOCK_SIZE, BLOCK_SIZE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) |
| 523 | { |
| 524 | NOTICE_LOG_FMT(MEMMAP, "Region splitting failed: {}", GetLastErrorString()); |
| 525 | |
| 526 | // release every split block as well as the remaining unsplit one |
| 527 | for (size_t j = 0; j < i + 1; ++j) |
| 528 | VirtualFree(memory + j * BLOCK_SIZE, 0, MEM_RELEASE); |
| 529 | |
| 530 | return nullptr; |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | m_memory = memory; |
| 535 | m_size = memory_size; |
| 536 | |
| 537 | // allocate a single block of real memory in the page file |
| 538 | HANDLE zero_block = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READONLY, |
| 539 | GetHighDWORD(BLOCK_SIZE), GetLowDWORD(BLOCK_SIZE), nullptr); |
| 540 | if (zero_block == nullptr) |
| 541 | { |
| 542 | NOTICE_LOG_FMT(MEMMAP, "CreateFileMapping() failed for zero block: {}", GetLastErrorString()); |
| 543 | Release(); |
| 544 | return nullptr; |
| 545 | } |
| 546 | |
| 547 | m_zero_block = zero_block; |
| 548 | |
| 549 | // map the zero page into every block |
| 550 | for (size_t i = 0; i < block_count; ++i) |
| 551 | { |
| 552 | void* result = reinterpret_cast<PMapViewOfFile3>(m_memory_functions.m_address_MapViewOfFile3)( |
| 553 | zero_block, nullptr, memory + i * BLOCK_SIZE, 0, BLOCK_SIZE, MEM_REPLACE_PLACEHOLDER, |
| 554 | PAGE_READONLY, nullptr, 0); |
| 555 | if (!result) |
| 556 | { |
| 557 | NOTICE_LOG_FMT(MEMMAP, "Mapping the zero block failed: {}", GetLastErrorString()); |
| 558 | Release(); |
| 559 | return nullptr; |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | m_writable_block_handles.resize(block_count, nullptr); |
| 564 | |
| 565 | return memory; |
| 566 | } |
| 567 | |
| 568 | void LazyMemoryRegion::Clear() |
| 569 | { |
| 570 | ASSERT(m_memory); |
| 571 | u8* const memory = static_cast<u8*>(m_memory); |
| 572 | |
| 573 | // reset every writable block back to the zero block |
| 574 | for (size_t i = 0; i < m_writable_block_handles.size(); ++i) |
| 575 | { |
| 576 | if (m_writable_block_handles[i] == nullptr) |
| 577 | continue; |
| 578 | |
| 579 | // unmap the writable block |
| 580 | if (!reinterpret_cast<PUnmapViewOfFileEx>(m_memory_functions.m_address_UnmapViewOfFileEx)( |
| 581 | memory + i * BLOCK_SIZE, MEM_PRESERVE_PLACEHOLDER)) |
| 582 | { |
| 583 | PanicAlertFmt("Failed to unmap the writable block: {}", GetLastErrorString()); |
| 584 | } |
| 585 | |
| 586 | // free the writable block |
| 587 | if (!CloseHandle(m_writable_block_handles[i])) |
| 588 | { |
| 589 | PanicAlertFmt("Failed to free the writable block: {}", GetLastErrorString()); |
| 590 | } |
| 591 | m_writable_block_handles[i] = nullptr; |
| 592 | |
| 593 | // map the zero block |
| 594 | void* map_result = |
| 595 | reinterpret_cast<PMapViewOfFile3>(m_memory_functions.m_address_MapViewOfFile3)( |
| 596 | m_zero_block, nullptr, memory + i * BLOCK_SIZE, 0, BLOCK_SIZE, MEM_REPLACE_PLACEHOLDER, |
| 597 | PAGE_READONLY, nullptr, 0); |
| 598 | if (!map_result) |
| 599 | { |
| 600 | PanicAlertFmt("Failed to re-map the zero block: {}", GetLastErrorString()); |
| 601 | } |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | void LazyMemoryRegion::Release() |
| 606 | { |
| 607 | if (m_memory) |
| 608 | { |
| 609 | // unmap all pages and release the not-zero block handles |
| 610 | u8* const memory = static_cast<u8*>(m_memory); |
| 611 | for (size_t i = 0; i < m_writable_block_handles.size(); ++i) |
| 612 | { |
| 613 | reinterpret_cast<PUnmapViewOfFileEx>(m_memory_functions.m_address_UnmapViewOfFileEx)( |
| 614 | memory + i * BLOCK_SIZE, MEM_PRESERVE_PLACEHOLDER); |
| 615 | if (m_writable_block_handles[i]) |
| 616 | { |
| 617 | CloseHandle(m_writable_block_handles[i]); |
| 618 | m_writable_block_handles[i] = nullptr; |
| 619 | } |
| 620 | } |
| 621 | } |
| 622 | if (m_zero_block) |
| 623 | { |
| 624 | CloseHandle(m_zero_block); |
| 625 | m_zero_block = nullptr; |
| 626 | } |
| 627 | if (m_memory) |
| 628 | { |
| 629 | u8* const memory = static_cast<u8*>(m_memory); |
| 630 | const size_t block_count = m_size / BLOCK_SIZE; |
| 631 | for (size_t i = 0; i < block_count; ++i) |
| 632 | VirtualFree(memory + i * BLOCK_SIZE, 0, MEM_RELEASE); |
| 633 | m_memory = nullptr; |
| 634 | m_size = 0; |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | void LazyMemoryRegion::MakeMemoryBlockWritable(size_t block_index) |
| 639 | { |
| 640 | u8* const memory = static_cast<u8*>(m_memory); |
| 641 | |
| 642 | // unmap the zero block |
| 643 | if (!reinterpret_cast<PUnmapViewOfFileEx>(m_memory_functions.m_address_UnmapViewOfFileEx)( |
| 644 | memory + block_index * BLOCK_SIZE, MEM_PRESERVE_PLACEHOLDER)) |
| 645 | { |
| 646 | PanicAlertFmt("Failed to unmap the zero block: {}", GetLastErrorString()); |
| 647 | return; |
| 648 | } |
| 649 | |
| 650 | // allocate a fresh block to map |
| 651 | HANDLE block = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, |
| 652 | GetHighDWORD(BLOCK_SIZE), GetLowDWORD(BLOCK_SIZE), nullptr); |
| 653 | if (block == nullptr) |
| 654 | { |
| 655 | PanicAlertFmt("CreateFileMapping() failed for writable block: {}", GetLastErrorString()); |
| 656 | return; |
| 657 | } |
| 658 | |
| 659 | // map the new block |
| 660 | void* map_result = reinterpret_cast<PMapViewOfFile3>(m_memory_functions.m_address_MapViewOfFile3)( |
| 661 | block, nullptr, memory + block_index * BLOCK_SIZE, 0, BLOCK_SIZE, MEM_REPLACE_PLACEHOLDER, |
| 662 | PAGE_READWRITE, nullptr, 0); |
| 663 | if (!map_result) |
| 664 | { |
| 665 | PanicAlertFmt("Failed to map the writable block: {}", GetLastErrorString()); |
| 666 | CloseHandle(block); |
| 667 | return; |
| 668 | } |
| 669 | |
| 670 | m_writable_block_handles[block_index] = block; |
| 671 | } |
| 672 | |
| 673 | } // namespace Common |