I'm having some problems implementing an algorithm to read a foreign process' memory. Here is the main code:
System.Diagnostics.Process.EnterDebugMode();
IntPtr retValue = WinApi.OpenProcess((int)WinApi.OpenProcess_Access.VMRead | (int)WinApi.OpenProcess_Access.QueryInformation, 0, (uint)_proc.Id);
_procHandle = retValue;
WinApi.MEMORY_BASIC_INFORMATION[] mbia = getMemoryBasicInformation().Where(p => p.State == 0x1000).ToArray();
foreach (WinApi.MEMORY_BASIC_INFORMATION mbi in mbia) {
byte[] buffer = Read((IntPtr)mbi.BaseAddress, mbi.RegionSize);
foreach (IntPtr addr in ByteSearcher.FindInBuffer(buffer, toFind, (IntPtr)0, mbi.RegionSize, increment)) {
yield return addr;
}
}
Read() ... method
if (!WinApi.ReadProcessMemory(_procHandle, address, buffer, size, out numberBytesRead)) {
throw new MemoryReaderException(
string.Format(
"There was an error with ReadProcessMemory()\nGetLastError() = {0}",
WinApi.GetLastError()
));
}
Although generally it seems to work correctly, the problem is that for some memory values ReadProcessMemory is returning false, and GetLastError is returning 299. From what I've googled, it seems to happen on vista because some params of OpenProcess were updated. Anyone knows what this is about? And what values should I try? Notice that as they changed, I wouldn't want to know if it's VM_READ or so, I want to know exactly what the values are.
EDIT: maybe it has something to do with not calling VirtualProtect()/VirtualProtectEx()? as seen on this SO url: http://stackoverflow.com/questions/1112339/writeprocessmemory-readprocessmemory-fail
Edit2: That was it! ^^ That is the solution, calling to VirtualProtectEx() first and after ReadProcessMemory()!