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