Skip to content

Instantly share code, notes, and snippets.

@es3n1n
Last active February 20, 2022 09:19
Show Gist options
  • Save es3n1n/de029e91ce059b89e90fa8def9d151d7 to your computer and use it in GitHub Desktop.
Save es3n1n/de029e91ce059b89e90fa8def9d151d7 to your computer and use it in GitHub Desktop.
virt2phys
// @note: es3n1n: this is never meant to be useful
// posting cz maybe i'll use it later in my projs
// i hate those pasted c stuff, that's why i
// made my own version, please don't blame me :(
//
uintptr_t virt2phys( uintptr_t virt_addr ) {
auto read_phys = [ ] ( uintptr_t addr, void* buffer, size_t size ) -> NTSTATUS {
size_t dummy = 0;
MM_COPY_ADDRESS copy_addr = { .PhysicalAddress = {.QuadPart = static_cast< LONGLONG >( addr ) } };
return LI_FN( MmCopyMemory )( buffer, copy_addr, size, MM_COPY_MEMORY_PHYSICAL, &dummy );
};
// @note: es3n1n: parsing virtual address
//
uint16_t pml4 = static_cast< uint16_t >( ( virt_addr >> 39 ) & 0x1FF );
uint16_t pdpt = static_cast< uint16_t >( ( virt_addr >> 30 ) & 0x1FF );
uint16_t pd = static_cast< uint16_t >( ( virt_addr >> 21 ) & 0x1FF );
uint16_t pt = static_cast< uint16_t >( ( virt_addr >> 12 ) & 0x1FF );
uint64_t pml4e, pdpte, pde, pte;
// @note: es3n1n: reading pml4e, pdpte, pde, pte
//
read_phys( __readcr3( ) + ( pml4 * 8 ), &pml4e, sizeof( pml4e ) );
if ( !pml4e ) return 0;
read_phys( ( pml4e & 0xFFFFFFFFFF000 ) + ( pdpt * 8 ), &pdpte, sizeof( pdpte ) );
if ( !pdpte ) return 0;
// @note: es3n1n: 1gb page
//
if ( ( pdpte & ( 1 << 7 ) ) != 0 ) return ( pdpte & 0xFFFFFC0000000 ) + ( virt_addr & 0x3FFFFFFF );
read_phys( ( pdpte & 0xFFFFFFFFFF000 ) + ( pd * 8 ), &pde, sizeof( pde ) );
if ( !pde ) return 0;
// @note: es3n1n: 2mb page
//
if ( ( pde & ( 1 << 7 ) ) != 0 ) return ( pde & 0xFFFFFFFE00000 ) + ( virt_addr & 0x1FFFFF );
read_phys( ( pde & 0xFFFFFFFFFF000 ) + ( pt * 8 ), &pte, sizeof( pte ) );
if ( !pte ) return 0;
// @note: es3n1n: assuming that our page is 4kb size
//
return ( pte & 0xFFFFFFFFFF000 ) + ( virt_addr & 0xFFF );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment