keybode

GetPtrFromRVA

Nov 23rd, 2014
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #define makeptr(cast, address, offset)      (cast)( (DWORD_PTR)address + (DWORD_PTR)offset )
  2. #define makedelta(cast, address, offset)    (cast)( (DWORD_PTR)address - (DWORD_PTR)offset )
  3.  
  4. IMAGE_SECTION_HEADER* GetEnclosingSectionHeader ( DWORD_PTR RVA, IMAGE_NT_HEADERS* NtHeader )
  5. {
  6.     IMAGE_SECTION_HEADER* Section = IMAGE_FIRST_SECTION(NtHeader);
  7.  
  8.     for ( int i = 0; i < NtHeader->FileHeader.NumberOfSections; i++, Section++ )
  9.     {
  10.         DWORD_PTR Size = Section->Misc.VirtualSize;
  11.  
  12.         if ( !Size )
  13.             Size = Section->SizeOfRawData;
  14.  
  15.         if ( (RVA >= Section->VirtualAddress) && (RVA < (Section->VirtualAddress + Size)) )
  16.             return Section;
  17.     }
  18.  
  19.     return 0;
  20. }
  21.  
  22. DWORD_PTR GetMappedSection ( IMAGE_SECTION_HEADER* SectionHeader, HMODULE Module, IMAGE_NT_HEADERS* NtHeader )
  23. {
  24.     IMAGE_SECTION_HEADER* Section = IMAGE_FIRST_SECTION(NtHeader);
  25.  
  26.     DWORD_PTR Offset = makedelta(DWORD_PTR, Section, Module);
  27.  
  28.     for ( int i = 0; i < NtHeader->FileHeader.NumberOfSections; i++, Section++ )
  29.     {
  30.         if ( Section->Name == SectionHeader->Name )
  31.         {
  32.             Offset = makedelta(DWORD_PTR, Section->VirtualAddress, Section->PointerToRawData);
  33.             break;
  34.         }
  35.     }
  36.  
  37.     return Offset;
  38. }
  39.  
  40. void* GetPtrFromRVA ( DWORD_PTR RVA, IMAGE_NT_HEADERS* NtHeader, HMODULE Module, bool Mapped )
  41. {
  42.     IMAGE_SECTION_HEADER* SectionHeader = GetEnclosingSectionHeader ( RVA, NtHeader );
  43.  
  44.     DWORD_PTR Offset = 0;
  45.  
  46.     if ( Mapped )
  47.         Offset = GetMappedSection ( SectionHeader, Module, NtHeader );
  48.  
  49.     DWORD_PTR Delta = (DWORD_PTR)( SectionHeader->VirtualAddress - SectionHeader->PointerToRawData );
  50.  
  51.     return (void*)( Module + RVA - Delta + Offset );
  52. }
Advertisement
Add Comment
Please, Sign In to add comment