MdePkg: Fix overflow issue in PeCoffLoaderRelocateImageForRuntime

RelocDir->Size is a UINT32 value, and RelocDir->VirtualAddress is
also a UINT32 value. The current code in
PeCoffLoaderRelocateImageForRuntime does not check for overflow when
adding RelocDir->Size to RelocDir->VirtualAddress. This patch uses
SafeIntLib to ensure that the addition does not overflow.

Signed-off-by: Sachin Ganesh <sachinganesh@ami.com>
This commit is contained in:
INDIA\sachinganesh 2025-01-13 16:15:54 +05:30 committed by mergify[bot]
parent b3bfb8f22d
commit aedcaa3df8
2 changed files with 14 additions and 12 deletions

View File

@ -24,6 +24,7 @@
**/ **/
#include "BasePeCoffLibInternals.h" #include "BasePeCoffLibInternals.h"
#include <Library/SafeIntLib.h>
/** /**
Adjust some fields in section header for TE image. Adjust some fields in section header for TE image.
@ -1767,6 +1768,7 @@ PeCoffLoaderRelocateImageForRuntime (
UINTN Adjust; UINTN Adjust;
RETURN_STATUS Status; RETURN_STATUS Status;
PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
UINT32 EndAddress;
if ((RelocationData == NULL) || (ImageBase == 0x0) || (VirtImageBase == 0x0)) { if ((RelocationData == NULL) || (ImageBase == 0x0) || (VirtImageBase == 0x0)) {
return; return;
@ -1828,24 +1830,23 @@ PeCoffLoaderRelocateImageForRuntime (
if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) { if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
RelocDir = DataDirectory + EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC; RelocDir = DataDirectory + EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC;
if ((RelocDir != NULL) && (RelocDir->Size > 0)) { if ((RelocDir != NULL) && (RelocDir->Size > 0)) {
Status = SafeUint32Add (RelocDir->VirtualAddress, (RelocDir->Size - 1), &EndAddress);
if (!RETURN_ERROR (Status)) {
RelocBase = (EFI_IMAGE_BASE_RELOCATION *)PeCoffLoaderImageAddress (&ImageContext, RelocDir->VirtualAddress, 0); RelocBase = (EFI_IMAGE_BASE_RELOCATION *)PeCoffLoaderImageAddress (&ImageContext, RelocDir->VirtualAddress, 0);
RelocBaseEnd = (EFI_IMAGE_BASE_RELOCATION *)PeCoffLoaderImageAddress ( RelocBaseEnd = (EFI_IMAGE_BASE_RELOCATION *)PeCoffLoaderImageAddress (
&ImageContext, &ImageContext,
RelocDir->VirtualAddress + RelocDir->Size - 1, EndAddress,
0 0
); );
} }
}
if ((RelocBase == NULL) || (RelocBaseEnd == NULL) || ((UINTN)RelocBaseEnd < (UINTN)RelocBase)) { if ((RelocBase == NULL) || (RelocBaseEnd == NULL) || ((UINTN)RelocBaseEnd < (UINTN)RelocBase)) {
// DEBUG ((DEBUG_ERROR, "Relocation block is not valid\n"));
// relocation block is not valid, just return
//
return; return;
} }
} else { } else {
// DEBUG ((DEBUG_ERROR, "Cannot find relocations, cannot continue to relocate the image\n"));
// Cannot find relocations, cannot continue to relocate the image, ASSERT for this invalid image.
//
ASSERT (FALSE); ASSERT (FALSE);
return; return;
} }

View File

@ -58,4 +58,5 @@
DebugLib DebugLib
PeCoffExtraActionLib PeCoffExtraActionLib
BaseMemoryLib BaseMemoryLib
SafeIntLib