From fc4c96b8c0b7a0fffa45e24c6f45e83b8b4941ea Mon Sep 17 00:00:00 2001 From: Antonio Date: Mon, 5 Aug 2024 22:31:01 -0400 Subject: [PATCH] Changed Protect for Windows --- src/core/address_space.cpp | 57 +++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/src/core/address_space.cpp b/src/core/address_space.cpp index 741cd4fe..d5d35157 100644 --- a/src/core/address_space.cpp +++ b/src/core/address_space.cpp @@ -217,29 +217,36 @@ struct AddressSpace::Impl { } void Protect(VAddr virtual_addr, size_t size, bool read, bool write, bool execute) { - DWORD new_flags{}; - if (read && write) { - new_flags = PAGE_READWRITE; - } else if (read && !write) { - new_flags = PAGE_READONLY; - } else if (!read && !write) { - new_flags = PAGE_NOACCESS; - } else { - UNIMPLEMENTED_MSG("Protection flag combination read={} write={}", read, write); - } - - const VAddr virtual_end = virtual_addr + size; - auto [it, end] = placeholders.equal_range({virtual_addr, virtual_end}); - while (it != end) { - const size_t offset = std::max(it->lower(), virtual_addr); - const size_t protect_length = std::min(it->upper(), virtual_end) - offset; - DWORD old_flags{}; - if (!VirtualProtect(virtual_base + offset, protect_length, new_flags, &old_flags)) { - LOG_CRITICAL(Common_Memory, "Failed to change virtual memory protect rules"); + DWORD new_flags{}; + if (read && write) { + new_flags = PAGE_READWRITE; + } else if (read && !write) { + new_flags = PAGE_READONLY; + } else if (!read && !write) { + new_flags = PAGE_NOACCESS; + } else { + UNIMPLEMENTED_MSG("Protection flag combination read={} write={}", read, write); } - ++it; - } - } + + MEMORY_BASIC_INFORMATION info; + VirtualQuery(reinterpret_cast(virtual_addr), &info, sizeof(info)); + LOG_INFO(Common_Memory, "Current protection flags: {}", info.Protect); + + if (info.Protect == new_flags) { + LOG_INFO(Common_Memory, "Protection flags already match, skipping VirtualProtect"); + return; + } + + + + if (!VirtualProtect(reinterpret_cast(virtual_addr), size, new_flags, nullptr)) { + DWORD error = GetLastError(); + LOG_CRITICAL( + Common_Memory, + "Failed to change virtual memory protect rules: error {}, new_flags = {:#x}", error, + new_flags); + } + } @@ -462,7 +469,11 @@ void AddressSpace::Unmap(VAddr virtual_addr, size_t size, bool has_backing) { } void AddressSpace::Protect(VAddr virtual_addr, size_t size, MemoryPermission perms) { - return impl->Protect(virtual_addr, size, true, true, true); + bool read = static_cast(perms & MemoryPermission::Read) != 0; + bool write = static_cast(perms & MemoryPermission::Write) != 0; + bool execute = static_cast(perms & MemoryPermission::Execute) != 0; // Assuming you have an Execute permission + + return impl->Protect(virtual_addr, size, read, write, execute); } } // namespace Core