备忘录——通过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之間的對應關系:
- ?=p+δ (參見圖左)
- δ=r-s (參見圖右)
- 因此,?=p+(r-s)
參考實現
清單1所示的方法給出了一種參考實現。需要注意的是,一定要在加載完所有節信息(即Section Headers)之后才能開始RVA到文件位置的換算。
清單1 - RvaToFilePosition方法
/// /// 將一個RVA換算成文件中的位置。 /// /// RVA。 /// 相對于文件開頭的偏移量。 /// 必須在調用了Load之后再調用該方法。 public UInt32 RvaToFilePosition(UInt32 rva) { // 檢查RVA位于哪個Section中 var sec = this.ImageSectionHeaders.FirstOrDefault(sechdr => rva >= sechdr.VirtualAddress.Value && rva < sechdr.VirtualAddress.Value + sechdr.VirtualSize.Value); if (sec == null) return 0; // 計算文件位置 var s = sec.VirtualAddress.Value; var p = sec.PointerToRawData.Value; return p + (rva - s); }EOF.
轉載于:https://www.cnblogs.com/AndersLiu/archive/2008/08/04/rva-to-file-position.html
總結
以上是生活随笔為你收集整理的备忘录——通过RVA计算文件位置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 下载软件的好地方
- 下一篇: 让使用MSN就像访问网页一样容易!