备忘录——通过RVA计算文件位置

备忘录——通过RVA计算文件位置

原创:Anders Liu

摘要:本文介绍了如何通过PE文件中某一项的RVA来计算其在文件中的位置。

参考文献

ECMA-335——Common Language Infrastructure (CLI) 4th Edition, June 2006

范畴

该备忘录描述了在分析PE(可移植可执行,Portable Executable)文件时,如何通过某一项的RVA确定该项在磁盘文件中的位置。

术语

  • 磁盘文件,文件——存储在磁盘上的可执行文件。
  • 镜像文件——内存中的一块地址空间,其内容按照某种映射关系对应于磁盘文件中的内容。
  • RVA——相对虚拟地址(Relative VirtualSize Address)。某一项加载到内存之后,将其地址减去镜像文件基地址后得到的值。
  • 文件位置——某一项在磁盘文件中,相对于文件起始位置(0字节)的位置值。

正文

以下是ECMA-335中对RVA的描述及文件位置的计算方法(Part II, 25, P299/556):

引用

The PE format frequently uses the term RVA (Relative Virtual Address). An RVA is the address of an item once loaded into memory, with the base address of the image file subtracted from it (i.e., the offset from the base address where the file is loaded). The RVA of an item will almost always differ from its position within the file on disk. To compute the file position of an item with RVA r, search all the sections in the PE file to find the section with RVA s, length l and file position p in which the RVA lies, ie s ≤ r < s+l. The file position of the item is then given by p+(r-s).

翻译如下:

参考翻译

PE格式经常使用术语RVA(相对虚拟地址,Relative Virtual Address)。RVA是将某一项加载到内存之后的地址,减去镜像文件的基地址得到的值(也就是从文件加载到内存之后的基地址开始的偏移量)。一个项的RVA通常与其在磁盘文件中的位置不一样。要计算一个RVA为r的项在文件中的位置,首先搜索PE文件中的所有节(section),找到一个RVA为s,长度为l的节,满足s ≤ r < s+l;假设该节的文件位置为p,则项的文件位置可以由p+(r-s)给出。

具体计算方法参见图1。

图1 - RVA和文件位置的对应关系

图1 - RVA和文件位置的对应关系

从图1不难看出文件位置(?)和RVA之间的对应关系:

  • ?=p+δ (参见图左)
  • δ=r-s (参见图右)
  • 因此,?=p+(r-s)

参考实现

清单1所示的方法给出了一种参考实现。需要注意的是,一定要在加载完所有节信息(即Section Headers)之后才能开始RVA到文件位置的换算。

清单1 - RvaToFilePosition方法

EOF.

posted @ 2008-08-04 12:41  Anders Liu  阅读(2531)  评论(9编辑  收藏  举报