首页
社区
课程
招聘
[原创]RVA与Offset 的换算函数
发表于: 2008-6-23 09:18 5634

[原创]RVA与Offset 的换算函数

2008-6-23 09:18
5634

function RVAToFileOffset(FileName:string; RVA: Cardinal): Cardinal;
var
  MemPE: TFileStream;
  PEDosHead: TImageDosHeader;
  PENtHead: TImageNtHeaders;
  Section : TImageSectionHeader;
  i, SectionsCount: Integer;
begin
  Result := RVA;
  MemPE:=TFileStream.Create(FileName,fmOpenReadWrite);
  try
    MemPE.Seek(0, soFromBeginning);
    MemPE.Read(PEDosHead, SizeOf(PEDosHead));
    MemPE.Seek(PEDosHead._lfanew, soFromBeginning);
    MemPE.Read(PENtHead, SizeOf(PENtHead));

    SectionsCount := PENtHead.FileHeader.NumberOfSections;

    if SectionsCount <> 0 then
      for i := 0 to SectionsCount - 1 do
      begin
        MemPE.Read(Section, SizeOf(Section));
        if (RVA >= Section.VirtualAddress) and (RVA < Section.VirtualAddress + Section.SizeOfRawData) then
        begin
          Result := RVA - Section.VirtualAddress + Section.PointerToRawData;
          Break;
        end;
      end;
  finally
    FreeAndNil(MemPE);
  end;
end;

function FileOffsetToRVA(FileName:string; Offset: Cardinal): Cardinal;
var
  MemPE: TFileStream;
  PEDosHead: TImageDosHeader;
  PENtHead: TImageNtHeaders;
  Section : TImageSectionHeader;
  i, SectionsCount: Integer;
begin
  Result :=Offset;
  MemPE:=TFileStream.Create(FileName,fmOpenReadWrite);
  try
    MemPE.Seek(0, soFromBeginning);
    MemPE.Read(PEDosHead, SizeOf(PEDosHead));
    MemPE.Seek(PEDosHead._lfanew, soFromBeginning);
    MemPE.Read(PENtHead, SizeOf(PENtHead));

    SectionsCount := PENtHead.FileHeader.NumberOfSections;

    if SectionsCount <> 0 then
      for i := 0 to SectionsCount - 1 do
      begin
        MemPE.Read(Section, SizeOf(Section));
        if (Offset >= Section.PointerToRawData) and (Offset < Section.PointerToRawData + Section.SizeOfRawData) then
        begin
          Result := Offset - Section.PointerToRawData + Section.VirtualAddress;
          Break;
        end;
      end;
  finally
    FreeAndNil(MemPE);
  end;
end;


[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

收藏
免费 7
支持
分享
最新回复 (1)
雪    币: 205
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
沙发。先顶再看
2008-6-25 10:51
0
游客
登录 | 注册 方可回帖
返回
//