Search code examples
cwindowsportable-executable

IMAGE_OPTIONAL_HEADER.DataDirectory has fixed or variable size?


I'm a bit confused about IMAGE_OPTIONAL_HEADER.DataDirectory. As PE/COFF Specification says,

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).

And also

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

And, finally,

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.

The last paragraph references the following table:

enter image description here

As I understand from the above, DataDirectory doesn't have to have fixed size of IMAGE_NUMBEROF_DIRECTORY_ENTRIES. It should contain NumberOfRvaAndSizes entries. Actually this contradicts with the table of directory entries above, where each type has its own offset in the table, and it confuses.

So, my question is: is it allowed to include less than IMAGE_NUMBEROF_DIRECTORY_ENTRIES in DataDirectory or it must always be that size?

How to properly compute NumberOfRvaAndSizes in that case? For example, I have only import directory. Then NumberOfRvaAndSizes should be 1. But I will still have 16 entries in DataDirectory and import entry at index 1?

Sorry for some misleading tags. I added them to draw some attention as specifying portable-executable only could lead to someone who is familiar with the format could miss the question


Solution

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

    yes, it allowed. NumberOfRvaAndSizes can be any value, including 0

    How to properly compute NumberOfRvaAndSizes in that case?

    strange question. simply read and use it - it count of valid entries in DataDirectory array.

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

    the NumberOfRvaAndSizes must be > than max index which you use. because IMAGE_DIRECTORY_ENTRY_IMPORT == 1 - NumberOfRvaAndSizes must be > 1 - how minimum 2.

    and look for source code for more understand this