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