]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdePkg/Library/BasePeCoffLib/BasePeCoff.c
MdePkg/BasePeCoffLib: remove PE/COFF header workaround for ELILO on IPF
[mirror_edk2.git] / MdePkg / Library / BasePeCoffLib / BasePeCoff.c
index ffff0c14aa17c7a3f37dcc4a466c248747c09b19..c57816a80887fe1b8a339515c5a6b2b4a4c227c8 100644 (file)
@@ -15,7 +15,7 @@
   PeCoffLoaderGetPeHeader() routine will do basic check for PE/COFF header.\r
   PeCoffLoaderGetImageInfo() routine will do basic check for whole PE/COFF image.\r
 \r
-  Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2006 - 2018, 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
 #include "BasePeCoffLibInternals.h"\r
 \r
 /**\r
-  Retrieves the magic value from the PE/COFF header.\r
+  Adjust some fields in section header for TE image.\r
 \r
-  @param  Hdr             The buffer in which to return the PE32, PE32+, or TE header.\r
-\r
-  @return EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC - Image is PE32\r
-  @return EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC - Image is PE32+\r
+  @param  SectionHeader             Pointer to the section header.\r
+  @param  TeStrippedOffset          Size adjust for the TE image.\r
 \r
 **/\r
-UINT16\r
-PeCoffLoaderGetPeHeaderMagicValue (\r
-  IN  EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION  Hdr\r
+VOID\r
+PeCoffLoaderAdjustOffsetForTeImage (\r
+  EFI_IMAGE_SECTION_HEADER              *SectionHeader,\r
+  UINT32                                TeStrippedOffset\r
   )\r
 {\r
-  //\r
-  // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value \r
-  //       in the PE/COFF Header.  If the MachineType is Itanium(IA64) and the \r
-  //       Magic value in the OptionalHeader is  EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC\r
-  //       then override the returned value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC\r
-  //\r
-  if (Hdr.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
-    return EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;\r
-  }\r
-  //\r
-  // Return the magic value from the PC/COFF Optional Header\r
-  //\r
-  return Hdr.Pe32->OptionalHeader.Magic;\r
+  SectionHeader->VirtualAddress   -= TeStrippedOffset;\r
+  SectionHeader->PointerToRawData -= TeStrippedOffset;\r
 }\r
 \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
 \r
   Caution: This function may receive untrusted input.\r
-  PE/COFF image is external input, so this routine will \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
+  PE/COFF image is external input, so this routine will\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
@@ -84,7 +71,6 @@ PeCoffLoaderGetPeHeader (
   EFI_IMAGE_DOS_HEADER  DosHdr;\r
   UINTN                 Size;\r
   UINTN                 ReadSize;\r
-  UINT16                Magic;\r
   UINT32                SectionHeaderOffset;\r
   UINT32                Index;\r
   UINT32                HeaderWithoutDataDir;\r
@@ -157,13 +143,55 @@ PeCoffLoaderGetPeHeader (
     ImageContext->SectionAlignment  = 0;\r
     ImageContext->SizeOfHeaders     = sizeof (EFI_TE_IMAGE_HEADER) + (UINTN)Hdr.Te->BaseOfCode - (UINTN)Hdr.Te->StrippedSize;\r
 \r
+    //\r
+    // Check the StrippedSize.\r
+    //\r
+    if (sizeof (EFI_TE_IMAGE_HEADER) >= (UINT32)Hdr.Te->StrippedSize) {\r
+      ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+      return RETURN_UNSUPPORTED;\r
+    }\r
+\r
+    //\r
+    // Check the SizeOfHeaders field.\r
+    //\r
+    if (Hdr.Te->BaseOfCode <= Hdr.Te->StrippedSize) {\r
+      ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+      return RETURN_UNSUPPORTED;\r
+    }\r
+\r
+    //\r
+    // Read last byte of Hdr.Te->SizeOfHeaders from the file.\r
+    //\r
+    Size = 1;\r
+    ReadSize = Size;\r
+    Status = ImageContext->ImageRead (\r
+                             ImageContext->Handle,\r
+                             ImageContext->SizeOfHeaders - 1,\r
+                             &Size,\r
+                             &BufferData\r
+                             );\r
+    if (RETURN_ERROR (Status) || (Size != ReadSize)) {\r
+      ImageContext->ImageError = IMAGE_ERROR_IMAGE_READ;\r
+      if (Size != ReadSize) {\r
+        Status = RETURN_UNSUPPORTED;\r
+      }\r
+      return Status;\r
+    }\r
+\r
+    //\r
+    // TE Image Data Directory Entry size is non-zero, but the Data Directory Virtual Address is zero.\r
+    // This case is not a valid TE image.\r
+    //\r
+    if ((Hdr.Te->DataDirectory[0].Size != 0 && Hdr.Te->DataDirectory[0].VirtualAddress == 0) ||\r
+        (Hdr.Te->DataDirectory[1].Size != 0 && Hdr.Te->DataDirectory[1].VirtualAddress == 0)) {\r
+      ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+      return RETURN_UNSUPPORTED;\r
+    }\r
   } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE)  {\r
     ImageContext->IsTeImage = FALSE;\r
     ImageContext->Machine = Hdr.Pe32->FileHeader.Machine;\r
 \r
-    Magic = PeCoffLoaderGetPeHeaderMagicValue (Hdr);\r
-\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // 1. Check OptionalHeader.NumberOfRvaAndSizes filed.\r
       //\r
@@ -174,7 +202,7 @@ PeCoffLoaderGetPeHeader (
 \r
       //\r
       // 2. Check the FileHeader.SizeOfOptionalHeader field.\r
-      // OptionalHeader.NumberOfRvaAndSizes is not bigger than 16, so \r
+      // OptionalHeader.NumberOfRvaAndSizes is not bigger than 16, so\r
       // OptionalHeader.NumberOfRvaAndSizes * sizeof (EFI_IMAGE_DATA_DIRECTORY) will not overflow.\r
       //\r
       HeaderWithoutDataDir = sizeof (EFI_IMAGE_OPTIONAL_HEADER32) - sizeof (EFI_IMAGE_DATA_DIRECTORY) * EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;\r
@@ -188,6 +216,10 @@ PeCoffLoaderGetPeHeader (
       //\r
       // 3. Check the FileHeader.NumberOfSections field.\r
       //\r
+      if (Hdr.Pe32->OptionalHeader.SizeOfImage <= SectionHeaderOffset) {\r
+        ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
       if ((Hdr.Pe32->OptionalHeader.SizeOfImage - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER <= Hdr.Pe32->FileHeader.NumberOfSections) {\r
         ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
         return RETURN_UNSUPPORTED;\r
@@ -196,6 +228,14 @@ PeCoffLoaderGetPeHeader (
       //\r
       // 4. Check the OptionalHeader.SizeOfHeaders field.\r
       //\r
+      if (Hdr.Pe32->OptionalHeader.SizeOfHeaders <= SectionHeaderOffset) {\r
+        ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
+      if (Hdr.Pe32->OptionalHeader.SizeOfHeaders >= Hdr.Pe32->OptionalHeader.SizeOfImage) {\r
+        ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
       if ((Hdr.Pe32->OptionalHeader.SizeOfHeaders - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER < (UINT32)Hdr.Pe32->FileHeader.NumberOfSections) {\r
         ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
         return RETURN_UNSUPPORTED;\r
@@ -266,7 +306,7 @@ PeCoffLoaderGetPeHeader (
       ImageContext->SectionAlignment  = Hdr.Pe32->OptionalHeader.SectionAlignment;\r
       ImageContext->SizeOfHeaders     = Hdr.Pe32->OptionalHeader.SizeOfHeaders;\r
 \r
-    } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {\r
+    } else if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {\r
       //\r
       // 1. Check FileHeader.NumberOfRvaAndSizes filed.\r
       //\r
@@ -276,7 +316,7 @@ PeCoffLoaderGetPeHeader (
       }\r
       //\r
       // 2. Check the FileHeader.SizeOfOptionalHeader field.\r
-      // OptionalHeader.NumberOfRvaAndSizes is not bigger than 16, so \r
+      // OptionalHeader.NumberOfRvaAndSizes is not bigger than 16, so\r
       // OptionalHeader.NumberOfRvaAndSizes * sizeof (EFI_IMAGE_DATA_DIRECTORY) will not overflow.\r
       //\r
       HeaderWithoutDataDir = sizeof (EFI_IMAGE_OPTIONAL_HEADER64) - sizeof (EFI_IMAGE_DATA_DIRECTORY) * EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;\r
@@ -290,6 +330,10 @@ PeCoffLoaderGetPeHeader (
       //\r
       // 3. Check the FileHeader.NumberOfSections field.\r
       //\r
+      if (Hdr.Pe32Plus->OptionalHeader.SizeOfImage <= SectionHeaderOffset) {\r
+        ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
       if ((Hdr.Pe32Plus->OptionalHeader.SizeOfImage - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER <= Hdr.Pe32Plus->FileHeader.NumberOfSections) {\r
         ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
         return RETURN_UNSUPPORTED;\r
@@ -298,6 +342,14 @@ PeCoffLoaderGetPeHeader (
       //\r
       // 4. Check the OptionalHeader.SizeOfHeaders field.\r
       //\r
+      if (Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders <= SectionHeaderOffset) {\r
+        ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
+      if (Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders >= Hdr.Pe32Plus->OptionalHeader.SizeOfImage) {\r
+        ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+        return RETURN_UNSUPPORTED;\r
+      }\r
       if ((Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER < (UINT32)Hdr.Pe32Plus->FileHeader.NumberOfSections) {\r
         ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
         return RETURN_UNSUPPORTED;\r
@@ -417,11 +469,18 @@ PeCoffLoaderGetPeHeader (
       return Status;\r
     }\r
 \r
+    //\r
+    // Adjust some field in Section Header for TE image.\r
+    //\r
+    if (ImageContext->IsTeImage) {\r
+      PeCoffLoaderAdjustOffsetForTeImage (&SectionHeader, (UINT32)Hdr.Te->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER));\r
+    }\r
+\r
     if (SectionHeader.SizeOfRawData > 0) {\r
       //\r
       // Section data should bigger than the Pe header.\r
       //\r
-      if (SectionHeader.VirtualAddress < ImageContext->SizeOfHeaders || \r
+      if (SectionHeader.VirtualAddress < ImageContext->SizeOfHeaders ||\r
           SectionHeader.PointerToRawData < ImageContext->SizeOfHeaders) {\r
         ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
         return RETURN_UNSUPPORTED;\r
@@ -469,22 +528,22 @@ PeCoffLoaderGetPeHeader (
 /**\r
   Retrieves information about a PE/COFF image.\r
 \r
-  Computes the PeCoffHeaderOffset, IsTeImage, ImageType, ImageAddress, ImageSize, \r
-  DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders, and \r
-  DebugDirectoryEntryRva fields of the ImageContext structure.  \r
-  If ImageContext is NULL, then return RETURN_INVALID_PARAMETER.  \r
-  If the PE/COFF image accessed through the ImageRead service in the ImageContext \r
-  structure is not a supported PE/COFF image type, then return RETURN_UNSUPPORTED.  \r
-  If any errors occur while computing the fields of ImageContext, \r
-  then the error status is returned in the ImageError field of ImageContext.  \r
+  Computes the PeCoffHeaderOffset, IsTeImage, ImageType, ImageAddress, ImageSize,\r
+  DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders, and\r
+  DebugDirectoryEntryRva fields of the ImageContext structure.\r
+  If ImageContext is NULL, then return RETURN_INVALID_PARAMETER.\r
+  If the PE/COFF image accessed through the ImageRead service in the ImageContext\r
+  structure is not a supported PE/COFF image type, then return RETURN_UNSUPPORTED.\r
+  If any errors occur while computing the fields of ImageContext,\r
+  then the error status is returned in the ImageError field of ImageContext.\r
   If the image is a TE image, then SectionAlignment is set to 0.\r
-  The ImageRead and Handle fields of ImageContext structure must be valid prior \r
+  The ImageRead and Handle fields of ImageContext structure must be valid prior\r
   to invoking this service.\r
 \r
   Caution: This function may receive untrusted input.\r
-  PE/COFF image is external input, so this routine will \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
+  PE/COFF image is external input, so this routine will\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
@@ -513,7 +572,7 @@ PeCoffLoaderGetImageInfo (
   EFI_IMAGE_SECTION_HEADER              SectionHeader;\r
   EFI_IMAGE_DEBUG_DIRECTORY_ENTRY       DebugEntry;\r
   UINT32                                NumberOfRvaAndSizes;\r
-  UINT16                                Magic;\r
+  UINT32                                TeStrippedOffset;\r
 \r
   if (ImageContext == NULL) {\r
     return RETURN_INVALID_PARAMETER;\r
@@ -529,13 +588,12 @@ PeCoffLoaderGetImageInfo (
     return Status;\r
   }\r
 \r
-  Magic = PeCoffLoaderGetPeHeaderMagicValue (Hdr);\r
-\r
   //\r
   // Retrieve the base address of the image\r
   //\r
   if (!(ImageContext->IsTeImage)) {\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    TeStrippedOffset = 0;\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // Use PE32 offset\r
       //\r
@@ -547,7 +605,8 @@ PeCoffLoaderGetImageInfo (
       ImageContext->ImageAddress = Hdr.Pe32Plus->OptionalHeader.ImageBase;\r
     }\r
   } else {\r
-    ImageContext->ImageAddress = (PHYSICAL_ADDRESS)(Hdr.Te->ImageBase + Hdr.Te->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER));\r
+    TeStrippedOffset = (UINT32)Hdr.Te->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);\r
+    ImageContext->ImageAddress = (PHYSICAL_ADDRESS)(Hdr.Te->ImageBase + TeStrippedOffset);\r
   }\r
 \r
   //\r
@@ -581,18 +640,9 @@ 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
-    ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
-    return RETURN_UNSUPPORTED;\r
-  }\r
 \r
   if (!(ImageContext->IsTeImage)) {\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // Use PE32 offset\r
       //\r
@@ -617,12 +667,10 @@ PeCoffLoaderGetImageInfo (
       //\r
       DebugDirectoryEntryFileOffset = 0;\r
 \r
-      SectionHeaderOffset = (UINTN)(\r
-                               ImageContext->PeCoffHeaderOffset +\r
-                               sizeof (UINT32) +\r
-                               sizeof (EFI_IMAGE_FILE_HEADER) +\r
-                               Hdr.Pe32->FileHeader.SizeOfOptionalHeader\r
-                               );\r
+      SectionHeaderOffset = ImageContext->PeCoffHeaderOffset +\r
+                            sizeof (UINT32) +\r
+                            sizeof (EFI_IMAGE_FILE_HEADER) +\r
+                            Hdr.Pe32->FileHeader.SizeOfOptionalHeader;\r
 \r
       for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {\r
         //\r
@@ -723,9 +771,8 @@ PeCoffLoaderGetImageInfo (
           DebugDirectoryEntryRva < SectionHeader.VirtualAddress + SectionHeader.Misc.VirtualSize) {\r
         DebugDirectoryEntryFileOffset = DebugDirectoryEntryRva -\r
                                         SectionHeader.VirtualAddress +\r
-                                        SectionHeader.PointerToRawData +\r
-                                        sizeof (EFI_TE_IMAGE_HEADER) -\r
-                                        Hdr.Te->StrippedSize;\r
+                                        SectionHeader.PointerToRawData -\r
+                                        TeStrippedOffset;\r
 \r
         //\r
         // File offset of the debug directory was found, if this is not the last\r
@@ -746,10 +793,10 @@ PeCoffLoaderGetImageInfo (
       // 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
-      // Section Table.  \r
+      // Section Table.\r
       //\r
       if ((++Index) == (UINTN)Hdr.Te->NumberOfSections) {\r
-        ImageContext->ImageSize = (SectionHeader.VirtualAddress + SectionHeader.Misc.VirtualSize);\r
+        ImageContext->ImageSize = (SectionHeader.VirtualAddress + SectionHeader.Misc.VirtualSize) - TeStrippedOffset;\r
       }\r
 \r
       SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);\r
@@ -791,8 +838,9 @@ PeCoffLoaderGetImageInfo (
 /**\r
   Converts an image address to the loaded address.\r
 \r
-  @param  ImageContext  The context of the image being loaded.\r
-  @param  Address       The relative virtual address to be converted to the loaded address.\r
+  @param  ImageContext      The context of the image being loaded.\r
+  @param  Address           The address to be converted to the loaded address.\r
+  @param  TeStrippedOffset  Stripped offset for TE image.\r
 \r
   @return The converted address or NULL if the address can not be converted.\r
 \r
@@ -800,18 +848,19 @@ PeCoffLoaderGetImageInfo (
 VOID *\r
 PeCoffLoaderImageAddress (\r
   IN OUT PE_COFF_LOADER_IMAGE_CONTEXT          *ImageContext,\r
-  IN     UINTN                                 Address\r
+  IN     UINTN                                 Address,\r
+  IN     UINTN                                 TeStrippedOffset\r
   )\r
 {\r
   //\r
   // Make sure that Address and ImageSize is correct for the loaded image.\r
   //\r
-  if (Address >= ImageContext->ImageSize) {\r
+  if (Address >= ImageContext->ImageSize + TeStrippedOffset) {\r
     ImageContext->ImageError = IMAGE_ERROR_INVALID_IMAGE_ADDRESS;\r
     return NULL;\r
   }\r
 \r
-  return (CHAR8 *)((UINTN) ImageContext->ImageAddress + Address);\r
+  return (CHAR8 *)((UINTN) ImageContext->ImageAddress + Address - TeStrippedOffset);\r
 }\r
 \r
 /**\r
@@ -821,12 +870,12 @@ PeCoffLoaderImageAddress (
   ImageContext as the relocation base address.  Otherwise, use the DestinationAddress field\r
   of ImageContext as the relocation base address.  The caller must allocate the relocation\r
   fixup log buffer and fill in the FixupData field of ImageContext prior to calling this function.\r
-  \r
-  The ImageRead, Handle, PeCoffHeaderOffset,  IsTeImage, Machine, ImageType, ImageAddress, \r
-  ImageSize, DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders, \r
-  DebugDirectoryEntryRva, EntryPoint, FixupDataSize, CodeView, PdbPointer, and FixupData of \r
+\r
+  The ImageRead, Handle, PeCoffHeaderOffset,  IsTeImage, Machine, ImageType, ImageAddress,\r
+  ImageSize, DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders,\r
+  DebugDirectoryEntryRva, EntryPoint, FixupDataSize, CodeView, PdbPointer, and FixupData of\r
   the ImageContext structure must be valid prior to invoking this service.\r
-    \r
+\r
   If ImageContext is NULL, then ASSERT().\r
 \r
   Note that if the platform does not maintain coherency between the instruction cache(s) and the data\r
@@ -854,6 +903,7 @@ PeCoffLoaderRelocateImage (
   EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION   Hdr;\r
   EFI_IMAGE_DATA_DIRECTORY              *RelocDir;\r
   UINT64                                Adjust;\r
+  EFI_IMAGE_BASE_RELOCATION             *RelocBaseOrg;\r
   EFI_IMAGE_BASE_RELOCATION             *RelocBase;\r
   EFI_IMAGE_BASE_RELOCATION             *RelocBaseEnd;\r
   UINT16                                *Reloc;\r
@@ -866,7 +916,7 @@ PeCoffLoaderRelocateImage (
   CHAR8                                 *FixupData;\r
   PHYSICAL_ADDRESS                      BaseAddress;\r
   UINT32                                NumberOfRvaAndSizes;\r
-  UINT16                                Magic;\r
+  UINT32                                TeStrippedOffset;\r
 \r
   ASSERT (ImageContext != NULL);\r
 \r
@@ -879,9 +929,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
+    // Applies additional environment specific actions to relocate fixups\r
     // to a PE/COFF image if needed\r
-    PeCoffLoaderRelocateImageExtraAction (ImageContext);  \r
+    PeCoffLoaderRelocateImageExtraAction (ImageContext);\r
     return RETURN_SUCCESS;\r
   }\r
 \r
@@ -897,10 +947,9 @@ PeCoffLoaderRelocateImage (
 \r
   if (!(ImageContext->IsTeImage)) {\r
     Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)ImageContext->ImageAddress + ImageContext->PeCoffHeaderOffset);\r
+    TeStrippedOffset = 0;\r
 \r
-    Magic = PeCoffLoaderGetPeHeaderMagicValue (Hdr);\r
-\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // Use PE32 offset\r
       //\r
@@ -930,48 +979,40 @@ PeCoffLoaderRelocateImage (
     // is present in the image. You have to check the NumberOfRvaAndSizes in\r
     // the optional header to verify a desired directory entry is there.\r
     //\r
-\r
-    if ((NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) && (RelocDir->Size > 0)) {\r
-      RelocBase = PeCoffLoaderImageAddress (ImageContext, RelocDir->VirtualAddress);\r
-      RelocBaseEnd = PeCoffLoaderImageAddress (\r
-                      ImageContext,\r
-                      RelocDir->VirtualAddress + RelocDir->Size - 1\r
-                      );\r
-      if (RelocBase == NULL || RelocBaseEnd == NULL) {\r
-        return RETURN_LOAD_ERROR;\r
-      }\r
-    } else {\r
-      //\r
-      // Set base and end to bypass processing below.\r
-      //\r
-      RelocBase = RelocBaseEnd = NULL;\r
+    if ((NumberOfRvaAndSizes < EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC)) {\r
+      RelocDir = NULL;\r
     }\r
   } 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
+    TeStrippedOffset   = (UINT32)Hdr.Te->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);\r
+    Adjust             = (UINT64) (BaseAddress - (Hdr.Te->ImageBase + TeStrippedOffset));\r
     if (Adjust != 0) {\r
-      Hdr.Te->ImageBase  = (UINT64) (BaseAddress - Hdr.Te->StrippedSize + sizeof (EFI_TE_IMAGE_HEADER));\r
+      Hdr.Te->ImageBase  = (UINT64) (BaseAddress - TeStrippedOffset);\r
     }\r
 \r
     //\r
     // Find the relocation block\r
     //\r
     RelocDir = &Hdr.Te->DataDirectory[0];\r
-    if (RelocDir->Size > 0) {\r
-      RelocBase = (EFI_IMAGE_BASE_RELOCATION *)(UINTN)(\r
-                                      ImageContext->ImageAddress +\r
-                                      RelocDir->VirtualAddress +\r
-                                      sizeof(EFI_TE_IMAGE_HEADER) -\r
-                                      Hdr.Te->StrippedSize\r
-                                      );\r
-      RelocBaseEnd = (EFI_IMAGE_BASE_RELOCATION *) ((UINTN) RelocBase + (UINTN) RelocDir->Size - 1);\r
-    } else {\r
-      //\r
-      // Set base and end to bypass processing below.\r
-      //\r
-      RelocBase = RelocBaseEnd = NULL;    \r
+  }\r
+\r
+  if ((RelocDir != NULL) && (RelocDir->Size > 0)) {\r
+    RelocBase = (EFI_IMAGE_BASE_RELOCATION *) PeCoffLoaderImageAddress (ImageContext, RelocDir->VirtualAddress, TeStrippedOffset);\r
+    RelocBaseEnd = (EFI_IMAGE_BASE_RELOCATION *) PeCoffLoaderImageAddress (ImageContext,\r
+                                                                            RelocDir->VirtualAddress + RelocDir->Size - 1,\r
+                                                                            TeStrippedOffset\r
+                                                                            );\r
+    if (RelocBase == NULL || RelocBaseEnd == NULL || RelocBaseEnd < RelocBase) {\r
+      ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+      return RETURN_LOAD_ERROR;\r
     }\r
+  } else {\r
+    //\r
+    // Set base and end to bypass processing below.\r
+    //\r
+    RelocBase = RelocBaseEnd = NULL;\r
   }\r
+  RelocBaseOrg = RelocBase;\r
 \r
   //\r
   // If Adjust is not zero, then apply fix ups to the image\r
@@ -987,32 +1028,35 @@ PeCoffLoaderRelocateImage (
       //\r
       // Add check for RelocBase->SizeOfBlock field.\r
       //\r
-      if ((RelocBase->SizeOfBlock == 0) || (RelocBase->SizeOfBlock > RelocDir->Size)) {\r
+      if (RelocBase->SizeOfBlock == 0) {\r
+        ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+        return RETURN_LOAD_ERROR;\r
+      }\r
+      if ((UINTN)RelocBase > MAX_ADDRESS - RelocBase->SizeOfBlock) {\r
         ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
         return RETURN_LOAD_ERROR;\r
       }\r
 \r
       RelocEnd  = (UINT16 *) ((CHAR8 *) RelocBase + RelocBase->SizeOfBlock);\r
-\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
+      if ((UINTN)RelocEnd > (UINTN)RelocBaseOrg + RelocDir->Size) {\r
+        ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+        return RETURN_LOAD_ERROR;\r
+      }\r
+      FixupBase = PeCoffLoaderImageAddress (ImageContext, RelocBase->VirtualAddress, TeStrippedOffset);\r
+      if (FixupBase == NULL) {\r
+        ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+        return RETURN_LOAD_ERROR;\r
+      }\r
 \r
       //\r
       // Run this relocation record\r
       //\r
       while (Reloc < RelocEnd) {\r
-\r
-        Fixup = FixupBase + (*Reloc & 0xFFF);\r
+        Fixup = PeCoffLoaderImageAddress (ImageContext, RelocBase->VirtualAddress + (*Reloc & 0xFFF), TeStrippedOffset);\r
+        if (Fixup == NULL) {\r
+          ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+          return RETURN_LOAD_ERROR;\r
+        }\r
         switch ((*Reloc) >> 12) {\r
         case EFI_IMAGE_REL_BASED_ABSOLUTE:\r
           break;\r
@@ -1079,6 +1123,7 @@ PeCoffLoaderRelocateImage (
       //\r
       RelocBase = (EFI_IMAGE_BASE_RELOCATION *) RelocEnd;\r
     }\r
+    ASSERT ((UINTN)FixupData <= (UINTN)ImageContext->FixupData + ImageContext->FixupDataSize);\r
 \r
     //\r
     // Adjust the EntryPoint to match the linked-to address\r
@@ -1088,11 +1133,11 @@ PeCoffLoaderRelocateImage (
        ImageContext->EntryPoint += (UINT64) ImageContext->DestinationAddress;\r
     }\r
   }\r
-  \r
-  // Applies additional environment specific actions to relocate fixups \r
+\r
+  // Applies additional environment specific actions to relocate fixups\r
   // to a PE/COFF image if needed\r
   PeCoffLoaderRelocateImageExtraAction (ImageContext);\r
-  \r
+\r
   return RETURN_SUCCESS;\r
 }\r
 \r
@@ -1103,10 +1148,10 @@ PeCoffLoaderRelocateImage (
   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, 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
+  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
+\r
   If ImageContext is NULL, then ASSERT().\r
 \r
   Note that if the platform does not maintain coherency between the instruction cache(s) and the data\r
@@ -1147,14 +1192,13 @@ PeCoffLoaderLoadImage (
   UINTN                                 Size;\r
   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
   UINT32                                Offset;\r
-\r
+  UINT32                                TeStrippedOffset;\r
 \r
   ASSERT (ImageContext != NULL);\r
 \r
@@ -1241,6 +1285,7 @@ PeCoffLoaderLoadImage (
                       Hdr.Pe32->FileHeader.SizeOfOptionalHeader\r
       );\r
     NumberOfSections = (UINTN) (Hdr.Pe32->FileHeader.NumberOfSections);\r
+    TeStrippedOffset = 0;\r
   } else {\r
     Status = ImageContext->ImageRead (\r
                             ImageContext->Handle,\r
@@ -1250,13 +1295,12 @@ PeCoffLoaderLoadImage (
                             );\r
 \r
     Hdr.Te = (EFI_TE_IMAGE_HEADER *)(UINTN)(ImageContext->ImageAddress);\r
-\r
     FirstSection = (EFI_IMAGE_SECTION_HEADER *) (\r
                       (UINTN)ImageContext->ImageAddress +\r
                       sizeof(EFI_TE_IMAGE_HEADER)\r
                       );\r
     NumberOfSections  = (UINTN) (Hdr.Te->NumberOfSections);\r
-\r
+    TeStrippedOffset  = (UINT32) Hdr.Te->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);\r
   }\r
 \r
   if (RETURN_ERROR (Status)) {\r
@@ -1280,11 +1324,8 @@ PeCoffLoaderLoadImage (
     //\r
     // Compute sections address\r
     //\r
-    Base = PeCoffLoaderImageAddress (ImageContext, Section->VirtualAddress);\r
-    End = PeCoffLoaderImageAddress (\r
-            ImageContext,\r
-            Section->VirtualAddress + Section->Misc.VirtualSize - 1\r
-            );\r
+    Base = PeCoffLoaderImageAddress (ImageContext, Section->VirtualAddress, TeStrippedOffset);\r
+    End  = PeCoffLoaderImageAddress (ImageContext, Section->VirtualAddress + Section->Misc.VirtualSize - 1, TeStrippedOffset);\r
 \r
     //\r
     // If the size of the section is non-zero and the base address or end address resolved to 0, then fail.\r
@@ -1294,28 +1335,13 @@ PeCoffLoaderLoadImage (
       return RETURN_LOAD_ERROR;\r
     }\r
 \r
-    if (ImageContext->IsTeImage) {\r
-      Base = (CHAR8 *)((UINTN) Base + sizeof (EFI_TE_IMAGE_HEADER) - (UINTN)Hdr.Te->StrippedSize);\r
-      End  = (CHAR8 *)((UINTN) End +  sizeof (EFI_TE_IMAGE_HEADER) - (UINTN)Hdr.Te->StrippedSize);\r
-    }\r
-\r
     if (Section->SizeOfRawData > 0) {\r
-      if (!(ImageContext->IsTeImage)) {\r
-        Status = ImageContext->ImageRead (\r
-                                ImageContext->Handle,\r
-                                Section->PointerToRawData,\r
-                                &Size,\r
-                                Base\r
-                                );\r
-      } else {\r
-        Status = ImageContext->ImageRead (\r
-                                ImageContext->Handle,\r
-                                Section->PointerToRawData + sizeof (EFI_TE_IMAGE_HEADER) - (UINTN)Hdr.Te->StrippedSize,\r
-                                &Size,\r
-                                Base\r
-                                );\r
-      }\r
-\r
+      Status = ImageContext->ImageRead (\r
+                              ImageContext->Handle,\r
+                              Section->PointerToRawData - TeStrippedOffset,\r
+                              &Size,\r
+                              Base\r
+                              );\r
       if (RETURN_ERROR (Status)) {\r
         ImageContext->ImageError = IMAGE_ERROR_IMAGE_READ;\r
         return Status;\r
@@ -1339,18 +1365,18 @@ PeCoffLoaderLoadImage (
   //\r
   // Get image's entry point\r
   //\r
-  Magic = PeCoffLoaderGetPeHeaderMagicValue (Hdr);\r
   if (!(ImageContext->IsTeImage)) {\r
     //\r
     // Sizes of AddressOfEntryPoint are different so we need to do this safely\r
     //\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // Use PE32 offset\r
       //\r
       ImageContext->EntryPoint = (PHYSICAL_ADDRESS)(UINTN)PeCoffLoaderImageAddress (\r
                                                             ImageContext,\r
-                                                            (UINTN)Hdr.Pe32->OptionalHeader.AddressOfEntryPoint\r
+                                                            (UINTN)Hdr.Pe32->OptionalHeader.AddressOfEntryPoint,\r
+                                                            0\r
                                                             );\r
     } else {\r
       //\r
@@ -1358,16 +1384,16 @@ PeCoffLoaderLoadImage (
       //\r
       ImageContext->EntryPoint = (PHYSICAL_ADDRESS)(UINTN)PeCoffLoaderImageAddress (\r
                                                             ImageContext,\r
-                                                            (UINTN)Hdr.Pe32Plus->OptionalHeader.AddressOfEntryPoint\r
+                                                            (UINTN)Hdr.Pe32Plus->OptionalHeader.AddressOfEntryPoint,\r
+                                                            0\r
                                                             );\r
     }\r
   } else {\r
-    ImageContext->EntryPoint =  (PHYSICAL_ADDRESS) (\r
-                                (UINTN)ImageContext->ImageAddress  +\r
-                                (UINTN)Hdr.Te->AddressOfEntryPoint +\r
-                                (UINTN)sizeof(EFI_TE_IMAGE_HEADER) -\r
-                                (UINTN)Hdr.Te->StrippedSize\r
-                                );\r
+    ImageContext->EntryPoint = (PHYSICAL_ADDRESS)(UINTN)PeCoffLoaderImageAddress (\r
+                                                          ImageContext,\r
+                                                          (UINTN)Hdr.Te->AddressOfEntryPoint,\r
+                                                          TeStrippedOffset\r
+                                                          );\r
   }\r
 \r
   //\r
@@ -1378,7 +1404,7 @@ PeCoffLoaderLoadImage (
   // the optional header to verify a desired directory entry is there.\r
   //\r
   if (!(ImageContext->IsTeImage)) {\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // Use PE32 offset\r
       //\r
@@ -1392,14 +1418,17 @@ PeCoffLoaderLoadImage (
       DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];\r
     }\r
 \r
+    //\r
+    // Must use UINT64 here, because there might a case that 32bit loader to load 64bit image.\r
+    //\r
     if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {\r
-      ImageContext->FixupDataSize = DirectoryEntry->Size / sizeof (UINT16) * sizeof (UINTN);\r
+      ImageContext->FixupDataSize = DirectoryEntry->Size / sizeof (UINT16) * sizeof (UINT64);\r
     } else {\r
       ImageContext->FixupDataSize = 0;\r
     }\r
   } else {\r
     DirectoryEntry              = &Hdr.Te->DataDirectory[0];\r
-    ImageContext->FixupDataSize = DirectoryEntry->Size / sizeof (UINT16) * sizeof (UINTN);\r
+    ImageContext->FixupDataSize = DirectoryEntry->Size / sizeof (UINT16) * sizeof (UINT64);\r
   }\r
   //\r
   // Consumer must allocate a buffer for the relocation fixup log.\r
@@ -1411,107 +1440,82 @@ PeCoffLoaderLoadImage (
   // Load the Codeview information if present\r
   //\r
   if (ImageContext->DebugDirectoryEntryRva != 0) {\r
-    if (!(ImageContext->IsTeImage)) {\r
-      DebugEntry = PeCoffLoaderImageAddress (\r
-                    ImageContext,\r
-                    ImageContext->DebugDirectoryEntryRva\r
-                    );\r
-    } else {\r
-      DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)(UINTN)(\r
-                      ImageContext->ImageAddress +\r
-                      ImageContext->DebugDirectoryEntryRva +\r
-                      sizeof(EFI_TE_IMAGE_HEADER) -\r
-                      Hdr.Te->StrippedSize\r
-                      );\r
+    DebugEntry = PeCoffLoaderImageAddress (\r
+                ImageContext,\r
+                ImageContext->DebugDirectoryEntryRva,\r
+                TeStrippedOffset\r
+                );\r
+    if (DebugEntry == NULL) {\r
+      ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+      return RETURN_LOAD_ERROR;\r
     }\r
 \r
-    if (DebugEntry != NULL) {\r
-      TempDebugEntryRva = DebugEntry->RVA;\r
-      if (DebugEntry->RVA == 0 && DebugEntry->FileOffset != 0) {\r
-        Section--;\r
-        if ((UINTN)Section->SizeOfRawData < Section->Misc.VirtualSize) {\r
-          TempDebugEntryRva = Section->VirtualAddress + Section->Misc.VirtualSize;\r
-        } else {\r
-          TempDebugEntryRva = Section->VirtualAddress + Section->SizeOfRawData;\r
-        }\r
+    TempDebugEntryRva = DebugEntry->RVA;\r
+    if (DebugEntry->RVA == 0 && DebugEntry->FileOffset != 0) {\r
+      Section--;\r
+      if ((UINTN)Section->SizeOfRawData < Section->Misc.VirtualSize) {\r
+        TempDebugEntryRva = Section->VirtualAddress + Section->Misc.VirtualSize;\r
+      } else {\r
+        TempDebugEntryRva = Section->VirtualAddress + Section->SizeOfRawData;\r
       }\r
+    }\r
 \r
-      if (TempDebugEntryRva != 0) {\r
-        if (!(ImageContext->IsTeImage)) {\r
-          ImageContext->CodeView = PeCoffLoaderImageAddress (ImageContext, TempDebugEntryRva);\r
-        } else {\r
-          ImageContext->CodeView = (VOID *)(\r
-                                    (UINTN)ImageContext->ImageAddress +\r
-                                    (UINTN)TempDebugEntryRva +\r
-                                    (UINTN)sizeof (EFI_TE_IMAGE_HEADER) -\r
-                                    (UINTN) Hdr.Te->StrippedSize\r
-                                    );\r
-        }\r
+    if (TempDebugEntryRva != 0) {\r
+      ImageContext->CodeView = PeCoffLoaderImageAddress (ImageContext, TempDebugEntryRva, TeStrippedOffset);\r
+      if (ImageContext->CodeView == NULL) {\r
+        ImageContext->ImageError = IMAGE_ERROR_FAILED_RELOCATION;\r
+        return RETURN_LOAD_ERROR;\r
+      }\r
+\r
+      if (DebugEntry->RVA == 0) {\r
+        Size = DebugEntry->SizeOfData;\r
+        Status = ImageContext->ImageRead (\r
+                                ImageContext->Handle,\r
+                                DebugEntry->FileOffset - TeStrippedOffset,\r
+                                &Size,\r
+                                ImageContext->CodeView\r
+                                );\r
+        //\r
+        // Should we apply fix up to this field according to the size difference between PE and TE?\r
+        // Because now we maintain TE header fields unfixed, this field will also remain as they are\r
+        // in original PE image.\r
+        //\r
 \r
-        if (ImageContext->CodeView == NULL) {\r
+        if (RETURN_ERROR (Status)) {\r
           ImageContext->ImageError = IMAGE_ERROR_IMAGE_READ;\r
           return RETURN_LOAD_ERROR;\r
         }\r
 \r
-        if (DebugEntry->RVA == 0) {\r
-          Size = DebugEntry->SizeOfData;\r
-          if (!(ImageContext->IsTeImage)) {\r
-            Status = ImageContext->ImageRead (\r
-                                    ImageContext->Handle,\r
-                                    DebugEntry->FileOffset,\r
-                                    &Size,\r
-                                    ImageContext->CodeView\r
-                                    );\r
-          } else {\r
-            Status = ImageContext->ImageRead (\r
-                                    ImageContext->Handle,\r
-                                    DebugEntry->FileOffset + sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize,\r
-                                    &Size,\r
-                                    ImageContext->CodeView\r
-                                    );\r
-            //\r
-            // Should we apply fix up to this field according to the size difference between PE and TE?\r
-            // Because now we maintain TE header fields unfixed, this field will also remain as they are\r
-            // in original PE image.\r
-            //\r
-          }\r
-\r
-          if (RETURN_ERROR (Status)) {\r
-            ImageContext->ImageError = IMAGE_ERROR_IMAGE_READ;\r
-            return RETURN_LOAD_ERROR;\r
-          }\r
+        DebugEntry->RVA = TempDebugEntryRva;\r
+      }\r
 \r
-          DebugEntry->RVA = TempDebugEntryRva;\r
+      switch (*(UINT32 *) ImageContext->CodeView) {\r
+      case CODEVIEW_SIGNATURE_NB10:\r
+        if (DebugEntry->SizeOfData < sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY)) {\r
+          ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+          return RETURN_UNSUPPORTED;\r
         }\r
+        ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY);\r
+        break;\r
 \r
-        switch (*(UINT32 *) ImageContext->CodeView) {\r
-        case CODEVIEW_SIGNATURE_NB10:\r
-          if (DebugEntry->SizeOfData < sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY)) {\r
-            ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
-            return RETURN_UNSUPPORTED;\r
-          }\r
-          ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY);\r
-          break;\r
-\r
-        case CODEVIEW_SIGNATURE_RSDS:\r
-          if (DebugEntry->SizeOfData < sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY)) {\r
-            ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
-            return RETURN_UNSUPPORTED;\r
-          }\r
-          ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY);\r
-          break;\r
-\r
-        case CODEVIEW_SIGNATURE_MTOC:\r
-          if (DebugEntry->SizeOfData < sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY)) {\r
-            ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
-            return RETURN_UNSUPPORTED;\r
-          }\r
-          ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY);\r
-          break;\r
+      case CODEVIEW_SIGNATURE_RSDS:\r
+        if (DebugEntry->SizeOfData < sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY)) {\r
+          ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+          return RETURN_UNSUPPORTED;\r
+        }\r
+        ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY);\r
+        break;\r
 \r
-        default:\r
-          break;\r
+      case CODEVIEW_SIGNATURE_MTOC:\r
+        if (DebugEntry->SizeOfData < sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY)) {\r
+          ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
+          return RETURN_UNSUPPORTED;\r
         }\r
+        ImageContext->PdbPointer = (CHAR8 *)ImageContext->CodeView + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY);\r
+        break;\r
+\r
+      default:\r
+        break;\r
       }\r
     }\r
   }\r
@@ -1521,7 +1525,7 @@ PeCoffLoaderLoadImage (
   //\r
   ImageContext->HiiResourceData = 0;\r
   if (!(ImageContext->IsTeImage)) {\r
-    if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+    if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
       //\r
       // Use PE32 offset\r
       //\r
@@ -1536,10 +1540,10 @@ PeCoffLoaderLoadImage (
     }\r
 \r
     if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE && DirectoryEntry->Size != 0) {\r
-      Base = PeCoffLoaderImageAddress (ImageContext, DirectoryEntry->VirtualAddress);\r
+      Base = PeCoffLoaderImageAddress (ImageContext, DirectoryEntry->VirtualAddress, 0);\r
       if (Base != NULL) {\r
         ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) Base;\r
-        Offset = sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY) * \r
+        Offset = sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY) *\r
                (ResourceDirectory->NumberOfNamedEntries + ResourceDirectory->NumberOfIdEntries);\r
         if (Offset > DirectoryEntry->Size) {\r
           ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
@@ -1575,7 +1579,7 @@ PeCoffLoaderLoadImage (
                   return RETURN_UNSUPPORTED;\r
                 }\r
                 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (Base + ResourceDirectoryEntry->u2.s.OffsetToDirectory);\r
-                Offset = ResourceDirectoryEntry->u2.s.OffsetToDirectory + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) + \r
+                Offset = ResourceDirectoryEntry->u2.s.OffsetToDirectory + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) +\r
                          sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY) * (ResourceDirectory->NumberOfNamedEntries + ResourceDirectory->NumberOfIdEntries);\r
                 if (Offset > DirectoryEntry->Size) {\r
                   ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
@@ -1592,7 +1596,7 @@ PeCoffLoaderLoadImage (
                     return RETURN_UNSUPPORTED;\r
                   }\r
                   ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (Base + ResourceDirectoryEntry->u2.s.OffsetToDirectory);\r
-                  Offset = ResourceDirectoryEntry->u2.s.OffsetToDirectory + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) + \r
+                  Offset = ResourceDirectoryEntry->u2.s.OffsetToDirectory + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) +\r
                            sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY) * (ResourceDirectory->NumberOfNamedEntries + ResourceDirectory->NumberOfIdEntries);\r
                   if (Offset > DirectoryEntry->Size) {\r
                     ImageContext->ImageError = IMAGE_ERROR_UNSUPPORTED;\r
@@ -1611,7 +1615,7 @@ PeCoffLoaderLoadImage (
                   return RETURN_UNSUPPORTED;\r
                 }\r
                 ResourceDataEntry = (EFI_IMAGE_RESOURCE_DATA_ENTRY *) (Base + ResourceDirectoryEntry->u2.OffsetToData);\r
-                ImageContext->HiiResourceData = (PHYSICAL_ADDRESS) (UINTN) PeCoffLoaderImageAddress (ImageContext, ResourceDataEntry->OffsetToData);\r
+                ImageContext->HiiResourceData = (PHYSICAL_ADDRESS) (UINTN) PeCoffLoaderImageAddress (ImageContext, ResourceDataEntry->OffsetToData, 0);\r
                 break;\r
               }\r
             }\r
@@ -1621,33 +1625,33 @@ PeCoffLoaderLoadImage (
       }\r
     }\r
   }\r
\r
+\r
   return Status;\r
 }\r
 \r
 \r
 /**\r
   Reapply fixups on a fixed up PE32/PE32+ image to allow virutal calling at EFI\r
-  runtime. \r
-  \r
-  This function reapplies relocation fixups to the PE/COFF image specified by ImageBase \r
-  and ImageSize so the image will execute correctly when the PE/COFF image is mapped \r
-  to the address specified by VirtualImageBase.  RelocationData must be identical \r
-  to the FiuxupData buffer from the PE_COFF_LOADER_IMAGE_CONTEXT structure \r
+  runtime.\r
+\r
+  This function reapplies relocation fixups to the PE/COFF image specified by ImageBase\r
+  and ImageSize so the image will execute correctly when the PE/COFF image is mapped\r
+  to the address specified by VirtualImageBase.  RelocationData must be identical\r
+  to the FiuxupData buffer from the PE_COFF_LOADER_IMAGE_CONTEXT structure\r
   after this PE/COFF image was relocated with PeCoffLoaderRelocateImage().\r
 \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
+  @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
   @param  ImageSize          The size, in bytes, of the PE/COFF image.\r
-  @param  RelocationData     A pointer to the relocation data that was collected when the PE/COFF \r
+  @param  RelocationData     A pointer to the relocation data that was collected when the PE/COFF\r
                              image was relocated using PeCoffLoaderRelocateImage().\r
-  \r
+\r
 **/\r
 VOID\r
 EFIAPI\r
@@ -1677,7 +1681,6 @@ PeCoffLoaderRelocateImageForRuntime (
   CHAR8                               *FixupData;\r
   UINTN                               Adjust;\r
   RETURN_STATUS                       Status;\r
-  UINT16                              Magic;\r
 \r
   OldBase = (CHAR8 *)((UINTN)ImageBase);\r
   NewBase = (CHAR8 *)((UINTN)VirtImageBase);\r
@@ -1706,9 +1709,7 @@ PeCoffLoaderRelocateImageForRuntime (
     return ;\r
   }\r
 \r
-  Magic = PeCoffLoaderGetPeHeaderMagicValue (Hdr);\r
-\r
-  if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
+  if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
     //\r
     // Use PE32 offset\r
     //\r
@@ -1740,7 +1741,7 @@ PeCoffLoaderRelocateImageForRuntime (
     ASSERT (FALSE);\r
     return ;\r
   }\r
-  \r
+\r
   //\r
   // ASSERT for the invalid image when RelocBase and RelocBaseEnd are both NULL.\r
   //\r
@@ -1818,13 +1819,6 @@ PeCoffLoaderRelocateImageForRuntime (
         FixupData = FixupData + sizeof (UINT64);\r
         break;\r
 \r
-      case EFI_IMAGE_REL_BASED_HIGHADJ:\r
-        //\r
-        // Not valid Relocation type for UEFI image, ASSERT\r
-        //\r
-        ASSERT (FALSE);\r
-        break;\r
-\r
       default:\r
         //\r
         // Only Itanium requires ConvertPeImage_Ex\r
@@ -1849,14 +1843,14 @@ PeCoffLoaderRelocateImageForRuntime (
 \r
 /**\r
   Reads contents of a PE/COFF image from a buffer in system memory.\r
-   \r
-  This is the default implementation of a PE_COFF_LOADER_READ_FILE function \r
-  that assumes FileHandle pointer to the beginning of a PE/COFF image.   \r
-  This function reads contents of the PE/COFF image that starts at the system memory \r
-  address specified by FileHandle.  The read operation copies ReadSize bytes from the \r
-  PE/COFF image starting at byte offset FileOffset into the buffer specified by Buffer.  \r
+\r
+  This is the default implementation of a PE_COFF_LOADER_READ_FILE function\r
+  that assumes FileHandle pointer to the beginning of a PE/COFF image.\r
+  This function reads contents of the PE/COFF image that starts at the system memory\r
+  address specified by FileHandle.  The read operation copies ReadSize bytes from the\r
+  PE/COFF image starting at byte offset FileOffset into the buffer specified by Buffer.\r
   The size of the buffer actually read is returned in ReadSize.\r
-  \r
+\r
   The caller must make sure the FileOffset and ReadSize within the file scope.\r
 \r
   If FileHandle is NULL, then ASSERT().\r
@@ -1865,11 +1859,11 @@ PeCoffLoaderRelocateImageForRuntime (
 \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
+  @param  ReadSize          On input, the size in bytes of the requested read operation.\r
                             On output, the number of bytes actually read.\r
   @param  Buffer            Output buffer that contains the data read from the PE/COFF image.\r
 \r
-  @retval RETURN_SUCCESS    Data is read from FileOffset from the Handle into \r
+  @retval RETURN_SUCCESS    Data is read from FileOffset from the Handle into\r
                             the buffer.\r
 **/\r
 RETURN_STATUS\r
@@ -1891,15 +1885,15 @@ PeCoffLoaderImageReadFromMemory (
 \r
 /**\r
   Unloads a loaded PE/COFF image from memory and releases its taken resource.\r
-  Releases any environment specific resources that were allocated when the image \r
-  specified by ImageContext was loaded using PeCoffLoaderLoadImage(). \r
\r
+  Releases any environment specific resources that were allocated when the image\r
+  specified by ImageContext was loaded using PeCoffLoaderLoadImage().\r
+\r
   For NT32 emulator, the PE/COFF image loaded by system needs to release.\r
-  For real platform, the PE/COFF image loaded by Core doesn't needs to be unloaded, \r
+  For real platform, the PE/COFF image loaded by Core doesn't needs to be unloaded,\r
   this function can simply return RETURN_SUCCESS.\r
-  \r
+\r
   If ImageContext is NULL, then ASSERT().\r
-  \r
+\r
   @param  ImageContext              The pointer to the image context structure that describes the PE/COFF\r
                                     image to be unloaded.\r
 \r
@@ -1912,7 +1906,7 @@ PeCoffLoaderUnloadImage (
   )\r
 {\r
   //\r
-  // Applies additional environment specific actions to unload a \r
+  // Applies additional environment specific actions to unload a\r
   // PE/COFF image if needed\r
   //\r
   PeCoffLoaderUnloadImageExtraAction (ImageContext);\r