Here's a piece of code for obtaining the time when a .NET assembly was built。注意:

const int c_LinkerTimestampOffset = 8;

然后:
int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);

此代码提取存储在程序集中的IMAGE_FILE_HEADER structureTimeDateStamp成员。结构定义如下:
typedef struct _IMAGE_FILE_HEADER {
    WORD  Machine;
    WORD  NumberOfSections;
    DWORD TimeDateStamp;
    DWORD PointerToSymbolTable;
    DWORD NumberOfSymbols;
    WORD  SizeOfOptionalHeader;
    WORD  Characteristics;
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;

WORD是两个字节,应对齐两个字节。当我使用Visual C++ 10编译以下代码时:
IMAGE_FILE_HEADER header;
char* start = (char*)&header;
char* field = (char*)(&header.TimeDateStamp);
int diff = field - start;

正如我个人所期望的,diff等于4

那是C#代码中的错误吗?为什么使用8的偏移值?

最佳答案

它用于跳过附加签名,因为i包含NT header 的偏移量,而不是文件图像 header 的偏移量(请参见formal PE structure):

typedef struct _IMAGE_NT_HEADERS {
    DWORD Signature; //<- we need to skip this
    IMAGE_FILE_HEADER FileHeader;
    IMAGE_OPTIONAL_HEADER32 OptionalHeader;
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;

所以实际的总和是sizeof(WORD /* FileHeader.Machine */) + sizeof(WORD /* FileHeader.NumberOfSections */) + sizeof(DWORD /* Signature */)
底线,不是错误,只是一些魔术,可以跳过一些结构嵌套/内联。

关于c# - 为什么此用于处理PE文件头的代码使用这种奇怪的偏移值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12639433/

10-13 06:50