2 WinNt emulator of pre-SEC phase. It's really a Win32 application, but this is
3 Ok since all the other modules for NT32 are NOT Win32 applications.
5 This program gets NT32 PCD setting and figures out what the memory layout
6 will be, how may FD's will be loaded and also what the boot mode is.
8 This code produces 128 K of temporary memory for the SEC stack by directly
9 allocate memory space with ReadWrite and Execute attribute.
11 Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.<BR>
12 (C) Copyright 2016-2020 Hewlett Packard Enterprise Development LP<BR>
13 SPDX-License-Identifier: BSD-2-Clause-Patent
18 #ifndef SE_TIME_ZONE_NAME
19 #define SE_TIME_ZONE_NAME TEXT("SeTimeZonePrivilege")
23 // The growth size for array of module handle entries
25 #define MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE 0x100
28 // Module handle entry structure
33 } PDB_NAME_TO_MOD_HANDLE
;
36 // An Array to hold the module handles
38 PDB_NAME_TO_MOD_HANDLE
*mPdbNameModHandleArray
= NULL
;
39 UINTN mPdbNameModHandleArraySize
= 0;
42 // Default information about where the FD is located.
43 // This array gets filled in with information from PcdWinNtFirmwareVolume
44 // The number of array elements is allocated base on parsing
45 // PcdWinNtFirmwareVolume and the memory is never freed.
47 UINTN gFdInfoCount
= 0;
51 // Array that supports separate memory ranges.
52 // The memory ranges are set by PcdWinNtMemorySizeForSecMain.
53 // The number of array elements is allocated base on parsing
54 // PcdWinNtMemorySizeForSecMain value and the memory is never freed.
56 UINTN gSystemMemoryCount
= 0;
57 NT_SYSTEM_MEMORY
*gSystemMemory
;
59 BASE_LIBRARY_JUMP_BUFFER mResetJumpBuffer
;
60 CHAR8
*mResetTypeStr
[] = {
64 "EfiResetPlatformSpecific"
70 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
71 It allows discontinuous memory regions to be supported by the emulator.
72 It uses gSystemMemory[] and gSystemMemoryCount that were created by
73 parsing the host environment variable EFI_MEMORY_SIZE.
74 The size comes from the varaible and the address comes from the call to
78 Index - Which memory region to use
79 MemoryBase - Return Base address of memory region
80 MemorySize - Return size in bytes of the memory region
83 EFI_SUCCESS - If memory region was mapped
84 EFI_UNSUPPORTED - If Index is not supported
90 OUT EFI_PHYSICAL_ADDRESS
*MemoryBase
,
91 OUT UINT64
*MemorySize
94 if (Index
>= gSystemMemoryCount
) {
95 return EFI_UNSUPPORTED
;
98 *MemoryBase
= gSystemMemory
[Index
].Memory
;
99 *MemorySize
= gSystemMemory
[Index
].Size
;
107 Return the FD Size and base address. Since the FD is loaded from a
108 file into host memory only the SEC will know its address.
111 Index - Which FD, starts at zero.
112 FdSize - Size of the FD in bytes
113 FdBase - Start address of the FD. Assume it points to an FV Header
114 FixUp - Difference between actual FD address and build address
117 EFI_SUCCESS - Return the Base address and size of the FV
118 EFI_UNSUPPORTED - Index does nto map to an FD in the system
124 IN OUT EFI_PHYSICAL_ADDRESS
*FdBase
,
125 IN OUT UINT64
*FdSize
,
126 IN OUT EFI_PHYSICAL_ADDRESS
*FixUp
129 if (Index
>= gFdInfoCount
) {
130 return EFI_UNSUPPORTED
;
133 *FdBase
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)gFdInfo
[Index
].Address
;
134 *FdSize
= (UINT64
)gFdInfo
[Index
].Size
;
137 if ((*FdBase
== 0) && (*FdSize
== 0)) {
138 return EFI_UNSUPPORTED
;
143 // FD 0 has XIP code and well known PCD values
144 // If the memory buffer could not be allocated at the FD build address
145 // the Fixup is the difference.
147 *FixUp
= *FdBase
- PcdGet64 (PcdEmuFdBaseAddress
);
156 Since the SEC is the only Unix program in stack it must export
157 an interface to do POSIX calls. gUnix is initialized in UnixThunk.c.
160 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
161 InterfaceBase - Address of the gUnix global
164 EFI_SUCCESS - Data returned
172 return &gEmuThunkProtocol
;
175 EMU_THUNK_PPI mSecEmuThunkPpi
= {
189 CHAR8 Buffer
[0x1000];
191 va_start (Marker
, Format
);
193 _vsnprintf (Buffer
, sizeof (Buffer
), Format
, Marker
);
197 CharCount
= strlen (Buffer
);
199 GetStdHandle (STD_OUTPUT_HANDLE
),
208 Resets the entire platform.
210 @param[in] ResetType The type of reset to perform.
211 @param[in] ResetStatus The status code for the reset.
212 @param[in] DataSize The size, in bytes, of ResetData.
213 @param[in] ResetData For a ResetType of EfiResetCold, EfiResetWarm, or EfiResetShutdown
214 the data buffer starts with a Null-terminated string, optionally
215 followed by additional binary data. The string is a description
216 that the caller may use to further indicate the reason for the
223 IN EFI_RESET_TYPE ResetType
,
224 IN EFI_STATUS ResetStatus
,
226 IN VOID
*ResetData OPTIONAL
229 ASSERT (ResetType
<= EfiResetPlatformSpecific
);
230 SecPrint (" Emu ResetSystem is called: ResetType = %s\n", mResetTypeStr
[ResetType
]);
232 if (ResetType
== EfiResetShutdown
) {
236 // Jump back to SetJump with jump code = ResetType + 1
238 LongJump (&mResetJumpBuffer
, ResetType
+ 1);
242 EFI_PEI_RESET2_PPI mEmuReset2Ppi
= {
249 Check to see if an address range is in the EFI GCD memory map.
251 This is all of GCD for system memory passed to DXE Core. FV
252 mapping and other device mapped into system memory are not
253 inlcuded in the check.
256 Index - Which memory region to use
257 MemoryBase - Return Base address of memory region
258 MemorySize - Return size in bytes of the memory region
261 TRUE - Address is in the EFI GCD memory map
262 FALSE - Address is NOT in memory map
266 EfiSystemMemoryRange (
267 IN VOID
*MemoryAddress
271 EFI_PHYSICAL_ADDRESS MemoryBase
;
273 MemoryBase
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)MemoryAddress
;
274 for (Index
= 0; Index
< gSystemMemoryCount
; Index
++) {
275 if ((MemoryBase
>= gSystemMemory
[Index
].Memory
) &&
276 (MemoryBase
< (gSystemMemory
[Index
].Memory
+ gSystemMemory
[Index
].Size
)))
287 IN CHAR16
*FileName OPTIONAL
,
289 IN DWORD CreationDisposition
,
290 IN OUT VOID
**BaseAddress
,
297 Opens and memory maps a file using WinNt services. If *BaseAddress is non zero
298 the process will try and allocate the memory starting at BaseAddress.
301 FileName - The name of the file to open and map
302 MapSize - The amount of the file to map in bytes
303 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
304 memory emulation, and exiting files for firmware volume emulation
305 BaseAddress - The base address of the mapped file in the user address space.
306 If *BaseAddress is 0, the new memory region is used.
307 If *BaseAddress is not 0, the request memory region is used for
308 the mapping of the file into the process space.
309 Length - The size of the mapped region in bytes
312 EFI_SUCCESS - The file was opened and mapped.
313 EFI_NOT_FOUND - FileName was not found in the current directory
314 EFI_DEVICE_ERROR - An error occurred attempting to map the opened file
320 VOID
*VirtualAddress
;
324 // Use Win API to open/create a file
326 NtFileHandle
= INVALID_HANDLE_VALUE
;
327 if (FileName
!= NULL
) {
328 NtFileHandle
= CreateFile (
330 GENERIC_READ
| GENERIC_WRITE
| GENERIC_EXECUTE
,
334 FILE_ATTRIBUTE_NORMAL
,
337 if (NtFileHandle
== INVALID_HANDLE_VALUE
) {
338 return EFI_NOT_FOUND
;
343 // Map the open file into a memory range
345 NtMapHandle
= CreateFileMapping (
348 PAGE_EXECUTE_READWRITE
,
353 if (NtMapHandle
== NULL
) {
354 return EFI_DEVICE_ERROR
;
358 // Get the virtual address (address in the emulator) of the mapped file
360 VirtualAddress
= MapViewOfFileEx (
362 FILE_MAP_EXECUTE
| FILE_MAP_ALL_ACCESS
,
368 if (VirtualAddress
== NULL
) {
369 return EFI_DEVICE_ERROR
;
374 // Seek to the end of the file to figure out the true file size.
376 FileSize
= SetFilePointer (
382 if (FileSize
== -1) {
383 return EFI_DEVICE_ERROR
;
391 *BaseAddress
= VirtualAddress
;
407 Main entry point to SEC for WinNt. This is a Windows program
410 Argc - Number of command line arguments
411 Argv - Array of command line argument strings
412 Envp - Array of environment variable strings
422 TOKEN_PRIVILEGES TokenPrivileges
;
424 UINT32 TemporaryRamSize
;
431 EFI_PEI_FILE_HANDLE FileHandle
;
433 CHAR16
*MemorySizeStr
;
434 CHAR16
*FirmwareVolumesStr
;
435 UINTN ProcessAffinityMask
;
436 UINTN SystemAffinityMask
;
441 // Enable the privilege so that RTC driver can successfully run SetTime()
443 OpenProcessToken (GetCurrentProcess (), TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY
, &Token
);
444 if (LookupPrivilegeValue (NULL
, SE_TIME_ZONE_NAME
, &TokenPrivileges
.Privileges
[0].Luid
)) {
445 TokenPrivileges
.PrivilegeCount
= 1;
446 TokenPrivileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
447 AdjustTokenPrivileges (Token
, FALSE
, &TokenPrivileges
, 0, (PTOKEN_PRIVILEGES
)NULL
, 0);
450 MemorySizeStr
= (CHAR16
*)PcdGetPtr (PcdEmuMemorySize
);
451 FirmwareVolumesStr
= (CHAR16
*)PcdGetPtr (PcdEmuFirmwareVolume
);
453 SecPrint ("\n\rEDK II WIN Host Emulation Environment from http://www.tianocore.org/edk2/\n\r");
456 // Determine the first thread available to this process.
458 if (GetProcessAffinityMask (GetCurrentProcess (), &ProcessAffinityMask
, &SystemAffinityMask
)) {
459 LowBit
= (INT32
)LowBitSet32 ((UINT32
)ProcessAffinityMask
);
462 // Force the system to bind the process to a single thread to work
463 // around odd semaphore type crashes.
465 SetProcessAffinityMask (GetCurrentProcess (), (INTN
)(BIT0
<< LowBit
));
470 // Make some Windows calls to Set the process to the highest priority in the
471 // idle class. We need this to have good performance.
473 SetPriorityClass (GetCurrentProcess (), IDLE_PRIORITY_CLASS
);
474 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST
);
476 SecInitializeThunk ();
478 // PPIs pased into PEI_CORE
480 AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI
, &gEmuThunkPpiGuid
, &mSecEmuThunkPpi
);
481 AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI
, &gEfiPeiReset2PpiGuid
, &mEmuReset2Ppi
);
484 // Emulator Bus Driver Thunks
486 AddThunkProtocol (&mWinNtWndThunkIo
, (CHAR16
*)PcdGetPtr (PcdEmuGop
), TRUE
);
487 AddThunkProtocol (&mWinNtFileSystemThunkIo
, (CHAR16
*)PcdGetPtr (PcdEmuFileSystem
), TRUE
);
488 AddThunkProtocol (&mWinNtBlockIoThunkIo
, (CHAR16
*)PcdGetPtr (PcdEmuVirtualDisk
), TRUE
);
489 AddThunkProtocol (&mWinNtSnpThunkIo
, (CHAR16
*)PcdGetPtr (PcdEmuNetworkInterface
), TRUE
);
492 // Allocate space for gSystemMemory Array
494 gSystemMemoryCount
= CountSeparatorsInString (MemorySizeStr
, '!') + 1;
495 gSystemMemory
= calloc (gSystemMemoryCount
, sizeof (NT_SYSTEM_MEMORY
));
496 if (gSystemMemory
== NULL
) {
497 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n\r", MemorySizeStr
);
502 // Allocate "physical" memory space for emulator. It will be reported out later throuth MemoryAutoScan()
504 for (Index
= 0, Done
= FALSE
; !Done
; Index
++) {
505 ASSERT (Index
< gSystemMemoryCount
);
506 gSystemMemory
[Index
].Size
= ((UINT64
)_wtoi (MemorySizeStr
)) * ((UINT64
)SIZE_1MB
);
507 gSystemMemory
[Index
].Memory
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)VirtualAlloc (NULL
, (SIZE_T
)(gSystemMemory
[Index
].Size
), MEM_COMMIT
, PAGE_EXECUTE_READWRITE
);
508 if (gSystemMemory
[Index
].Memory
== 0) {
509 return EFI_OUT_OF_RESOURCES
;
513 // Find the next region
515 for (Index1
= 0; MemorySizeStr
[Index1
] != '!' && MemorySizeStr
[Index1
] != 0; Index1
++) {
518 if (MemorySizeStr
[Index1
] == 0) {
522 MemorySizeStr
= MemorySizeStr
+ Index1
+ 1;
526 // Allocate space for gSystemMemory Array
528 gFdInfoCount
= CountSeparatorsInString (FirmwareVolumesStr
, '!') + 1;
529 gFdInfo
= calloc (gFdInfoCount
, sizeof (NT_FD_INFO
));
530 if (gFdInfo
== NULL
) {
531 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n\r", FirmwareVolumesStr
);
538 SecPrint (" BootMode 0x%02x\n\r", PcdGet32 (PcdEmuBootMode
));
541 // Allocate 128K memory to emulate temp memory for PEI.
542 // on a real platform this would be SRAM, or using the cache as RAM.
543 // Set TemporaryRam to zero so WinNtOpenFile will allocate a new mapping
545 TemporaryRamSize
= TEMPORARY_RAM_SIZE
;
546 TemporaryRam
= VirtualAlloc (NULL
, (SIZE_T
)(TemporaryRamSize
), MEM_COMMIT
, PAGE_EXECUTE_READWRITE
);
547 if (TemporaryRam
== NULL
) {
548 SecPrint ("ERROR : Can not allocate enough space for SecStack\n\r");
553 // If enabled use the magic page to communicate between modules
554 // This replaces the PI PeiServicesTable pointer mechanism that
555 // deos not work in the emulator. It also allows the removal of
556 // writable globals from SEC, PEI_CORE (libraries), PEIMs
558 EmuMagicPage
= (VOID
*)(UINTN
)(FixedPcdGet64 (PcdPeiServicesTablePage
) & MAX_UINTN
);
559 if (EmuMagicPage
!= NULL
) {
561 Status
= WinNtOpenFile (
568 if (EFI_ERROR (Status
)) {
569 SecPrint ("ERROR : Could not allocate PeiServicesTablePage @ %p\n\r", EmuMagicPage
);
570 return EFI_DEVICE_ERROR
;
575 // Open All the firmware volumes and remember the info in the gFdInfo global
576 // Meanwhile, find the SEC Core.
578 FileNamePtr
= AllocateCopyPool (StrSize (FirmwareVolumesStr
), FirmwareVolumesStr
);
579 if (FileNamePtr
== NULL
) {
580 SecPrint ("ERROR : Can not allocate memory for firmware volume string\n\r");
584 for (Done
= FALSE
, Index
= 0, SecFile
= NULL
; !Done
; Index
++) {
585 FileName
= FileNamePtr
;
586 for (Index1
= 0; (FileNamePtr
[Index1
] != '!') && (FileNamePtr
[Index1
] != 0); Index1
++) {
589 if (FileNamePtr
[Index1
] == 0) {
592 FileNamePtr
[Index1
] = '\0';
593 FileNamePtr
= &FileNamePtr
[Index1
+ 1];
597 // Open the FD and remember where it got mapped into our processes address space
599 Status
= WinNtOpenFile (
603 &gFdInfo
[Index
].Address
,
606 if (EFI_ERROR (Status
)) {
607 SecPrint ("ERROR : Can not open Firmware Device File %S (0x%X). Exiting.\n\r", FileName
, Status
);
611 SecPrint (" FD loaded from %S", FileName
);
613 if (SecFile
== NULL
) {
615 // Assume the beginning of the FD is an FV and look for the SEC Core.
616 // Load the first one we find.
619 Status
= PeiServicesFfsFindNextFile (
620 EFI_FV_FILETYPE_SECURITY_CORE
,
621 (EFI_PEI_FV_HANDLE
)gFdInfo
[Index
].Address
,
624 if (!EFI_ERROR (Status
)) {
625 Status
= PeiServicesFfsFindSectionData (EFI_SECTION_PE32
, FileHandle
, &SecFile
);
626 if (!EFI_ERROR (Status
)) {
627 SecPrint (" contains SEC Core");
635 ResetJumpCode
= SetJump (&mResetJumpBuffer
);
638 // Do not clear memory content for warm reset.
640 if (ResetJumpCode
!= EfiResetWarm
+ 1) {
641 SecPrint (" OS Emulator clearing temp RAM and physical RAM (to be discovered later)......\n\r");
642 SetMem32 (TemporaryRam
, TemporaryRamSize
, PcdGet32 (PcdInitValueInTempStack
));
643 for (Index
= 0; Index
< gSystemMemoryCount
; Index
++) {
644 SetMem32 ((VOID
*)(UINTN
)gSystemMemory
[Index
].Memory
, (UINTN
)gSystemMemory
[Index
].Size
, PcdGet32 (PcdInitValueInTempStack
));
649 " OS Emulator passing in %u KB of temp RAM at 0x%08lx to SEC\n\r",
650 TemporaryRamSize
/ SIZE_1KB
,
654 // Hand off to SEC Core
656 SecLoadSecCore ((UINTN
)TemporaryRam
, TemporaryRamSize
, gFdInfo
[0].Address
, gFdInfo
[0].Size
, SecFile
);
659 // If we get here, then the SEC Core returned. This is an error as SEC should
660 // always hand off to PEI Core and then on to DXE Core.
662 SecPrint ("ERROR : SEC returned\n\r");
668 IN UINTN TemporaryRam
,
669 IN UINTN TemporaryRamSize
,
670 IN VOID
*BootFirmwareVolumeBase
,
671 IN UINTN BootFirmwareVolumeSize
,
672 IN VOID
*SecCorePe32File
678 This is the service to load the SEC Core from the Firmware Volume
681 TemporaryRam - Memory to use for SEC.
682 TemporaryRamSize - Size of Memory to use for SEC
683 BootFirmwareVolumeBase - Start of the Boot FV
684 SecCorePe32File - SEC Core PE32
687 Success means control is transferred and thus we should never return
693 VOID
*SecCoreEntryPoint
;
694 EFI_SEC_PEI_HAND_OFF
*SecCoreData
;
698 // Compute Top Of Memory for Stack and PEI Core Allocations
700 SecStackSize
= TemporaryRamSize
>> 1;
703 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
706 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
709 // |-----------| <---- TemporaryRamBase
711 TopOfStack
= (VOID
*)(TemporaryRam
+ SecStackSize
);
714 // Reservet space for storing PeiCore's parament in stack.
716 TopOfStack
= (VOID
*)((UINTN
)TopOfStack
- sizeof (EFI_SEC_PEI_HAND_OFF
) - CPU_STACK_ALIGNMENT
);
717 TopOfStack
= ALIGN_POINTER (TopOfStack
, CPU_STACK_ALIGNMENT
);
720 // Bind this information into the SEC hand-off state
722 SecCoreData
= (EFI_SEC_PEI_HAND_OFF
*)(UINTN
)TopOfStack
;
723 SecCoreData
->DataSize
= sizeof (EFI_SEC_PEI_HAND_OFF
);
724 SecCoreData
->BootFirmwareVolumeBase
= BootFirmwareVolumeBase
;
725 SecCoreData
->BootFirmwareVolumeSize
= BootFirmwareVolumeSize
;
726 SecCoreData
->TemporaryRamBase
= (VOID
*)TemporaryRam
;
727 SecCoreData
->TemporaryRamSize
= TemporaryRamSize
;
728 SecCoreData
->StackBase
= SecCoreData
->TemporaryRamBase
;
729 SecCoreData
->StackSize
= SecStackSize
;
730 SecCoreData
->PeiTemporaryRamBase
= (VOID
*)((UINTN
)SecCoreData
->TemporaryRamBase
+ SecStackSize
);
731 SecCoreData
->PeiTemporaryRamSize
= TemporaryRamSize
- SecStackSize
;
734 // Load the PEI Core from a Firmware Volume
736 Status
= SecPeCoffGetEntryPoint (
740 if (EFI_ERROR (Status
)) {
745 // Transfer control to the SEC Core
748 (SWITCH_STACK_ENTRY_POINT
)(UINTN
)SecCoreEntryPoint
,
754 // If we get here, then the SEC Core returned. This is an error
761 SecPeCoffGetEntryPoint (
763 IN OUT VOID
**EntryPoint
767 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
769 ZeroMem (&ImageContext
, sizeof (ImageContext
));
770 ImageContext
.Handle
= Pe32Data
;
772 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
)SecImageRead
;
774 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
775 if (EFI_ERROR (Status
)) {
780 // XIP for SEC and PEI_CORE
782 ImageContext
.ImageAddress
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)Pe32Data
;
784 Status
= PeCoffLoaderLoadImage (&ImageContext
);
785 if (EFI_ERROR (Status
)) {
789 Status
= PeCoffLoaderRelocateImage (&ImageContext
);
790 if (EFI_ERROR (Status
)) {
794 *EntryPoint
= (VOID
*)(UINTN
)ImageContext
.EntryPoint
;
804 IN OUT UINTN
*ReadSize
,
811 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
814 FileHandle - The handle to the PE/COFF file
815 FileOffset - The offset, in bytes, into the file to read
816 ReadSize - The number of bytes to read from the file starting at FileOffset
817 Buffer - A pointer to the buffer to read the data into.
820 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
828 Destination8
= Buffer
;
829 Source8
= (CHAR8
*)((UINTN
)FileHandle
+ FileOffset
);
832 *(Destination8
++) = *(Source8
++);
841 IN UINTN
*StrLen OPTIONAL
847 Convert the passed in Ascii string to Unicode.
848 Optionally return the length of the strings.
851 Ascii - Ascii string to convert
852 StrLen - Length of string
855 Pointer to malloc'ed Unicode version of Ascii
863 // Allocate a buffer for unicode string
865 for (Index
= 0; Ascii
[Index
] != '\0'; Index
++) {
868 Unicode
= malloc ((Index
+ 1) * sizeof (CHAR16
));
869 if (Unicode
== NULL
) {
873 for (Index
= 0; Ascii
[Index
] != '\0'; Index
++) {
874 Unicode
[Index
] = (CHAR16
)Ascii
[Index
];
877 Unicode
[Index
] = '\0';
879 if (StrLen
!= NULL
) {
887 CountSeparatorsInString (
888 IN CONST CHAR16
*String
,
895 Count the number of separators in String
898 String - String to process
899 Separator - Item to count
902 Number of Separator in String
908 for (Count
= 0; *String
!= '\0'; String
++) {
909 if (*String
== Separator
) {
918 Store the ModHandle in an array indexed by the Pdb File name.
919 The ModHandle is needed to unload the image.
920 @param ImageContext - Input data returned from PE Laoder Library. Used to find the
921 .PDB file name of the PE Image.
922 @param ModHandle - Returned from LoadLibraryEx() and stored for call to
924 @return return EFI_SUCCESS when ModHandle was stored.
928 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
,
934 PDB_NAME_TO_MOD_HANDLE
*Array
;
936 PDB_NAME_TO_MOD_HANDLE
*TempArray
;
941 // Return EFI_ALREADY_STARTED if this DLL has already been loaded
943 Array
= mPdbNameModHandleArray
;
944 for (Index
= 0; Index
< mPdbNameModHandleArraySize
; Index
++, Array
++) {
945 if ((Array
->PdbPointer
!= NULL
) && (Array
->ModHandle
== ModHandle
)) {
946 return EFI_ALREADY_STARTED
;
950 Array
= mPdbNameModHandleArray
;
951 for (Index
= 0; Index
< mPdbNameModHandleArraySize
; Index
++, Array
++) {
952 if (Array
->PdbPointer
== NULL
) {
954 // Make a copy of the stirng and store the ModHandle
956 Handle
= GetProcessHeap ();
957 Size
= AsciiStrLen (ImageContext
->PdbPointer
) + 1;
958 Array
->PdbPointer
= HeapAlloc (Handle
, HEAP_ZERO_MEMORY
, Size
);
959 ASSERT (Array
->PdbPointer
!= NULL
);
961 AsciiStrCpyS (Array
->PdbPointer
, Size
, ImageContext
->PdbPointer
);
962 Array
->ModHandle
= ModHandle
;
968 // No free space in mPdbNameModHandleArray so grow it by
969 // MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE entires.
971 PreviousSize
= mPdbNameModHandleArraySize
* sizeof (PDB_NAME_TO_MOD_HANDLE
);
972 mPdbNameModHandleArraySize
+= MAX_PDB_NAME_TO_MOD_HANDLE_ARRAY_SIZE
;
974 // re-allocate a new buffer and copy the old values to the new locaiton.
976 TempArray
= HeapAlloc (
979 mPdbNameModHandleArraySize
* sizeof (PDB_NAME_TO_MOD_HANDLE
)
982 CopyMem ((VOID
*)(UINTN
)TempArray
, (VOID
*)(UINTN
)mPdbNameModHandleArray
, PreviousSize
);
984 HeapFree (GetProcessHeap (), 0, mPdbNameModHandleArray
);
986 mPdbNameModHandleArray
= TempArray
;
987 if (mPdbNameModHandleArray
== NULL
) {
989 return EFI_OUT_OF_RESOURCES
;
992 return AddModHandle (ImageContext
, ModHandle
);
996 Return the ModHandle and delete the entry in the array.
997 @param ImageContext - Input data returned from PE Laoder Library. Used to find the
998 .PDB file name of the PE Image.
1000 ModHandle - ModHandle assoicated with ImageContext is returned
1001 NULL - No ModHandle associated with ImageContext
1005 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
1009 PDB_NAME_TO_MOD_HANDLE
*Array
;
1011 if (ImageContext
->PdbPointer
== NULL
) {
1013 // If no PDB pointer there is no ModHandle so return NULL
1018 Array
= mPdbNameModHandleArray
;
1019 for (Index
= 0; Index
< mPdbNameModHandleArraySize
; Index
++, Array
++) {
1020 if ((Array
->PdbPointer
!= NULL
) && (AsciiStrCmp (Array
->PdbPointer
, ImageContext
->PdbPointer
) == 0)) {
1022 // If you find a match return it and delete the entry
1024 HeapFree (GetProcessHeap (), 0, Array
->PdbPointer
);
1025 Array
->PdbPointer
= NULL
;
1026 return Array
->ModHandle
;
1035 PeCoffLoaderRelocateImageExtraAction (
1036 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
1040 VOID
*DllEntryPoint
;
1041 CHAR16
*DllFileName
;
1045 ASSERT (ImageContext
!= NULL
);
1047 // If we load our own PE COFF images the Windows debugger can not source
1048 // level debug our code. If a valid PDB pointer exists use it to load
1049 // the *.dll file as a library using Windows* APIs. This allows
1050 // source level debug. The image is still loaded and relocated
1051 // in the Framework memory space like on a real system (by the code above),
1052 // but the entry point points into the DLL loaded by the code below.
1055 DllEntryPoint
= NULL
;
1058 // Load the DLL if it's not an EBC image.
1060 if ((ImageContext
->PdbPointer
!= NULL
) &&
1061 (ImageContext
->Machine
!= EFI_IMAGE_MACHINE_EBC
))
1064 // Convert filename from ASCII to Unicode
1066 DllFileName
= AsciiToUnicode (ImageContext
->PdbPointer
, &Index
);
1069 // Check that we have a valid filename
1071 if ((Index
< 5) || (DllFileName
[Index
- 4] != '.')) {
1075 // Never return an error if PeCoffLoaderRelocateImage() succeeded.
1076 // The image will run, but we just can't source level debug. If we
1077 // return an error the image will not run.
1083 // Replace .PDB with .DLL on the filename
1085 DllFileName
[Index
- 3] = 'D';
1086 DllFileName
[Index
- 2] = 'L';
1087 DllFileName
[Index
- 1] = 'L';
1090 // Load the .DLL file into the user process's address space for source
1093 Library
= LoadLibraryEx (DllFileName
, NULL
, DONT_RESOLVE_DLL_REFERENCES
);
1094 if (Library
!= NULL
) {
1096 // InitializeDriver is the entry point we put in all our EFI DLL's. The
1097 // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() suppresses the
1098 // normal DLL entry point of DllMain, and prevents other modules that are
1099 // referenced in side the DllFileName from being loaded. There is no error
1100 // checking as the we can point to the PE32 image loaded by Tiano. This
1101 // step is only needed for source level debugging
1103 DllEntryPoint
= (VOID
*)(UINTN
)GetProcAddress (Library
, "InitializeDriver");
1106 if ((Library
!= NULL
) && (DllEntryPoint
!= NULL
)) {
1107 Status
= AddModHandle (ImageContext
, Library
);
1108 if (Status
== EFI_ALREADY_STARTED
) {
1110 // If the DLL has already been loaded before, then this instance of the DLL can not be debugged.
1112 ImageContext
->PdbPointer
= NULL
;
1113 SecPrint ("WARNING: DLL already loaded. No source level debug %S.\n\r", DllFileName
);
1116 // This DLL is not already loaded, so source level debugging is supported.
1118 ImageContext
->EntryPoint
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)DllEntryPoint
;
1119 SecPrint ("LoadLibraryEx (\n\r %S,\n\r NULL, DONT_RESOLVE_DLL_REFERENCES)\n\r", DllFileName
);
1122 SecPrint ("WARNING: No source level debug %S. \n\r", DllFileName
);
1131 PeCoffLoaderUnloadImageExtraAction (
1132 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
1137 ASSERT (ImageContext
!= NULL
);
1139 ModHandle
= RemoveModHandle (ImageContext
);
1140 if (ModHandle
!= NULL
) {
1141 FreeLibrary (ModHandle
);
1142 SecPrint ("FreeLibrary (\n\r %s)\n\r", ImageContext
->PdbPointer
);
1144 SecPrint ("WARNING: Unload image without source level debug\n\r");