windows 如何使用其标头确定准确的 PE 图像文件大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8197134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:30:18  来源:igfitidea点击:

How do i determine exact PE image file size using its header(s)?

windowsdelphilanguage-agnosticportable-executable

提问by OnTheFly

I need byte size, IMAGE_OPTIONAL_HEADER.SizeOfImage appears to be rounded up to (unsure) boundary and is greater than real file size.

我需要字节大小,IMAGE_OPTIONAL_HEADER.SizeOfImage 似乎四舍五入到(不确定)边界并且大于实际文件大小。

回答by pezcode

IMAGE_OPTIONAL_HEADER.SizeOfImageis the size of the loaded executable/dll in virtual memory. It is not the same as the size on disk.

IMAGE_OPTIONAL_HEADER.SizeOfImage是虚拟内存中加载的可执行文件/dll 的大小。它与磁盘上的大小不同。

You can calculate it with VirtualAddress + VirtualSizeof the last section.

你可以用VirtualAddress + VirtualSize最后一节的来计算它。

IMAGE_OPTIONAL_HEADER.SizeOfImageis that value rounded up to the value of IMAGE_OPTIONAL_HEADER.SectionAlignment(usually the same as the page size).

IMAGE_OPTIONAL_HEADER.SizeOfImage是四舍五入到 的值IMAGE_OPTIONAL_HEADER.SectionAlignment(通常与页面大小相同)。

回答by user2971588

if(LastSectionVirtualSize >= LastSectionSizeOfRawData)
{
    if( LastSectionVirtualSize % LastSectionSectionAlignment )
    {
        TempValue = LastSectionVirtualSize - (LastSectionVirtualSize % LastSectionSectionAlignment) + LastSectionSectionAlignment ;
    }
    else
    {
        TempValue = LastSectionVirtualSize ;    
    }
}
else
{
    if(LastSectionSizeOfRawData % LastSectionSectionAlignment)
    {
        TempValue = LastSectionSizeOfRawData - (LastSectionSizeOfRawData % LastSectionSectionAlignment) + LastSectionSectionAlignment ;
    }
    else
    {
        TempValue = LastSectionSizeOfRawData ;
    }
}

OH.SizeOfImage  = TempValue + dwLastSecRVA ;

回答by toster-cx

Actually, the accepted answer is incorrect. To get the executable's size on disk, you should calculate PointerToRawData+ SizeOfRawDataof the last section, not the virtual counterparts. For an example see http://www.strchr.com/creating_self-extracting_executables

实际上,接受的答案是不正确的。要在磁盘上获取可执行文件的大小,您应该计算最后一部分的PointerToRawData+ SizeOfRawData,而不是虚拟副本。有关示例,请参阅http://www.strchr.com/creating_self-extracting_executables

Also note that some compilers like to append debug information after the last section. Be sure to strip any symbol tables or set release mode, depending on what compiler you use, for this to work.

另请注意,某些编译器喜欢在最后一节之后附加调试信息。确保删除任何符号表或设置发布模式,具体取决于您使用的编译器,以使其正常工作。