]> git.proxmox.com Git - mirror_edk2.git/blob - EdkNt32Pkg/Sec/SecMain.c
Make NT32 SecMain not depend on ReportStatusCodeLib
[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 #pragma warning(disable : 4996)
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 *)PcdGetPtr (PcdWinNtMemorySizeForSecMain);
164 FirmwareVolumesStr = (CHAR16 *)PcdGetPtr (PcdWinNtFirmwareVolume);
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 #define BYTES_PER_RECORD 512
424
425 /**
426 Extracts ASSERT() information from a status code structure.
427
428 Converts the status code specified by CodeType, Value, and Data to the ASSERT()
429 arguments specified by Filename, Description, and LineNumber. If CodeType is
430 an EFI_ERROR_CODE, and CodeType has a severity of EFI_ERROR_UNRECOVERED, and
431 Value has an operation mask of EFI_SW_EC_ILLEGAL_SOFTWARE_STATE, extract
432 Filename, Description, and LineNumber from the optional data area of the
433 status code buffer specified by Data. The optional data area of Data contains
434 a Null-terminated ASCII string for the FileName, followed by a Null-terminated
435 ASCII string for the Description, followed by a 32-bit LineNumber. If the
436 ASSERT() information could be extracted from Data, then return TRUE.
437 Otherwise, FALSE is returned.
438
439 If Data is NULL, then ASSERT().
440 If Filename is NULL, then ASSERT().
441 If Description is NULL, then ASSERT().
442 If LineNumber is NULL, then ASSERT().
443
444 @param CodeType The type of status code being converted.
445 @param Value The status code value being converted.
446 @param Data Pointer to status code data buffer.
447 @param Filename Pointer to the source file name that generated the ASSERT().
448 @param Description Pointer to the description of the ASSERT().
449 @param LineNumber Pointer to source line number that generated the ASSERT().
450
451 @retval TRUE The status code specified by CodeType, Value, and Data was
452 converted ASSERT() arguments specified by Filename, Description,
453 and LineNumber.
454 @retval FALSE The status code specified by CodeType, Value, and Data could
455 not be converted to ASSERT() arguments.
456
457 **/
458 STATIC
459 BOOLEAN
460 ReportStatusCodeExtractAssertInfo (
461 IN EFI_STATUS_CODE_TYPE CodeType,
462 IN EFI_STATUS_CODE_VALUE Value,
463 IN CONST EFI_STATUS_CODE_DATA *Data,
464 OUT CHAR8 **Filename,
465 OUT CHAR8 **Description,
466 OUT UINT32 *LineNumber
467 )
468 {
469 EFI_DEBUG_ASSERT_DATA *AssertData;
470
471 ASSERT (Data != NULL);
472 ASSERT (Filename != NULL);
473 ASSERT (Description != NULL);
474 ASSERT (LineNumber != NULL);
475
476 if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
477 ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) &&
478 ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) {
479 AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1);
480 *Filename = (CHAR8 *)(AssertData + 1);
481 *Description = *Filename + AsciiStrLen (*Filename) + 1;
482 *LineNumber = AssertData->LineNumber;
483 return TRUE;
484 }
485 return FALSE;
486 }
487
488 EFI_STATUS
489 EFIAPI
490 SecPeiReportStatusCode (
491 IN EFI_PEI_SERVICES **PeiServices,
492 IN EFI_STATUS_CODE_TYPE CodeType,
493 IN EFI_STATUS_CODE_VALUE Value,
494 IN UINT32 Instance,
495 IN EFI_GUID * CallerId,
496 IN EFI_STATUS_CODE_DATA * Data OPTIONAL
497 )
498 /*++
499
500 Routine Description:
501
502 This routine produces the ReportStatusCode PEI service. It's passed
503 up to the PEI Core via a PPI. T
504
505 This code currently uses the NT clib printf. This does not work the same way
506 as the EFI Print (), as %t, %g, %s as Unicode are not supported.
507
508 Arguments:
509 (see EFI_PEI_REPORT_STATUS_CODE)
510
511 Returns:
512 EFI_SUCCESS - Always return success
513
514 --*/
515 // TODO: PeiServices - add argument and description to function comment
516 // TODO: CodeType - add argument and description to function comment
517 // TODO: Value - add argument and description to function comment
518 // TODO: Instance - add argument and description to function comment
519 // TODO: CallerId - add argument and description to function comment
520 // TODO: Data - add argument and description to function comment
521 {
522 CHAR8 *Format;
523 EFI_DEBUG_INFO *DebugInfo;
524 VA_LIST Marker;
525 CHAR8 PrintBuffer[BYTES_PER_RECORD * 2];
526 CHAR8 *Filename;
527 CHAR8 *Description;
528 UINT32 LineNumber;
529
530 if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
531 //
532 // This supports DEBUG () marcos
533 // Data format
534 // EFI_STATUS_CODE_DATA
535 // EFI_DEBUG_INFO
536 //
537 // The first 12 * UINT64 bytes of the string are really an
538 // arguement stack to support varargs on the Format string.
539 //
540 if (Data != NULL) {
541 DebugInfo = (EFI_DEBUG_INFO *) (Data + 1);
542 Marker = (VA_LIST) (DebugInfo + 1);
543 Format = (CHAR8 *) (((UINT64 *) Marker) + 12);
544
545 AsciiVSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
546 printf (PrintBuffer);
547 } else {
548 printf ("DEBUG <null>\n");
549 }
550 }
551
552 if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
553 ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED)
554 ) {
555 if (Data != NULL && ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
556 //
557 // Support ASSERT () macro
558 //
559 printf ("ASSERT %s(%d): %s\n", Filename, LineNumber, Description);
560 } else {
561 printf ("ASSERT <null>\n");
562 }
563 CpuBreakpoint ();
564 }
565
566 return EFI_SUCCESS;
567 }
568
569
570 VOID
571 SecLoadFromCore (
572 IN UINTN LargestRegion,
573 IN UINTN LargestRegionSize,
574 IN UINTN BootFirmwareVolumeBase,
575 IN VOID *PeiCorePe32File
576 )
577 /*++
578
579 Routine Description:
580 This is the service to load the PEI Core from the Firmware Volume
581
582 Arguments:
583 LargestRegion - Memory to use for PEI.
584 LargestRegionSize - Size of Memory to use for PEI
585 BootFirmwareVolumeBase - Start of the Boot FV
586 PeiCorePe32File - PEI Core PE32
587
588 Returns:
589 Success means control is transfered and thus we should never return
590
591 --*/
592 {
593 EFI_STATUS Status;
594 EFI_PHYSICAL_ADDRESS TopOfMemory;
595 VOID *TopOfStack;
596 UINT64 PeiCoreSize;
597 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
598 EFI_PHYSICAL_ADDRESS PeiImageAddress;
599 EFI_PEI_STARTUP_DESCRIPTOR *PeiStartup;
600
601 //
602 // Compute Top Of Memory for Stack and PEI Core Allocations
603 //
604 TopOfMemory = LargestRegion + ((LargestRegionSize) & (~15));
605
606 //
607 // Allocate 128KB for the Stack
608 //
609 TopOfStack = (VOID *) (UINTN) (TopOfMemory - sizeof (EFI_PEI_STARTUP_DESCRIPTOR));
610 TopOfMemory = TopOfMemory - STACK_SIZE;
611
612 //
613 // Patch value in dispatch table values
614 //
615 gPrivateDispatchTable[0].Ppi = gPeiEfiPeiPeCoffLoader;
616
617 //
618 // Bind this information into the SEC hand-off state
619 //
620 PeiStartup = (EFI_PEI_STARTUP_DESCRIPTOR *) (UINTN) TopOfStack;
621 PeiStartup->DispatchTable = (EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable;
622 PeiStartup->SizeOfCacheAsRam = STACK_SIZE;
623 PeiStartup->BootFirmwareVolume = BootFirmwareVolumeBase;
624
625 //
626 // Load the PEI Core from a Firmware Volume
627 //
628 Status = SecWinNtPeiLoadFile (
629 PeiCorePe32File,
630 &PeiImageAddress,
631 &PeiCoreSize,
632 &PeiCoreEntryPoint
633 );
634 if (EFI_ERROR (Status)) {
635 return ;
636 }
637 //
638 // Transfer control to the PEI Core
639 //
640 SwitchStack (
641 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
642 PeiStartup,
643 NULL,
644 TopOfStack
645 );
646 //
647 // If we get here, then the PEI Core returned. This is an error
648 //
649 return ;
650 }
651
652 EFI_STATUS
653 EFIAPI
654 SecWinNtPeiAutoScan (
655 IN UINTN Index,
656 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
657 OUT UINT64 *MemorySize
658 )
659 /*++
660
661 Routine Description:
662 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
663 It allows discontiguous memory regions to be supported by the emulator.
664 It uses gSystemMemory[] and gSystemMemoryCount that were created by
665 parsing the Windows environment variable EFI_MEMORY_SIZE.
666 The size comes from the varaible and the address comes from the call to
667 WinNtOpenFile.
668
669 Arguments:
670 Index - Which memory region to use
671 MemoryBase - Return Base address of memory region
672 MemorySize - Return size in bytes of the memory region
673
674 Returns:
675 EFI_SUCCESS - If memory region was mapped
676 EFI_UNSUPPORTED - If Index is not supported
677
678 --*/
679 {
680 EFI_STATUS Status;
681
682 if (Index >= gSystemMemoryCount) {
683 return EFI_UNSUPPORTED;
684 }
685
686 *MemoryBase = 0;
687 Status = WinNtOpenFile (
688 gSystemMemory[Index].FileName,
689 (UINT32) gSystemMemory[Index].Size,
690 OPEN_ALWAYS,
691 MemoryBase,
692 MemorySize
693 );
694
695 gSystemMemory[Index].Memory = *MemoryBase;
696
697 return Status;
698 }
699
700 VOID *
701 EFIAPI
702 SecWinNtWinNtThunkAddress (
703 VOID
704 )
705 /*++
706
707 Routine Description:
708 Since the SEC is the only Windows program in stack it must export
709 an interface to do Win API calls. That's what the WinNtThunk address
710 is for. gWinNt is initailized in WinNtThunk.c.
711
712 Arguments:
713 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
714 InterfaceBase - Address of the gWinNt global
715
716 Returns:
717 EFI_SUCCESS - Data returned
718
719 --*/
720 {
721 return gWinNt;
722 }
723
724
725 EFI_STATUS
726 EFIAPI
727 SecWinNtPeiLoadFile (
728 IN VOID *Pe32Data,
729 IN EFI_PHYSICAL_ADDRESS *ImageAddress,
730 IN UINT64 *ImageSize,
731 IN EFI_PHYSICAL_ADDRESS *EntryPoint
732 )
733 /*++
734
735 Routine Description:
736 Loads and relocates a PE/COFF image into memory.
737
738 Arguments:
739 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
740 ImageAddress - The base address of the relocated PE/COFF image
741 ImageSize - The size of the relocated PE/COFF image
742 EntryPoint - The entry point of the relocated PE/COFF image
743
744 Returns:
745 EFI_SUCCESS - The file was loaded and relocated
746 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
747
748 --*/
749 {
750 EFI_STATUS Status;
751 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
752
753 ZeroMem (&ImageContext, sizeof (ImageContext));
754 ImageContext.Handle = Pe32Data;
755
756 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
757
758 Status = gPeiEfiPeiPeCoffLoader->GetImageInfo (gPeiEfiPeiPeCoffLoader, &ImageContext);
759 if (EFI_ERROR (Status)) {
760 return Status;
761 }
762 //
763 // Allocate space in NT (not emulator) memory. Extra space is for alignment
764 //
765 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) malloc ((UINTN) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)));
766 if (ImageContext.ImageAddress == 0) {
767 return EFI_OUT_OF_RESOURCES;
768 }
769 //
770 // Align buffer on section boundry
771 //
772 ImageContext.ImageAddress += ImageContext.SectionAlignment;
773 ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);
774
775 Status = gPeiEfiPeiPeCoffLoader->LoadImage (gPeiEfiPeiPeCoffLoader, &ImageContext);
776 if (EFI_ERROR (Status)) {
777 return Status;
778 }
779
780 Status = gPeiEfiPeiPeCoffLoader->RelocateImage (gPeiEfiPeiPeCoffLoader, &ImageContext);
781 if (EFI_ERROR (Status)) {
782 return Status;
783 }
784
785 //
786 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
787 //
788
789 *ImageAddress = ImageContext.ImageAddress;
790 *ImageSize = ImageContext.ImageSize;
791 *EntryPoint = ImageContext.EntryPoint;
792
793 return EFI_SUCCESS;
794 }
795
796 EFI_STATUS
797 EFIAPI
798 SecWinNtFdAddress (
799 IN UINTN Index,
800 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
801 IN OUT UINT64 *FdSize
802 )
803 /*++
804
805 Routine Description:
806 Return the FD Size and base address. Since the FD is loaded from a
807 file into Windows memory only the SEC will know it's address.
808
809 Arguments:
810 Index - Which FD, starts at zero.
811 FdSize - Size of the FD in bytes
812 FdBase - Start address of the FD. Assume it points to an FV Header
813
814 Returns:
815 EFI_SUCCESS - Return the Base address and size of the FV
816 EFI_UNSUPPORTED - Index does nto map to an FD in the system
817
818 --*/
819 {
820 if (Index >= gFdInfoCount) {
821 return EFI_UNSUPPORTED;
822 }
823
824 *FdBase = gFdInfo[Index].Address;
825 *FdSize = gFdInfo[Index].Size;
826
827 if (*FdBase == 0 && *FdSize == 0) {
828 return EFI_UNSUPPORTED;
829 }
830
831 return EFI_SUCCESS;
832 }
833
834 EFI_STATUS
835 EFIAPI
836 SecImageRead (
837 IN VOID *FileHandle,
838 IN UINTN FileOffset,
839 IN OUT UINTN *ReadSize,
840 OUT VOID *Buffer
841 )
842 /*++
843
844 Routine Description:
845 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
846
847 Arguments:
848 FileHandle - The handle to the PE/COFF file
849 FileOffset - The offset, in bytes, into the file to read
850 ReadSize - The number of bytes to read from the file starting at FileOffset
851 Buffer - A pointer to the buffer to read the data into.
852
853 Returns:
854 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
855
856 --*/
857 {
858 CHAR8 *Destination8;
859 CHAR8 *Source8;
860 UINTN Length;
861
862 Destination8 = Buffer;
863 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
864 Length = *ReadSize;
865 while (Length--) {
866 *(Destination8++) = *(Source8++);
867 }
868
869 return EFI_SUCCESS;
870 }
871
872 CHAR16 *
873 AsciiToUnicode (
874 IN CHAR8 *Ascii,
875 IN UINTN *StrLen OPTIONAL
876 )
877 /*++
878
879 Routine Description:
880 Convert the passed in Ascii string to Unicode.
881 Optionally return the length of the strings.
882
883 Arguments:
884 Ascii - Ascii string to convert
885 StrLen - Length of string
886
887 Returns:
888 Pointer to malloc'ed Unicode version of Ascii
889
890 --*/
891 {
892 UINTN Index;
893 CHAR16 *Unicode;
894
895 //
896 // Allocate a buffer for unicode string
897 //
898 for (Index = 0; Ascii[Index] != '\0'; Index++)
899 ;
900 Unicode = malloc ((Index + 1) * sizeof (CHAR16));
901 if (Unicode == NULL) {
902 return NULL;
903 }
904
905 for (Index = 0; Ascii[Index] != '\0'; Index++) {
906 Unicode[Index] = (CHAR16) Ascii[Index];
907 }
908
909 Unicode[Index] = '\0';
910
911 if (StrLen != NULL) {
912 *StrLen = Index;
913 }
914
915 return Unicode;
916 }
917
918 UINTN
919 CountSeperatorsInString (
920 IN const CHAR16 *String,
921 IN CHAR16 Seperator
922 )
923 /*++
924
925 Routine Description:
926 Count the number of seperators in String
927
928 Arguments:
929 String - String to process
930 Seperator - Item to count
931
932 Returns:
933 Number of Seperator in String
934
935 --*/
936 {
937 UINTN Count;
938
939 for (Count = 0; *String != '\0'; String++) {
940 if (*String == Seperator) {
941 Count++;
942 }
943 }
944
945 return Count;
946 }
947
948
949 EFI_STATUS
950 AddModHandle (
951 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
952 IN VOID *ModHandle
953 )
954 /*++
955
956 Routine Description:
957 Store the ModHandle in an array indexed by the Pdb File name.
958 The ModHandle is needed to unload the image.
959
960 Arguments:
961 ImageContext - Input data returned from PE Laoder Library. Used to find the
962 .PDB file name of the PE Image.
963 ModHandle - Returned from LoadLibraryEx() and stored for call to
964 FreeLibrary().
965
966 Returns:
967 EFI_SUCCESS - ModHandle was stored.
968
969 --*/
970 {
971 UINTN Index;
972 PDB_NAME_TO_MOD_HANDLE *Array;
973 UINTN PreviousSize;
974
975
976 Array = mPdbNameModHandleArray;
977 for (Index = 0; Index < mPdbNameModHandleArraySize; Index++, Array++) {
978 if (Array->PdbPointer == NULL) {
979 //
980 // Make a copy of the stirng and store the ModHandle
981 //
982 Array->PdbPointer = malloc (strlen (ImageContext->PdbPointer) + 1);
983 ASSERT (Array->PdbPointer != NULL);
984
985 strcpy (Array->PdbPointer, ImageContext->PdbPointer);
986 Array->ModHandle = ModHandle;
987 return EFI_SUCCESS;
988 }
989 }
990
991 //
992 // No free space in mPdbNameModHandleArray so grow it by
993 // MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE entires. realloc will
994 // copy the old values to the new locaiton. But it does
995 // not zero the new memory area.
996 //
997 PreviousSize = mPdbNameModHandleArraySize * sizeof (PDB_NAME_TO_MOD_HANDLE);
998 mPdbNameModHandleArraySize += MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE;
999
1000 mPdbNameModHandleArray = realloc (mPdbNameModHandleArray, mPdbNameModHandleArraySize * sizeof (PDB_NAME_TO_MOD_HANDLE));
1001 if (mPdbNameModHandleArray == NULL) {
1002 ASSERT (FALSE);
1003 return EFI_OUT_OF_RESOURCES;
1004 }
1005
1006 memset (mPdbNameModHandleArray + PreviousSize, 0, MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (PDB_NAME_TO_MOD_HANDLE));
1007
1008 return AddModHandle (ImageContext, ModHandle);
1009 }
1010
1011
1012 VOID *
1013 RemoveModeHandle (
1014 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1015 )
1016 /*++
1017
1018 Routine Description:
1019 Return the ModHandle and delete the entry in the array.
1020
1021 Arguments:
1022 ImageContext - Input data returned from PE Laoder Library. Used to find the
1023 .PDB file name of the PE Image.
1024
1025 Returns:
1026 ModHandle - ModHandle assoicated with ImageContext is returned
1027 NULL - No ModHandle associated with ImageContext
1028
1029 --*/
1030 {
1031 UINTN Index;
1032 PDB_NAME_TO_MOD_HANDLE *Array;
1033
1034 if (ImageContext->PdbPointer == NULL) {
1035 //
1036 // If no PDB pointer there is no ModHandle so return NULL
1037 //
1038 return NULL;
1039 }
1040
1041 Array = mPdbNameModHandleArray;
1042 for (Index = 0; Index < mPdbNameModHandleArraySize; Index++, Array++) {
1043 if ((Array->PdbPointer != NULL) && (strcmp(Array->PdbPointer, ImageContext->PdbPointer) == 0)) {
1044 //
1045 // If you find a match return it and delete the entry
1046 //
1047 free (Array->PdbPointer);
1048 Array->PdbPointer = NULL;
1049 return Array->ModHandle;
1050 }
1051 }
1052
1053 return NULL;
1054 }
1055
1056
1057
1058 EFI_STATUS
1059 EFIAPI
1060 SecNt32PeCoffGetImageInfo (
1061 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
1062 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1063 )
1064 {
1065 EFI_STATUS Status;
1066
1067 Status = PeCoffLoaderGetImageInfo (ImageContext);
1068 if (EFI_ERROR (Status)) {
1069 return Status;
1070 }
1071
1072 switch (ImageContext->ImageType) {
1073
1074 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
1075 ImageContext->ImageCodeMemoryType = EfiLoaderCode;
1076 ImageContext->ImageDataMemoryType = EfiLoaderData;
1077 break;
1078
1079 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
1080 ImageContext->ImageCodeMemoryType = EfiBootServicesCode;
1081 ImageContext->ImageDataMemoryType = EfiBootServicesData;
1082 break;
1083
1084 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
1085 case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
1086 ImageContext->ImageCodeMemoryType = EfiRuntimeServicesCode;
1087 ImageContext->ImageDataMemoryType = EfiRuntimeServicesData;
1088 break;
1089
1090 default:
1091 ImageContext->ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM;
1092 return RETURN_UNSUPPORTED;
1093 }
1094
1095 return Status;
1096 }
1097
1098 EFI_STATUS
1099 EFIAPI
1100 SecNt32PeCoffLoadImage (
1101 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
1102 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1103 )
1104 {
1105 EFI_STATUS Status;
1106
1107 Status = PeCoffLoaderLoadImage (ImageContext);
1108 return Status;
1109 }
1110
1111 EFI_STATUS
1112 EFIAPI
1113 SecNt32PeCoffRelocateImage (
1114 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
1115 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1116 )
1117 {
1118 EFI_STATUS Status;
1119 VOID *DllEntryPoint;
1120 CHAR16 *DllFileName;
1121 HMODULE Library;
1122 UINTN Index;
1123
1124
1125 Status = PeCoffLoaderRelocateImage (ImageContext);
1126 if (EFI_ERROR (Status)) {
1127 //
1128 // We could not relocated the image in memory properly
1129 //
1130 return Status;
1131 }
1132
1133 //
1134 // If we load our own PE COFF images the Windows debugger can not source
1135 // level debug our code. If a valid PDB pointer exists usw it to load
1136 // the *.dll file as a library using Windows* APIs. This allows
1137 // source level debug. The image is still loaded and reloaced
1138 // in the Framework memory space like on a real system (by the code above),
1139 // but the entry point points into the DLL loaded by the code bellow.
1140 //
1141
1142 DllEntryPoint = NULL;
1143
1144 //
1145 // Load the DLL if it's not an EBC image.
1146 //
1147 if ((ImageContext->PdbPointer != NULL) &&
1148 (ImageContext->Machine != EFI_IMAGE_MACHINE_EBC)) {
1149 //
1150 // Convert filename from ASCII to Unicode
1151 //
1152 DllFileName = AsciiToUnicode (ImageContext->PdbPointer, &Index);
1153
1154 //
1155 // Check that we have a valid filename
1156 //
1157 if (Index < 5 || DllFileName[Index - 4] != '.') {
1158 free (DllFileName);
1159
1160 //
1161 // Never return an error if PeCoffLoaderRelocateImage() succeeded.
1162 // The image will run, but we just can't source level debug. If we
1163 // return an error the image will not run.
1164 //
1165 return EFI_SUCCESS;
1166 }
1167 //
1168 // Replace .PDB with .DLL on the filename
1169 //
1170 DllFileName[Index - 3] = 'D';
1171 DllFileName[Index - 2] = 'L';
1172 DllFileName[Index - 1] = 'L';
1173
1174 //
1175 // Load the .DLL file into the user process's address space for source
1176 // level debug
1177 //
1178 Library = LoadLibraryEx (DllFileName, NULL, DONT_RESOLVE_DLL_REFERENCES);
1179 if (Library != NULL) {
1180 //
1181 // InitializeDriver is the entry point we put in all our EFI DLL's. The
1182 // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() supresses the
1183 // normal DLL entry point of DllMain, and prevents other modules that are
1184 // referenced in side the DllFileName from being loaded. There is no error
1185 // checking as the we can point to the PE32 image loaded by Tiano. This
1186 // step is only needed for source level debuging
1187 //
1188 DllEntryPoint = (VOID *) (UINTN) GetProcAddress (Library, "InitializeDriver");
1189
1190 }
1191
1192 if ((Library != NULL) && (DllEntryPoint != NULL)) {
1193 AddModHandle (ImageContext, Library);
1194 ImageContext->EntryPoint = (EFI_PHYSICAL_ADDRESS) (UINTN) DllEntryPoint;
1195 wprintf (L"LoadLibraryEx (%s,\n NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);
1196 } else {
1197 wprintf (L"WARNING: No source level debug %s. \n", DllFileName);
1198 }
1199
1200 free (DllFileName);
1201 }
1202
1203 //
1204 // Never return an error if PeCoffLoaderRelocateImage() succeeded.
1205 // The image will run, but we just can't source level debug. If we
1206 // return an error the image will not run.
1207 //
1208 return EFI_SUCCESS;
1209 }
1210
1211
1212 EFI_STATUS
1213 EFIAPI
1214 SecNt32PeCoffUnloadimage (
1215 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
1216 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1217 )
1218 {
1219 VOID *ModHandle;
1220
1221 ModHandle = RemoveModeHandle (ImageContext);
1222 if (ModHandle != NULL) {
1223 FreeLibrary (ModHandle);
1224 }
1225 return EFI_SUCCESS;
1226 }
1227
1228 VOID
1229 _ModuleEntryPoint (
1230 VOID
1231 )
1232 {
1233 }
1234
1235 #pragma warning(default : 4996)