Examples Delphi

Title: OffSet - Rva & Rva - Offset
Question: How to change RVA (Relative Virtual Address) to psysical Offset and inversely
Answer:
I would like to write two functions converting psysical address in executable to Relative Virtual Address(RVA) and RVA to Offset.
Someday I was trying to find these functions working with Olly Debugger and trying to find out how to change psysical Offset in executable to Olly's one.
It was really hard to find it in internet, especially something written in Object Pascal. However Finally I have found function: rva2offset.
After testing, it turned out, that this function needs one more line of code to work properly. I added this line and wrote very similar function converting offset to rva address.
Here is the result:
function rva2offset( pAddrOfFile: Pointer; dwRva : dword ):dword;
var i : byte;
sectionh : PIMAGE_SECTION_HEADER;
dosh : PIMAGE_DOS_HEADER;
peh : PIMAGE_NT_HEADERS;
begin
if dwRva = 0 then begin
result:=dwRva;
exit;
end;
dosh := PIMAGE_DOS_HEADER(pAddrOfFile);
peh := PIMAGE_NT_HEADERS(Longword(dosh) + Longword(dosh.e_lfanew));
Sectionh := PIMAGE_SECTION_HEADER(peh);
inc(pimage_nt_headers(Sectionh));
dwRva := dwRva - peh.OptionalHeader.ImageBase;
for i:=1 to peh.FileHeader.NumberOfSections do begin
if (dwRva = Sectionh.VirtualAddress) and
(dwRva inc(sectionh);
end;
result:=dwRva - sectionh.VirtualAddress + sectionh.PointerToRawData;
end;
function offset2rva (pAddrOfFile: Pointer; dwRva : dword ):dword;
var i : byte;
sectionh : PIMAGE_SECTION_HEADER;
dosh : PIMAGE_DOS_HEADER;
peh : PIMAGE_NT_HEADERS;
temp: dword;
begin
if dwRva = 0 then begin
result:=dwRva;
exit;
end;
dosh := PIMAGE_DOS_HEADER(pAddrOfFile);
peh := PIMAGE_NT_HEADERS(Longword(dosh) + Longword(dosh.e_lfanew));
Sectionh := PIMAGE_SECTION_HEADER(peh);
inc(pimage_nt_headers(Sectionh));
inc (sectionh, peh.FileHeader.NumberOfSections);
for i:=peh.FileHeader.NumberOfSections downto 1 do begin
temp := dwRva + sectionh.VirtualAddress - sectionh.PointerToRawData;
if (temp = Sectionh.VirtualAddress) and
(temp dec(sectionh);
end;
dwRva := temp + peh.OptionalHeader.ImageBase;
Result := dwRva;
end;
This two function need rxtypes unit which can be easily found in:
Delphi\Demos\Resxplor directory.
Enjoy :)