Skip to content

Commit 6d4055a

Browse files
committed
Add hat::process::is_readable
1 parent f002f79 commit 6d4055a

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

include/libhat/Process.hpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ namespace hat::process {
1414
}
1515

1616
/// Returns the complete memory region for the given module. This may include portions which are uncommitted.
17+
/// To verify whether the region is safe to read, use hat::process::is_readable.
1718
[[nodiscard]] std::span<std::byte> get_module_data() const;
1819

1920
/// Returns the memory region for a named section
@@ -29,6 +30,9 @@ namespace hat::process {
2930
uintptr_t baseAddress{};
3031
};
3132

33+
/// Returns whether the entirety of a given memory region is readable
34+
[[nodiscard]] bool is_readable(std::span<const std::byte> region);
35+
3236
/// Returns the module for the current process's base executable
3337
[[nodiscard]] hat::process::module get_process_module();
3438

src/os/win32/Process.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,23 @@ namespace hat::process {
4141
return *reinterpret_cast<const IMAGE_NT_HEADERS*>(scanBytes + dosHeader->e_lfanew);
4242
}
4343

44+
bool hat::process::is_readable(const std::span<const std::byte> region) {
45+
for (auto* addr = region.data(); addr < region.data() + region.size();) {
46+
MEMORY_BASIC_INFORMATION mbi{};
47+
if (!VirtualQuery(addr, &mbi, sizeof(mbi))) {
48+
return false;
49+
}
50+
if (mbi.State != MEM_COMMIT) {
51+
return false;
52+
}
53+
if (!(mbi.Protect & (PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_READONLY | PAGE_READWRITE))) {
54+
return false;
55+
}
56+
addr = static_cast<const std::byte*>(mbi.BaseAddress) + mbi.RegionSize;
57+
}
58+
return true;
59+
}
60+
4461
hat::process::module get_process_module() {
4562
return module{reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr))};
4663
}

0 commit comments

Comments
 (0)