Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The size of a PE Header

Is there a way to find out the size of a PE Header without reading all of it or the entire file?

like image 832
Idov Avatar asked Nov 19 '11 11:11

Idov


1 Answers

You can calculate the total size of the PE header like this:

sizeof(Signature) + sizeof(FileHeader) + sizeof(OptionalHeader) + sizeof(SectionTable)

The file header always has the same size but the OptionalHeader's size can differ, as can the section table size.

The OptionalHeader's size is stored in FileHeader.SizeOfOptionalHeader, and the section table size equals FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)

And some C code:

DWORD SizeOfPEHeader(const IMAGE_NT_HEADERS * pNTH)
{
    return (offsetof(IMAGE_NT_HEADERS, OptionalHeader) + pNTH->FileHeader.SizeOfOptionalHeader + (pNTH->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)));
}

All you have to do is read the DOS header, get the PE offset (e_lfanew) and read PE.Signature + PE.FileHeader into memory. That's two reading operations of fixed size and you have all the info you need.

like image 70
pezcode Avatar answered Nov 13 '22 08:11

pezcode