]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdePkg/Library/BasePeCoffLib/BasePeCoff.c
Validate some fields in PE image to make sure not access violation for later code.
[mirror_edk2.git] / MdePkg / Library / BasePeCoffLib / BasePeCoff.c
index 9274f31aa22d15b0b1351bc9356be0e8c940b830..6342a665df329875aa2d1f983fec681974f7e826 100644 (file)
@@ -2,11 +2,12 @@
   Base PE/COFF loader supports loading any PE32/PE32+ or TE image, but\r
   only supports relocating IA32, x64, IPF, and EBC images.\r
 \r
-  Copyright (c) 2006 - 2008, Intel Corporation\r
-  All rights reserved. This program and the accompanying materials\r
+  Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>\r
+  Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>\r
+  This program and the accompanying materials\r
   are licensed and made available under the terms and conditions of the BSD License\r
   which accompanies this distribution.  The full text of the license may be found at\r
-  http://opensource.org/licenses/bsd-license.php\r
+  http://opensource.org/licenses/bsd-license.php.\r
 \r
   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
@@ -46,7 +47,9 @@ PeCoffLoaderGetPeHeaderMagicValue (
 \r
 \r
 /**\r
-  Retrieves the PE or TE Header from a PE/COFF or TE image.\r
+  Retrieves the PE or TE Header from a PE/COFF or TE image. \r
+  Also done many checks in PE image to make sure PE image DosHeader, PeOptionHeader, \r
+  SizeOfHeader, Section Data Region and Security Data Region be in PE image range. \r
 \r
   @param  ImageContext    The context of the image being loaded.\r
   @param  Hdr             The buffer in which to return the PE32, PE32+, or TE header.\r
@@ -65,9 +68,13 @@ PeCoffLoaderGetPeHeader (
   EFI_IMAGE_DOS_HEADER  DosHdr;\r
   UINTN                 Size;\r
   UINT16                Magic;\r
+  UINT32                SectionHeaderOffset;\r
+  UINT32                Index;\r
+  CHAR8                 BufferData;\r
+  EFI_IMAGE_SECTION_HEADER  SectionHeader;\r
 \r
   //\r
-  // Read the DOS image header to check for it's existance\r
+  // Read the DOS image header to check for its existence\r
   //\r
   Size = sizeof (EFI_IMAGE_DOS_HEADER);\r
   Status = ImageContext->ImageRead (\r
@@ -92,8 +99,8 @@ PeCoffLoaderGetPeHeader (
 \r
   //\r
   // Read the PE/COFF Header. For PE32 (32-bit) this will read in too much\r
-  // data, but that should not hurt anythine. Hdr.Pe32->OptionalHeader.Magic\r
-  // determins if this is a PE32 or PE32+ image. The magic is in the same\r
+  // data, but that should not hurt anything. Hdr.Pe32->OptionalHeader.Magic\r
+  // determines if this is a PE32 or PE32+ image. The magic is in the same\r
   // location in both images.\r
   //\r
   Size = sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION);\r
@@ -130,6 +137,74 @@ PeCoffLoaderGetPeHeader (
     Magic = PeCoffLoaderGetPeHeaderMagicValue (Hdr);\r
 \r
     if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+      //\r
+      // 1. Check FileHeader.SizeOfOptionalHeader filed.\r
+      //\r
+      if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes) {\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
+\r
+      if (Hdr.Pe32->FileHeader.SizeOfOptionalHeader != sizeof (EFI_IMAGE_OPTIONAL_HEADER32) - (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES - Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes) * sizeof (EFI_IMAGE_DATA_DIRECTORY)) {\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
+\r
+      //\r
+      // 2. Check the OptionalHeader.SizeOfHeaders field.\r
+      // This field will be use like the following mode, so just compare the result.\r
+      // The DataDirectory array begin with 1, not 0, so here use < to compare not <=.\r
+      //\r
+      if (EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1 < Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes) {\r
+        if (Hdr.Pe32->OptionalHeader.SizeOfHeaders < (UINT32)((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - (UINT8 *) &Hdr)) {\r
+          return RETURN_UNSUPPORTED;\r
+        }\r
+      }\r
+\r
+      //\r
+      // Read Hdr.Pe32.OptionalHeader.SizeOfHeaders data from file\r
+      //\r
+      Size = 1;\r
+      Status = ImageContext->ImageRead (\r
+                               ImageContext->Handle,\r
+                               Hdr.Pe32->OptionalHeader.SizeOfHeaders - 1,\r
+                               &Size,\r
+                               &BufferData\r
+                               );\r
+      if (RETURN_ERROR (Status)) {\r
+        return Status;\r
+      }\r
+\r
+      //\r
+      // Check the EFI_IMAGE_DIRECTORY_ENTRY_SECURITY data.\r
+      // Read the last byte to make sure the data is in the image region.\r
+      // The DataDirectory array begin with 1, not 0, so here use < to compare not <=.\r
+      //\r
+      if (EFI_IMAGE_DIRECTORY_ENTRY_SECURITY < Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes) {\r
+        if (Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size != 0) {\r
+          //\r
+          // Check the member data to avoid overflow.\r
+          //\r
+          if ((UINT32) (~0) - Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress <\r
+              Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size) {\r
+            return RETURN_INVALID_PARAMETER;\r
+          }\r
+\r
+          //\r
+          // Read section header from file\r
+          //\r
+          Size = 1;\r
+          Status = ImageContext->ImageRead (\r
+                                   ImageContext->Handle,\r
+                                   Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress +\r
+                                    Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size - 1,\r
+                                   &Size,\r
+                                   &BufferData\r
+                                   );\r
+          if (RETURN_ERROR (Status)) {\r
+            return Status;\r
+          }\r
+        }\r
+      }\r
+\r
       //\r
       // Use PE32 offset\r
       //\r
@@ -139,6 +214,74 @@ PeCoffLoaderGetPeHeader (
       ImageContext->SizeOfHeaders     = Hdr.Pe32->OptionalHeader.SizeOfHeaders;\r
 \r
     } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {\r
+      //\r
+      // 1. Check FileHeader.SizeOfOptionalHeader filed.\r
+      //\r
+      if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes) {\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
+\r
+      if (Hdr.Pe32Plus->FileHeader.SizeOfOptionalHeader != sizeof (EFI_IMAGE_OPTIONAL_HEADER32) - (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES - Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes) * sizeof (EFI_IMAGE_DATA_DIRECTORY)) {\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
+\r
+      //\r
+      // 2. Check the OptionalHeader.SizeOfHeaders field.\r
+      // This field will be use like the following mode, so just compare the result.\r
+      // The DataDirectory array begin with 1, not 0, so here use < to compare not <=.\r
+      //\r
+      if (EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1 < Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes) {\r
+        if (Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders < (UINT32)((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - (UINT8 *) &Hdr)) {\r
+          return RETURN_UNSUPPORTED;\r
+        }\r
+      }\r
+\r
+      //\r
+      // Read Hdr.Pe32.OptionalHeader.SizeOfHeaders data from file\r
+      //\r
+      Size = 1;\r
+      Status = ImageContext->ImageRead (\r
+                               ImageContext->Handle,\r
+                               Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - 1,\r
+                               &Size,\r
+                               &BufferData\r
+                               );\r
+      if (RETURN_ERROR (Status)) {\r
+        return Status;\r
+      }\r
+\r
+      //\r
+      // Check the EFI_IMAGE_DIRECTORY_ENTRY_SECURITY data.\r
+      // Read the last byte to make sure the data is in the image region.\r
+      // The DataDirectory array begin with 1, not 0, so here use < to compare not <=.\r
+      //\r
+      if (EFI_IMAGE_DIRECTORY_ENTRY_SECURITY < Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes) {\r
+        if (Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size != 0) {\r
+          //\r
+          // Check the member data to avoid overflow.\r
+          //\r
+          if ((UINT32) (~0) - Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress <\r
+              Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size) {\r
+            return RETURN_INVALID_PARAMETER;\r
+          }\r
+\r
+          //\r
+          // Read section header from file\r
+          //\r
+          Size = 1;\r
+          Status = ImageContext->ImageRead (\r
+                                   ImageContext->Handle,\r
+                                   Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress +\r
+                                    Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size - 1,\r
+                                   &Size,\r
+                                   &BufferData\r
+                                   );\r
+          if (RETURN_ERROR (Status)) {\r
+            return Status;\r
+          }\r
+        }\r
+      }\r
+\r
       //\r
       // Use PE32+ offset\r
       //\r
@@ -158,13 +301,62 @@ PeCoffLoaderGetPeHeader (
   if (!PeCoffLoaderImageFormatSupported (ImageContext->Machine)) {\r
     //\r
     // If the PE/COFF loader does not support the image type return\r
-    // unsupported. This library can suport lots of types of images\r
+    // unsupported. This library can support lots of types of images\r
     // this does not mean the user of this library can call the entry\r
     // point of the image.\r
     //\r
     return RETURN_UNSUPPORTED;\r
   }\r
 \r
+  //\r
+  // Check each section field.\r
+  //\r
+  SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + sizeof (UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) + Hdr.Pe32->FileHeader.SizeOfOptionalHeader;\r
+  for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {\r
+    //\r
+    // Read section header from file\r
+    //\r
+    Size = sizeof (EFI_IMAGE_SECTION_HEADER);\r
+    Status = ImageContext->ImageRead (\r
+                             ImageContext->Handle,\r
+                             SectionHeaderOffset,\r
+                             &Size,\r
+                             &SectionHeader\r
+                             );\r
+    if (RETURN_ERROR (Status)) {\r
+      return Status;\r
+    }\r
+\r
+    if (SectionHeader.SizeOfRawData > 0) {\r
+      //\r
+      // Check the member data to avoid overflow.\r
+      //\r
+      if ((UINT32) (~0) - SectionHeader.PointerToRawData < SectionHeader.SizeOfRawData) {\r
+        return RETURN_INVALID_PARAMETER;\r
+      }\r
+\r
+      //\r
+      // Base on the ImageRead function to check the section data field.\r
+      // Read the last byte to make sure the data is in the image region.\r
+      //\r
+      Size = 1;\r
+      Status = ImageContext->ImageRead (\r
+                               ImageContext->Handle,\r
+                               SectionHeader.PointerToRawData + SectionHeader.SizeOfRawData - 1,\r
+                               &Size,\r
+                               &BufferData\r
+                               );\r
+      if (RETURN_ERROR (Status)) {\r
+        return Status;\r
+      }\r
+    }\r
+\r
+    //\r
+    // Check next section.\r
+    //\r
+    SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);\r
+  }\r
+\r
   return RETURN_SUCCESS;\r
 }\r
 \r
@@ -184,7 +376,10 @@ PeCoffLoaderGetPeHeader (
   The ImageRead and Handle fields of ImageContext structure must be valid prior \r
   to invoking this service.\r
 \r
-  @param  ImageContext              Pointer to the image context structure that describes the PE/COFF\r
+  Also done many checks in PE image to make sure PE image DosHeader, PeOptionHeader, \r
+  SizeOfHeader, Section Data Region and Security Data Region be in PE image range. \r
+\r
+  @param  ImageContext              The pointer to the image context structure that describes the PE/COFF\r
                                     image that needs to be examined by this function.\r
 \r
   @retval RETURN_SUCCESS            The information on the PE/COFF image was collected.\r
@@ -254,10 +449,11 @@ PeCoffLoaderGetImageInfo (
   ImageContext->DestinationAddress = 0;\r
 \r
   //\r
-  // Initialize the codeview pointer.\r
+  // Initialize the debug codeview pointer.\r
   //\r
-  ImageContext->CodeView    = NULL;\r
-  ImageContext->PdbPointer  = NULL;\r
+  ImageContext->DebugDirectoryEntryRva = 0;\r
+  ImageContext->CodeView               = NULL;\r
+  ImageContext->PdbPointer             = NULL;\r
 \r
   //\r
   // Three cases with regards to relocations:\r
@@ -268,7 +464,7 @@ PeCoffLoaderGetImageInfo (
   // Obviously having base relocations with RELOCS_STRIPPED==1 is invalid.\r
   //\r
   // Look at the file header to determine if relocations have been stripped, and\r
-  // save this info in the image context for later use.\r
+  // save this information in the image context for later use.\r
   //\r
   if ((!(ImageContext->IsTeImage)) && ((Hdr.Pe32->FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) != 0)) {\r
     ImageContext->RelocationsStripped = TRUE;\r
@@ -277,6 +473,14 @@ PeCoffLoaderGetImageInfo (
   } else {\r
     ImageContext->RelocationsStripped = FALSE;\r
   }\r
+  \r
+  //\r
+  // TE Image Relocation Data Directory Entry size is non-zero, but the Relocation Data Directory Virtual Address is zero.\r
+  // This case is not a valid TE image. \r
+  //\r
+  if ((ImageContext->IsTeImage) && (Hdr.Te->DataDirectory[0].Size != 0) && (Hdr.Te->DataDirectory[0].VirtualAddress == 0)) {\r
+    return RETURN_INVALID_PARAMETER;\r
+  }\r
 \r
   if (!(ImageContext->IsTeImage)) {\r
     if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
@@ -345,7 +549,7 @@ PeCoffLoaderGetImageInfo (
           Size = sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);\r
           Status = ImageContext->ImageRead (\r
                                    ImageContext->Handle,\r
-                                   DebugDirectoryEntryFileOffset,\r
+                                   DebugDirectoryEntryFileOffset + Index,\r
                                    &Size,\r
                                    &DebugEntry\r
                                    );\r
@@ -411,7 +615,7 @@ PeCoffLoaderGetImageInfo (
       // In Te image header there is not a field to describe the ImageSize.\r
       // Actually, the ImageSize equals the RVA plus the VirtualSize of\r
       // the last section mapped into memory (Must be rounded up to\r
-      // a mulitple of Section Alignment). Per the PE/COFF specification, the\r
+      // a multiple of Section Alignment). Per the PE/COFF specification, the\r
       // section headers in the Section Table must appear in order of the RVA\r
       // values for the corresponding sections. So the ImageSize can be determined\r
       // by the RVA and the VirtualSize of the last section header in the\r
@@ -432,7 +636,7 @@ PeCoffLoaderGetImageInfo (
         Size = sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);\r
         Status = ImageContext->ImageRead (\r
                                  ImageContext->Handle,\r
-                                 DebugDirectoryEntryFileOffset,\r
+                                 DebugDirectoryEntryFileOffset + Index,\r
                                  &Size,\r
                                  &DebugEntry\r
                                  );\r
@@ -494,7 +698,11 @@ PeCoffLoaderImageAddress (
     \r
   If ImageContext is NULL, then ASSERT().\r
 \r
-  @param  ImageContext        Pointer to the image context structure that describes the PE/COFF\r
+  Note that if the platform does not maintain coherency between the instruction cache(s) and the data\r
+  cache(s) in hardware, then the caller is responsible for performing cache maintenance operations\r
+  prior to transferring control to a PE/COFF image that is loaded using this library.\r
+\r
+  @param  ImageContext        The pointer to the image context structure that describes the PE/COFF\r
                               image that is being relocated.\r
 \r
   @retval RETURN_SUCCESS      The PE/COFF image was relocated.\r
@@ -540,9 +748,9 @@ PeCoffLoaderRelocateImage (
   // If there are no relocation entries, then we are done\r
   //\r
   if (ImageContext->RelocationsStripped) {\r
-       // Applies additional environment specific actions to relocate fixups \r
-       // to a PE/COFF image if needed\r
-       PeCoffLoaderRelocateImageExtraAction (ImageContext);    \r
+    // Applies additional environment specific actions to relocate fixups \r
+    // to a PE/COFF image if needed\r
+    PeCoffLoaderRelocateImageExtraAction (ImageContext);  \r
     return RETURN_SUCCESS;\r
   }\r
 \r
@@ -566,7 +774,9 @@ PeCoffLoaderRelocateImage (
       // Use PE32 offset\r
       //\r
       Adjust = (UINT64)BaseAddress - Hdr.Pe32->OptionalHeader.ImageBase;\r
-      Hdr.Pe32->OptionalHeader.ImageBase = (UINT32)BaseAddress;\r
+      if (Adjust != 0) {\r
+        Hdr.Pe32->OptionalHeader.ImageBase = (UINT32)BaseAddress;\r
+      }\r
 \r
       NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;\r
       RelocDir  = &Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];\r
@@ -575,7 +785,9 @@ PeCoffLoaderRelocateImage (
       // Use PE32+ offset\r
       //\r
       Adjust = (UINT64) BaseAddress - Hdr.Pe32Plus->OptionalHeader.ImageBase;\r
-      Hdr.Pe32Plus->OptionalHeader.ImageBase = (UINT64)BaseAddress;\r
+      if (Adjust != 0) {\r
+        Hdr.Pe32Plus->OptionalHeader.ImageBase = (UINT64)BaseAddress;\r
+      }\r
 \r
       NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;\r
       RelocDir  = &Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];\r
@@ -606,7 +818,9 @@ PeCoffLoaderRelocateImage (
   } else {\r
     Hdr.Te             = (EFI_TE_IMAGE_HEADER *)(UINTN)(ImageContext->ImageAddress);\r
     Adjust             = (UINT64) (BaseAddress - Hdr.Te->StrippedSize + sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->ImageBase);\r
-    Hdr.Te->ImageBase  = (UINT64) (BaseAddress - Hdr.Te->StrippedSize + sizeof (EFI_TE_IMAGE_HEADER));\r
+    if (Adjust != 0) {\r
+      Hdr.Te->ImageBase  = (UINT64) (BaseAddress - Hdr.Te->StrippedSize + sizeof (EFI_TE_IMAGE_HEADER));\r
+    }\r
 \r
     //\r
     // Find the relocation block\r
@@ -629,115 +843,120 @@ PeCoffLoaderRelocateImage (
   }\r
 \r
   //\r
-  // Run the relocation information and apply the fixups\r
+  // If Adjust is not zero, then apply fix ups to the image\r
   //\r
-  FixupData = ImageContext->FixupData;\r
-  while (RelocBase < RelocBaseEnd) {\r
-\r
-    Reloc     = (UINT16 *) ((CHAR8 *) RelocBase + sizeof (EFI_IMAGE_BASE_RELOCATION));\r
-    RelocEnd  = (UINT16 *) ((CHAR8 *) RelocBase + RelocBase->SizeOfBlock);\r
-    \r
+  if (Adjust != 0) {\r
     //\r
-    // Make sure RelocEnd is in the Image range.\r
+    // Run the relocation information and apply the fixups\r
     //\r
-    if ((CHAR8 *) RelocEnd < (CHAR8 *)((UINTN) ImageContext->ImageAddress) ||\r
-        (CHAR8 *) RelocEnd > (CHAR8 *)((UINTN)ImageContext->ImageAddress + (UINTN)ImageContext->ImageSize)) {\r
-      ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
-      return RETURN_LOAD_ERROR;\r
-    }\r
+    FixupData = ImageContext->FixupData;\r
+    while (RelocBase < RelocBaseEnd) {\r
 \r
-    if (!(ImageContext->IsTeImage)) {\r
-      FixupBase = PeCoffLoaderImageAddress (ImageContext, RelocBase->VirtualAddress);\r
-      if (FixupBase == NULL) {\r
+      Reloc     = (UINT16 *) ((CHAR8 *) RelocBase + sizeof (EFI_IMAGE_BASE_RELOCATION));\r
+      RelocEnd  = (UINT16 *) ((CHAR8 *) RelocBase + RelocBase->SizeOfBlock);\r
+      \r
+      //\r
+      // Make sure RelocEnd is in the Image range.\r
+      //\r
+      if ((CHAR8 *) RelocEnd < (CHAR8 *)((UINTN) ImageContext->ImageAddress) ||\r
+          (CHAR8 *) RelocEnd > (CHAR8 *)((UINTN)ImageContext->ImageAddress + (UINTN)ImageContext->ImageSize)) {\r
+        ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
         return RETURN_LOAD_ERROR;\r
       }\r
-    } else {\r
-      FixupBase = (CHAR8 *)(UINTN)(ImageContext->ImageAddress +\r
-                    RelocBase->VirtualAddress +\r
-                    sizeof(EFI_TE_IMAGE_HEADER) -\r
-                    Hdr.Te->StrippedSize\r
-                    );\r
-    }    \r
 \r
-    //\r
-    // Run this relocation record\r
-    //\r
-    while (Reloc < RelocEnd) {\r
+      if (!(ImageContext->IsTeImage)) {\r
+        FixupBase = PeCoffLoaderImageAddress (ImageContext, RelocBase->VirtualAddress);\r
+        if (FixupBase == NULL) {\r
+          return RETURN_LOAD_ERROR;\r
+        }\r
+      } else {\r
+        FixupBase = (CHAR8 *)(UINTN)(ImageContext->ImageAddress +\r
+                      RelocBase->VirtualAddress +\r
+                      sizeof(EFI_TE_IMAGE_HEADER) -\r
+                      Hdr.Te->StrippedSize\r
+                      );\r
+      }    \r
 \r
-      Fixup = FixupBase + (*Reloc & 0xFFF);\r
-      switch ((*Reloc) >> 12) {\r
-      case EFI_IMAGE_REL_BASED_ABSOLUTE:\r
-        break;\r
+      //\r
+      // Run this relocation record\r
+      //\r
+      while (Reloc < RelocEnd) {\r
 \r
-      case EFI_IMAGE_REL_BASED_HIGH:\r
-        Fixup16   = (UINT16 *) Fixup;\r
-        *Fixup16 = (UINT16) (*Fixup16 + ((UINT16) ((UINT32) Adjust >> 16)));\r
-        if (FixupData != NULL) {\r
-          *(UINT16 *) FixupData = *Fixup16;\r
-          FixupData             = FixupData + sizeof (UINT16);\r
-        }\r
-        break;\r
+        Fixup = FixupBase + (*Reloc & 0xFFF);\r
+        switch ((*Reloc) >> 12) {\r
+        case EFI_IMAGE_REL_BASED_ABSOLUTE:\r
+          break;\r
 \r
-      case EFI_IMAGE_REL_BASED_LOW:\r
-        Fixup16   = (UINT16 *) Fixup;\r
-        *Fixup16  = (UINT16) (*Fixup16 + (UINT16) Adjust);\r
-        if (FixupData != NULL) {\r
-          *(UINT16 *) FixupData = *Fixup16;\r
-          FixupData             = FixupData + sizeof (UINT16);\r
-        }\r
-        break;\r
+        case EFI_IMAGE_REL_BASED_HIGH:\r
+          Fixup16   = (UINT16 *) Fixup;\r
+          *Fixup16 = (UINT16) (*Fixup16 + ((UINT16) ((UINT32) Adjust >> 16)));\r
+          if (FixupData != NULL) {\r
+            *(UINT16 *) FixupData = *Fixup16;\r
+            FixupData             = FixupData + sizeof (UINT16);\r
+          }\r
+          break;\r
 \r
-      case EFI_IMAGE_REL_BASED_HIGHLOW:\r
-        Fixup32   = (UINT32 *) Fixup;\r
-        *Fixup32  = *Fixup32 + (UINT32) Adjust;\r
-        if (FixupData != NULL) {\r
-          FixupData             = ALIGN_POINTER (FixupData, sizeof (UINT32));\r
-          *(UINT32 *)FixupData  = *Fixup32;\r
-          FixupData             = FixupData + sizeof (UINT32);\r
-        }\r
-        break;\r
+        case EFI_IMAGE_REL_BASED_LOW:\r
+          Fixup16   = (UINT16 *) Fixup;\r
+          *Fixup16  = (UINT16) (*Fixup16 + (UINT16) Adjust);\r
+          if (FixupData != NULL) {\r
+            *(UINT16 *) FixupData = *Fixup16;\r
+            FixupData             = FixupData + sizeof (UINT16);\r
+          }\r
+          break;\r
 \r
-      case EFI_IMAGE_REL_BASED_DIR64:\r
-        Fixup64 = (UINT64 *) Fixup;\r
-        *Fixup64 = *Fixup64 + (UINT64) Adjust;\r
-        if (FixupData != NULL) {\r
-          FixupData = ALIGN_POINTER (FixupData, sizeof(UINT64));\r
-          *(UINT64 *)(FixupData) = *Fixup64;\r
-          FixupData = FixupData + sizeof(UINT64);\r
+        case EFI_IMAGE_REL_BASED_HIGHLOW:\r
+          Fixup32   = (UINT32 *) Fixup;\r
+          *Fixup32  = *Fixup32 + (UINT32) Adjust;\r
+          if (FixupData != NULL) {\r
+            FixupData             = ALIGN_POINTER (FixupData, sizeof (UINT32));\r
+            *(UINT32 *)FixupData  = *Fixup32;\r
+            FixupData             = FixupData + sizeof (UINT32);\r
+          }\r
+          break;\r
+\r
+        case EFI_IMAGE_REL_BASED_DIR64:\r
+          Fixup64 = (UINT64 *) Fixup;\r
+          *Fixup64 = *Fixup64 + (UINT64) Adjust;\r
+          if (FixupData != NULL) {\r
+            FixupData = ALIGN_POINTER (FixupData, sizeof(UINT64));\r
+            *(UINT64 *)(FixupData) = *Fixup64;\r
+            FixupData = FixupData + sizeof(UINT64);\r
+          }\r
+          break;\r
+\r
+        default:\r
+          //\r
+          // The common code does not handle some of the stranger IPF relocations\r
+          // PeCoffLoaderRelocateImageEx () adds support for these complex fixups\r
+          // on IPF and is a No-Op on other architectures.\r
+          //\r
+          Status = PeCoffLoaderRelocateImageEx (Reloc, Fixup, &FixupData, Adjust);\r
+          if (RETURN_ERROR (Status)) {\r
+            ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+            return Status;\r
+          }\r
         }\r
-        break;\r
 \r
-      default:\r
         //\r
-        // The common code does not handle some of the stranger IPF relocations\r
-        // PeCoffLoaderRelocateImageEx () addes support for these complex fixups\r
-        // on IPF and is a No-Op on other archtiectures.\r
+        // Next relocation record\r
         //\r
-        Status = PeCoffLoaderRelocateImageEx (Reloc, Fixup, &FixupData, Adjust);\r
-        if (RETURN_ERROR (Status)) {\r
-          ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
-          return Status;\r
-        }\r
+        Reloc += 1;\r
       }\r
 \r
       //\r
-      // Next relocation record\r
+      // Next reloc block\r
       //\r
-      Reloc += 1;\r
+      RelocBase = (EFI_IMAGE_BASE_RELOCATION *) RelocEnd;\r
     }\r
 \r
     //\r
-    // Next reloc block\r
+    // Adjust the EntryPoint to match the linked-to address\r
     //\r
-    RelocBase = (EFI_IMAGE_BASE_RELOCATION *) RelocEnd;\r
-  }\r
-\r
-  //\r
-  // Adjust the EntryPoint to match the linked-to address\r
-  //\r
-  if (ImageContext->DestinationAddress != 0) {\r
-     ImageContext->EntryPoint -= (UINT64) ImageContext->ImageAddress;\r
-     ImageContext->EntryPoint += (UINT64) ImageContext->DestinationAddress;\r
+    if (ImageContext->DestinationAddress != 0) {\r
+       ImageContext->EntryPoint -= (UINT64) ImageContext->ImageAddress;\r
+       ImageContext->EntryPoint += (UINT64) ImageContext->DestinationAddress;\r
+    }\r
   }\r
   \r
   // Applies additional environment specific actions to relocate fixups \r
@@ -753,14 +972,18 @@ PeCoffLoaderRelocateImage (
   Loads the PE/COFF image accessed through the ImageRead service of ImageContext into the buffer\r
   specified by the ImageAddress and ImageSize fields of ImageContext.  The caller must allocate\r
   the load buffer and fill in the ImageAddress and ImageSize fields prior to calling this function.\r
-  The EntryPoint, FixupDataSize, CodeView, and PdbPointer fields of ImageContext are computed.\r
+  The EntryPoint, FixupDataSize, CodeView, PdbPointer and HiiResourceData fields of ImageContext are computed.\r
   The ImageRead, Handle, PeCoffHeaderOffset,  IsTeImage,  Machine, ImageType, ImageAddress, ImageSize, \r
   DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders, and DebugDirectoryEntryRva \r
   fields of the ImageContext structure must be valid prior to invoking this service.\r
   \r
   If ImageContext is NULL, then ASSERT().\r
 \r
-  @param  ImageContext              Pointer to the image context structure that describes the PE/COFF\r
+  Note that if the platform does not maintain coherency between the instruction cache(s) and the data\r
+  cache(s) in hardware, then the caller is responsible for performing cache maintenance operations\r
+  prior to transferring control to a PE/COFF image that is loaded using this library.\r
+\r
+  @param  ImageContext              The pointer to the image context structure that describes the PE/COFF\r
                                     image that is being loaded.\r
 \r
   @retval RETURN_SUCCESS            The PE/COFF image was loaded into the buffer specified by\r
@@ -796,6 +1019,12 @@ PeCoffLoaderLoadImage (
   UINT32                                TempDebugEntryRva;\r
   UINT32                                NumberOfRvaAndSizes;\r
   UINT16                                Magic;\r
+  EFI_IMAGE_RESOURCE_DIRECTORY          *ResourceDirectory;\r
+  EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY    *ResourceDirectoryEntry;\r
+  EFI_IMAGE_RESOURCE_DIRECTORY_STRING   *ResourceDirectoryString;\r
+  EFI_IMAGE_RESOURCE_DATA_ENTRY         *ResourceDataEntry;\r
+  CHAR16                                *String;\r
+\r
 \r
   ASSERT (ImageContext != NULL);\r
 \r
@@ -805,7 +1034,7 @@ PeCoffLoaderLoadImage (
   ImageContext->ImageError = IMAGE_ERROR_SUCCESS;\r
 \r
   //\r
-  // Copy the provided context info into our local version, get what we\r
+  // Copy the provided context information into our local version, get what we\r
   // can from the original image, and then use that to make sure everything\r
   // is legit.\r
   //\r
@@ -910,6 +1139,14 @@ PeCoffLoaderLoadImage (
   //\r
   Section = FirstSection;\r
   for (Index = 0, MaxEnd = NULL; Index < NumberOfSections; Index++) {\r
+    //\r
+    // Read the section\r
+    //\r
+    Size = (UINTN) Section->Misc.VirtualSize;\r
+    if ((Size == 0) || (Size > Section->SizeOfRawData)) {\r
+      Size = (UINTN) Section->SizeOfRawData;\r
+    }\r
+\r
     //\r
     // Compute sections address\r
     //\r
@@ -920,9 +1157,9 @@ PeCoffLoaderLoadImage (
             );\r
 \r
     //\r
-    // If the base start or end address resolved to 0, then fail.\r
+    // If the size of the section is non-zero and the base address or end address resolved to 0, then fail.\r
     //\r
-    if ((Base == NULL) || (End == NULL)) {\r
+    if ((Size > 0) && ((Base == NULL) || (End == NULL))) {\r
       ImageContext->ImageError = IMAGE_ERROR_SECTION_NOT_LOADED;\r
       return RETURN_LOAD_ERROR;\r
     }\r
@@ -936,14 +1173,6 @@ PeCoffLoaderLoadImage (
       MaxEnd = End;\r
     }\r
 \r
-    //\r
-    // Read the section\r
-    //\r
-    Size = (UINTN) Section->Misc.VirtualSize;\r
-    if ((Size == 0) || (Size > Section->SizeOfRawData)) {\r
-      Size = (UINTN) Section->SizeOfRawData;\r
-    }\r
-\r
     if (Section->SizeOfRawData > 0) {\r
       if (!(ImageContext->IsTeImage)) {\r
         Status = ImageContext->ImageRead (\r
@@ -968,7 +1197,7 @@ PeCoffLoaderLoadImage (
     }\r
 \r
     //\r
-    // If raw size is less then virt size, zero fill the remaining\r
+    // If raw size is less then virtual size, zero fill the remaining\r
     //\r
 \r
     if (Size < Section->Misc.VirtualSize) {\r
@@ -1053,7 +1282,7 @@ PeCoffLoaderLoadImage (
   ImageContext->FixupData = NULL;\r
 \r
   //\r
-  // Load the Codeview info if present\r
+  // Load the Codeview information if present\r
   //\r
   if (ImageContext->DebugDirectoryEntryRva != 0) {\r
     if (!(ImageContext->IsTeImage)) {\r
@@ -1138,6 +1367,10 @@ PeCoffLoaderLoadImage (
           ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY);\r
           break;\r
 \r
+        case CODEVIEW_SIGNATURE_MTOC:\r
+          ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY);\r
+          break;\r
+\r
         default:\r
           break;\r
         }\r
@@ -1145,6 +1378,73 @@ PeCoffLoaderLoadImage (
     }\r
   }\r
 \r
+  //\r
+  // Get Image's HII resource section\r
+  //\r
+  ImageContext->HiiResourceData = 0;\r
+  if (!(ImageContext->IsTeImage)) {\r
+    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+      //\r
+      // Use PE32 offset\r
+      //\r
+      DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE];\r
+    } else {\r
+      //\r
+      // Use PE32+ offset\r
+      //\r
+      DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE];\r
+    }\r
+\r
+    if (DirectoryEntry->Size != 0) {\r
+      Base = PeCoffLoaderImageAddress (ImageContext, DirectoryEntry->VirtualAddress);\r
+      if (Base != NULL) {\r
+        ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) Base;\r
+        ResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (ResourceDirectory + 1);\r
+\r
+        for (Index = 0; Index < ResourceDirectory->NumberOfNamedEntries; Index++) {\r
+          if (ResourceDirectoryEntry->u1.s.NameIsString) {\r
+            ResourceDirectoryString = (EFI_IMAGE_RESOURCE_DIRECTORY_STRING *) (Base + ResourceDirectoryEntry->u1.s.NameOffset);\r
+            String = &ResourceDirectoryString->String[0];\r
+\r
+            if (ResourceDirectoryString->Length == 3 &&\r
+                String[0] == L'H' &&\r
+                String[1] == L'I' &&\r
+                String[2] == L'I') {\r
+              //\r
+              // Resource Type "HII" found\r
+              //\r
+              if (ResourceDirectoryEntry->u2.s.DataIsDirectory) {\r
+                //\r
+                // Move to next level - resource Name\r
+                //\r
+                ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (Base + ResourceDirectoryEntry->u2.s.OffsetToDirectory);\r
+                ResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (ResourceDirectory + 1);\r
+\r
+                if (ResourceDirectoryEntry->u2.s.DataIsDirectory) {\r
+                  //\r
+                  // Move to next level - resource Language\r
+                  //\r
+                  ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (Base + ResourceDirectoryEntry->u2.s.OffsetToDirectory);\r
+                  ResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (ResourceDirectory + 1);\r
+                }\r
+              }\r
+\r
+              //\r
+              // Now it ought to be resource Data\r
+              //\r
+              if (!ResourceDirectoryEntry->u2.s.DataIsDirectory) {\r
+                ResourceDataEntry = (EFI_IMAGE_RESOURCE_DATA_ENTRY *) (Base + ResourceDirectoryEntry->u2.OffsetToData);\r
+                ImageContext->HiiResourceData = (PHYSICAL_ADDRESS) (UINTN) PeCoffLoaderImageAddress (ImageContext, ResourceDataEntry->OffsetToData);\r
+                break;\r
+              }\r
+            }\r
+          }\r
+          ResourceDirectoryEntry++;\r
+        }\r
+      }\r
+    }\r
+  }\r
\r
   return Status;\r
 }\r
 \r
@@ -1159,7 +1459,11 @@ PeCoffLoaderLoadImage (
   to the FiuxupData buffer from the PE_COFF_LOADER_IMAGE_CONTEXT structure \r
   after this PE/COFF image was relocated with PeCoffLoaderRelocateImage().\r
 \r
-  @param  ImageBase          Base address of a PE/COFF image that has been loaded \r
+  Note that if the platform does not maintain coherency between the instruction cache(s) and the data\r
+  cache(s) in hardware, then the caller is responsible for performing cache maintenance operations\r
+  prior to transferring control to a PE/COFF image that is loaded using this library.\r
+\r
+  @param  ImageBase          The base address of a PE/COFF image that has been loaded \r
                              and relocated into system memory.\r
   @param  VirtImageBase      The request virtual address that the PE/COFF image is to\r
                              be fixed up for.\r
@@ -1371,7 +1675,7 @@ PeCoffLoaderRelocateImageForRuntime (
   If ReadSize is NULL, then ASSERT().\r
   If Buffer is NULL, then ASSERT().\r
 \r
-  @param  FileHandle        Pointer to base of the input stream\r
+  @param  FileHandle        The pointer to base of the input stream\r
   @param  FileOffset        Offset into the PE/COFF image to begin the read operation.\r
   @param  ReadSize          On input, the size in bytes of the requested read operation.  \r
                             On output, the number of bytes actually read.\r
@@ -1408,7 +1712,7 @@ PeCoffLoaderImageReadFromMemory (
   \r
   If ImageContext is NULL, then ASSERT().\r
   \r
-  @param  ImageContext              Pointer to the image context structure that describes the PE/COFF\r
+  @param  ImageContext              The pointer to the image context structure that describes the PE/COFF\r
                                     image to be unloaded.\r
 \r
   @retval RETURN_SUCCESS            The PE/COFF image was unloaded successfully.\r
@@ -1419,8 +1723,10 @@ PeCoffLoaderUnloadImage (
   IN OUT PE_COFF_LOADER_IMAGE_CONTEXT  *ImageContext\r
   )\r
 {\r
+  //\r
   // Applies additional environment specific actions to unload a \r
   // PE/COFF image if needed\r
+  //\r
   PeCoffLoaderUnloadImageExtraAction (ImageContext);\r
   return RETURN_SUCCESS;\r
 }\r