MmMapIoSpace Failing

Hey! I am pretty new to a lot of these topics and am trying to achieve something relatively simple:

  1. Translate a Virtual Address to Physical
  2. Read the Physical Address Into a Virtual Buffer

This has all been perfectly fine with my current method of reading which is using MmMapIoSpace and memcpy, given what I already know this solution should work completely fine. Here’s the thing though, when entering a (known) valid physical address, like the MZ of a module this solution works perfectly fine but the problem shows itself whenever I try to translate the address, and given my little knowledge the only explanation I could come up with was that the memory was shadowed and protected in some way from MmMapIoSpace because thats the one function that always returns zero when trying to access the PFN of the PLM4 entry. Any help much appreciated.

First of all, what is ‘the MZ of a module’?

I don’t understand what you are trying to accomplish by (incorrectly) translating a virtual address to physical. and then re-mapping (incorrectly) that physical address to a virtual address.

However the manual translation of a buffer starting at VA n to a PA for the VA n is NOT a translation of all of the PAs that constitute the entire buffer. There is no guarantee that an arbitrary VA buffer maps to a contiguous set of PAs. You can use MmProbeAndLockPages to get an array of PFns. Those PFns can then be individually translated to a PA.

If you try to create a new mapping for an address that already has a mapping, the cache setting must match the existing mapping.

  1. The MZ of a module is the PE+ Header Identifier, I am reading the first two bytes of the modules base address. Which is a very reliable way to validate whether or not the read functioned, like I stated previously when I give it an already translated address (which I found using some tool I did not make) the physical address read functions perfectly, however when I try to translate that modules given virtual address into physical the very first read (attempting to access the PFN of the target PLM4 entry) fails at MmMapIoSpace and I don’t know why, I don’t want to have to resort to using different functions if there is an easy solution that I am missing

  2. There is no pre-existing mapping I don’t think, it would not make sense as every successful map I unmap the space as soon as I am finished with it

Read Physical Memory Code:
PHYSICAL_ADDRESS TargetPhysicalAddress = { 0 };
TargetPhysicalAddress.QuadPart = (LONGLONG)TargetAddress;

PVOID MappedMemory = MmMapIoSpaceEx(TargetPhysicalAddress, Size, PAGE_READWRITE);
if (!MappedMemory)
return (NTSTATUS)3;

memcpy(Buffer, MappedMemory, Size);

MmUnmapIoSpace(MappedMemory, Size);

Of course there is an existing mapping. If there wasn’t, where did you get a physical address to map?