]> git.proxmox.com Git - mirror_edk2.git/blob - Nt32Pkg/Sec/SecMain.c
Remove unnecessary use of FixedPcdxxx() functions and [FixedPcd] INF sections. These...
[mirror_edk2.git] / Nt32Pkg / Sec / SecMain.c
1 /**@file
2
3 Copyright (c) 2006 - 2010, 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 _vsnprintf (Buffer, sizeof (Buffer), Format, Marker);
123
124 CharCount = strlen (Buffer);
125 WriteFile (
126 GetStdHandle (STD_OUTPUT_HANDLE),
127 Buffer,
128 CharCount,
129 (LPDWORD)&CharCount,
130 NULL
131 );
132 }
133
134 INTN
135 EFIAPI
136 main (
137 IN INTN Argc,
138 IN CHAR8 **Argv,
139 IN CHAR8 **Envp
140 )
141 /*++
142
143 Routine Description:
144 Main entry point to SEC for WinNt. This is a Windows program
145
146 Arguments:
147 Argc - Number of command line arguments
148 Argv - Array of command line argument strings
149 Envp - Array of environmemt variable strings
150
151 Returns:
152 0 - Normal exit
153 1 - Abnormal exit
154
155 --*/
156 {
157 EFI_STATUS Status;
158 EFI_PHYSICAL_ADDRESS InitialStackMemory;
159 UINT64 InitialStackMemorySize;
160 UINTN Index;
161 UINTN Index1;
162 UINTN Index2;
163 CHAR16 *FileName;
164 CHAR16 *FileNamePtr;
165 BOOLEAN Done;
166 VOID *PeiCoreFile;
167 CHAR16 *MemorySizeStr;
168 CHAR16 *FirmwareVolumesStr;
169 UINTN *StackPointer;
170
171 MemorySizeStr = (CHAR16 *) PcdGetPtr (PcdWinNtMemorySizeForSecMain);
172 FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdWinNtFirmwareVolume);
173
174 SecPrint ("\nEDK II SEC Main NT Emulation Environment from www.TianoCore.org\n");
175
176 //
177 // Make some Windows calls to Set the process to the highest priority in the
178 // idle class. We need this to have good performance.
179 //
180 SetPriorityClass (GetCurrentProcess (), IDLE_PRIORITY_CLASS);
181 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);
182
183 //
184 // Allocate space for gSystemMemory Array
185 //
186 gSystemMemoryCount = CountSeperatorsInString (MemorySizeStr, '!') + 1;
187 gSystemMemory = calloc (gSystemMemoryCount, sizeof (NT_SYSTEM_MEMORY));
188 if (gSystemMemory == NULL) {
189 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n", MemorySizeStr);
190 exit (1);
191 }
192 //
193 // Allocate space for gSystemMemory Array
194 //
195 gFdInfoCount = CountSeperatorsInString (FirmwareVolumesStr, '!') + 1;
196 gFdInfo = calloc (gFdInfoCount, sizeof (NT_FD_INFO));
197 if (gFdInfo == NULL) {
198 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n", FirmwareVolumesStr);
199 exit (1);
200 }
201 //
202 // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)
203 //
204 SecPrint (" BootMode 0x%02x\n", PcdGet32 (PcdWinNtBootMode));
205
206 //
207 // Allocate 128K memory to emulate temp memory for PEI.
208 // on a real platform this would be SRAM, or using the cache as RAM.
209 // Set InitialStackMemory to zero so WinNtOpenFile will allocate a new mapping
210 //
211 InitialStackMemorySize = STACK_SIZE;
212 InitialStackMemory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (InitialStackMemorySize), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
213 if (InitialStackMemory == 0) {
214 SecPrint ("ERROR : Can not allocate enough space for SecStack\n");
215 exit (1);
216 }
217
218 for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;
219 StackPointer < (UINTN*) ((UINTN)InitialStackMemory + (SIZE_T) InitialStackMemorySize);
220 StackPointer ++) {
221 *StackPointer = 0x5AA55AA5;
222 }
223
224 SecPrint (" SEC passing in %d bytes of temp RAM to PEI\n", InitialStackMemorySize);
225
226 //
227 // Open All the firmware volumes and remember the info in the gFdInfo global
228 //
229 FileNamePtr = (CHAR16 *)malloc (StrLen ((CHAR16 *)FirmwareVolumesStr) * sizeof(CHAR16));
230 if (FileNamePtr == NULL) {
231 SecPrint ("ERROR : Can not allocate memory for firmware volume string\n");
232 exit (1);
233 }
234
235 StrCpy (FileNamePtr, (CHAR16*)FirmwareVolumesStr);
236
237 for (Done = FALSE, Index = 0, PeiCoreFile = NULL; !Done; Index++) {
238 FileName = FileNamePtr;
239 for (Index1 = 0; (FileNamePtr[Index1] != '!') && (FileNamePtr[Index1] != 0); Index1++)
240 ;
241 if (FileNamePtr[Index1] == 0) {
242 Done = TRUE;
243 } else {
244 FileNamePtr[Index1] = '\0';
245 FileNamePtr = FileNamePtr + Index1 + 1;
246 }
247
248 //
249 // Open the FD and remmeber where it got mapped into our processes address space
250 //
251 Status = WinNtOpenFile (
252 FileName,
253 0,
254 OPEN_EXISTING,
255 &gFdInfo[Index].Address,
256 &gFdInfo[Index].Size
257 );
258 if (EFI_ERROR (Status)) {
259 SecPrint ("ERROR : Can not open Firmware Device File %S (0x%X). Exiting.\n", FileName, Status);
260 exit (1);
261 }
262
263 SecPrint (" FD loaded from");
264 //
265 // printf can't print filenames directly as the \ gets interperted as an
266 // escape character.
267 //
268 for (Index2 = 0; FileName[Index2] != '\0'; Index2++) {
269 SecPrint ("%c", FileName[Index2]);
270 }
271
272 if (PeiCoreFile == NULL) {
273 //
274 // Assume the beginning of the FD is an FV and look for the PEI Core.
275 // Load the first one we find.
276 //
277 Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);
278 if (!EFI_ERROR (Status)) {
279 SecPrint (" contains SEC Core");
280 }
281 }
282
283 SecPrint ("\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 SecPrint ("\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 SecPrint ("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 BASE_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 SecPrint ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);
480
481 } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
482 //
483 // Process DEBUG () macro
484 //
485 AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
486 SecPrint (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 VOID *TopOfStack;
575 UINT64 PeiCoreSize;
576 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
577 EFI_PHYSICAL_ADDRESS PeiImageAddress;
578 EFI_SEC_PEI_HAND_OFF *SecCoreData;
579 UINTN PeiStackSize;
580
581 //
582 // Compute Top Of Memory for Stack and PEI Core Allocations
583 //
584 PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);
585
586 //
587 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
588 // | Heap |
589 // | |
590 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
591 // | |
592 // | Stack |
593 // |-----------| <---- TemporaryRamBase
594 //
595 TopOfStack = (VOID *)(LargestRegion + PeiStackSize);
596
597 //
598 // Reservet space for storing PeiCore's parament in stack.
599 //
600 TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
601 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
602
603 //
604 // Bind this information into the SEC hand-off state
605 //
606 SecCoreData = (EFI_SEC_PEI_HAND_OFF*)(UINTN) TopOfStack;
607 SecCoreData->DataSize = sizeof(EFI_SEC_PEI_HAND_OFF);
608 SecCoreData->BootFirmwareVolumeBase = (VOID*)BootFirmwareVolumeBase;
609 SecCoreData->BootFirmwareVolumeSize = PcdGet32(PcdWinNtFirmwareFdSize);
610 SecCoreData->TemporaryRamBase = (VOID*)(UINTN)LargestRegion;
611 SecCoreData->TemporaryRamSize = STACK_SIZE;
612 SecCoreData->StackBase = SecCoreData->TemporaryRamBase;
613 SecCoreData->StackSize = PeiStackSize;
614 SecCoreData->PeiTemporaryRamBase = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + PeiStackSize);
615 SecCoreData->PeiTemporaryRamSize = STACK_SIZE - PeiStackSize;
616
617 //
618 // Load the PEI Core from a Firmware Volume
619 //
620 Status = SecWinNtPeiLoadFile (
621 PeiCorePe32File,
622 &PeiImageAddress,
623 &PeiCoreSize,
624 &PeiCoreEntryPoint
625 );
626 if (EFI_ERROR (Status)) {
627 return ;
628 }
629
630 //
631 // Transfer control to the PEI Core
632 //
633 PeiSwitchStacks (
634 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
635 SecCoreData,
636 (VOID *) (UINTN) ((EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable),
637 NULL,
638 TopOfStack
639 );
640 //
641 // If we get here, then the PEI Core returned. This is an error
642 //
643 return ;
644 }
645
646 EFI_STATUS
647 EFIAPI
648 SecWinNtPeiAutoScan (
649 IN UINTN Index,
650 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
651 OUT UINT64 *MemorySize
652 )
653 /*++
654
655 Routine Description:
656 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
657 It allows discontiguous memory regions to be supported by the emulator.
658 It uses gSystemMemory[] and gSystemMemoryCount that were created by
659 parsing PcdWinNtMemorySizeForSecMain value.
660 The size comes from the Pcd value and the address comes from the memory space
661 with ReadWrite and Execute attributes allocated by VirtualAlloc() API.
662
663 Arguments:
664 Index - Which memory region to use
665 MemoryBase - Return Base address of memory region
666 MemorySize - Return size in bytes of the memory region
667
668 Returns:
669 EFI_SUCCESS - If memory region was mapped
670 EFI_UNSUPPORTED - If Index is not supported
671
672 --*/
673 {
674 if (Index >= gSystemMemoryCount) {
675 return EFI_UNSUPPORTED;
676 }
677
678 //
679 // Allocate enough memory space for emulator
680 //
681 gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
682 if (gSystemMemory[Index].Memory == 0) {
683 return EFI_OUT_OF_RESOURCES;
684 }
685
686 *MemoryBase = gSystemMemory[Index].Memory;
687 *MemorySize = gSystemMemory[Index].Size;
688
689 return EFI_SUCCESS;
690 }
691
692 VOID *
693 EFIAPI
694 SecWinNtWinNtThunkAddress (
695 VOID
696 )
697 /*++
698
699 Routine Description:
700 Since the SEC is the only Windows program in stack it must export
701 an interface to do Win API calls. That's what the WinNtThunk address
702 is for. gWinNt is initailized in WinNtThunk.c.
703
704 Arguments:
705 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
706 InterfaceBase - Address of the gWinNt global
707
708 Returns:
709 EFI_SUCCESS - Data returned
710
711 --*/
712 {
713 return gWinNt;
714 }
715
716
717 EFI_STATUS
718 EFIAPI
719 SecWinNtPeiLoadFile (
720 IN VOID *Pe32Data,
721 IN EFI_PHYSICAL_ADDRESS *ImageAddress,
722 IN UINT64 *ImageSize,
723 IN EFI_PHYSICAL_ADDRESS *EntryPoint
724 )
725 /*++
726
727 Routine Description:
728 Loads and relocates a PE/COFF image into memory.
729
730 Arguments:
731 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
732 ImageAddress - The base address of the relocated PE/COFF image
733 ImageSize - The size of the relocated PE/COFF image
734 EntryPoint - The entry point of the relocated PE/COFF image
735
736 Returns:
737 EFI_SUCCESS - The file was loaded and relocated
738 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
739
740 --*/
741 {
742 EFI_STATUS Status;
743 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
744
745 ZeroMem (&ImageContext, sizeof (ImageContext));
746 ImageContext.Handle = Pe32Data;
747
748 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
749
750 Status = PeCoffLoaderGetImageInfo (&ImageContext);
751 if (EFI_ERROR (Status)) {
752 return Status;
753 }
754 //
755 // Allocate space in NT (not emulator) memory with ReadWrite and Execute attribue.
756 // Extra space is for alignment
757 //
758 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
759 if (ImageContext.ImageAddress == 0) {
760 return EFI_OUT_OF_RESOURCES;
761 }
762 //
763 // Align buffer on section boundry
764 //
765 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
766 ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);
767
768 Status = PeCoffLoaderLoadImage (&ImageContext);
769 if (EFI_ERROR (Status)) {
770 return Status;
771 }
772
773 Status = SecNt32PeCoffRelocateImage (&ImageContext);
774 if (EFI_ERROR (Status)) {
775 return Status;
776 }
777
778 //
779 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
780 //
781
782 *ImageAddress = ImageContext.ImageAddress;
783 *ImageSize = ImageContext.ImageSize;
784 *EntryPoint = ImageContext.EntryPoint;
785
786 return EFI_SUCCESS;
787 }
788
789 EFI_STATUS
790 EFIAPI
791 SecWinNtFdAddress (
792 IN UINTN Index,
793 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
794 IN OUT UINT64 *FdSize
795 )
796 /*++
797
798 Routine Description:
799 Return the FD Size and base address. Since the FD is loaded from a
800 file into Windows memory only the SEC will know it's address.
801
802 Arguments:
803 Index - Which FD, starts at zero.
804 FdSize - Size of the FD in bytes
805 FdBase - Start address of the FD. Assume it points to an FV Header
806
807 Returns:
808 EFI_SUCCESS - Return the Base address and size of the FV
809 EFI_UNSUPPORTED - Index does nto map to an FD in the system
810
811 --*/
812 {
813 if (Index >= gFdInfoCount) {
814 return EFI_UNSUPPORTED;
815 }
816
817 *FdBase = gFdInfo[Index].Address;
818 *FdSize = gFdInfo[Index].Size;
819
820 if (*FdBase == 0 && *FdSize == 0) {
821 return EFI_UNSUPPORTED;
822 }
823
824 return EFI_SUCCESS;
825 }
826
827 EFI_STATUS
828 EFIAPI
829 SecImageRead (
830 IN VOID *FileHandle,
831 IN UINTN FileOffset,
832 IN OUT UINTN *ReadSize,
833 OUT VOID *Buffer
834 )
835 /*++
836
837 Routine Description:
838 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
839
840 Arguments:
841 FileHandle - The handle to the PE/COFF file
842 FileOffset - The offset, in bytes, into the file to read
843 ReadSize - The number of bytes to read from the file starting at FileOffset
844 Buffer - A pointer to the buffer to read the data into.
845
846 Returns:
847 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
848
849 --*/
850 {
851 CHAR8 *Destination8;
852 CHAR8 *Source8;
853 UINTN Length;
854
855 Destination8 = Buffer;
856 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
857 Length = *ReadSize;
858 while (Length--) {
859 *(Destination8++) = *(Source8++);
860 }
861
862 return EFI_SUCCESS;
863 }
864
865 CHAR16 *
866 AsciiToUnicode (
867 IN CHAR8 *Ascii,
868 IN UINTN *StrLen OPTIONAL
869 )
870 /*++
871
872 Routine Description:
873 Convert the passed in Ascii string to Unicode.
874 Optionally return the length of the strings.
875
876 Arguments:
877 Ascii - Ascii string to convert
878 StrLen - Length of string
879
880 Returns:
881 Pointer to malloc'ed Unicode version of Ascii
882
883 --*/
884 {
885 UINTN Index;
886 CHAR16 *Unicode;
887
888 //
889 // Allocate a buffer for unicode string
890 //
891 for (Index = 0; Ascii[Index] != '\0'; Index++)
892 ;
893 Unicode = malloc ((Index + 1) * sizeof (CHAR16));
894 if (Unicode == NULL) {
895 return NULL;
896 }
897
898 for (Index = 0; Ascii[Index] != '\0'; Index++) {
899 Unicode[Index] = (CHAR16) Ascii[Index];
900 }
901
902 Unicode[Index] = '\0';
903
904 if (StrLen != NULL) {
905 *StrLen = Index;
906 }
907
908 return Unicode;
909 }
910
911 UINTN
912 CountSeperatorsInString (
913 IN CONST CHAR16 *String,
914 IN CHAR16 Seperator
915 )
916 /*++
917
918 Routine Description:
919 Count the number of seperators in String
920
921 Arguments:
922 String - String to process
923 Seperator - Item to count
924
925 Returns:
926 Number of Seperator in String
927
928 --*/
929 {
930 UINTN Count;
931
932 for (Count = 0; *String != '\0'; String++) {
933 if (*String == Seperator) {
934 Count++;
935 }
936 }
937
938 return Count;
939 }
940
941
942 EFI_STATUS
943 SecNt32PeCoffRelocateImage (
944 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
945 )
946 {
947 EFI_STATUS Status;
948 VOID *DllEntryPoint;
949 CHAR16 *DllFileName;
950 HMODULE Library;
951 UINTN Index;
952
953
954 Status = PeCoffLoaderRelocateImage (ImageContext);
955 if (EFI_ERROR (Status)) {
956 //
957 // We could not relocated the image in memory properly
958 //
959 return Status;
960 }
961
962 //
963 // If we load our own PE COFF images the Windows debugger can not source
964 // level debug our code. If a valid PDB pointer exists usw it to load
965 // the *.dll file as a library using Windows* APIs. This allows
966 // source level debug. The image is still loaded and reloaced
967 // in the Framework memory space like on a real system (by the code above),
968 // but the entry point points into the DLL loaded by the code bellow.
969 //
970
971 DllEntryPoint = NULL;
972
973 //
974 // Load the DLL if it's not an EBC image.
975 //
976 if ((ImageContext->PdbPointer != NULL) &&
977 (ImageContext->Machine != EFI_IMAGE_MACHINE_EBC)) {
978 //
979 // Convert filename from ASCII to Unicode
980 //
981 DllFileName = AsciiToUnicode (ImageContext->PdbPointer, &Index);
982
983 //
984 // Check that we have a valid filename
985 //
986 if (Index < 5 || DllFileName[Index - 4] != '.') {
987 free (DllFileName);
988
989 //
990 // Never return an error if PeCoffLoaderRelocateImage() succeeded.
991 // The image will run, but we just can't source level debug. If we
992 // return an error the image will not run.
993 //
994 return EFI_SUCCESS;
995 }
996 //
997 // Replace .PDB with .DLL on the filename
998 //
999 DllFileName[Index - 3] = 'D';
1000 DllFileName[Index - 2] = 'L';
1001 DllFileName[Index - 1] = 'L';
1002
1003 //
1004 // Load the .DLL file into the user process's address space for source
1005 // level debug
1006 //
1007 Library = LoadLibraryEx (DllFileName, NULL, DONT_RESOLVE_DLL_REFERENCES);
1008 if (Library != NULL) {
1009 //
1010 // InitializeDriver is the entry point we put in all our EFI DLL's. The
1011 // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() supresses the
1012 // normal DLL entry point of DllMain, and prevents other modules that are
1013 // referenced in side the DllFileName from being loaded. There is no error
1014 // checking as the we can point to the PE32 image loaded by Tiano. This
1015 // step is only needed for source level debuging
1016 //
1017 DllEntryPoint = (VOID *) (UINTN) GetProcAddress (Library, "InitializeDriver");
1018
1019 }
1020
1021 if ((Library != NULL) && (DllEntryPoint != NULL)) {
1022 ImageContext->EntryPoint = (EFI_PHYSICAL_ADDRESS) (UINTN) DllEntryPoint;
1023 SecPrint ("LoadLibraryEx (%S,\n NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);
1024 } else {
1025 SecPrint ("WARNING: No source level debug %S. \n", DllFileName);
1026 }
1027
1028 free (DllFileName);
1029 }
1030
1031 //
1032 // Never return an error if PeCoffLoaderRelocateImage() succeeded.
1033 // The image will run, but we just can't source level debug. If we
1034 // return an error the image will not run.
1035 //
1036 return EFI_SUCCESS;
1037 }
1038
1039
1040
1041
1042 VOID
1043 _ModuleEntryPoint (
1044 VOID
1045 )
1046 {
1047 }
1048
1049 EFI_STATUS
1050 EFIAPI
1051 SecTemporaryRamSupport (
1052 IN CONST EFI_PEI_SERVICES **PeiServices,
1053 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,
1054 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,
1055 IN UINTN CopySize
1056 )
1057 {
1058 //
1059 // Migrate the whole temporary memory to permenent memory.
1060 //
1061 CopyMem (
1062 (VOID*)(UINTN)PermanentMemoryBase,
1063 (VOID*)(UINTN)TemporaryMemoryBase,
1064 CopySize
1065 );
1066
1067 //
1068 // SecSwitchStack function must be invoked after the memory migration
1069 // immediatly, also we need fixup the stack change caused by new call into
1070 // permenent memory.
1071 //
1072 SecSwitchStack (
1073 (UINT32) TemporaryMemoryBase,
1074 (UINT32) PermanentMemoryBase
1075 );
1076
1077 //
1078 // We need *not* fix the return address because currently,
1079 // The PeiCore is excuted in flash.
1080 //
1081
1082 //
1083 // Simulate to invalid temporary memory, terminate temporary memory
1084 //
1085 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);
1086
1087 return EFI_SUCCESS;
1088 }
1089