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