Changed Protect for Windows

This commit is contained in:
Antonio 2024-08-05 22:31:01 -04:00
parent 9ad6317f01
commit fc4c96b8c0
1 changed files with 34 additions and 23 deletions

View File

@ -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<LPVOID>(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<LPVOID>(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<int>(perms & MemoryPermission::Read) != 0;
bool write = static_cast<int>(perms & MemoryPermission::Write) != 0;
bool execute = static_cast<int>(perms & MemoryPermission::Execute) != 0; // Assuming you have an Execute permission
return impl->Protect(virtual_addr, size, read, write, execute);
}
} // namespace Core