Fix Pe.OptHdr.SizeOfImage and SizeOfHeaders

SizeOfImage is defined as:

  The size (in bytes) of the image, including all headers, as the image
  is loaded in memory. It must be a multiple of SectionAlignment.

SizeOfHeaders likewise is defined as:

  The combined size of an MS-DOS stub, PE header, and section headers
  rounded up to a multiple of FileAlignment.

Currently SizeOfImage represents .bss and .text, but it doesn't include
.header or .setup, nor any sections we'll add later, and there's nothing
enforcing that it matches SectionAlignment.  Additionally, since .bss is
being set up in our running code and /not/ by the loader, the current
value is dangerously high, as in the event there is an error in the
section table, it could potentially lead the loader to mark memory
allocated at runtime holding user-supplied data by any EFI binary loaded
before us as executable.

This patch adds a new symbol, _img_end, which is after .text and is
rounded up to 4kB (which is also what SectionAlignment is set to).  It
also adds a local label, anchored with ".org 512", and uses that to set
SizeOfHeaders - this will ensure the build fails without outputting and
invalid binary if the headers take too much space.

Signed-off-by: Peter Jones <pjones@redhat.com>
This commit is contained in:
Peter Jones 2022-03-31 13:32:14 -04:00 committed by Sam Demeulemeester
parent 3dd1fa8959
commit e022441544
3 changed files with 9 additions and 2 deletions

View File

@ -146,8 +146,8 @@ extra_header_fields:
.word 0 # MinorSubsystemVersion
.long 0 # Win32VersionValue
.long BASE_OF_CODE + _init_size # SizeOfImage
.long 512 # SizeOfHeaders
.long BASE_OF_CODE + _img_end # SizeOfImage
.long end_of_headers # SizeOfHeaders
.long 0 # CheckSum
.word 10 # Subsystem (EFI application)
.word 0 # DllCharacteristics
@ -214,3 +214,6 @@ root_dev:
.word 0
boot_flag:
.word 0xAA55
.org 512
end_of_headers:

View File

@ -17,6 +17,8 @@ SECTIONS {
. = ALIGN(512);
_text_end = . ;
}
. = ALIGN(4096);
_img_end = . ;
/DISCARD/ : { *(*) }
_text_size = (_text_end - _text_start);

View File

@ -17,6 +17,8 @@ SECTIONS {
. = ALIGN(512);
_text_end = . ;
}
. = ALIGN(4096);
_img_end = . ;
/DISCARD/ : { *(*) }
_text_size = (_text_end - _text_start);