]> git.proxmox.com Git - mirror_edk2.git/blame_incremental - Nt32Pkg/Sec/SecMain.c
MdePkg UefiLib: Use comparison logic to check UINTN parameter
[mirror_edk2.git] / Nt32Pkg / Sec / SecMain.c
... / ...
CommitLineData
1/**@file\r
2\r
3Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>\r
4(C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>\r
5This program and the accompanying materials\r
6are licensed and made available under the terms and conditions of the BSD License\r
7which accompanies this distribution. The full text of the license may be found at\r
8http://opensource.org/licenses/bsd-license.php\r
9\r
10THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
11WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
12\r
13Module Name:\r
14\r
15 SecMain.c\r
16\r
17Abstract:\r
18 WinNt emulator of SEC phase. It's really a Win32 application, but this is\r
19 Ok since all the other modules for NT32 are NOT Win32 applications.\r
20\r
21 This program gets NT32 PCD setting and figures out what the memory layout \r
22 will be, how may FD's will be loaded and also what the boot mode is.\r
23\r
24 The SEC registers a set of services with the SEC core. gPrivateDispatchTable\r
25 is a list of PPI's produced by the SEC that are available for usage in PEI.\r
26\r
27 This code produces 128 K of temporary memory for the PEI stack by directly\r
28 allocate memory space with ReadWrite and Execute attribute.\r
29\r
30**/\r
31\r
32#include "SecMain.h"\r
33\r
34#ifndef SE_TIME_ZONE_NAME\r
35#define SE_TIME_ZONE_NAME TEXT("SeTimeZonePrivilege")\r
36#endif\r
37\r
38NT_PEI_LOAD_FILE_PPI mSecNtLoadFilePpi = { SecWinNtPeiLoadFile };\r
39\r
40PEI_NT_AUTOSCAN_PPI mSecNtAutoScanPpi = { SecWinNtPeiAutoScan };\r
41\r
42PEI_NT_THUNK_PPI mSecWinNtThunkPpi = { SecWinNtWinNtThunkAddress };\r
43\r
44EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { SecPeiReportStatusCode };\r
45\r
46NT_FWH_PPI mSecFwhInformationPpi = { SecWinNtFdAddress };\r
47\r
48EFI_PEI_TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi = {SecTemporaryRamSupport};\r
49\r
50EFI_PEI_PPI_DESCRIPTOR gPrivateDispatchTable[] = {\r
51 {\r
52 EFI_PEI_PPI_DESCRIPTOR_PPI,\r
53 &gNtPeiLoadFilePpiGuid,\r
54 &mSecNtLoadFilePpi\r
55 },\r
56 {\r
57 EFI_PEI_PPI_DESCRIPTOR_PPI,\r
58 &gPeiNtAutoScanPpiGuid,\r
59 &mSecNtAutoScanPpi\r
60 },\r
61 {\r
62 EFI_PEI_PPI_DESCRIPTOR_PPI,\r
63 &gPeiNtThunkPpiGuid,\r
64 &mSecWinNtThunkPpi\r
65 },\r
66 {\r
67 EFI_PEI_PPI_DESCRIPTOR_PPI,\r
68 &gEfiPeiStatusCodePpiGuid,\r
69 &mSecStatusCodePpi\r
70 },\r
71 {\r
72 EFI_PEI_PPI_DESCRIPTOR_PPI,\r
73 &gEfiTemporaryRamSupportPpiGuid,\r
74 &mSecTemporaryRamSupportPpi\r
75 },\r
76 {\r
77 EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,\r
78 &gNtFwhPpiGuid,\r
79 &mSecFwhInformationPpi\r
80 }\r
81};\r
82\r
83\r
84//\r
85// Default information about where the FD is located.\r
86// This array gets filled in with information from PcdWinNtFirmwareVolume\r
87// The number of array elements is allocated base on parsing\r
88// PcdWinNtFirmwareVolume and the memory is never freed.\r
89//\r
90UINTN gFdInfoCount = 0;\r
91NT_FD_INFO *gFdInfo;\r
92\r
93//\r
94// Array that supports seperate memory rantes.\r
95// The memory ranges are set by PcdWinNtMemorySizeForSecMain.\r
96// The number of array elements is allocated base on parsing\r
97// PcdWinNtMemorySizeForSecMain value and the memory is never freed.\r
98//\r
99UINTN gSystemMemoryCount = 0;\r
100NT_SYSTEM_MEMORY *gSystemMemory;\r
101\r
102VOID\r
103EFIAPI\r
104SecSwitchStack (\r
105 UINT32 TemporaryMemoryBase,\r
106 UINT32 PermenentMemoryBase\r
107 );\r
108EFI_STATUS\r
109SecNt32PeCoffRelocateImage (\r
110 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext\r
111 );\r
112\r
113VOID\r
114EFIAPI\r
115PeiSwitchStacks (\r
116 IN SWITCH_STACK_ENTRY_POINT EntryPoint,\r
117 IN VOID *Context1, OPTIONAL\r
118 IN VOID *Context2, OPTIONAL\r
119 IN VOID *Context3, OPTIONAL\r
120 IN VOID *NewStack\r
121 );\r
122\r
123VOID\r
124SecPrint (\r
125 CHAR8 *Format,\r
126 ...\r
127 )\r
128{\r
129 va_list Marker;\r
130 UINTN CharCount;\r
131 CHAR8 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];\r
132\r
133 va_start (Marker, Format);\r
134 \r
135 _vsnprintf (Buffer, sizeof (Buffer), Format, Marker);\r
136\r
137 va_end (Marker);\r
138\r
139 CharCount = strlen (Buffer);\r
140 WriteFile (\r
141 GetStdHandle (STD_OUTPUT_HANDLE), \r
142 Buffer,\r
143 (DWORD)CharCount,\r
144 (LPDWORD)&CharCount,\r
145 NULL\r
146 );\r
147}\r
148\r
149INTN\r
150EFIAPI\r
151main (\r
152 IN INTN Argc,\r
153 IN CHAR8 **Argv,\r
154 IN CHAR8 **Envp\r
155 )\r
156/*++\r
157\r
158Routine Description:\r
159 Main entry point to SEC for WinNt. This is a Windows program\r
160\r
161Arguments:\r
162 Argc - Number of command line arguments\r
163 Argv - Array of command line argument strings\r
164 Envp - Array of environment variable strings\r
165\r
166Returns:\r
167 0 - Normal exit\r
168 1 - Abnormal exit\r
169\r
170--*/\r
171{\r
172 EFI_STATUS Status;\r
173 HANDLE Token;\r
174 TOKEN_PRIVILEGES TokenPrivileges;\r
175 EFI_PHYSICAL_ADDRESS InitialStackMemory;\r
176 UINT64 InitialStackMemorySize;\r
177 UINTN Index;\r
178 UINTN Index1;\r
179 UINTN Index2;\r
180 CHAR16 *FileName;\r
181 CHAR16 *FileNamePtr;\r
182 BOOLEAN Done;\r
183 VOID *PeiCoreFile;\r
184 CHAR16 *MemorySizeStr;\r
185 CHAR16 *FirmwareVolumesStr;\r
186 UINTN *StackPointer;\r
187 UINT32 ProcessAffinityMask;\r
188 UINT32 SystemAffinityMask;\r
189 INT32 LowBit;\r
190\r
191\r
192 //\r
193 // Enable the privilege so that RTC driver can successfully run SetTime()\r
194 //\r
195 OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &Token);\r
196 if (LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &TokenPrivileges.Privileges[0].Luid)) {\r
197 TokenPrivileges.PrivilegeCount = 1;\r
198 TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\r
199 AdjustTokenPrivileges(Token, FALSE, &TokenPrivileges, 0, (PTOKEN_PRIVILEGES) NULL, 0);\r
200 }\r
201\r
202 MemorySizeStr = (CHAR16 *) PcdGetPtr (PcdWinNtMemorySizeForSecMain);\r
203 FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdWinNtFirmwareVolume);\r
204\r
205 SecPrint ("\nEDK II SEC Main NT Emulation Environment from www.TianoCore.org\n");\r
206\r
207 //\r
208 // Determine the first thread available to this process.\r
209 //\r
210 if (GetProcessAffinityMask (GetCurrentProcess (), &ProcessAffinityMask, &SystemAffinityMask)) {\r
211 LowBit = (INT32)LowBitSet32 (ProcessAffinityMask);\r
212 if (LowBit != -1) {\r
213 //\r
214 // Force the system to bind the process to a single thread to work\r
215 // around odd semaphore type crashes.\r
216 //\r
217 SetProcessAffinityMask (GetCurrentProcess (), (INTN)(BIT0 << LowBit));\r
218 }\r
219 }\r
220\r
221 //\r
222 // Make some Windows calls to Set the process to the highest priority in the\r
223 // idle class. We need this to have good performance.\r
224 //\r
225 SetPriorityClass (GetCurrentProcess (), IDLE_PRIORITY_CLASS);\r
226 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);\r
227\r
228 //\r
229 // Allocate space for gSystemMemory Array\r
230 //\r
231 gSystemMemoryCount = CountSeparatorsInString (MemorySizeStr, '!') + 1;\r
232 gSystemMemory = calloc (gSystemMemoryCount, sizeof (NT_SYSTEM_MEMORY));\r
233 if (gSystemMemory == NULL) {\r
234 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n", MemorySizeStr);\r
235 exit (1);\r
236 }\r
237 //\r
238 // Allocate space for gSystemMemory Array\r
239 //\r
240 gFdInfoCount = CountSeparatorsInString (FirmwareVolumesStr, '!') + 1;\r
241 gFdInfo = calloc (gFdInfoCount, sizeof (NT_FD_INFO));\r
242 if (gFdInfo == NULL) {\r
243 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n", FirmwareVolumesStr);\r
244 exit (1);\r
245 }\r
246 //\r
247 // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)\r
248 //\r
249 SecPrint (" BootMode 0x%02x\n", PcdGet32 (PcdWinNtBootMode));\r
250\r
251 //\r
252 // Allocate 128K memory to emulate temp memory for PEI.\r
253 // on a real platform this would be SRAM, or using the cache as RAM.\r
254 // Set InitialStackMemory to zero so WinNtOpenFile will allocate a new mapping\r
255 //\r
256 InitialStackMemorySize = STACK_SIZE;\r
257 InitialStackMemory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (InitialStackMemorySize), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r
258 if (InitialStackMemory == 0) {\r
259 SecPrint ("ERROR : Can not allocate enough space for SecStack\n");\r
260 exit (1);\r
261 }\r
262\r
263 for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;\r
264 StackPointer < (UINTN*) ((UINTN)InitialStackMemory + (SIZE_T) InitialStackMemorySize);\r
265 StackPointer ++) {\r
266 *StackPointer = PcdGet32 (PcdInitValueInTempStack);\r
267 }\r
268 \r
269 SecPrint (" SEC passing in %d bytes of temp RAM to PEI\n", InitialStackMemorySize);\r
270\r
271 //\r
272 // Open All the firmware volumes and remember the info in the gFdInfo global\r
273 //\r
274 FileNamePtr = (CHAR16 *)malloc (StrLen ((CHAR16 *)FirmwareVolumesStr) * sizeof(CHAR16));\r
275 if (FileNamePtr == NULL) {\r
276 SecPrint ("ERROR : Can not allocate memory for firmware volume string\n");\r
277 exit (1);\r
278 }\r
279\r
280 StrCpy (FileNamePtr, (CHAR16*)FirmwareVolumesStr);\r
281\r
282 for (Done = FALSE, Index = 0, PeiCoreFile = NULL; !Done; Index++) {\r
283 FileName = FileNamePtr;\r
284 for (Index1 = 0; (FileNamePtr[Index1] != '!') && (FileNamePtr[Index1] != 0); Index1++)\r
285 ;\r
286 if (FileNamePtr[Index1] == 0) {\r
287 Done = TRUE;\r
288 } else {\r
289 FileNamePtr[Index1] = '\0';\r
290 FileNamePtr = FileNamePtr + Index1 + 1;\r
291 }\r
292\r
293 //\r
294 // Open the FD and remember where it got mapped into our processes address space\r
295 //\r
296 Status = WinNtOpenFile (\r
297 FileName,\r
298 0,\r
299 OPEN_EXISTING,\r
300 &gFdInfo[Index].Address,\r
301 &gFdInfo[Index].Size\r
302 );\r
303 if (EFI_ERROR (Status)) {\r
304 SecPrint ("ERROR : Can not open Firmware Device File %S (0x%X). Exiting.\n", FileName, Status);\r
305 exit (1);\r
306 }\r
307\r
308 SecPrint (" FD loaded from");\r
309 //\r
310 // printf can't print filenames directly as the \ gets interpreted as an\r
311 // escape character.\r
312 //\r
313 for (Index2 = 0; FileName[Index2] != '\0'; Index2++) {\r
314 SecPrint ("%c", FileName[Index2]);\r
315 }\r
316\r
317 if (PeiCoreFile == NULL) {\r
318 //\r
319 // Assume the beginning of the FD is an FV and look for the PEI Core.\r
320 // Load the first one we find.\r
321 //\r
322 Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);\r
323 if (!EFI_ERROR (Status)) {\r
324 SecPrint (" contains SEC Core");\r
325 }\r
326 }\r
327\r
328 SecPrint ("\n");\r
329 }\r
330 //\r
331 // Calculate memory regions and store the information in the gSystemMemory\r
332 // global for later use. The autosizing code will use this data to\r
333 // map this memory into the SEC process memory space.\r
334 //\r
335 for (Index = 0, Done = FALSE; !Done; Index++) {\r
336 //\r
337 // Save the size of the memory and make a Unicode filename SystemMemory00, ...\r
338 //\r
339 gSystemMemory[Index].Size = _wtoi (MemorySizeStr) * 0x100000;\r
340\r
341 //\r
342 // Find the next region\r
343 //\r
344 for (Index1 = 0; MemorySizeStr[Index1] != '!' && MemorySizeStr[Index1] != 0; Index1++)\r
345 ;\r
346 if (MemorySizeStr[Index1] == 0) {\r
347 Done = TRUE;\r
348 }\r
349\r
350 MemorySizeStr = MemorySizeStr + Index1 + 1;\r
351 }\r
352\r
353 SecPrint ("\n");\r
354\r
355 //\r
356 // Hand off to PEI Core\r
357 //\r
358 SecLoadFromCore ((UINTN) InitialStackMemory, (UINTN) InitialStackMemorySize, (UINTN) gFdInfo[0].Address, PeiCoreFile);\r
359\r
360 //\r
361 // If we get here, then the PEI Core returned. This is an error as PEI should\r
362 // always hand off to DXE.\r
363 //\r
364 SecPrint ("ERROR : PEI Core returned\n");\r
365 exit (1);\r
366}\r
367\r
368EFI_STATUS\r
369WinNtOpenFile (\r
370 IN CHAR16 *FileName,\r
371 IN UINT32 MapSize,\r
372 IN DWORD CreationDisposition,\r
373 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,\r
374 OUT UINT64 *Length\r
375 )\r
376/*++\r
377\r
378Routine Description:\r
379 Opens and memory maps a file using WinNt services. If BaseAddress is non zero\r
380 the process will try and allocate the memory starting at BaseAddress.\r
381\r
382Arguments:\r
383 FileName - The name of the file to open and map\r
384 MapSize - The amount of the file to map in bytes\r
385 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for\r
386 memory emulation, and exiting files for firmware volume emulation\r
387 BaseAddress - The base address of the mapped file in the user address space.\r
388 If passed in as NULL the new memory region is used.\r
389 If passed in as non NULL the request memory region is used for\r
390 the mapping of the file into the process space.\r
391 Length - The size of the mapped region in bytes\r
392\r
393Returns:\r
394 EFI_SUCCESS - The file was opened and mapped.\r
395 EFI_NOT_FOUND - FileName was not found in the current directory\r
396 EFI_DEVICE_ERROR - An error occured attempting to map the opened file\r
397\r
398--*/\r
399{\r
400 HANDLE NtFileHandle;\r
401 HANDLE NtMapHandle;\r
402 VOID *VirtualAddress;\r
403 UINTN FileSize;\r
404\r
405 //\r
406 // Use Win API to open/create a file\r
407 //\r
408 NtFileHandle = CreateFile (\r
409 FileName,\r
410 GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE,\r
411 FILE_SHARE_READ,\r
412 NULL,\r
413 CreationDisposition,\r
414 FILE_ATTRIBUTE_NORMAL,\r
415 NULL\r
416 );\r
417 if (NtFileHandle == INVALID_HANDLE_VALUE) {\r
418 return EFI_NOT_FOUND;\r
419 }\r
420 //\r
421 // Map the open file into a memory range\r
422 //\r
423 NtMapHandle = CreateFileMapping (\r
424 NtFileHandle,\r
425 NULL,\r
426 PAGE_EXECUTE_READWRITE,\r
427 0,\r
428 MapSize,\r
429 NULL\r
430 );\r
431 if (NtMapHandle == NULL) {\r
432 return EFI_DEVICE_ERROR;\r
433 }\r
434 //\r
435 // Get the virtual address (address in the emulator) of the mapped file\r
436 //\r
437 VirtualAddress = MapViewOfFileEx (\r
438 NtMapHandle,\r
439 FILE_MAP_EXECUTE | FILE_MAP_ALL_ACCESS,\r
440 0,\r
441 0,\r
442 MapSize,\r
443 (LPVOID) (UINTN) *BaseAddress\r
444 );\r
445 if (VirtualAddress == NULL) {\r
446 return EFI_DEVICE_ERROR;\r
447 }\r
448\r
449 if (MapSize == 0) {\r
450 //\r
451 // Seek to the end of the file to figure out the true file size.\r
452 //\r
453 FileSize = SetFilePointer (\r
454 NtFileHandle,\r
455 0,\r
456 NULL,\r
457 FILE_END\r
458 );\r
459 if (FileSize == -1) {\r
460 return EFI_DEVICE_ERROR;\r
461 }\r
462\r
463 *Length = (UINT64) FileSize;\r
464 } else {\r
465 *Length = (UINT64) MapSize;\r
466 }\r
467\r
468 *BaseAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAddress;\r
469\r
470 return EFI_SUCCESS;\r
471}\r
472\r
473\r
474#define BYTES_PER_RECORD 512\r
475\r
476EFI_STATUS\r
477EFIAPI\r
478SecPeiReportStatusCode (\r
479 IN CONST EFI_PEI_SERVICES **PeiServices,\r
480 IN EFI_STATUS_CODE_TYPE CodeType,\r
481 IN EFI_STATUS_CODE_VALUE Value,\r
482 IN UINT32 Instance,\r
483 IN CONST EFI_GUID *CallerId,\r
484 IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL\r
485 )\r
486/*++\r
487\r
488Routine Description:\r
489\r
490 This routine produces the ReportStatusCode PEI service. It's passed\r
491 up to the PEI Core via a PPI. T\r
492\r
493 This code currently uses the NT clib printf. This does not work the same way\r
494 as the EFI Print (), as %t, %g, %s as Unicode are not supported.\r
495\r
496Arguments:\r
497 (see EFI_PEI_REPORT_STATUS_CODE)\r
498\r
499Returns:\r
500 EFI_SUCCESS - Always return success\r
501\r
502--*/\r
503// TODO: PeiServices - add argument and description to function comment\r
504// TODO: CodeType - add argument and description to function comment\r
505// TODO: Value - add argument and description to function comment\r
506// TODO: Instance - add argument and description to function comment\r
507// TODO: CallerId - add argument and description to function comment\r
508// TODO: Data - add argument and description to function comment\r
509{\r
510 CHAR8 *Format;\r
511 BASE_LIST Marker;\r
512 CHAR8 PrintBuffer[BYTES_PER_RECORD * 2];\r
513 CHAR8 *Filename;\r
514 CHAR8 *Description;\r
515 UINT32 LineNumber;\r
516 UINT32 ErrorLevel;\r
517\r
518\r
519 if (Data == NULL) {\r
520 } else if (ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {\r
521 //\r
522 // Processes ASSERT ()\r
523 //\r
524 SecPrint ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);\r
525\r
526 } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {\r
527 //\r
528 // Process DEBUG () macro \r
529 //\r
530 AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);\r
531 SecPrint (PrintBuffer);\r
532 }\r
533\r
534 return EFI_SUCCESS;\r
535}\r
536\r
537#if defined (MDE_CPU_IA32)\r
538/**\r
539 Transfers control to a function starting with a new stack.\r
540\r
541 Transfers control to the function specified by EntryPoint using the new stack\r
542 specified by NewStack and passing in the parameters specified by Context1 and\r
543 Context2. Context1 and Context2 are optional and may be NULL. The function\r
544 EntryPoint must never return.\r
545\r
546 If EntryPoint is NULL, then ASSERT().\r
547 If NewStack is NULL, then ASSERT().\r
548\r
549 @param EntryPoint A pointer to function to call with the new stack.\r
550 @param Context1 A pointer to the context to pass into the EntryPoint\r
551 function.\r
552 @param Context2 A pointer to the context to pass into the EntryPoint\r
553 function.\r
554 @param NewStack A pointer to the new stack to use for the EntryPoint\r
555 function.\r
556 @param NewBsp A pointer to the new BSP for the EntryPoint on IPF. It's\r
557 Reserved on other architectures.\r
558\r
559**/\r
560VOID\r
561EFIAPI\r
562PeiSwitchStacks (\r
563 IN SWITCH_STACK_ENTRY_POINT EntryPoint,\r
564 IN VOID *Context1, OPTIONAL\r
565 IN VOID *Context2, OPTIONAL\r
566 IN VOID *Context3, OPTIONAL\r
567 IN VOID *NewStack\r
568 )\r
569{\r
570 BASE_LIBRARY_JUMP_BUFFER JumpBuffer;\r
571 \r
572 ASSERT (EntryPoint != NULL);\r
573 ASSERT (NewStack != NULL);\r
574\r
575 //\r
576 // Stack should be aligned with CPU_STACK_ALIGNMENT\r
577 //\r
578 ASSERT (((UINTN)NewStack & (CPU_STACK_ALIGNMENT - 1)) == 0);\r
579\r
580 JumpBuffer.Eip = (UINTN)EntryPoint;\r
581 JumpBuffer.Esp = (UINTN)NewStack - sizeof (VOID*);\r
582 JumpBuffer.Esp -= sizeof (Context1) + sizeof (Context2) + sizeof(Context3);\r
583 ((VOID**)JumpBuffer.Esp)[1] = Context1;\r
584 ((VOID**)JumpBuffer.Esp)[2] = Context2;\r
585 ((VOID**)JumpBuffer.Esp)[3] = Context3;\r
586\r
587 LongJump (&JumpBuffer, (UINTN)-1);\r
588 \r
589\r
590 //\r
591 // InternalSwitchStack () will never return\r
592 //\r
593 ASSERT (FALSE); \r
594}\r
595#endif\r
596\r
597VOID\r
598SecLoadFromCore (\r
599 IN UINTN LargestRegion,\r
600 IN UINTN LargestRegionSize,\r
601 IN UINTN BootFirmwareVolumeBase,\r
602 IN VOID *PeiCorePe32File\r
603 )\r
604/*++\r
605\r
606Routine Description:\r
607 This is the service to load the PEI Core from the Firmware Volume\r
608\r
609Arguments:\r
610 LargestRegion - Memory to use for PEI.\r
611 LargestRegionSize - Size of Memory to use for PEI\r
612 BootFirmwareVolumeBase - Start of the Boot FV\r
613 PeiCorePe32File - PEI Core PE32\r
614\r
615Returns:\r
616 Success means control is transfered and thus we should never return\r
617\r
618--*/\r
619{\r
620 EFI_STATUS Status;\r
621 VOID *TopOfStack;\r
622 UINT64 PeiCoreSize;\r
623 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;\r
624 EFI_PHYSICAL_ADDRESS PeiImageAddress;\r
625 EFI_SEC_PEI_HAND_OFF *SecCoreData;\r
626 UINTN PeiStackSize;\r
627\r
628 //\r
629 // Compute Top Of Memory for Stack and PEI Core Allocations\r
630 //\r
631 PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);\r
632\r
633 //\r
634 // |-----------| <---- TemporaryRamBase + TemporaryRamSize\r
635 // | Heap |\r
636 // | |\r
637 // |-----------| <---- StackBase / PeiTemporaryMemoryBase\r
638 // | |\r
639 // | Stack |\r
640 // |-----------| <---- TemporaryRamBase\r
641 // \r
642 TopOfStack = (VOID *)(LargestRegion + PeiStackSize);\r
643\r
644 //\r
645 // Reservet space for storing PeiCore's parament in stack.\r
646 // \r
647 TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);\r
648 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);\r
649\r
650 //\r
651 // Bind this information into the SEC hand-off state\r
652 //\r
653 SecCoreData = (EFI_SEC_PEI_HAND_OFF*)(UINTN) TopOfStack;\r
654 SecCoreData->DataSize = sizeof(EFI_SEC_PEI_HAND_OFF);\r
655 SecCoreData->BootFirmwareVolumeBase = (VOID*)BootFirmwareVolumeBase;\r
656 SecCoreData->BootFirmwareVolumeSize = PcdGet32(PcdWinNtFirmwareFdSize);\r
657 SecCoreData->TemporaryRamBase = (VOID*)(UINTN)LargestRegion; \r
658 SecCoreData->TemporaryRamSize = STACK_SIZE;\r
659 SecCoreData->StackBase = SecCoreData->TemporaryRamBase;\r
660 SecCoreData->StackSize = PeiStackSize;\r
661 SecCoreData->PeiTemporaryRamBase = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + PeiStackSize);\r
662 SecCoreData->PeiTemporaryRamSize = STACK_SIZE - PeiStackSize;\r
663\r
664 //\r
665 // Load the PEI Core from a Firmware Volume\r
666 //\r
667 Status = SecWinNtPeiLoadFile (\r
668 PeiCorePe32File,\r
669 &PeiImageAddress,\r
670 &PeiCoreSize,\r
671 &PeiCoreEntryPoint\r
672 );\r
673 if (EFI_ERROR (Status)) {\r
674 return ;\r
675 }\r
676 \r
677 //\r
678 // Transfer control to the PEI Core\r
679 //\r
680 PeiSwitchStacks (\r
681 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,\r
682 SecCoreData,\r
683 (VOID *) (UINTN) ((EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable),\r
684 NULL,\r
685 TopOfStack\r
686 );\r
687 //\r
688 // If we get here, then the PEI Core returned. This is an error\r
689 //\r
690 return ;\r
691}\r
692\r
693EFI_STATUS\r
694EFIAPI\r
695SecWinNtPeiAutoScan (\r
696 IN UINTN Index,\r
697 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,\r
698 OUT UINT64 *MemorySize\r
699 )\r
700/*++\r
701\r
702Routine Description:\r
703 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.\r
704 It allows discontinuous memory regions to be supported by the emulator.\r
705 It uses gSystemMemory[] and gSystemMemoryCount that were created by\r
706 parsing PcdWinNtMemorySizeForSecMain value.\r
707 The size comes from the Pcd value and the address comes from the memory space \r
708 with ReadWrite and Execute attributes allocated by VirtualAlloc() API.\r
709\r
710Arguments:\r
711 Index - Which memory region to use\r
712 MemoryBase - Return Base address of memory region\r
713 MemorySize - Return size in bytes of the memory region\r
714\r
715Returns:\r
716 EFI_SUCCESS - If memory region was mapped\r
717 EFI_UNSUPPORTED - If Index is not supported\r
718\r
719--*/\r
720{\r
721 if (Index >= gSystemMemoryCount) {\r
722 return EFI_UNSUPPORTED;\r
723 }\r
724 \r
725 //\r
726 // Allocate enough memory space for emulator \r
727 //\r
728 gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r
729 if (gSystemMemory[Index].Memory == 0) {\r
730 return EFI_OUT_OF_RESOURCES;\r
731 }\r
732 \r
733 *MemoryBase = gSystemMemory[Index].Memory;\r
734 *MemorySize = gSystemMemory[Index].Size;\r
735\r
736 return EFI_SUCCESS;\r
737}\r
738\r
739VOID *\r
740EFIAPI\r
741SecWinNtWinNtThunkAddress (\r
742 VOID\r
743 )\r
744/*++\r
745\r
746Routine Description:\r
747 Since the SEC is the only Windows program in stack it must export\r
748 an interface to do Win API calls. That's what the WinNtThunk address\r
749 is for. gWinNt is initialized in WinNtThunk.c.\r
750\r
751Arguments:\r
752 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);\r
753 InterfaceBase - Address of the gWinNt global\r
754\r
755Returns:\r
756 EFI_SUCCESS - Data returned\r
757\r
758--*/\r
759{\r
760 return gWinNt;\r
761}\r
762\r
763\r
764EFI_STATUS\r
765EFIAPI\r
766SecWinNtPeiLoadFile (\r
767 IN VOID *Pe32Data,\r
768 IN EFI_PHYSICAL_ADDRESS *ImageAddress,\r
769 IN UINT64 *ImageSize,\r
770 IN EFI_PHYSICAL_ADDRESS *EntryPoint\r
771 )\r
772/*++\r
773\r
774Routine Description:\r
775 Loads and relocates a PE/COFF image into memory.\r
776\r
777Arguments:\r
778 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated\r
779 ImageAddress - The base address of the relocated PE/COFF image\r
780 ImageSize - The size of the relocated PE/COFF image\r
781 EntryPoint - The entry point of the relocated PE/COFF image\r
782\r
783Returns:\r
784 EFI_SUCCESS - The file was loaded and relocated\r
785 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file\r
786\r
787--*/\r
788{\r
789 EFI_STATUS Status;\r
790 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;\r
791\r
792 ZeroMem (&ImageContext, sizeof (ImageContext));\r
793 ImageContext.Handle = Pe32Data;\r
794\r
795 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;\r
796\r
797 Status = PeCoffLoaderGetImageInfo (&ImageContext);\r
798 if (EFI_ERROR (Status)) {\r
799 return Status;\r
800 }\r
801 //\r
802 // Allocate space in NT (not emulator) memory with ReadWrite and Execute attribute. \r
803 // Extra space is for alignment\r
804 //\r
805 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r
806 if (ImageContext.ImageAddress == 0) {\r
807 return EFI_OUT_OF_RESOURCES;\r
808 }\r
809 //\r
810 // Align buffer on section boundary\r
811 //\r
812 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;\r
813 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);\r
814\r
815 Status = PeCoffLoaderLoadImage (&ImageContext);\r
816 if (EFI_ERROR (Status)) {\r
817 return Status;\r
818 }\r
819\r
820 Status = SecNt32PeCoffRelocateImage (&ImageContext);\r
821 if (EFI_ERROR (Status)) {\r
822 return Status;\r
823 }\r
824\r
825 //\r
826 // BugBug: Flush Instruction Cache Here when CPU Lib is ready\r
827 //\r
828\r
829 *ImageAddress = ImageContext.ImageAddress;\r
830 *ImageSize = ImageContext.ImageSize;\r
831 *EntryPoint = ImageContext.EntryPoint;\r
832\r
833 return EFI_SUCCESS;\r
834}\r
835\r
836EFI_STATUS\r
837EFIAPI\r
838SecWinNtFdAddress (\r
839 IN UINTN Index,\r
840 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,\r
841 IN OUT UINT64 *FdSize\r
842 )\r
843/*++\r
844\r
845Routine Description:\r
846 Return the FD Size and base address. Since the FD is loaded from a\r
847 file into Windows memory only the SEC will know it's address.\r
848\r
849Arguments:\r
850 Index - Which FD, starts at zero.\r
851 FdSize - Size of the FD in bytes\r
852 FdBase - Start address of the FD. Assume it points to an FV Header\r
853\r
854Returns:\r
855 EFI_SUCCESS - Return the Base address and size of the FV\r
856 EFI_UNSUPPORTED - Index does not map to an FD in the system\r
857\r
858--*/\r
859{\r
860 if (Index >= gFdInfoCount) {\r
861 return EFI_UNSUPPORTED;\r
862 }\r
863\r
864 *FdBase = gFdInfo[Index].Address;\r
865 *FdSize = gFdInfo[Index].Size;\r
866\r
867 if (*FdBase == 0 && *FdSize == 0) {\r
868 return EFI_UNSUPPORTED;\r
869 }\r
870\r
871 return EFI_SUCCESS;\r
872}\r
873\r
874EFI_STATUS\r
875EFIAPI\r
876SecImageRead (\r
877 IN VOID *FileHandle,\r
878 IN UINTN FileOffset,\r
879 IN OUT UINTN *ReadSize,\r
880 OUT VOID *Buffer\r
881 )\r
882/*++\r
883\r
884Routine Description:\r
885 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file\r
886\r
887Arguments:\r
888 FileHandle - The handle to the PE/COFF file\r
889 FileOffset - The offset, in bytes, into the file to read\r
890 ReadSize - The number of bytes to read from the file starting at FileOffset\r
891 Buffer - A pointer to the buffer to read the data into.\r
892\r
893Returns:\r
894 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset\r
895\r
896--*/\r
897{\r
898 CHAR8 *Destination8;\r
899 CHAR8 *Source8;\r
900 UINTN Length;\r
901\r
902 Destination8 = Buffer;\r
903 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);\r
904 Length = *ReadSize;\r
905 while (Length--) {\r
906 *(Destination8++) = *(Source8++);\r
907 }\r
908\r
909 return EFI_SUCCESS;\r
910}\r
911\r
912CHAR16 *\r
913AsciiToUnicode (\r
914 IN CHAR8 *Ascii,\r
915 IN UINTN *StrLen OPTIONAL\r
916 )\r
917/*++\r
918\r
919Routine Description:\r
920 Convert the passed in Ascii string to Unicode.\r
921 Optionally return the length of the strings.\r
922\r
923Arguments:\r
924 Ascii - Ascii string to convert\r
925 StrLen - Length of string\r
926\r
927Returns:\r
928 Pointer to malloc'ed Unicode version of Ascii\r
929\r
930--*/\r
931{\r
932 UINTN Index;\r
933 CHAR16 *Unicode;\r
934\r
935 //\r
936 // Allocate a buffer for unicode string\r
937 //\r
938 for (Index = 0; Ascii[Index] != '\0'; Index++)\r
939 ;\r
940 Unicode = malloc ((Index + 1) * sizeof (CHAR16));\r
941 if (Unicode == NULL) {\r
942 return NULL;\r
943 }\r
944\r
945 for (Index = 0; Ascii[Index] != '\0'; Index++) {\r
946 Unicode[Index] = (CHAR16) Ascii[Index];\r
947 }\r
948\r
949 Unicode[Index] = '\0';\r
950\r
951 if (StrLen != NULL) {\r
952 *StrLen = Index;\r
953 }\r
954\r
955 return Unicode;\r
956}\r
957\r
958UINTN\r
959CountSeparatorsInString (\r
960 IN CONST CHAR16 *String,\r
961 IN CHAR16 Separator\r
962 )\r
963/*++\r
964\r
965Routine Description:\r
966 Count the number of separators in String\r
967\r
968Arguments:\r
969 String - String to process\r
970 Separator - Item to count\r
971\r
972Returns:\r
973 Number of Separator in String\r
974\r
975--*/\r
976{\r
977 UINTN Count;\r
978\r
979 for (Count = 0; *String != '\0'; String++) {\r
980 if (*String == Separator) {\r
981 Count++;\r
982 }\r
983 }\r
984\r
985 return Count;\r
986}\r
987\r
988\r
989EFI_STATUS\r
990SecNt32PeCoffRelocateImage (\r
991 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext\r
992 )\r
993{\r
994 EFI_STATUS Status;\r
995 VOID *DllEntryPoint;\r
996 CHAR16 *DllFileName;\r
997 HMODULE Library;\r
998 UINTN Index;\r
999\r
1000\r
1001 Status = PeCoffLoaderRelocateImage (ImageContext);\r
1002 if (EFI_ERROR (Status)) {\r
1003 //\r
1004 // We could not relocated the image in memory properly\r
1005 //\r
1006 return Status;\r
1007 }\r
1008\r
1009 //\r
1010 // If we load our own PE COFF images the Windows debugger can not source\r
1011 // level debug our code. If a valid PDB pointer exists usw it to load\r
1012 // the *.dll file as a library using Windows* APIs. This allows \r
1013 // source level debug. The image is still loaded and relocated\r
1014 // in the Framework memory space like on a real system (by the code above),\r
1015 // but the entry point points into the DLL loaded by the code bellow. \r
1016 //\r
1017\r
1018 DllEntryPoint = NULL;\r
1019\r
1020 //\r
1021 // Load the DLL if it's not an EBC image.\r
1022 //\r
1023 if ((ImageContext->PdbPointer != NULL) &&\r
1024 (ImageContext->Machine != EFI_IMAGE_MACHINE_EBC)) {\r
1025 //\r
1026 // Convert filename from ASCII to Unicode\r
1027 //\r
1028 DllFileName = AsciiToUnicode (ImageContext->PdbPointer, &Index);\r
1029\r
1030 //\r
1031 // Check that we have a valid filename\r
1032 //\r
1033 if (Index < 5 || DllFileName[Index - 4] != '.') {\r
1034 free (DllFileName);\r
1035\r
1036 //\r
1037 // Never return an error if PeCoffLoaderRelocateImage() succeeded.\r
1038 // The image will run, but we just can't source level debug. If we\r
1039 // return an error the image will not run.\r
1040 //\r
1041 return EFI_SUCCESS;\r
1042 }\r
1043 //\r
1044 // Replace .PDB with .DLL on the filename\r
1045 //\r
1046 DllFileName[Index - 3] = 'D';\r
1047 DllFileName[Index - 2] = 'L';\r
1048 DllFileName[Index - 1] = 'L';\r
1049\r
1050 //\r
1051 // Load the .DLL file into the user process's address space for source \r
1052 // level debug\r
1053 //\r
1054 Library = LoadLibraryEx (DllFileName, NULL, DONT_RESOLVE_DLL_REFERENCES);\r
1055 if (Library != NULL) {\r
1056 //\r
1057 // InitializeDriver is the entry point we put in all our EFI DLL's. The\r
1058 // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() suppresses the \r
1059 // normal DLL entry point of DllMain, and prevents other modules that are\r
1060 // referenced in side the DllFileName from being loaded. There is no error \r
1061 // checking as the we can point to the PE32 image loaded by Tiano. This \r
1062 // step is only needed for source level debugging\r
1063 //\r
1064 DllEntryPoint = (VOID *) (UINTN) GetProcAddress (Library, "InitializeDriver");\r
1065\r
1066 }\r
1067\r
1068 if ((Library != NULL) && (DllEntryPoint != NULL)) {\r
1069 ImageContext->EntryPoint = (EFI_PHYSICAL_ADDRESS) (UINTN) DllEntryPoint;\r
1070 SecPrint ("LoadLibraryEx (%S,\n NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);\r
1071 } else {\r
1072 SecPrint ("WARNING: No source level debug %S. \n", DllFileName);\r
1073 }\r
1074\r
1075 free (DllFileName);\r
1076 }\r
1077\r
1078 //\r
1079 // Never return an error if PeCoffLoaderRelocateImage() succeeded.\r
1080 // The image will run, but we just can't source level debug. If we\r
1081 // return an error the image will not run.\r
1082 //\r
1083 return EFI_SUCCESS;\r
1084}\r
1085\r
1086\r
1087\r
1088\r
1089VOID\r
1090_ModuleEntryPoint (\r
1091 VOID\r
1092 )\r
1093{\r
1094}\r
1095\r
1096EFI_STATUS\r
1097EFIAPI\r
1098SecTemporaryRamSupport (\r
1099 IN CONST EFI_PEI_SERVICES **PeiServices,\r
1100 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,\r
1101 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,\r
1102 IN UINTN CopySize\r
1103 )\r
1104{\r
1105 //\r
1106 // Migrate the whole temporary memory to permanent memory.\r
1107 // \r
1108 CopyMem (\r
1109 (VOID*)(UINTN)PermanentMemoryBase, \r
1110 (VOID*)(UINTN)TemporaryMemoryBase, \r
1111 CopySize\r
1112 );\r
1113\r
1114 //\r
1115 // SecSwitchStack function must be invoked after the memory migration\r
1116 // immediately, also we need fixup the stack change caused by new call into \r
1117 // permanent memory.\r
1118 // \r
1119 SecSwitchStack (\r
1120 (UINT32) TemporaryMemoryBase,\r
1121 (UINT32) PermanentMemoryBase\r
1122 );\r
1123\r
1124 //\r
1125 // We need *not* fix the return address because currently, \r
1126 // The PeiCore is executed in flash.\r
1127 //\r
1128\r
1129 //\r
1130 // Simulate to invalid temporary memory, terminate temporary memory\r
1131 // \r
1132 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);\r
1133 \r
1134 return EFI_SUCCESS;\r
1135}\r
1136\r