The secondary header (not the DOS header) of a PE/COFF binary
does not reside at a fixed offset. Instead, its offset into the
file is recorded in the DOS header.

This gives us the flexibility to move it, along with the section
headers, to right before the first section if there is considerable
space before it, i.e., when the PE/COFF file alignment is substantially
larger than the size of the header.

Since the PE/COFF to TE conversion replaces everything before the
section headers with a simple TE header, this change removes all
the header padding from such images, leading to smaller files.

Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Ard Biesheuvel <ard.biesheu...@linaro.org>
---
 BaseTools/Source/C/GenFw/Elf32Convert.c | 10 ++++++++++
 BaseTools/Source/C/GenFw/Elf64Convert.c | 10 ++++++++++
 2 files changed, 20 insertions(+)

diff --git a/BaseTools/Source/C/GenFw/Elf32Convert.c 
b/BaseTools/Source/C/GenFw/Elf32Convert.c
index 53bb14a47dbf..e1b92ebd713e 100644
--- a/BaseTools/Source/C/GenFw/Elf32Convert.c
+++ b/BaseTools/Source/C/GenFw/Elf32Convert.c
@@ -307,6 +307,16 @@ ScanSections32 (
   }
 
   //
+  // Move the PE/COFF header right before the first section. This will help us
+  // save space when converting to TE.
+  //
+  if (mCoffAlignment > mCoffOffset) {
+    mNtHdrOffset += mCoffAlignment - mCoffOffset;
+    mTableOffset += mCoffAlignment - mCoffOffset;
+    mCoffOffset = mCoffAlignment;
+  }
+
+  //
   // First text sections.
   //
   mCoffOffset = CoffAlign(mCoffOffset);
diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c 
b/BaseTools/Source/C/GenFw/Elf64Convert.c
index 7650afe54cfc..1c0f4a4dc87c 100644
--- a/BaseTools/Source/C/GenFw/Elf64Convert.c
+++ b/BaseTools/Source/C/GenFw/Elf64Convert.c
@@ -301,6 +301,16 @@ ScanSections64 (
   }
 
   //
+  // Move the PE/COFF header right before the first section. This will help us
+  // save space when converting to TE.
+  //
+  if (mCoffAlignment > mCoffOffset) {
+    mNtHdrOffset += mCoffAlignment - mCoffOffset;
+    mTableOffset += mCoffAlignment - mCoffOffset;
+    mCoffOffset = mCoffAlignment;
+  }
+
+  //
   // First text sections.
   //
   mCoffOffset = CoffAlign(mCoffOffset);
-- 
1.9.1

_______________________________________________
edk2-devel mailing list
edk2-devel@lists.01.org
https://lists.01.org/mailman/listinfo/edk2-devel

Reply via email to