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