From a8b0b600ddcf02605da8582b4eac1932a3bb13fa Mon Sep 17 00:00:00 2001
From: Mike Beaton <mjsbeaton@gmail.com>
Date: Mon, 10 Apr 2023 07:25:51 +0000
Subject: [PATCH] pe: only process RelocDir->Size of reloc section

Previously processing full padding-aligned Section->Misc.VirtualSize
relied on padding reloc entries being inserted by GenFw, which is
not required by spec.

This changes it to only process the amount referenced by Size, rather
than VirtualSize which may be bigger than the data present.

Signed-off-by: Mike Beaton <mjsbeaton@gmail.com>
---
 pe.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/pe.c b/pe.c
index 85b64c0..18f3e8f 100644
--- a/pe.c
+++ b/pe.c
@@ -87,7 +87,7 @@ relocate_coff (PE_COFF_LOADER_IMAGE_CONTEXT *context,
 	/* RelocBaseEnd here is the address of the first entry /past/ the
 	 * table.  */
 	RelocBaseEnd = ImageAddress(orig, size, Section->PointerToRawData +
-						Section->Misc.VirtualSize);
+						context->RelocDir->Size);
 
 	if (!RelocBase && !RelocBaseEnd)
 		return EFI_SUCCESS;
@@ -741,7 +741,7 @@ read_header(void *data, unsigned int datasize,
 	context->NumberOfSections = PEHdr->Pe32.FileHeader.NumberOfSections;
 
 	if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < context->NumberOfRvaAndSizes) {
-		perror(L"Image header too small\n");
+		perror(L"Image header too large\n");
 		return EFI_UNSUPPORTED;
 	}
 
@@ -1277,8 +1277,11 @@ handle_image (void *data, unsigned int datasize,
 					Section->Misc.VirtualSize &&
 					base && end &&
 					RelocBase == base &&
-					RelocBaseEnd == end) {
+					RelocBaseEnd <= end) {
 				RelocSection = Section;
+			} else {
+				perror(L"Relocation section is invalid \n");
+				return EFI_UNSUPPORTED;
 			}
 		}
 
-- 
2.27.0

