erocarrera / pefile

pefile is a Python module to read and work with PE (Portable Executable) files
MIT License
1.88k stars 522 forks source link

The size and contents of pe.OPTIONAL_HEADER #411

Open pooyan-123 opened 5 months ago

pooyan-123 commented 5 months ago

Hi,

I want to know the size and contents of OptionalHeader in the below code:

OptionalHeader = bytes()
OptionalHeader += pe.OPTIONAL_HEADER.__pack__()
for data_directory_entry in pe.OPTIONAL_HEADER.DATA_DIRECTORY:
  OptionalHeader += data_directory_entry.__pack__()

After a cursory review of pefile.py, I believe pe.OPTIONAL_HEADER.__pack__() always includes all fields of IMAGE_OPTIONAL_HEADER except for the data directory entries. If some of those fields are missing from the file's Optional Header then those missing fields are compensated with zeros. Additionally, up to 16 data directory entries are included in pe.OPTIONAL_HEADER.DATA_DIRECTORY. At most 16 data directory entries are appended to pe.OPTIONAL_HEADER.DATA_DIRECTORY; further data directory entries are ignored. If there are less than 16 data directory entries then the missing data directory entries are not compensated. So, in a PE32 file, the size of OptionalHeader is always between 96 and 96 + 8 16. While, in a PE32+ file, the size of OptionalHeader is always between 112 and 112 + 8 16.

Is this correct?

Thanks in advance.