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