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