IMAGE_OPTIONAL_HEADER.DataDirectory 大小是固定的还是可变的?

IMAGE_OPTIONAL_HEADER.DataDirectory has fixed or variable size?

我对 IMAGE_OPTIONAL_HEADER.DataDirectory 有点困惑。正如 PE/COFF Specification 所说,

Header part: Data Directories

Size: Variable

Description: Address/size pairs for special tables that are found in the image file and are used by the operating system (for example, the import table and the export table).

还有

NumberOfRvaAndSizes: The number of data-directory entries in the remainder of the optional header. Each describes a location and size.

最后,

3.4.3. Optional Header Data Directories (Image Only)

Note that the number of directories is not fixed. Before looking for a specific directory, check the NumberOfRvaAndSizes field in the optional header.

Also, do not assume that the RVAs in this table point to the beginning of a section or that the sections that contain specific tables have specific names.

最后一段引用了以下内容table:

正如我从上面了解到的,DataDirectory 不必具有 IMAGE_NUMBEROF_DIRECTORY_ENTRIES 的固定大小。它应该包含 NumberOfRvaAndSizes 个条目。实际上这与上面目录条目的 table 相矛盾,其中每种类型在 table 中都有自己的偏移量,并且它会混淆。

所以,我的问题是:是否允许在 DataDirectory 中包含小于 IMAGE_NUMBEROF_DIRECTORY_ENTRIES 的大小,或者它必须始终是那个大小?

在那种情况下如何正确计算 NumberOfRvaAndSizes?例如,我只有导入目录。那么 NumberOfRvaAndSizes 应该是 1。但是我仍然会在 DataDirectory 中有 16 个条目并在索引 1 处导入条目?

对于一些误导性标签,我们深表歉意。我添加它们是为了引起一些注意,因为指定 portable-executable 只会导致熟悉格式的人可能会错过问题

Address/size 对在映像文件中找到并由操作系统使用的特殊 table 对(例如,导入 table 和导出 table).

is it allowed to include less than IMAGE_NUMBEROF_DIRECTORY_ENTRIES in DataDirectory or it must always be that size?

是的,它允许。 NumberOfRvaAndSizes 可以是任何值,包括 0

How to properly compute NumberOfRvaAndSizes in that case?

奇怪的问题。只需阅读并使用它 - 它计算 DataDirectory 数组中的有效条目。

For example, I have only import directory. Then NumberOfRvaAndSizes should be 1.

NumberOfRvaAndSizes 必须大于您使用的最大索引。因为 IMAGE_DIRECTORY_ENTRY_IMPORT == 1 - NumberOfRvaAndSizes 必须 > 1 - 最小值 2.

并查找 source 代码以了解更多信息