Creating a "simple internal memory reader" using the Windows API can mean a few things:
- Reading memory within your own process: This is generally straightforward, as you have direct access to your process's memory space. You'd primarily use
VirtualQuery to get information about memory regions and then just dereference pointers (or ReadProcessMemory on your own handle for consistency).
- Reading memory from another process: This is more complex and requires specific permissions. It involves
OpenProcess to get a handle to the target process, then VirtualQueryEx to enumerate its memory regions, and finally ReadProcessMemory to read the actual data.
Given the "simple" constraint, I'll provide an example primarily focused on reading memory within your own process, showing how to inspect regions and read values using Windows API functions. I will also briefly mention and demonstrate the core function for reading from another process (ReadProcessMemory) as it's fundamental.
Core Windows API Functions Used:
VirtualQuery (or VirtualQueryEx for other processes): This function retrieves information about a range of pages in the virtual address space of a process. It tells you about the base address, size, state (committed, reserved, free), and protection (read, write, execute) of a memory region.
ReadProcessMemory: Reads data from an area of memory in a specified process. This is the primary function for getting the actual byte content.
GetCurrentProcess: Gets a pseudohandle for the current process. This handle can be used by functions that require a process handle.
OpenProcess: (If reading from another process) Opens an existing local process object. You need specific access rights (e.g., PROCESS_VM_READ).
Example: Simple Internal Memory Reader (Current Process)
This example will:
- Define a global variable and read its value using
ReadProcessMemory.
- Enumerate some of the current process's memory regions using
VirtualQuery and print their basic information.
- Provide a utility function to read arbitrary bytes from a given address within the current process, checking for readability.
Prerequisites:
- A C++ compiler (like MSVC in Visual Studio, or MinGW-w64).
- Windows SDK (usually comes with Visual Studio).
#include <iostream>
#include <windows.h> // For Windows API functions
#include <vector> // For dynamic arrays
#include <iomanip> // For std::hex, std::setfill, std::setw
// A global variable to demonstrate reading a known address
int g_myGlobalVariable = 0xDEADBEEF; // Some distinct value
// --- Helper function to convert memory protection flags to human-readable string ---
std::string GetProtectionString(DWORD protect) {
std::string s;
if (protect == 0) return "UNKNOWN"; // Should not happen with valid pages
// Common flags
if (protect & PAGE_NOACCESS) s += "NOACCESS";
else if (protect & PAGE_READONLY) s += "READONLY";
else if (protect & PAGE_READWRITE) s += "READWRITE";
else if (protect & PAGE_WRITECOPY) s += "WRITECOPY";
else if (protect & PAGE_EXECUTE) s += "EXECUTE";
else if (protect & PAGE_EXECUTE_READ) s += "EXECUTE_READ";
else if (protect & PAGE_EXECUTE_READWRITE) s += "EXECUTE_READWRITE";
else if (protect & PAGE_EXECUTE_WRITECOPY) s += "EXECUTE_WRITECOPY";
// Modifiers (can be combined with base protection)
if (protect & PAGE_GUARD) s += " | GUARD";
if (protect & PAGE_NOCACHE) s += " | NOCACHE";
if (protect & PAGE_WRITECOMBINE) s += " | WRITECOMBINE";
return s;
}
// --- Function to read bytes from a specified address in the current process ---
// (This uses ReadProcessMemory for consistency, though direct dereference is also possible for self)
bool ReadMemoryBytes(LPCVOID address, SIZE_T size, std::vector<BYTE>& outBuffer) {
// Before attempting to read, check if the memory region is valid and readable
MEMORY_BASIC_INFORMATION mbi;
if (VirtualQuery(address, &mbi, sizeof(mbi)) == 0) {
std::cerr << "Error: VirtualQuery failed for address " << std::hex << (ULONG_PTR)address << std::dec << std::endl;
return false;
}
// Check if the memory is committed and readable
// PAGE_NOACCESS is not readable, others usually are (unless specifically restricted by other flags)
if (mbi.State != MEM_COMMIT || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
std::cerr << "Memory at " << std::hex << (ULONG_PTR)address << std::dec << " is not committed or is guarded/no-access. State: "
<< mbi.State << ", Protect: " << GetProtectionString(mbi.Protect) << std::endl;
return false;
}
// Ensure the requested size doesn't exceed the region size
if (size > mbi.RegionSize) {
size = mbi.RegionSize; // Adjust size to not read past the valid region
std::cout << "Warning: Requested size (" << size << ") exceeds region size. Reading only "
<< mbi.RegionSize << " bytes." << std::endl;
}
outBuffer.resize(size);
SIZE_T bytesRead = 0;
// ReadProcessMemory for the current process
// GetCurrentProcess() returns a pseudohandle for the current process.
if (!ReadProcessMemory(GetCurrentProcess(), address, outBuffer.data(), size, &bytesRead)) {
std::cerr << "Error: ReadProcessMemory failed for address " << std::hex << (ULONG_PTR)address
<< std::dec << ". Error code: " << GetLastError() << std::endl;
return false;
}
outBuffer.resize(bytesRead); // Adjust buffer size to actual bytes read
return true;
}
// --- Main function ---
int main() {
std::cout << "--- Simple Internal Memory Reader (Current Process) ---" << std::endl;
// --- Part 1: Reading a known global variable ---
std::cout << "\n--- Part 1: Reading a known global variable ---" << std::endl;
std::cout << "Address of g_myGlobalVariable: 0x" << std::hex << (ULONG_PTR)&g_myGlobalVariable << std::dec << std::endl;
int valueFromMemory = 0;
SIZE_T bytesRead = 0;
// Use ReadProcessMemory to read the value of g_myGlobalVariable
// GetCurrentProcess() gets a handle to our own process.
if (ReadProcessMemory(GetCurrentProcess(), &g_myGlobalVariable, &valueFromMemory, sizeof(g_myGlobalVariable), &bytesRead)) {
std::cout << "Value read from memory: 0x" << std::hex << valueFromMemory << std::dec << std::endl;
std::cout << "Bytes read: " << bytesRead << std::endl;
} else {
std::cerr << "Failed to read g_myGlobalVariable. Error code: " << GetLastError() << std::endl;
}
// --- Part 2: Enumerating and inspecting memory regions (VirtualQuery) ---
std::cout << "\n--- Part 2: Enumerating Memory Regions (Current Process) ---" << std::endl;
LPVOID address = 0; // Start at the base of the address space
while (true) {
MEMORY_BASIC_INFORMATION mbi;
// VirtualQuery for the current process
SIZE_T result = VirtualQuery(address, &mbi, sizeof(mbi));
if (result == 0) {
// End of address space or an error occurred
if (GetLastError() == ERROR_INVALID_PARAMETER) { // Likely end of address space
break;
}
std::cerr << "VirtualQuery failed at address 0x" << std::hex << (ULONG_PTR)address
<< std::dec << ". Error code: " << GetLastError() << std::endl;
break;
}
std::cout << " BaseAddress: 0x" << std::hex << std::setw(16) << std::setfill('0') << (ULONG_PTR)mbi.BaseAddress;
std::cout << " RegionSize: 0x" << std::hex << std::setw(8) << std::setfill('0') << mbi.RegionSize << std::dec;
std::cout << " State: " << (mbi.State == MEM_COMMIT ? "MEM_COMMIT" : mbi.State == MEM_RESERVE ? "MEM_RESERVE" : "MEM_FREE");
std::cout << " Protection: " << GetProtectionString(mbi.Protect);
std::cout << " Type: " << (mbi.Type == MEM_IMAGE ? "MEM_IMAGE" : mbi.Type == MEM_MAPPED ? "MEM_MAPPED" : mbi.Type == MEM_PRIVATE ? "MEM_PRIVATE" : "UNKNOWN");
std::cout << std::endl;
// Move to the next region
address = (LPBYTE)mbi.BaseAddress + mbi.RegionSize;
// Prevent infinite loops if the address space is huge or an error occurs
if ((ULONG_PTR)address < (ULONG_PTR)mbi.BaseAddress) { // Check for overflow
std::cerr << "Address overflow detected. Stopping scan." << std::endl;
break;
}
}
// --- Part 3: Reading content from a specific memory address (using helper function) ---
std::cout << "\n--- Part 3: Reading content from a specific address ---" << std::endl;
std::vector<BYTE> buffer;
// Example: Read 16 bytes from the address of g_myGlobalVariable
// Note: The actual content might be different depending on padding, compiler, etc.
// We are reading raw bytes around the variable.
LPCVOID targetAddress = (LPCVOID)&g_myGlobalVariable;
SIZE_T bytesToRead = 16;
std::cout << "Attempting to read " << bytesToRead << " bytes from 0x"
<< std::hex << (ULONG_PTR)targetAddress << std::dec << std::endl;
if (ReadMemoryBytes(targetAddress, bytesToRead, buffer)) {
std::cout << "Successfully read " << buffer.size() << " bytes:" << std::endl;
std::cout << "Bytes: ";
for (BYTE b : buffer) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)b << " ";
}
std::cout << std::endl;
// You can also try to interpret the data, e.g., print as ASCII if it looks like text
std::cout << "ASCII: ";
for (BYTE b : buffer) {
if (b >= 32 && b <= 126) { // Printable ASCII characters
std::cout << (char)b;
} else {
std::cout << "."; // Non-printable
}
}
std::cout << std::endl;
} else {
std::cerr << "Failed to read memory at 0x" << std::hex << (ULONG_PTR)targetAddress << std::dec << std::endl;
}
// Example of trying to read from an invalid address (will fail)
std::cout << "\n--- Part 4: Attempting to read from an invalid address (e.g., 0x1) ---" << std::endl;
LPCVOID invalidAddress = (LPCVOID)0x1; // A very low, typically unmapped address
if (!ReadMemoryBytes(invalidAddress, 16, buffer)) {
std::cout << "As expected, failed to read from invalid address 0x"
<< std::hex << (ULONG_PTR)invalidAddress << std::dec << std::endl;
}
std::cout << "\n--- End of Program ---" << std::endl;
return 0;
}
How to Compile and Run (Visual Studio):
- Open Visual Studio.
- Create a new project: "Console App" (C++).
- Replace the content of the
.cpp file with the code above.
- Build the project (
Ctrl+Shift+B or Build -> Build Solution).
- Run the project (
F5 or Debug -> Start Debugging).
Explanation of Key Parts:
g_myGlobalVariable: A simple int variable defined globally. Its address is fixed at compile time relative to the program's base address, making it a good target to demonstrate reading.
ReadMemoryBytes Function:
- Takes an
address and size as input.
VirtualQuery: Crucially, it first calls VirtualQuery on the given address. This is essential for safety: it checks if the memory region is actually committed (allocated and backed by physical storage) and if it has appropriate read permissions (PAGE_NOACCESS means no access, PAGE_GUARD means it's a guard page used to detect stack overflows, etc., and should not be read directly).
ReadProcessMemory(GetCurrentProcess(), ...): This is the core API call.
GetCurrentProcess(): Gets a handle to the current process.
address: The starting virtual address to read from.
outBuffer.data(): Pointer to our local buffer where the read bytes will be stored.
size: Number of bytes to read.
&bytesRead: A pointer to a SIZE_T variable that will receive the actual number of bytes read.
- Returns
true on success, false on failure (e.g., invalid address, no permission).
- Enumerating Memory Regions (Part 2):
- A
while loop iterates through the process's entire virtual address space.
address = 0;: Starts scanning from the lowest possible address.
VirtualQuery(address, &mbi, sizeof(mbi)): Retrieves information about the memory region starting at address.
mbi.BaseAddress: The base address of the region.
mbi.RegionSize: The size of the region.
mbi.State: Indicates if the region is MEM_COMMIT (allocated), MEM_RESERVE (reserved but not yet backed by physical memory), or MEM_FREE (unallocated).
mbi.Protect: Bitmask indicating memory protection (read, write, execute, etc.). The GetProtectionString helper translates these into readable names.
mbi.Type: Indicates if the region is an (part of an executable or DLL), (mapped file), or (private data).
Limitations & Next Steps:
- Error Handling: The error handling is basic. In a real application, you'd want more robust logging and specific error messages.
- Performance: Iterating through the entire address space with
VirtualQuery and then ReadProcessMemory for every interesting region can be slow for large processes.
- External Process Reading: To read memory from another process, you'd replace
GetCurrentProcess() with a handle obtained from OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId). dwDesiredAccess would need to include PROCESS_VM_READ and PROCESS_QUERY_INFORMATION. You'd then use VirtualQueryEx instead of VirtualQuery. This requires elevated privileges in many cases.
- Interpreting Data: This example reads raw bytes. Interpreting them as meaningful data (e.g., specific variable types, strings, pointers) requires knowledge of the memory layout of the target application.
- Security: Modifying memory (e.g., using
WriteProcessMemory) without proper understanding can crash programs or introduce security vulnerabilities. Be extremely careful.
- Anti-Cheat/Anti-Tamper: Many applications use anti-cheat or anti-tamper mechanisms that detect memory reading/writing from external processes and can terminate the application or ban users.