]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Core/Pei/Image/Image.c
MdeModulePkg PeiCore: Always use PeiImageRead() function to load PEI image
[mirror_edk2.git] / MdeModulePkg / Core / Pei / Image / Image.c
index 75dd9b2a97fd57a7607e1249f39fe5a3b019e3cb..315b551bfdb7f56b61761a8601c6caf181eb4338 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   Pei Core Load Image Support\r
 \r
-Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2006 - 2018, Intel Corporation. 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
@@ -50,97 +50,25 @@ PeiImageRead (
 {\r
   CHAR8 *Destination8;\r
   CHAR8 *Source8;\r
-  \r
-  Destination8  = Buffer;\r
-  Source8       = (CHAR8 *) ((UINTN) FileHandle + FileOffset);\r
-  if (Destination8 != Source8) {\r
-    CopyMem (Destination8, Source8, *ReadSize);\r
-  }\r
-\r
-  return EFI_SUCCESS;\r
-}\r
-\r
-/**\r
-\r
-  Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file.\r
-  The function is implemented as PIC so as to support shadowing.\r
-\r
-  @param FileHandle      - The handle to the PE/COFF file\r
-  @param FileOffset      - The offset, in bytes, into the file to read\r
-  @param ReadSize        - The number of bytes to read from the file starting at FileOffset\r
-  @param Buffer          - A pointer to the buffer to read the data into.\r
-\r
-  @return EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset\r
-\r
-**/\r
-EFI_STATUS\r
-EFIAPI\r
-PeiImageReadForShadow (\r
-  IN     VOID    *FileHandle,\r
-  IN     UINTN   FileOffset,\r
-  IN     UINTN   *ReadSize,\r
-  OUT    VOID    *Buffer\r
-  )\r
-{\r
-  CHAR8 *Destination8;\r
-  CHAR8 *Source8;\r
-  UINTN Length;\r
 \r
   Destination8  = Buffer;\r
   Source8       = (CHAR8 *) ((UINTN) FileHandle + FileOffset);\r
   if (Destination8 != Source8) {\r
-    Length        = *ReadSize;\r
-    while ((Length--) > 0) {\r
-      *(Destination8++) = *(Source8++);\r
-    }\r
+    CopyMem (Destination8, Source8, *ReadSize);\r
   }\r
 \r
   return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
+  To check memory usage bit map array to figure out if the memory range the image will be loaded in is available or not. If\r
+  memory range is available, the function will mark the corresponding bits to 1 which indicates the memory range is used.\r
+  The function is only invoked when load modules at fixed address feature is enabled.\r
 \r
-  Support routine to get the Image read file function.\r
-\r
-  @param ImageContext    - The context of the image being loaded\r
-\r
-  @retval EFI_SUCCESS - If Image function location is found\r
-\r
-**/\r
-EFI_STATUS\r
-GetImageReadFunction (\r
-  IN      PE_COFF_LOADER_IMAGE_CONTEXT  *ImageContext\r
-  )\r
-{\r
-  PEI_CORE_INSTANCE  *Private;\r
-  VOID*  MemoryBuffer;\r
-\r
-  Private = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ());\r
-\r
-  if (!Private->PeiMemoryInstalled || (Private->HobList.HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME) || EFI_IMAGE_MACHINE_TYPE_SUPPORTED(EFI_IMAGE_MACHINE_IA64)) {\r
-    ImageContext->ImageRead = PeiImageRead;\r
-  } else {\r
-    if (Private->ShadowedImageRead == NULL) {\r
-      MemoryBuffer = AllocatePages (0x400 / EFI_PAGE_SIZE + 1);\r
-      ASSERT (MemoryBuffer != NULL);\r
-      CopyMem (MemoryBuffer, (CONST VOID *) (UINTN) PeiImageReadForShadow, 0x400);\r
-      Private->ShadowedImageRead = (PE_COFF_LOADER_READ_FILE) (UINTN) MemoryBuffer;\r
-    }\r
-\r
-    ImageContext->ImageRead = Private->ShadowedImageRead;\r
-  }\r
-\r
-  return EFI_SUCCESS;\r
-}\r
-/**\r
-  To check memory usage bit map arry to figure out if the memory range the image will be loaded in is available or not. If \r
-  memory range is avaliable, the function will mark the correponding bits to 1 which indicates the memory range is used.\r
-  The function is only invoked when load modules at fixed address feature is enabled. \r
-  \r
   @param  Private                  Pointer to the private data passed in from caller\r
-  @param  ImageBase                The base addres the image will be loaded at.\r
+  @param  ImageBase                The base address the image will be loaded at.\r
   @param  ImageSize                The size of the image\r
-  \r
+\r
   @retval EFI_SUCCESS              The memory range the image will be loaded in is available\r
   @retval EFI_NOT_FOUND            The memory range the image will be loaded in is not available\r
 **/\r
@@ -158,7 +86,7 @@ CheckAndMarkFixLoadingMemoryUsageBitMap (
    UINT32                             TopOffsetPageNumber;\r
    UINT32                             Index;\r
    UINT64                             *MemoryUsageBitMap;\r
-   \r
+\r
 \r
    //\r
    // The reserved code range includes RuntimeCodePage range, Boot time code range and PEI code range.\r
@@ -167,19 +95,19 @@ CheckAndMarkFixLoadingMemoryUsageBitMap (
    DxeCodePageNumber += PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber);\r
    ReservedCodeSize  = EFI_PAGES_TO_SIZE(DxeCodePageNumber + PcdGet32(PcdLoadFixAddressPeiCodePageNumber));\r
    PeiCodeBase       = Private->LoadModuleAtFixAddressTopAddress - ReservedCodeSize;\r
-   \r
+\r
    //\r
    // Test the memory range for loading the image in the PEI code range.\r
    //\r
    if ((Private->LoadModuleAtFixAddressTopAddress - EFI_PAGES_TO_SIZE(DxeCodePageNumber)) < (ImageBase + ImageSize) ||\r
-       (PeiCodeBase > ImageBase)) {         \r
-     return EFI_NOT_FOUND; \r
+       (PeiCodeBase > ImageBase)) {\r
+     return EFI_NOT_FOUND;\r
    }\r
-   \r
+\r
    //\r
    // Test if the memory is avalaible or not.\r
    //\r
-   MemoryUsageBitMap    = Private->PeiCodeMemoryRangeUsageBitMap;  \r
+   MemoryUsageBitMap    = Private->PeiCodeMemoryRangeUsageBitMap;\r
    BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - PeiCodeBase));\r
    TopOffsetPageNumber  = EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - PeiCodeBase));\r
    for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {\r
@@ -187,21 +115,21 @@ CheckAndMarkFixLoadingMemoryUsageBitMap (
        //\r
        // This page is already used.\r
        //\r
-       return EFI_NOT_FOUND;  \r
+       return EFI_NOT_FOUND;\r
      }\r
    }\r
-   \r
+\r
    //\r
    // Being here means the memory range is available.  So mark the bits for the memory range\r
-   // \r
+   //\r
    for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {\r
      MemoryUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64));\r
    }\r
-   return  EFI_SUCCESS;   \r
+   return  EFI_SUCCESS;\r
 }\r
 /**\r
 \r
-  Get the fixed loadding address from image header assigned by build tool. This function only be called\r
+  Get the fixed loading address from image header assigned by build tool. This function only be called\r
   when Loading module at Fixed address feature enabled.\r
 \r
   @param ImageContext              Pointer to the image context structure that describes the PE/COFF\r
@@ -209,7 +137,7 @@ CheckAndMarkFixLoadingMemoryUsageBitMap (
   @param Private                    Pointer to the private data passed in from caller\r
 \r
   @retval EFI_SUCCESS               An fixed loading address is assigned to this image by build tools .\r
-  @retval EFI_NOT_FOUND             The image has no assigned fixed loadding address.\r
+  @retval EFI_NOT_FOUND             The image has no assigned fixed loading address.\r
 \r
 **/\r
 EFI_STATUS\r
@@ -222,14 +150,14 @@ GetPeCoffImageFixLoadingAssignedAddress(
    EFI_STATUS                         Status;\r
    EFI_IMAGE_SECTION_HEADER           SectionHeader;\r
    EFI_IMAGE_OPTIONAL_HEADER_UNION    *ImgHdr;\r
-   EFI_PHYSICAL_ADDRESS               FixLoaddingAddress;\r
+   EFI_PHYSICAL_ADDRESS               FixLoadingAddress;\r
    UINT16                             Index;\r
    UINTN                              Size;\r
    UINT16                             NumberOfSections;\r
    UINT64                             ValueInSectionHeader;\r
\r
 \r
-   FixLoaddingAddress = 0;\r
+\r
+   FixLoadingAddress = 0;\r
    Status = EFI_NOT_FOUND;\r
 \r
    //\r
@@ -238,18 +166,16 @@ GetPeCoffImageFixLoadingAssignedAddress(
    ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);\r
    if (ImageContext->IsTeImage) {\r
      //\r
-     // for TE image, the fix loadding address is saved in first section header that doesn't point\r
+     // for TE image, the fix loading address is saved in first section header that doesn't point\r
      // to code section.\r
      //\r
      SectionHeaderOffset = sizeof (EFI_TE_IMAGE_HEADER);\r
      NumberOfSections = ImgHdr->Te.NumberOfSections;\r
    } else {\r
-     SectionHeaderOffset = (UINTN)(\r
-                                 ImageContext->PeCoffHeaderOffset +\r
-                                 sizeof (UINT32) +\r
-                                 sizeof (EFI_IMAGE_FILE_HEADER) +\r
-                                 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader\r
-                                 );\r
+     SectionHeaderOffset = ImageContext->PeCoffHeaderOffset +\r
+                           sizeof (UINT32) +\r
+                           sizeof (EFI_IMAGE_FILE_HEADER) +\r
+                           ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader;\r
       NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;\r
    }\r
    //\r
@@ -280,7 +206,7 @@ GetPeCoffImageFixLoadingAssignedAddress(
        // for XIP PEIM, ImageBase field holds the image base address running on the Flash. And PointerToRelocations & PointerToLineNumbers\r
        // hold the image base address when it is shadow to the memory. And there is an assumption that when the feature is enabled, if a\r
        // module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers fields should NOT be Zero, or\r
-       // else, these 2 fileds should be set to Zero\r
+       // else, these 2 fields should be set to Zero\r
        //\r
        ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations);\r
        if (ValueInSectionHeader != 0) {\r
@@ -290,32 +216,32 @@ GetPeCoffImageFixLoadingAssignedAddress(
          if ((INT64)PcdGet64(PcdLoadModuleAtFixAddressEnable) > 0) {\r
            //\r
            // When LMFA feature is configured as Load Module at Fixed Absolute Address mode, PointerToRelocations & PointerToLineNumbers field\r
-           // hold the absolute address of image base runing in memory\r
+           // hold the absolute address of image base running in memory\r
            //\r
-           FixLoaddingAddress = ValueInSectionHeader;\r
+           FixLoadingAddress = ValueInSectionHeader;\r
          } else {\r
            //\r
            // When LMFA feature is configured as Load Module at Fixed offset mode, PointerToRelocations & PointerToLineNumbers field\r
            // hold the offset relative to a platform-specific top address.\r
            //\r
-           FixLoaddingAddress = (EFI_PHYSICAL_ADDRESS)(Private->LoadModuleAtFixAddressTopAddress + (INT64)ValueInSectionHeader);\r
+           FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(Private->LoadModuleAtFixAddressTopAddress + (INT64)ValueInSectionHeader);\r
          }\r
          //\r
-         // Check if the memory range is avaliable.\r
+         // Check if the memory range is available.\r
          //\r
-         Status = CheckAndMarkFixLoadingMemoryUsageBitMap (Private, FixLoaddingAddress, (UINT32) ImageContext->ImageSize);\r
+         Status = CheckAndMarkFixLoadingMemoryUsageBitMap (Private, FixLoadingAddress, (UINT32) ImageContext->ImageSize);\r
          if (!EFI_ERROR(Status)) {\r
            //\r
-           // The assigned address is valid. Return the specified loadding address\r
+           // The assigned address is valid. Return the specified loading address\r
            //\r
-           ImageContext->ImageAddress = FixLoaddingAddress;\r
+           ImageContext->ImageAddress = FixLoadingAddress;\r
          }\r
        }\r
        break;\r
      }\r
      SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);\r
    }\r
-   DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status= %r \n", (VOID *)(UINTN)FixLoaddingAddress, Status));\r
+   DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status= %r \n", (VOID *)(UINTN)FixLoadingAddress, Status));\r
    return Status;\r
 }\r
 /**\r
@@ -323,6 +249,7 @@ GetPeCoffImageFixLoadingAssignedAddress(
   Loads and relocates a PE/COFF image into memory.\r
   If the image is not relocatable, it will not be loaded into memory and be loaded as XIP image.\r
 \r
+  @param FileHandle      - Pointer to the FFS file header of the image.\r
   @param Pe32Data        - The base address of the PE/COFF file that is to be loaded and relocated\r
   @param ImageAddress    - The base address of the relocated PE/COFF image\r
   @param ImageSize       - The size of the relocated PE/COFF image\r
@@ -330,10 +257,14 @@ GetPeCoffImageFixLoadingAssignedAddress(
 \r
   @retval EFI_SUCCESS           The file was loaded and relocated\r
   @retval EFI_OUT_OF_RESOURCES  There was not enough memory to load and relocate the PE/COFF file\r
+  @retval EFI_WARN_BUFFER_TOO_SMALL\r
+                                There is not enough heap to allocate the requested size.\r
+                                This will not prevent the XIP image from being invoked.\r
 \r
 **/\r
 EFI_STATUS\r
 LoadAndRelocatePeCoffImage (\r
+  IN  EFI_PEI_FILE_HANDLE                       FileHandle,\r
   IN  VOID                                      *Pe32Data,\r
   OUT EFI_PHYSICAL_ADDRESS                      *ImageAddress,\r
   OUT UINT64                                    *ImageSize,\r
@@ -343,23 +274,68 @@ LoadAndRelocatePeCoffImage (
   EFI_STATUS                            Status;\r
   PE_COFF_LOADER_IMAGE_CONTEXT          ImageContext;\r
   PEI_CORE_INSTANCE                     *Private;\r
+  UINT64                                AlignImageSize;\r
+  BOOLEAN                               IsXipImage;\r
+  EFI_STATUS                            ReturnStatus;\r
+  BOOLEAN                               IsS3Boot;\r
+  BOOLEAN                               IsPeiModule;\r
+  BOOLEAN                               IsRegisterForShadow;\r
+  EFI_FV_FILE_INFO                      FileInfo;\r
 \r
   Private = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ());\r
 \r
+  ReturnStatus = EFI_SUCCESS;\r
+  IsXipImage   = FALSE;\r
   ZeroMem (&ImageContext, sizeof (ImageContext));\r
   ImageContext.Handle = Pe32Data;\r
-  Status              = GetImageReadFunction (&ImageContext);\r
-\r
-  ASSERT_EFI_ERROR (Status);\r
+  ImageContext.ImageRead = PeiImageRead;\r
 \r
   Status = PeCoffLoaderGetImageInfo (&ImageContext);\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
+\r
+  //\r
+  // Initilize local IsS3Boot and IsRegisterForShadow variable\r
+  //\r
+  IsS3Boot = FALSE;\r
+  if (Private->HobList.HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME) {\r
+    IsS3Boot = TRUE;\r
+  }\r
+  IsRegisterForShadow = FALSE;\r
+  if ((Private->CurrentFileHandle == FileHandle)\r
+    && (Private->Fv[Private->CurrentPeimFvCount].PeimState[Private->CurrentPeimCount] == PEIM_STATE_REGISTER_FOR_SHADOW)) {\r
+    IsRegisterForShadow = TRUE;\r
+  }\r
+\r
+  //\r
+  // XIP image that ImageAddress is same to Image handle.\r
+  //\r
+  if (ImageContext.ImageAddress == (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) {\r
+    IsXipImage = TRUE;\r
+  }\r
+\r
+  //\r
+  // Get file type first\r
+  //\r
+  Status = PeiServicesFfsGetFileInfo (FileHandle, &FileInfo);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Check whether the file type is PEI module.\r
+  //\r
+  IsPeiModule = FALSE;\r
+  if (FileInfo.FileType == EFI_FV_FILETYPE_PEI_CORE ||\r
+      FileInfo.FileType == EFI_FV_FILETYPE_PEIM ||\r
+      FileInfo.FileType == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER) {\r
+    IsPeiModule = TRUE;\r
+  }\r
+\r
   //\r
   // When Image has no reloc section, it can't be relocated into memory.\r
   //\r
-  if (ImageContext.RelocationsStripped && (Private->PeiMemoryInstalled) && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) {\r
+  if (ImageContext.RelocationsStripped && (Private->PeiMemoryInstalled) && ((!IsPeiModule) ||\r
+      (!IsS3Boot && (PcdGetBool (PcdShadowPeimOnBoot) || IsRegisterForShadow)) || (IsS3Boot && PcdGetBool (PcdShadowPeimOnS3Boot)))) {\r
     DEBUG ((EFI_D_INFO|EFI_D_LOAD, "The image at 0x%08x without reloc section can't be loaded into memory\n", (UINTN) Pe32Data));\r
   }\r
 \r
@@ -369,33 +345,76 @@ LoadAndRelocatePeCoffImage (
   ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data;\r
 \r
   //\r
-  // Allocate Memory for the image when memory is ready, boot mode is not S3, and image is relocatable.\r
+  // Allocate Memory for the image when memory is ready, and image is relocatable.\r
+  // On normal boot, PcdShadowPeimOnBoot decides whether load PEIM or PeiCore into memory.\r
+  // On S3 boot, PcdShadowPeimOnS3Boot decides whether load PEIM or PeiCore into memory.\r
   //\r
-  if ((!ImageContext.RelocationsStripped) && (Private->PeiMemoryInstalled) && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) {\r
-    if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {\r
+  if ((!ImageContext.RelocationsStripped) && (Private->PeiMemoryInstalled) && ((!IsPeiModule) ||\r
+      (!IsS3Boot && (PcdGetBool (PcdShadowPeimOnBoot) || IsRegisterForShadow)) || (IsS3Boot && PcdGetBool (PcdShadowPeimOnS3Boot)))) {\r
+    //\r
+    // Allocate more buffer to avoid buffer overflow.\r
+    //\r
+    if (ImageContext.IsTeImage) {\r
+      AlignImageSize = ImageContext.ImageSize + ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);\r
+    } else {\r
+      AlignImageSize = ImageContext.ImageSize;\r
+    }\r
+\r
+    if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) {\r
+      AlignImageSize += ImageContext.SectionAlignment;\r
+    }\r
+\r
+    if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) {\r
       Status = GetPeCoffImageFixLoadingAssignedAddress(&ImageContext, Private);\r
       if (EFI_ERROR (Status)){\r
         DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n"));\r
         //\r
         // The PEIM is not assiged valid address, try to allocate page to load it.\r
         //\r
-        ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocatePages (EFI_SIZE_TO_PAGES ((UINT32) ImageContext.ImageSize));\r
+        Status = PeiServicesAllocatePages (EfiBootServicesCode,\r
+                                           EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize),\r
+                                           &ImageContext.ImageAddress);\r
       }\r
     } else {\r
-      ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocatePages (EFI_SIZE_TO_PAGES ((UINT32) ImageContext.ImageSize));\r
-    }\r
-    ASSERT (ImageContext.ImageAddress != 0);\r
-    if (ImageContext.ImageAddress == 0) {\r
-      return EFI_OUT_OF_RESOURCES;\r
+      Status = PeiServicesAllocatePages (EfiBootServicesCode,\r
+                                         EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize),\r
+                                         &ImageContext.ImageAddress);\r
     }\r
-\r
-    //\r
-    // Skip the reserved space for the stripped PeHeader when load TeImage into memory.\r
-    //\r
-    if (ImageContext.IsTeImage) {\r
-      ImageContext.ImageAddress = ImageContext.ImageAddress +\r
-                                  ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize -\r
-                                  sizeof (EFI_TE_IMAGE_HEADER);\r
+    if (!EFI_ERROR (Status)) {\r
+      //\r
+      // Adjust the Image Address to make sure it is section alignment.\r
+      //\r
+      if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) {\r
+        ImageContext.ImageAddress =\r
+            (ImageContext.ImageAddress + ImageContext.SectionAlignment - 1) &\r
+            ~((UINTN)ImageContext.SectionAlignment - 1);\r
+      }\r
+      //\r
+      // Fix alignment requirement when Load IPF TeImage into memory.\r
+      // Skip the reserved space for the stripped PeHeader when load TeImage into memory.\r
+      //\r
+      if (ImageContext.IsTeImage) {\r
+        ImageContext.ImageAddress = ImageContext.ImageAddress +\r
+                                    ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize -\r
+                                    sizeof (EFI_TE_IMAGE_HEADER);\r
+      }\r
+    } else {\r
+      //\r
+      // No enough memory resource.\r
+      //\r
+      if (IsXipImage) {\r
+        //\r
+        // XIP image can still be invoked.\r
+        //\r
+        ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data;\r
+        ReturnStatus = EFI_WARN_BUFFER_TOO_SMALL;\r
+      } else {\r
+        //\r
+        // Non XIP image can't be loaded because no enough memory is allocated.\r
+        //\r
+        ASSERT (FALSE);\r
+        return EFI_OUT_OF_RESOURCES;\r
+      }\r
     }\r
   }\r
 \r
@@ -404,6 +423,9 @@ LoadAndRelocatePeCoffImage (
   //\r
   Status = PeCoffLoaderLoadImage (&ImageContext);\r
   if (EFI_ERROR (Status)) {\r
+    if (ImageContext.ImageError == IMAGE_ERROR_INVALID_SECTION_ALIGNMENT) {\r
+      DEBUG ((DEBUG_ERROR, "PEIM Image Address 0x%11p doesn't meet with section alignment 0x%x.\n", (VOID*)(UINTN)ImageContext.ImageAddress, ImageContext.SectionAlignment));\r
+    }\r
     return Status;\r
   }\r
   //\r
@@ -417,7 +439,7 @@ LoadAndRelocatePeCoffImage (
   //\r
   // Flush the instruction cache so the image data is written before we execute it\r
   //\r
-  if ((!ImageContext.RelocationsStripped) && (Private->PeiMemoryInstalled) && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) {\r
+  if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) {\r
     InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize);\r
   }\r
 \r
@@ -425,7 +447,7 @@ LoadAndRelocatePeCoffImage (
   *ImageSize    = ImageContext.ImageSize;\r
   *EntryPoint   = ImageContext.EntryPoint;\r
 \r
-  return EFI_SUCCESS;\r
+  return ReturnStatus;\r
 }\r
 \r
 /**\r
@@ -443,6 +465,9 @@ LoadAndRelocatePeCoffImage (
   @retval EFI_SUCCESS      Image is successfully loaded.\r
   @retval EFI_NOT_FOUND    Fail to locate necessary PPI.\r
   @retval EFI_UNSUPPORTED  Image Machine Type is not supported.\r
+  @retval EFI_WARN_BUFFER_TOO_SMALL\r
+                           There is not enough heap to allocate the requested size.\r
+                           This will not prevent the XIP image from being invoked.\r
 \r
 **/\r
 EFI_STATUS\r
@@ -480,33 +505,40 @@ PeiLoadImageLoadImage (
   // Try to find a first exe section (if PcdPeiCoreImageLoaderSearchTeSectionFirst\r
   // is true, TE will be searched first).\r
   //\r
-  Status = PeiServicesFfsFindSectionData (\r
+  Status = PeiServicesFfsFindSectionData3 (\r
              SearchType1,\r
+             0,\r
              FileHandle,\r
-             &Pe32Data\r
+             &Pe32Data,\r
+             AuthenticationState\r
              );\r
   //\r
   // If we didn't find a first exe section, try to find the second exe section.\r
   //\r
   if (EFI_ERROR (Status)) {\r
-    Status = PeiServicesFfsFindSectionData (\r
+    Status = PeiServicesFfsFindSectionData3 (\r
                SearchType2,\r
+               0,\r
                FileHandle,\r
-               &Pe32Data\r
+               &Pe32Data,\r
+               AuthenticationState\r
                );\r
     if (EFI_ERROR (Status)) {\r
       //\r
-      // PEI core only carry the loader function fro TE and PE32 executables\r
+      // PEI core only carry the loader function for TE and PE32 executables\r
       // If this two section does not exist, just return.\r
       //\r
       return Status;\r
     }\r
   }\r
 \r
+  DEBUG ((DEBUG_INFO, "Loading PEIM %g\n", FileHandle));\r
+\r
   //\r
   // If memory is installed, perform the shadow operations\r
   //\r
   Status = LoadAndRelocatePeCoffImage (\r
+    FileHandle,\r
     Pe32Data,\r
     &ImageAddress,\r
     &ImageSize,\r
@@ -544,9 +576,9 @@ PeiLoadImageLoadImage (
 \r
   DEBUG_CODE_BEGIN ();\r
     CHAR8                              *AsciiString;\r
-    CHAR8                              AsciiBuffer[512];\r
+    CHAR8                              EfiFileName[512];\r
     INT32                              Index;\r
-    INT32                              Index1;\r
+    INT32                              StartIndex;\r
 \r
     //\r
     // Print debug message: Loading PEIM at 0x12345678 EntryPoint=0x12345688 Driver.efi\r
@@ -566,19 +598,37 @@ PeiLoadImageLoadImage (
     AsciiString = PeCoffLoaderGetPdbPointer (Pe32Data);\r
 \r
     if (AsciiString != NULL) {\r
-      for (Index = (INT32) AsciiStrLen (AsciiString) - 1; Index >= 0; Index --) {\r
-        if (AsciiString[Index] == '\\') {\r
-          break;\r
+      StartIndex = 0;\r
+      for (Index = 0; AsciiString[Index] != 0; Index++) {\r
+        if (AsciiString[Index] == '\\' || AsciiString[Index] == '/') {\r
+          StartIndex = Index + 1;\r
         }\r
       }\r
 \r
-      if (Index != 0) {\r
-        for (Index1 = 0; AsciiString[Index + 1 + Index1] != '.'; Index1 ++) {\r
-          AsciiBuffer [Index1] = AsciiString[Index + 1 + Index1];\r
+      //\r
+      // Copy the PDB file name to our temporary string, and replace .pdb with .efi\r
+      // The PDB file name is limited in the range of 0~511.\r
+      // If the length is bigger than 511, trim the redudant characters to avoid overflow in array boundary.\r
+      //\r
+      for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {\r
+        EfiFileName[Index] = AsciiString[Index + StartIndex];\r
+        if (EfiFileName[Index] == 0) {\r
+          EfiFileName[Index] = '.';\r
+        }\r
+        if (EfiFileName[Index] == '.') {\r
+          EfiFileName[Index + 1] = 'e';\r
+          EfiFileName[Index + 2] = 'f';\r
+          EfiFileName[Index + 3] = 'i';\r
+          EfiFileName[Index + 4] = 0;\r
+          break;\r
         }\r
-        AsciiBuffer [Index1] = '\0';\r
-        DEBUG ((EFI_D_INFO | EFI_D_LOAD, "%a.efi", AsciiBuffer));\r
       }\r
+\r
+      if (Index == sizeof (EfiFileName) - 4) {\r
+        EfiFileName[Index] = 0;\r
+      }\r
+\r
+      DEBUG ((EFI_D_INFO | EFI_D_LOAD, "%a", EfiFileName));\r
     }\r
 \r
   DEBUG_CODE_END ();\r
@@ -739,11 +789,11 @@ PeiLoadImage (
                           EntryPoint,\r
                           AuthenticationState\r
                           );\r
-      if (!EFI_ERROR (Status)) {\r
+      if (!EFI_ERROR (Status) || Status == EFI_WARN_BUFFER_TOO_SMALL) {\r
         //\r
         // The shadowed PEIM must be relocatable.\r
         //\r
-        if (PeimState == PEIM_STATE_REGISITER_FOR_SHADOW) {\r
+        if (PeimState == PEIM_STATE_REGISTER_FOR_SHADOW) {\r
           IsStrip = RelocationIsStrip ((VOID *) (UINTN) ImageAddress);\r
           ASSERT (!IsStrip);\r
           if (IsStrip) {\r
@@ -758,7 +808,7 @@ PeiLoadImage (
         if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *) (UINTN) ImageAddress))) {\r
           return EFI_UNSUPPORTED;\r
         }\r
-        return Status;\r
+        return EFI_SUCCESS;\r
       }\r
     }\r
     Index++;\r