]> git.proxmox.com Git - mirror_edk2.git/blobdiff - Nt32Pkg/Sec/SecMain.c
Nt32Pkg: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / Nt32Pkg / Sec / SecMain.c
index ab66dfc52cb94aa393b25b2c863eeac8c4ffff43..c3bfe470248389d9448b74b45f196a43ed932ec0 100644 (file)
@@ -1,13 +1,8 @@
-/*++\r
-\r
-Copyright (c) 2006, Intel Corporation\r
-All rights reserved. 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
+/**@file\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
+Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>\r
+(C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>\r
+SPDX-License-Identifier: BSD-2-Clause-Patent\r
 \r
 Module Name:\r
 \r
@@ -17,40 +12,22 @@ Abstract:
   WinNt emulator of SEC phase. It's really a Win32 application, but this is\r
   Ok since all the other modules for NT32 are NOT Win32 applications.\r
 \r
-  This program processes Windows environment variables and figures out\r
-  what the memory layout will be, how may FD's will be loaded and also\r
-  what the boot mode is.\r
+  This program gets NT32 PCD setting and figures out what the memory layout \r
+  will be, how may FD's will be loaded and also what the boot mode is.\r
 \r
   The SEC registers a set of services with the SEC core. gPrivateDispatchTable\r
-  is a list of PPI's produced by the SEC that are availble for usage in PEI.\r
-\r
-  This code produces 128 K of temporary memory for the PEI stack by opening a\r
-  Windows file and mapping it directly to memory addresses.\r
+  is a list of PPI's produced by the SEC that are available for usage in PEI.\r
 \r
-  The system.cmd script is used to set windows environment variables that drive\r
-  the configuration opitons of the SEC.\r
+  This code produces 128 K of temporary memory for the PEI stack by directly\r
+  allocate memory space with ReadWrite and Execute attribute.\r
 \r
---*/\r
+**/\r
 \r
 #include "SecMain.h"\r
 \r
-\r
-//\r
-// Globals\r
-//\r
-EFI_PEI_PE_COFF_LOADER_PROTOCOL_INSTANCE  mPeiEfiPeiPeCoffLoaderInstance = {\r
-  {\r
-    SecNt32PeCoffGetImageInfo,\r
-    SecNt32PeCoffLoadImage,\r
-    SecNt32PeCoffRelocateImage,\r
-    SecNt32PeCoffUnloadimage\r
-  },\r
-  NULL\r
-};\r
-\r
-\r
-\r
-EFI_PEI_PE_COFF_LOADER_PROTOCOL           *gPeiEfiPeiPeCoffLoader = &mPeiEfiPeiPeCoffLoaderInstance.PeCoff;\r
+#ifndef SE_TIME_ZONE_NAME\r
+#define SE_TIME_ZONE_NAME                 TEXT("SeTimeZonePrivilege")\r
+#endif\r
 \r
 NT_PEI_LOAD_FILE_PPI                      mSecNtLoadFilePpi     = { SecWinNtPeiLoadFile };\r
 \r
@@ -62,13 +39,9 @@ EFI_PEI_PROGRESS_CODE_PPI                 mSecStatusCodePpi     = { SecPeiReport
 \r
 NT_FWH_PPI                                mSecFwhInformationPpi = { SecWinNtFdAddress };\r
 \r
+EFI_PEI_TEMPORARY_RAM_SUPPORT_PPI         mSecTemporaryRamSupportPpi = {SecTemporaryRamSupport};\r
 \r
 EFI_PEI_PPI_DESCRIPTOR  gPrivateDispatchTable[] = {\r
-  {\r
-    EFI_PEI_PPI_DESCRIPTOR_PPI,\r
-    &gEfiPeiPeCoffLoaderGuid,\r
-    NULL\r
-  },\r
   {\r
     EFI_PEI_PPI_DESCRIPTOR_PPI,\r
     &gNtPeiLoadFilePpiGuid,\r
@@ -89,6 +62,11 @@ EFI_PEI_PPI_DESCRIPTOR  gPrivateDispatchTable[] = {
     &gEfiPeiStatusCodePpiGuid,\r
     &mSecStatusCodePpi\r
   },\r
+  {\r
+    EFI_PEI_PPI_DESCRIPTOR_PPI,\r
+    &gEfiTemporaryRamSupportPpiGuid,\r
+    &mSecTemporaryRamSupportPpi\r
+  },\r
   {\r
     EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,\r
     &gNtFwhPpiGuid,\r
@@ -99,29 +77,68 @@ EFI_PEI_PPI_DESCRIPTOR  gPrivateDispatchTable[] = {
 \r
 //\r
 // Default information about where the FD is located.\r
-//  This array gets filled in with information from EFI_FIRMWARE_VOLUMES\r
-//  EFI_FIRMWARE_VOLUMES is a Windows environment variable set by system.cmd.\r
+//  This array gets filled in with information from PcdWinNtFirmwareVolume\r
 //  The number of array elements is allocated base on parsing\r
-//  EFI_FIRMWARE_VOLUMES and the memory is never freed.\r
+//  PcdWinNtFirmwareVolume and the memory is never freed.\r
 //\r
 UINTN                                     gFdInfoCount = 0;\r
 NT_FD_INFO                                *gFdInfo;\r
 \r
 //\r
 // Array that supports seperate memory rantes.\r
-//  The memory ranges are set in system.cmd via the EFI_MEMORY_SIZE variable.\r
+//  The memory ranges are set by PcdWinNtMemorySizeForSecMain.\r
 //  The number of array elements is allocated base on parsing\r
-//  EFI_MEMORY_SIZE and the memory is never freed.\r
+//  PcdWinNtMemorySizeForSecMain value and the memory is never freed.\r
 //\r
 UINTN                                     gSystemMemoryCount = 0;\r
 NT_SYSTEM_MEMORY                          *gSystemMemory;\r
 \r
+VOID\r
+EFIAPI\r
+SecSwitchStack (\r
+  UINT32   TemporaryMemoryBase,\r
+  UINT32   PermenentMemoryBase\r
+  );\r
+EFI_STATUS\r
+SecNt32PeCoffRelocateImage (\r
+  IN OUT PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext\r
+  );\r
+\r
+VOID\r
+EFIAPI\r
+PeiSwitchStacks (\r
+  IN      SWITCH_STACK_ENTRY_POINT  EntryPoint,\r
+  IN      VOID                      *Context1,  OPTIONAL\r
+  IN      VOID                      *Context2,  OPTIONAL\r
+  IN      VOID                      *Context3,  OPTIONAL\r
+  IN      VOID                      *NewStack\r
+  );\r
 \r
-UINTN                   mPdbNameModHandleArraySize = 0;\r
-PDB_NAME_TO_MOD_HANDLE  *mPdbNameModHandleArray = NULL;\r
+VOID\r
+SecPrint (\r
+  CHAR8  *Format,\r
+  ...\r
+  )\r
+{\r
+  va_list  Marker;\r
+  UINTN    CharCount;\r
+  CHAR8    Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];\r
 \r
+  va_start (Marker, Format);\r
+  \r
+  _vsnprintf (Buffer, sizeof (Buffer), Format, Marker);\r
 \r
+  va_end (Marker);\r
 \r
+  CharCount = strlen (Buffer);\r
+  WriteFile (\r
+    GetStdHandle (STD_OUTPUT_HANDLE), \r
+    Buffer,\r
+    (DWORD)CharCount,\r
+    (LPDWORD)&CharCount,\r
+    NULL\r
+    );\r
+}\r
 \r
 INTN\r
 EFIAPI\r
@@ -138,7 +155,7 @@ Routine Description:
 Arguments:\r
   Argc - Number of command line arguments\r
   Argv - Array of command line argument strings\r
-  Envp - Array of environmemt variable strings\r
+  Envp - Array of environment variable strings\r
 \r
 Returns:\r
   0 - Normal exit\r
@@ -147,23 +164,53 @@ Returns:
 --*/\r
 {\r
   EFI_STATUS            Status;\r
+  HANDLE                Token;\r
+  TOKEN_PRIVILEGES      TokenPrivileges;\r
   EFI_PHYSICAL_ADDRESS  InitialStackMemory;\r
   UINT64                InitialStackMemorySize;\r
   UINTN                 Index;\r
   UINTN                 Index1;\r
   UINTN                 Index2;\r
-  UINTN                 PeiIndex;\r
   CHAR16                *FileName;\r
   CHAR16                *FileNamePtr;\r
   BOOLEAN               Done;\r
   VOID                  *PeiCoreFile;\r
   CHAR16                *MemorySizeStr;\r
   CHAR16                *FirmwareVolumesStr;\r
+  UINTN                 *StackPointer;\r
+  UINT32                ProcessAffinityMask;\r
+  UINT32                SystemAffinityMask;\r
+  INT32                 LowBit;\r
+\r
 \r
-  MemorySizeStr      = (CHAR16 *)L"64!64";\r
-  FirmwareVolumesStr = (CHAR16 *)L"..\\Fv\\Fv_Recovery.fd";\r
+  //\r
+  // Enable the privilege so that RTC driver can successfully run SetTime()\r
+  //\r
+  OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &Token);\r
+  if (LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &TokenPrivileges.Privileges[0].Luid)) {\r
+    TokenPrivileges.PrivilegeCount = 1;\r
+    TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\r
+    AdjustTokenPrivileges(Token, FALSE, &TokenPrivileges, 0, (PTOKEN_PRIVILEGES) NULL, 0);\r
+  }\r
 \r
-  printf ("\nEDK SEC Main NT Emulation Environment from www.TianoCore.org\n");\r
+  MemorySizeStr      = (CHAR16 *) PcdGetPtr (PcdWinNtMemorySizeForSecMain);\r
+  FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdWinNtFirmwareVolume);\r
+\r
+  SecPrint ("\nEDK II SEC Main NT Emulation Environment from www.TianoCore.org\n");\r
+\r
+  //\r
+  // Determine the first thread available to this process.\r
+  //\r
+  if (GetProcessAffinityMask (GetCurrentProcess (), &ProcessAffinityMask, &SystemAffinityMask)) {\r
+    LowBit = (INT32)LowBitSet32 (ProcessAffinityMask);\r
+    if (LowBit != -1) {\r
+      //\r
+      // Force the system to bind the process to a single thread to work\r
+      // around odd semaphore type crashes.\r
+      //\r
+      SetProcessAffinityMask (GetCurrentProcess (), (INTN)(BIT0 << LowBit));\r
+    }\r
+  }\r
 \r
   //\r
   // Make some Windows calls to Set the process to the highest priority in the\r
@@ -175,59 +222,58 @@ Returns:
   //\r
   // Allocate space for gSystemMemory Array\r
   //\r
-  gSystemMemoryCount  = CountSeperatorsInString (MemorySizeStr, '!') + 1;\r
+  gSystemMemoryCount  = CountSeparatorsInString (MemorySizeStr, '!') + 1;\r
   gSystemMemory       = calloc (gSystemMemoryCount, sizeof (NT_SYSTEM_MEMORY));\r
   if (gSystemMemory == NULL) {\r
-    printf ("ERROR : Can not allocate memory for %s.  Exiting.\n", MemorySizeStr);\r
+    SecPrint ("ERROR : Can not allocate memory for %S.  Exiting.\n", MemorySizeStr);\r
     exit (1);\r
   }\r
   //\r
   // Allocate space for gSystemMemory Array\r
   //\r
-  gFdInfoCount  = CountSeperatorsInString (FirmwareVolumesStr, '!') + 1;\r
+  gFdInfoCount  = CountSeparatorsInString (FirmwareVolumesStr, '!') + 1;\r
   gFdInfo       = calloc (gFdInfoCount, sizeof (NT_FD_INFO));\r
   if (gFdInfo == NULL) {\r
-    printf ("ERROR : Can not allocate memory for %s.  Exiting.\n", FirmwareVolumesStr);\r
+    SecPrint ("ERROR : Can not allocate memory for %S.  Exiting.\n", FirmwareVolumesStr);\r
     exit (1);\r
   }\r
   //\r
   // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)\r
   //\r
-  printf ("  BootMode 0x%02x\n", FixedPcdGet32 (PcdWinNtBootMode));\r
+  SecPrint ("  BootMode 0x%02x\n", PcdGet32 (PcdWinNtBootMode));\r
 \r
   //\r
-  // Open up a 128K file to emulate temp memory for PEI.\r
+  //  Allocate 128K memory to emulate temp memory for PEI.\r
   //  on a real platform this would be SRAM, or using the cache as RAM.\r
   //  Set InitialStackMemory to zero so WinNtOpenFile will allocate a new mapping\r
   //\r
-  InitialStackMemory      = 0;\r
-  InitialStackMemorySize  = 0x20000;\r
-  Status = WinNtOpenFile (\r
-            L"SecStack",\r
-            (UINT32) InitialStackMemorySize,\r
-            OPEN_ALWAYS,\r
-            &InitialStackMemory,\r
-            &InitialStackMemorySize\r
-            );\r
-  if (EFI_ERROR (Status)) {\r
-    printf ("ERROR : Can not open SecStack Exiting\n");\r
+  InitialStackMemorySize  = STACK_SIZE;\r
+  InitialStackMemory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (InitialStackMemorySize), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r
+  if (InitialStackMemory == 0) {\r
+    SecPrint ("ERROR : Can not allocate enough space for SecStack\n");\r
     exit (1);\r
   }\r
 \r
-  printf ("  SEC passing in %d bytes of temp RAM to PEI\n", InitialStackMemorySize);\r
+  for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;\r
+       StackPointer < (UINTN*) ((UINTN)InitialStackMemory + (SIZE_T) InitialStackMemorySize);\r
+       StackPointer ++) {\r
+    *StackPointer = PcdGet32 (PcdInitValueInTempStack);\r
+  }\r
+  \r
+  SecPrint ("  SEC passing in %d bytes of temp RAM to PEI\n", InitialStackMemorySize);\r
 \r
   //\r
   // Open All the firmware volumes and remember the info in the gFdInfo global\r
   //\r
   FileNamePtr = (CHAR16 *)malloc (StrLen ((CHAR16 *)FirmwareVolumesStr) * sizeof(CHAR16));\r
   if (FileNamePtr == NULL) {\r
-    printf ("ERROR : Can not allocate memory for firmware volume string\n");\r
+    SecPrint ("ERROR : Can not allocate memory for firmware volume string\n");\r
     exit (1);\r
   }\r
 \r
   StrCpy (FileNamePtr, (CHAR16*)FirmwareVolumesStr);\r
 \r
-  for (Done = FALSE, Index = 0, PeiIndex = 0, PeiCoreFile = NULL; !Done; Index++) {\r
+  for (Done = FALSE, Index = 0, PeiCoreFile = NULL; !Done; Index++) {\r
     FileName = FileNamePtr;\r
     for (Index1 = 0; (FileNamePtr[Index1] != '!') && (FileNamePtr[Index1] != 0); Index1++)\r
       ;\r
@@ -239,7 +285,7 @@ Returns:
     }\r
 \r
     //\r
-    // Open the FD and remmeber where it got mapped into our processes address space\r
+    // Open the FD and remember where it got mapped into our processes address space\r
     //\r
     Status = WinNtOpenFile (\r
               FileName,\r
@@ -249,17 +295,17 @@ Returns:
               &gFdInfo[Index].Size\r
               );\r
     if (EFI_ERROR (Status)) {\r
-      printf ("ERROR : Can not open Firmware Device File %S (%r).  Exiting.\n", FileName, Status);\r
+      SecPrint ("ERROR : Can not open Firmware Device File %S (0x%X).  Exiting.\n", FileName, Status);\r
       exit (1);\r
     }\r
 \r
-    printf ("  FD loaded from");\r
+    SecPrint ("  FD loaded from");\r
     //\r
-    // printf can't print filenames directly as the \ gets interperted as an\r
+    // printf can't print filenames directly as the \ gets interpreted as an\r
     //  escape character.\r
     //\r
     for (Index2 = 0; FileName[Index2] != '\0'; Index2++) {\r
-      printf ("%c", FileName[Index2]);\r
+      SecPrint ("%c", FileName[Index2]);\r
     }\r
 \r
     if (PeiCoreFile == NULL) {\r
@@ -269,12 +315,11 @@ Returns:
       //\r
       Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);\r
       if (!EFI_ERROR (Status)) {\r
-        PeiIndex = Index;\r
-        printf (" contains SEC Core");\r
+        SecPrint (" contains SEC Core");\r
       }\r
     }\r
 \r
-    printf ("\n");\r
+    SecPrint ("\n");\r
   }\r
   //\r
   // Calculate memory regions and store the information in the gSystemMemory\r
@@ -286,7 +331,6 @@ Returns:
     // Save the size of the memory and make a Unicode filename SystemMemory00, ...\r
     //\r
     gSystemMemory[Index].Size = _wtoi (MemorySizeStr) * 0x100000;\r
-    _snwprintf (gSystemMemory[Index].FileName, NT_SYSTEM_MEMORY_FILENAME_SIZE, L"SystemMemory%02d", Index);\r
 \r
     //\r
     // Find the next region\r
@@ -300,7 +344,7 @@ Returns:
     MemorySizeStr = MemorySizeStr + Index1 + 1;\r
   }\r
 \r
-  printf ("\n");\r
+  SecPrint ("\n");\r
 \r
   //\r
   // Hand off to PEI Core\r
@@ -311,7 +355,7 @@ Returns:
   // If we get here, then the PEI Core returned. This is an error as PEI should\r
   //  always hand off to DXE.\r
   //\r
-  printf ("ERROR : PEI Core returned\n");\r
+  SecPrint ("ERROR : PEI Core returned\n");\r
   exit (1);\r
 }\r
 \r
@@ -335,7 +379,7 @@ Arguments:
   CreationDisposition - The flags to pass to CreateFile().  Use to create new files for\r
                         memory emulation, and exiting files for firmware volume emulation\r
   BaseAddress         - The base address of the mapped file in the user address space.\r
-                         If passed in as NULL the new memory region is used.\r
+                         If passed in as NULL the new memory region is used.\r
                          If passed in as non NULL the request memory region is used for\r
                           the mapping of the file into the process space.\r
   Length              - The size of the mapped region in bytes\r
@@ -357,7 +401,7 @@ Returns:
   //\r
   NtFileHandle = CreateFile (\r
                   FileName,\r
-                  GENERIC_READ | GENERIC_WRITE,\r
+                  GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE,\r
                   FILE_SHARE_READ,\r
                   NULL,\r
                   CreationDisposition,\r
@@ -373,7 +417,7 @@ Returns:
   NtMapHandle = CreateFileMapping (\r
                   NtFileHandle,\r
                   NULL,\r
-                  PAGE_READWRITE,\r
+                  PAGE_EXECUTE_READWRITE,\r
                   0,\r
                   MapSize,\r
                   NULL\r
@@ -386,7 +430,7 @@ Returns:
   //\r
   VirtualAddress = MapViewOfFileEx (\r
                     NtMapHandle,\r
-                    FILE_MAP_ALL_ACCESS,\r
+                    FILE_MAP_EXECUTE | FILE_MAP_ALL_ACCESS,\r
                     0,\r
                     0,\r
                     MapSize,\r
@@ -458,7 +502,7 @@ Returns:
 // TODO:    Data - add argument and description to function comment\r
 {\r
   CHAR8           *Format;\r
-  VA_LIST         Marker;\r
+  BASE_LIST       Marker;\r
   CHAR8           PrintBuffer[BYTES_PER_RECORD * 2];\r
   CHAR8           *Filename;\r
   CHAR8           *Description;\r
@@ -471,19 +515,78 @@ Returns:
     //\r
     // Processes ASSERT ()\r
     //\r
-    printf ("ASSERT %s(%d): %s\n", Filename, LineNumber, Description);\r
+    SecPrint ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);\r
 \r
   } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {\r
     //\r
     // Process DEBUG () macro \r
     //\r
-    AsciiVSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);\r
-    printf (PrintBuffer);\r
+    AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);\r
+    SecPrint (PrintBuffer);\r
   }\r
 \r
   return EFI_SUCCESS;\r
 }\r
 \r
+#if defined (MDE_CPU_IA32)\r
+/**\r
+  Transfers control to a function starting with a new stack.\r
+\r
+  Transfers control to the function specified by EntryPoint using the new stack\r
+  specified by NewStack and passing in the parameters specified by Context1 and\r
+  Context2. Context1 and Context2 are optional and may be NULL. The function\r
+  EntryPoint must never return.\r
+\r
+  If EntryPoint is NULL, then ASSERT().\r
+  If NewStack is NULL, then ASSERT().\r
+\r
+  @param  EntryPoint  A pointer to function to call with the new stack.\r
+  @param  Context1    A pointer to the context to pass into the EntryPoint\r
+                      function.\r
+  @param  Context2    A pointer to the context to pass into the EntryPoint\r
+                      function.\r
+  @param  NewStack    A pointer to the new stack to use for the EntryPoint\r
+                      function.\r
+  @param  NewBsp      A pointer to the new BSP for the EntryPoint on IPF. It's\r
+                      Reserved on other architectures.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+PeiSwitchStacks (\r
+  IN      SWITCH_STACK_ENTRY_POINT  EntryPoint,\r
+  IN      VOID                      *Context1,  OPTIONAL\r
+  IN      VOID                      *Context2,  OPTIONAL\r
+  IN      VOID                      *Context3,  OPTIONAL\r
+  IN      VOID                      *NewStack\r
+  )\r
+{\r
+  BASE_LIBRARY_JUMP_BUFFER  JumpBuffer;\r
+  \r
+  ASSERT (EntryPoint != NULL);\r
+  ASSERT (NewStack != NULL);\r
+\r
+  //\r
+  // Stack should be aligned with CPU_STACK_ALIGNMENT\r
+  //\r
+  ASSERT (((UINTN)NewStack & (CPU_STACK_ALIGNMENT - 1)) == 0);\r
+\r
+  JumpBuffer.Eip = (UINTN)EntryPoint;\r
+  JumpBuffer.Esp = (UINTN)NewStack - sizeof (VOID*);\r
+  JumpBuffer.Esp -= sizeof (Context1) + sizeof (Context2) + sizeof(Context3);\r
+  ((VOID**)JumpBuffer.Esp)[1] = Context1;\r
+  ((VOID**)JumpBuffer.Esp)[2] = Context2;\r
+  ((VOID**)JumpBuffer.Esp)[3] = Context3;\r
+\r
+  LongJump (&JumpBuffer, (UINTN)-1);\r
+  \r
+\r
+  //\r
+  // InternalSwitchStack () will never return\r
+  //\r
+  ASSERT (FALSE);  \r
+}\r
+#endif\r
 \r
 VOID\r
 SecLoadFromCore (\r
@@ -509,37 +612,48 @@ Returns:
 --*/\r
 {\r
   EFI_STATUS                  Status;\r
-  EFI_PHYSICAL_ADDRESS        TopOfMemory;\r
   VOID                        *TopOfStack;\r
   UINT64                      PeiCoreSize;\r
   EFI_PHYSICAL_ADDRESS        PeiCoreEntryPoint;\r
   EFI_PHYSICAL_ADDRESS        PeiImageAddress;\r
-  EFI_PEI_STARTUP_DESCRIPTOR  *PeiStartup;\r
+  EFI_SEC_PEI_HAND_OFF        *SecCoreData;\r
+  UINTN                       PeiStackSize;\r
 \r
   //\r
   // Compute Top Of Memory for Stack and PEI Core Allocations\r
   //\r
-  TopOfMemory = LargestRegion + LargestRegionSize;\r
+  PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);\r
 \r
   //\r
-  // Allocate 128KB for the Stack\r
-  //\r
-  TopOfStack  = (VOID *)((UINTN)TopOfMemory - sizeof (EFI_PEI_STARTUP_DESCRIPTOR) - CPU_STACK_ALIGNMENT);\r
-  TopOfStack  = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);\r
-  TopOfMemory = TopOfMemory - STACK_SIZE;\r
+  // |-----------| <---- TemporaryRamBase + TemporaryRamSize\r
+  // |   Heap    |\r
+  // |           |\r
+  // |-----------| <---- StackBase / PeiTemporaryMemoryBase\r
+  // |           |\r
+  // |  Stack    |\r
+  // |-----------| <---- TemporaryRamBase\r
+  // \r
+  TopOfStack  = (VOID *)(LargestRegion + PeiStackSize);\r
 \r
   //\r
-  // Patch value in dispatch table values\r
-  //\r
-  gPrivateDispatchTable[0].Ppi = gPeiEfiPeiPeCoffLoader;\r
+  // Reservet space for storing PeiCore's parament in stack.\r
+  // \r
+  TopOfStack  = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);\r
+  TopOfStack  = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);\r
 \r
   //\r
   // Bind this information into the SEC hand-off state\r
   //\r
-  PeiStartup = (EFI_PEI_STARTUP_DESCRIPTOR *) (UINTN) TopOfStack;\r
-  PeiStartup->DispatchTable      = (EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable;\r
-  PeiStartup->SizeOfCacheAsRam   = STACK_SIZE;\r
-  PeiStartup->BootFirmwareVolume = BootFirmwareVolumeBase;\r
+  SecCoreData                        = (EFI_SEC_PEI_HAND_OFF*)(UINTN) TopOfStack;\r
+  SecCoreData->DataSize               = sizeof(EFI_SEC_PEI_HAND_OFF);\r
+  SecCoreData->BootFirmwareVolumeBase = (VOID*)BootFirmwareVolumeBase;\r
+  SecCoreData->BootFirmwareVolumeSize = PcdGet32(PcdWinNtFirmwareFdSize);\r
+  SecCoreData->TemporaryRamBase       = (VOID*)(UINTN)LargestRegion; \r
+  SecCoreData->TemporaryRamSize       = STACK_SIZE;\r
+  SecCoreData->StackBase              = SecCoreData->TemporaryRamBase;\r
+  SecCoreData->StackSize              = PeiStackSize;\r
+  SecCoreData->PeiTemporaryRamBase    = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + PeiStackSize);\r
+  SecCoreData->PeiTemporaryRamSize    = STACK_SIZE - PeiStackSize;\r
 \r
   //\r
   // Load the PEI Core from a Firmware Volume\r
@@ -553,12 +667,14 @@ Returns:
   if (EFI_ERROR (Status)) {\r
     return ;\r
   }\r
+  \r
   //\r
   // Transfer control to the PEI Core\r
   //\r
-  SwitchStack (\r
+  PeiSwitchStacks (\r
     (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,\r
-    PeiStartup,\r
+    SecCoreData,\r
+    (VOID *) (UINTN) ((EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable),\r
     NULL,\r
     TopOfStack\r
     );\r
@@ -579,11 +695,11 @@ SecWinNtPeiAutoScan (
 \r
 Routine Description:\r
   This service is called from Index == 0 until it returns EFI_UNSUPPORTED.\r
-  It allows discontiguous memory regions to be supported by the emulator.\r
+  It allows discontinuous memory regions to be supported by the emulator.\r
   It uses gSystemMemory[] and gSystemMemoryCount that were created by\r
-  parsing the Windows environment variable EFI_MEMORY_SIZE.\r
-  The size comes from the varaible and the address comes from the call to\r
-  WinNtOpenFile.\r
+  parsing PcdWinNtMemorySizeForSecMain value.\r
+  The size comes from the Pcd value and the address comes from the memory space \r
+  with ReadWrite and Execute attributes allocated by VirtualAlloc() API.\r
 \r
 Arguments:\r
   Index      - Which memory region to use\r
@@ -596,24 +712,22 @@ Returns:
 \r
 --*/\r
 {\r
-  EFI_STATUS  Status;\r
-\r
   if (Index >= gSystemMemoryCount) {\r
     return EFI_UNSUPPORTED;\r
   }\r
+  \r
+  //\r
+  // Allocate enough memory space for emulator \r
+  //\r
+  gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r
+  if (gSystemMemory[Index].Memory == 0) {\r
+    return EFI_OUT_OF_RESOURCES;\r
+  }\r
+  \r
+  *MemoryBase = gSystemMemory[Index].Memory;\r
+  *MemorySize = gSystemMemory[Index].Size;\r
 \r
-  *MemoryBase = 0;\r
-  Status = WinNtOpenFile (\r
-            gSystemMemory[Index].FileName,\r
-            (UINT32) gSystemMemory[Index].Size,\r
-            OPEN_ALWAYS,\r
-            MemoryBase,\r
-            MemorySize\r
-            );\r
-\r
-  gSystemMemory[Index].Memory = *MemoryBase;\r
-\r
-  return Status;\r
+  return EFI_SUCCESS;\r
 }\r
 \r
 VOID *\r
@@ -626,7 +740,7 @@ SecWinNtWinNtThunkAddress (
 Routine Description:\r
   Since the SEC is the only Windows program in stack it must export\r
   an interface to do Win API calls. That's what the WinNtThunk address\r
-  is for. gWinNt is initailized in WinNtThunk.c.\r
+  is for. gWinNt is initialized in WinNtThunk.c.\r
 \r
 Arguments:\r
   InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);\r
@@ -674,29 +788,30 @@ Returns:
 \r
   ImageContext.ImageRead  = (PE_COFF_LOADER_READ_FILE) SecImageRead;\r
 \r
-  Status                  = gPeiEfiPeiPeCoffLoader->GetImageInfo (gPeiEfiPeiPeCoffLoader, &ImageContext);\r
+  Status                  = PeCoffLoaderGetImageInfo (&ImageContext);\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
   //\r
-  // Allocate space in NT (not emulator) memory. Extra space is for alignment\r
+  // Allocate space in NT (not emulator) memory with ReadWrite and Execute attribute. \r
+  // Extra space is for alignment\r
   //\r
-  ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) malloc ((UINTN) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)));\r
+  ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r
   if (ImageContext.ImageAddress == 0) {\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
   //\r
-  // Align buffer on section boundry\r
+  // Align buffer on section boundary\r
   //\r
-  ImageContext.ImageAddress += ImageContext.SectionAlignment;\r
-  ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);\r
+  ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;\r
+  ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);\r
 \r
-  Status = gPeiEfiPeiPeCoffLoader->LoadImage (gPeiEfiPeiPeCoffLoader, &ImageContext);\r
+  Status = PeCoffLoaderLoadImage (&ImageContext);\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
 \r
-  Status = gPeiEfiPeiPeCoffLoader->RelocateImage (gPeiEfiPeiPeCoffLoader, &ImageContext);\r
+  Status = SecNt32PeCoffRelocateImage (&ImageContext);\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
@@ -732,7 +847,7 @@ Arguments:
 \r
 Returns:\r
   EFI_SUCCESS     - Return the Base address and size of the FV\r
-  EFI_UNSUPPORTED - Index does nto map to an FD in the system\r
+  EFI_UNSUPPORTED - Index does not map to an FD in the system\r
 \r
 --*/\r
 {\r
@@ -835,28 +950,28 @@ Returns:
 }\r
 \r
 UINTN\r
-CountSeperatorsInString (\r
-  IN  const CHAR16   *String,\r
-  IN  CHAR16         Seperator\r
+CountSeparatorsInString (\r
+  IN  CONST CHAR16   *String,\r
+  IN  CHAR16         Separator\r
   )\r
 /*++\r
 \r
 Routine Description:\r
-  Count the number of seperators in String\r
+  Count the number of separators in String\r
 \r
 Arguments:\r
   String    - String to process\r
-  Seperator - Item to count\r
+  Separator - Item to count\r
 \r
 Returns:\r
-  Number of Seperator in String\r
+  Number of Separator in String\r
 \r
 --*/\r
 {\r
   UINTN Count;\r
 \r
   for (Count = 0; *String != '\0'; String++) {\r
-    if (*String == Seperator) {\r
+    if (*String == Separator) {\r
       Count++;\r
     }\r
   }\r
@@ -866,171 +981,7 @@ Returns:
 \r
 \r
 EFI_STATUS\r
-AddModHandle (\r
-  IN  PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext,\r
-  IN  VOID                                 *ModHandle\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
-  Store the ModHandle in an array indexed by the Pdb File name.\r
-  The ModHandle is needed to unload the image. \r
-\r
-Arguments:\r
-  ImageContext - Input data returned from PE Laoder Library. Used to find the \r
-                 .PDB file name of the PE Image.\r
-  ModHandle    - Returned from LoadLibraryEx() and stored for call to \r
-                 FreeLibrary().\r
-\r
-Returns:\r
-  EFI_SUCCESS - ModHandle was stored. \r
-\r
---*/\r
-{\r
-  UINTN                   Index;\r
-  PDB_NAME_TO_MOD_HANDLE  *Array;\r
-  UINTN                   PreviousSize;\r
-\r
-\r
-  Array = mPdbNameModHandleArray;\r
-  for (Index = 0; Index < mPdbNameModHandleArraySize; Index++, Array++) {\r
-    if (Array->PdbPointer == NULL) {\r
-      //\r
-      // Make a copy of the stirng and store the ModHandle\r
-      //\r
-      Array->PdbPointer = malloc (strlen (ImageContext->PdbPointer) + 1);\r
-      ASSERT (Array->PdbPointer != NULL);\r
-\r
-      strcpy (Array->PdbPointer, ImageContext->PdbPointer);\r
-      Array->ModHandle = ModHandle;\r
-      return EFI_SUCCESS;\r
-    }\r
-  }\r
-  \r
-  //\r
-  // No free space in mPdbNameModHandleArray so grow it by \r
-  // MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE entires. realloc will\r
-  // copy the old values to the new locaiton. But it does\r
-  // not zero the new memory area.\r
-  //\r
-  PreviousSize = mPdbNameModHandleArraySize * sizeof (PDB_NAME_TO_MOD_HANDLE);\r
-  mPdbNameModHandleArraySize += MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE;\r
-\r
-  mPdbNameModHandleArray = realloc (mPdbNameModHandleArray, mPdbNameModHandleArraySize * sizeof (PDB_NAME_TO_MOD_HANDLE));\r
-  if (mPdbNameModHandleArray == NULL) {\r
-    ASSERT (FALSE);\r
-    return EFI_OUT_OF_RESOURCES;\r
-  }\r
-  \r
-  memset (mPdbNameModHandleArray + PreviousSize, 0, MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (PDB_NAME_TO_MOD_HANDLE));\r
\r
-  return AddModHandle (ImageContext, ModHandle);\r
-}\r
-\r
-\r
-VOID *\r
-RemoveModeHandle (\r
-  IN  PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
-  Return the ModHandle and delete the entry in the array.\r
-\r
-Arguments:\r
-  ImageContext - Input data returned from PE Laoder Library. Used to find the \r
-                 .PDB file name of the PE Image.\r
-\r
-Returns:\r
-  ModHandle - ModHandle assoicated with ImageContext is returned\r
-  NULL      - No ModHandle associated with ImageContext\r
-\r
---*/\r
-{\r
-  UINTN                   Index;\r
-  PDB_NAME_TO_MOD_HANDLE  *Array;\r
-\r
-  if (ImageContext->PdbPointer == NULL) {\r
-    //\r
-    // If no PDB pointer there is no ModHandle so return NULL\r
-    //\r
-    return NULL;\r
-  }\r
-\r
-  Array = mPdbNameModHandleArray;\r
-  for (Index = 0; Index < mPdbNameModHandleArraySize; Index++, Array++) {\r
-    if ((Array->PdbPointer != NULL) && (strcmp(Array->PdbPointer, ImageContext->PdbPointer) == 0)) {\r
-      //\r
-      // If you find a match return it and delete the entry\r
-      //\r
-      free (Array->PdbPointer);\r
-      Array->PdbPointer = NULL;\r
-      return Array->ModHandle;\r
-    }\r
-  }\r
-\r
-  return NULL;\r
-}\r
-\r
-\r
-\r
-EFI_STATUS\r
-EFIAPI\r
-SecNt32PeCoffGetImageInfo (\r
-  IN EFI_PEI_PE_COFF_LOADER_PROTOCOL          *This,\r
-  IN OUT PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext\r
-  )\r
-{\r
-  EFI_STATUS  Status;\r
-\r
-  Status = PeCoffLoaderGetImageInfo (ImageContext);\r
-  if (EFI_ERROR (Status)) {\r
-    return Status;\r
-  }\r
-\r
-  switch (ImageContext->ImageType) {\r
-\r
-  case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:\r
-    ImageContext->ImageCodeMemoryType = EfiLoaderCode;\r
-    ImageContext->ImageDataMemoryType = EfiLoaderData;\r
-    break;\r
-\r
-  case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:\r
-    ImageContext->ImageCodeMemoryType = EfiBootServicesCode;\r
-    ImageContext->ImageDataMemoryType = EfiBootServicesData;\r
-    break;\r
-\r
-  case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:\r
-  case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:\r
-    ImageContext->ImageCodeMemoryType = EfiRuntimeServicesCode;\r
-    ImageContext->ImageDataMemoryType = EfiRuntimeServicesData;\r
-    break;\r
-\r
-  default:\r
-    ImageContext->ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM;\r
-    return RETURN_UNSUPPORTED;\r
-  }\r
-\r
-  return Status;\r
-}\r
-\r
-EFI_STATUS\r
-EFIAPI\r
-SecNt32PeCoffLoadImage (\r
-  IN EFI_PEI_PE_COFF_LOADER_PROTOCOL          *This,\r
-  IN OUT PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext\r
-  )\r
-{\r
-  EFI_STATUS  Status;\r
-\r
-  Status = PeCoffLoaderLoadImage (ImageContext);\r
-  return Status;\r
-}\r
-\r
-EFI_STATUS\r
-EFIAPI\r
 SecNt32PeCoffRelocateImage (\r
-  IN EFI_PEI_PE_COFF_LOADER_PROTOCOL          *This,\r
   IN OUT PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext\r
   )\r
 {\r
@@ -1053,7 +1004,7 @@ SecNt32PeCoffRelocateImage (
   // If we load our own PE COFF images the Windows debugger can not source\r
   //  level debug our code. If a valid PDB pointer exists usw it to load\r
   //  the *.dll file as a library using Windows* APIs. This allows \r
-  //  source level debug. The image is still loaded and reloaced\r
+  //  source level debug. The image is still loaded and relocated\r
   //  in the Framework memory space like on a real system (by the code above),\r
   //  but the entry point points into the DLL loaded by the code bellow. \r
   //\r
@@ -1098,22 +1049,21 @@ SecNt32PeCoffRelocateImage (
     if (Library != NULL) {\r
       //\r
       // InitializeDriver is the entry point we put in all our EFI DLL's. The\r
-      // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() supresses the \r
+      // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() suppresses the \r
       // normal DLL entry point of DllMain, and prevents other modules that are\r
       // referenced in side the DllFileName from being loaded. There is no error \r
       // checking as the we can point to the PE32 image loaded by Tiano. This \r
-      // step is only needed for source level debuging\r
+      // step is only needed for source level debugging\r
       //\r
       DllEntryPoint = (VOID *) (UINTN) GetProcAddress (Library, "InitializeDriver");\r
 \r
     }\r
 \r
     if ((Library != NULL) && (DllEntryPoint != NULL)) {\r
-      AddModHandle (ImageContext, Library);\r
       ImageContext->EntryPoint  = (EFI_PHYSICAL_ADDRESS) (UINTN) DllEntryPoint;\r
-      wprintf (L"LoadLibraryEx (%s,\n               NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);\r
+      SecPrint ("LoadLibraryEx (%S,\n               NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);\r
     } else {\r
-      wprintf (L"WARNING: No source level debug %s. \n", DllFileName);\r
+      SecPrint ("WARNING: No source level debug %S. \n", DllFileName);\r
     }\r
 \r
     free (DllFileName);\r
@@ -1128,21 +1078,7 @@ SecNt32PeCoffRelocateImage (
 }\r
 \r
 \r
-EFI_STATUS\r
-EFIAPI\r
-SecNt32PeCoffUnloadimage (\r
-  IN EFI_PEI_PE_COFF_LOADER_PROTOCOL      *This,\r
-  IN PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext\r
-  )\r
-{\r
-  VOID *ModHandle;\r
 \r
-  ModHandle = RemoveModeHandle (ImageContext);\r
-  if (ModHandle != NULL) {\r
-    FreeLibrary (ModHandle);\r
-  }\r
-  return EFI_SUCCESS;\r
-}\r
 \r
 VOID\r
 _ModuleEntryPoint (\r
@@ -1151,3 +1087,44 @@ _ModuleEntryPoint (
 {\r
 }\r
 \r
+EFI_STATUS\r
+EFIAPI\r
+SecTemporaryRamSupport (\r
+  IN CONST EFI_PEI_SERVICES   **PeiServices,\r
+  IN EFI_PHYSICAL_ADDRESS     TemporaryMemoryBase,\r
+  IN EFI_PHYSICAL_ADDRESS     PermanentMemoryBase,\r
+  IN UINTN                    CopySize\r
+  )\r
+{\r
+  //\r
+  // Migrate the whole temporary memory to permanent memory.\r
+  // \r
+  CopyMem (\r
+    (VOID*)(UINTN)PermanentMemoryBase, \r
+    (VOID*)(UINTN)TemporaryMemoryBase, \r
+    CopySize\r
+    );\r
+\r
+  //\r
+  // SecSwitchStack function must be invoked after the memory migration\r
+  // immediately, also we need fixup the stack change caused by new call into \r
+  // permanent memory.\r
+  // \r
+  SecSwitchStack (\r
+    (UINT32) TemporaryMemoryBase,\r
+    (UINT32) PermanentMemoryBase\r
+    );\r
+\r
+  //\r
+  // We need *not* fix the return address because currently, \r
+  // The PeiCore is executed in flash.\r
+  //\r
+\r
+  //\r
+  // Simulate to invalid temporary memory, terminate temporary memory\r
+  // \r
+  //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);\r
+  \r
+  return EFI_SUCCESS;\r
+}\r
+\r