I'm trying to understand the DOS header deeply and I'm stuck with these ones. I know the only required bytes are the MZ signature and the pointer to the PE section but I have to know what these two are exactly:
USHORT e_cblp; // Bytes on last page of file
USHORT e_cp; // Pages in file
In most executables' binary code these values are 90h and 03h respectively. A page is 512 bytes of code, so there are 3 pages, but where? Where can I find them in the file? How can I identify these 90h (144) bytes in the last page of 512 bytes?
This information is only requested by DOS. The only code of a PE file, that will run in DOS, is the DOS stub and it is not 3 pages of code but merely 64 bytes. So, what is 90h and 03h has to do there? Can't I just say e_cblp=01h
and e_cp=DOS header+DOS stub
?
It's the size of the "entire" MZ format executable, anything past the last byte in the last page is ignored. When MS-DOS loads an MZ format executable it copies everything in the file after the headers up until this limit. So the the fact most PECOFF executables have this field set to a value bigger than the MS-DOS stub just means that the PECOFF headers and part of PECOFF section data will be loaded into memory when the executable is run under MS-DOS.
I don't know why the default DOS stub used by the Microsoft linker (and the GNU linker, but not Borland's or Watcom's) says that its size 1168 bytes, when in fact is much smaller. If you supply your own stub when using Microsoft's linker it uses the size from the provided executable. Windows seems to ignore this value when loading PECOFF executables, and the default DOS stub doesn't have any use for the extra data.
Note that is possible to use Microsoft's linker to create a valid PECOFF executable that's only 1024 bytes long. This requires that the executable only have one section and that's less than 512 bytes in size. While Windows will load and run the executable, MS-DOS will refuse to because the file size is less than 1168 size value given in the MZ headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With