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