3 Copyright (c) 2006 - 2009 Intel Corporation.
4 Portions copyright (c) 2008-2009 Apple Inc.
5 All rights reserved. This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
18 Unix emulator of SEC phase. It's really a Posix application, but this is
19 Ok since all the other modules for NT32 are NOT Posix applications.
21 This program processes host environment variables and figures out
22 what the memory layout will be, how may FD's will be loaded and also
23 what the boot mode is.
25 The SEC registers a set of services with the SEC core. gPrivateDispatchTable
26 is a list of PPI's produced by the SEC that are availble for usage in PEI.
28 This code produces 128 K of temporary memory for the PEI stack by opening a
29 host file and mapping it directly to memory addresses.
31 The system.cmd script is used to set host environment variables that drive
32 the configuration opitons of the SEC.
38 #include <Ppi/UnixPeiLoadFile.h>
39 #include <Framework/StatusCode.h>
40 #include <Ppi/TemporaryRamSupport.h>
44 #define MAP_ANONYMOUS MAP_ANON
45 char *gGdbWorkingFileName
= NULL
;
53 UNIX_PEI_LOAD_FILE_PPI mSecUnixLoadFilePpi
= { SecUnixPeiLoadFile
};
55 PEI_UNIX_AUTOSCAN_PPI mSecUnixAutoScanPpi
= { SecUnixPeiAutoScan
};
57 PEI_UNIX_THUNK_PPI mSecUnixThunkPpi
= { SecUnixUnixThunkAddress
};
59 EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi
= { SecPeiReportStatusCode
};
61 UNIX_FWH_PPI mSecFwhInformationPpi
= { SecUnixFdAddress
};
63 TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi
= {SecTemporaryRamSupport
};
65 EFI_PEI_PPI_DESCRIPTOR gPrivateDispatchTable
[] = {
67 EFI_PEI_PPI_DESCRIPTOR_PPI
,
68 &gUnixPeiLoadFilePpiGuid
,
72 EFI_PEI_PPI_DESCRIPTOR_PPI
,
73 &gPeiUnixAutoScanPpiGuid
,
77 EFI_PEI_PPI_DESCRIPTOR_PPI
,
78 &gPeiUnixThunkPpiGuid
,
82 EFI_PEI_PPI_DESCRIPTOR_PPI
,
83 &gEfiPeiStatusCodePpiGuid
,
87 EFI_PEI_PPI_DESCRIPTOR_PPI
,
88 &gEfiTemporaryRamSupportPpiGuid
,
89 &mSecTemporaryRamSupportPpi
93 EFI_PEI_PPI_DESCRIPTOR_PPI
| EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST
,
95 &mSecFwhInformationPpi
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 host 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.
107 UINTN gFdInfoCount
= 0;
108 UNIX_FD_INFO
*gFdInfo
;
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.
116 UINTN gSystemMemoryCount
= 0;
117 UNIX_SYSTEM_MEMORY
*gSystemMemory
;
121 UINTN mImageContextModHandleArraySize
= 0;
122 IMAGE_CONTEXT_TO_MOD_HANDLE
*mImageContextModHandleArray
= NULL
;
128 UINT32 TemporaryMemoryBase
,
129 UINT32 PermenentMemoryBase
132 EFI_PHYSICAL_ADDRESS
*
142 IN OUT EFI_PHYSICAL_ADDRESS
*BaseAddress
,
147 SecNt32PeCoffRelocateImage (
148 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
161 Main entry point to SEC for Unix. This is a unix program
164 Argc - Number of command line arguments
165 Argv - Array of command line argument strings
166 Envp - Array of environmemt variable strings
175 EFI_PHYSICAL_ADDRESS InitialStackMemory
;
176 UINT64 InitialStackMemorySize
;
184 CHAR16
*MemorySizeStr
;
185 CHAR16
*FirmwareVolumesStr
;
191 MemorySizeStr
= (CHAR16
*) FixedPcdGetPtr (PcdUnixMemorySizeForSecMain
);
192 FirmwareVolumesStr
= (CHAR16
*) FixedPcdGetPtr (PcdUnixFirmwareVolume
);
194 printf ("\nEDK SEC Main UNIX Emulation Environment from www.TianoCore.org\n");
198 // We can't use dlopen on OS X, so we need a scheme to get symboles into gdb
199 // We need to create a temp file that contains gdb commands so we can load
200 // symbols when we load every PE/COFF image.
202 Index
= strlen (*Argv
);
203 gGdbWorkingFileName
= malloc (Index
+ strlen(".gdb"));
204 strcpy (gGdbWorkingFileName
, *Argv
);
205 strcat (gGdbWorkingFileName
, ".gdb");
210 // Allocate space for gSystemMemory Array
212 gSystemMemoryCount
= CountSeperatorsInString (MemorySizeStr
, '!') + 1;
213 gSystemMemory
= calloc (gSystemMemoryCount
, sizeof (UNIX_SYSTEM_MEMORY
));
214 if (gSystemMemory
== NULL
) {
215 printf ("ERROR : Can not allocate memory for system. Exiting.\n");
219 // Allocate space for gSystemMemory Array
221 gFdInfoCount
= CountSeperatorsInString (FirmwareVolumesStr
, '!') + 1;
222 gFdInfo
= calloc (gFdInfoCount
, sizeof (UNIX_FD_INFO
));
223 if (gFdInfo
== NULL
) {
224 printf ("ERROR : Can not allocate memory for fd info. Exiting.\n");
228 // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)
230 printf (" BootMode 0x%02x\n", (unsigned int)FixedPcdGet32 (PcdUnixBootMode
));
233 // Open up a 128K file to emulate temp memory for PEI.
234 // on a real platform this would be SRAM, or using the cache as RAM.
235 // Set InitialStackMemory to zero so UnixOpenFile will allocate a new mapping
237 InitialStackMemorySize
= STACK_SIZE
;
238 InitialStackMemory
= (UINTN
)MapMemory(0,
239 (UINT32
) InitialStackMemorySize
,
240 PROT_READ
| PROT_WRITE
,
241 MAP_ANONYMOUS
| MAP_PRIVATE
);
242 if (InitialStackMemory
== 0) {
243 printf ("ERROR : Can not open SecStack Exiting\n");
247 printf (" SEC passing in %u KB of temp RAM at 0x%08lx to PEI\n",
248 (unsigned int)(InitialStackMemorySize
/ 1024),
249 (unsigned long)InitialStackMemory
);
251 for (StackPointer
= (UINTN
*) (UINTN
) InitialStackMemory
;
252 StackPointer
< (UINTN
*)(UINTN
)((UINTN
) InitialStackMemory
+ (UINT64
) InitialStackMemorySize
);
254 *StackPointer
= 0x5AA55AA5;
258 // Open All the firmware volumes and remember the info in the gFdInfo global
260 FileName
= (CHAR8
*)malloc (StrLen (FirmwareVolumesStr
) + 1);
261 if (FileName
== NULL
) {
262 printf ("ERROR : Can not allocate memory for firmware volume string\n");
267 for (Done
= FALSE
, Index
= 0, PeiIndex
= 0, PeiCoreFile
= NULL
;
268 FirmwareVolumesStr
[Index2
] != 0;
270 for (Index1
= 0; (FirmwareVolumesStr
[Index2
] != '!') && (FirmwareVolumesStr
[Index2
] != 0); Index2
++)
271 FileName
[Index1
++] = FirmwareVolumesStr
[Index2
];
272 if (FirmwareVolumesStr
[Index2
] == '!')
274 FileName
[Index1
] = '\0';
277 // Open the FD and remmeber where it got mapped into our processes address space
281 &gFdInfo
[Index
].Address
,
284 if (EFI_ERROR (Status
)) {
285 printf ("ERROR : Can not open Firmware Device File %s (%x). Exiting.\n", FileName
, (unsigned int)Status
);
289 printf (" FD loaded from %s at 0x%08lx",
290 FileName
, (unsigned long)gFdInfo
[Index
].Address
);
292 if (PeiCoreFile
== NULL
) {
294 // Assume the beginning of the FD is an FV and look for the PEI Core.
295 // Load the first one we find.
297 Status
= SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER
*) (UINTN
) gFdInfo
[Index
].Address
, &PeiCoreFile
);
298 if (!EFI_ERROR (Status
)) {
300 printf (" contains SEC Core");
307 // Calculate memory regions and store the information in the gSystemMemory
308 // global for later use. The autosizing code will use this data to
309 // map this memory into the SEC process memory space.
316 // Save the size of the memory.
318 while (MemorySizeStr
[Index1
] >= '0' && MemorySizeStr
[Index1
] <= '9') {
319 val
= val
* 10 + MemorySizeStr
[Index1
] - '0';
322 gSystemMemory
[Index
++].Size
= val
* 0x100000;
323 if (MemorySizeStr
[Index1
] == 0)
331 // Hand off to PEI Core
333 SecLoadFromCore ((UINTN
) InitialStackMemory
, (UINTN
) InitialStackMemorySize
, (UINTN
) gFdInfo
[0].Address
, PeiCoreFile
);
336 // If we get here, then the PEI Core returned. This is an error as PEI should
337 // always hand off to DXE.
339 printf ("ERROR : PEI Core returned\n");
343 EFI_PHYSICAL_ADDRESS
*
350 STATIC UINTN base
= 0x40000000;
351 CONST UINTN align
= (1 << 24);
353 BOOLEAN isAligned
= 0;
356 // Try to get an aligned block somewhere in the address space of this
359 while((!isAligned
) && (base
!= 0)) {
360 res
= mmap ((void *)base
, length
, prot
, flags
, fd
, 0);
361 if (res
== MAP_FAILED
) {
364 if ((((UINTN
)res
) & ~(align
-1)) == (UINTN
)res
) {
378 IN OUT EFI_PHYSICAL_ADDRESS
*BaseAddress
,
384 Opens and memory maps a file using Unix services. If BaseAddress is non zero
385 the process will try and allocate the memory starting at BaseAddress.
388 FileName - The name of the file to open and map
389 MapSize - The amount of the file to map in bytes
390 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
391 memory emulation, and exiting files for firmware volume emulation
392 BaseAddress - The base address of the mapped file in the user address space.
393 If passed in as NULL the a new memory region is used.
394 If passed in as non NULL the request memory region is used for
395 the mapping of the file into the process space.
396 Length - The size of the mapped region in bytes
399 EFI_SUCCESS - The file was opened and mapped.
400 EFI_NOT_FOUND - FileName was not found in the current directory
401 EFI_DEVICE_ERROR - An error occured attempting to map the opened file
409 fd
= open (FileName
, O_RDONLY
);
411 return EFI_NOT_FOUND
;
412 FileSize
= lseek (fd
, 0, SEEK_END
);
417 /* Read entry address. */
418 lseek (fd
, FileSize
- 0x20, SEEK_SET
);
419 if (read (fd
, &EntryAddress
, 4) != 4)
422 return EFI_DEVICE_ERROR
;
427 res
= MapMemory(fd
, FileSize
, PROT_READ
| PROT_WRITE
| PROT_EXEC
, MAP_PRIVATE
);
431 if (res
== MAP_FAILED
)
432 return EFI_DEVICE_ERROR
;
434 *Length
= (UINT64
) FileSize
;
435 *BaseAddress
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) res
;
440 #define BYTES_PER_RECORD 512
444 SecPeiReportStatusCode (
445 IN CONST EFI_PEI_SERVICES
**PeiServices
,
446 IN EFI_STATUS_CODE_TYPE CodeType
,
447 IN EFI_STATUS_CODE_VALUE Value
,
449 IN CONST EFI_GUID
*CallerId
,
450 IN CONST EFI_STATUS_CODE_DATA
*Data OPTIONAL
456 This routine produces the ReportStatusCode PEI service. It's passed
457 up to the PEI Core via a PPI. T
459 This code currently uses the UNIX clib printf. This does not work the same way
460 as the EFI Print (), as %t, %g, %s as Unicode are not supported.
463 (see EFI_PEI_REPORT_STATUS_CODE)
466 EFI_SUCCESS - Always return success
469 // TODO: PeiServices - add argument and description to function comment
470 // TODO: CodeType - add argument and description to function comment
471 // TODO: Value - add argument and description to function comment
472 // TODO: Instance - add argument and description to function comment
473 // TODO: CallerId - add argument and description to function comment
474 // TODO: Data - add argument and description to function comment
478 CHAR8 PrintBuffer
[BYTES_PER_RECORD
* 2];
486 } else if (ReportStatusCodeExtractAssertInfo (CodeType
, Value
, Data
, &Filename
, &Description
, &LineNumber
)) {
488 // Processes ASSERT ()
490 printf ("ASSERT %s(%d): %s\n", Filename
, (int)LineNumber
, Description
);
492 } else if (ReportStatusCodeExtractDebugInfo (Data
, &ErrorLevel
, &Marker
, &Format
)) {
494 // Process DEBUG () macro
496 AsciiBSPrint (PrintBuffer
, BYTES_PER_RECORD
, Format
, Marker
);
497 printf (PrintBuffer
);
504 Transfers control to a function starting with a new stack.
506 Transfers control to the function specified by EntryPoint using the new stack
507 specified by NewStack and passing in the parameters specified by Context1 and
508 Context2. Context1 and Context2 are optional and may be NULL. The function
509 EntryPoint must never return.
511 If EntryPoint is NULL, then ASSERT().
512 If NewStack is NULL, then ASSERT().
514 @param EntryPoint A pointer to function to call with the new stack.
515 @param Context1 A pointer to the context to pass into the EntryPoint
517 @param Context2 A pointer to the context to pass into the EntryPoint
519 @param NewStack A pointer to the new stack to use for the EntryPoint
521 @param NewBsp A pointer to the new BSP for the EntryPoint on IPF. It's
522 Reserved on other architectures.
528 IN SWITCH_STACK_ENTRY_POINT EntryPoint
,
529 IN VOID
*Context1
, OPTIONAL
530 IN VOID
*Context2
, OPTIONAL
531 IN VOID
*Context3
, OPTIONAL
535 BASE_LIBRARY_JUMP_BUFFER JumpBuffer
;
537 ASSERT (EntryPoint
!= NULL
);
538 ASSERT (NewStack
!= NULL
);
541 // Stack should be aligned with CPU_STACK_ALIGNMENT
543 ASSERT (((UINTN
)NewStack
& (CPU_STACK_ALIGNMENT
- 1)) == 0);
545 JumpBuffer
.Eip
= (UINTN
)EntryPoint
;
546 JumpBuffer
.Esp
= (UINTN
)NewStack
- sizeof (VOID
*);
547 JumpBuffer
.Esp
-= sizeof (Context1
) + sizeof (Context2
) + sizeof(Context3
);
548 ((VOID
**)JumpBuffer
.Esp
)[1] = Context1
;
549 ((VOID
**)JumpBuffer
.Esp
)[2] = Context2
;
550 ((VOID
**)JumpBuffer
.Esp
)[3] = Context3
;
552 LongJump (&JumpBuffer
, (UINTN
)-1);
556 // InternalSwitchStack () will never return
563 IN UINTN LargestRegion
,
564 IN UINTN LargestRegionSize
,
565 IN UINTN BootFirmwareVolumeBase
,
566 IN VOID
*PeiCorePe32File
571 This is the service to load the PEI Core from the Firmware Volume
574 LargestRegion - Memory to use for PEI.
575 LargestRegionSize - Size of Memory to use for PEI
576 BootFirmwareVolumeBase - Start of the Boot FV
577 PeiCorePe32File - PEI Core PE32
580 Success means control is transfered and thus we should never return
585 EFI_PHYSICAL_ADDRESS TopOfMemory
;
588 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint
;
589 EFI_PHYSICAL_ADDRESS PeiImageAddress
;
590 EFI_SEC_PEI_HAND_OFF
*SecCoreData
;
594 // Compute Top Of Memory for Stack and PEI Core Allocations
596 TopOfMemory
= LargestRegion
+ LargestRegionSize
;
597 PeiStackSize
= (UINTN
)RShiftU64((UINT64
)STACK_SIZE
,1);
600 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
603 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
606 // |-----------| <---- TemporaryRamBase
608 TopOfStack
= (VOID
*)(LargestRegion
+ PeiStackSize
);
609 TopOfMemory
= LargestRegion
+ PeiStackSize
;
612 // Reservet space for storing PeiCore's parament in stack.
614 TopOfStack
= (VOID
*)((UINTN
)TopOfStack
- sizeof (EFI_SEC_PEI_HAND_OFF
) - CPU_STACK_ALIGNMENT
);
615 TopOfStack
= ALIGN_POINTER (TopOfStack
, CPU_STACK_ALIGNMENT
);
619 // Bind this information into the SEC hand-off state
621 SecCoreData
= (EFI_SEC_PEI_HAND_OFF
*)(UINTN
) TopOfStack
;
622 SecCoreData
->DataSize
= sizeof(EFI_SEC_PEI_HAND_OFF
);
623 SecCoreData
->BootFirmwareVolumeBase
= (VOID
*)BootFirmwareVolumeBase
;
624 SecCoreData
->BootFirmwareVolumeSize
= FixedPcdGet32(PcdUnixFirmwareFdSize
);
625 SecCoreData
->TemporaryRamBase
= (VOID
*)(UINTN
)LargestRegion
;
626 SecCoreData
->TemporaryRamSize
= STACK_SIZE
;
627 SecCoreData
->StackBase
= SecCoreData
->TemporaryRamBase
;
628 SecCoreData
->StackSize
= PeiStackSize
;
629 SecCoreData
->PeiTemporaryRamBase
= (VOID
*) ((UINTN
) SecCoreData
->TemporaryRamBase
+ PeiStackSize
);
630 SecCoreData
->PeiTemporaryRamSize
= STACK_SIZE
- PeiStackSize
;
633 // Load the PEI Core from a Firmware Volume
635 Status
= SecUnixPeiLoadFile (
641 if (EFI_ERROR (Status
)) {
646 // Transfer control to the PEI Core
649 (SWITCH_STACK_ENTRY_POINT
) (UINTN
) PeiCoreEntryPoint
,
651 (VOID
*) (UINTN
) ((EFI_PEI_PPI_DESCRIPTOR
*) &gPrivateDispatchTable
),
656 // If we get here, then the PEI Core returned. This is an error
665 OUT EFI_PHYSICAL_ADDRESS
*MemoryBase
,
666 OUT UINT64
*MemorySize
671 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
672 It allows discontiguous memory regions to be supported by the emulator.
673 It uses gSystemMemory[] and gSystemMemoryCount that were created by
674 parsing the host environment variable EFI_MEMORY_SIZE.
675 The size comes from the varaible and the address comes from the call to
679 Index - Which memory region to use
680 MemoryBase - Return Base address of memory region
681 MemorySize - Return size in bytes of the memory region
684 EFI_SUCCESS - If memory region was mapped
685 EFI_UNSUPPORTED - If Index is not supported
691 if (Index
>= gSystemMemoryCount
) {
692 return EFI_UNSUPPORTED
;
696 res
= MapMemory(0, gSystemMemory
[Index
].Size
,
697 PROT_READ
| PROT_WRITE
| PROT_EXEC
,
698 MAP_PRIVATE
| MAP_ANONYMOUS
);
699 if (res
== MAP_FAILED
)
700 return EFI_DEVICE_ERROR
;
701 *MemorySize
= gSystemMemory
[Index
].Size
;
702 *MemoryBase
= (UINTN
)res
;
703 gSystemMemory
[Index
].Memory
= *MemoryBase
;
710 SecUnixUnixThunkAddress (
716 Since the SEC is the only Unix program in stack it must export
717 an interface to do POSIX calls. gUnix is initailized in UnixThunk.c.
720 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
721 InterfaceBase - Address of the gUnix global
724 EFI_SUCCESS - Data returned
735 OUT EFI_PHYSICAL_ADDRESS
*ImageAddress
,
736 OUT UINT64
*ImageSize
,
737 OUT EFI_PHYSICAL_ADDRESS
*EntryPoint
742 Loads and relocates a PE/COFF image into memory.
745 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
746 ImageAddress - The base address of the relocated PE/COFF image
747 ImageSize - The size of the relocated PE/COFF image
748 EntryPoint - The entry point of the relocated PE/COFF image
751 EFI_SUCCESS - The file was loaded and relocated
752 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
757 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
759 ZeroMem (&ImageContext
, sizeof (ImageContext
));
760 ImageContext
.Handle
= Pe32Data
;
762 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) SecImageRead
;
764 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
765 if (EFI_ERROR (Status
)) {
769 // Allocate space in UNIX (not emulator) memory. Extra space is for alignment
771 ImageContext
.ImageAddress
= (EFI_PHYSICAL_ADDRESS
) (UINTN
) malloc ((UINTN
) (ImageContext
.ImageSize
+ (ImageContext
.SectionAlignment
* 2)));
772 if (ImageContext
.ImageAddress
== 0) {
773 return EFI_OUT_OF_RESOURCES
;
776 // Align buffer on section boundry
778 ImageContext
.ImageAddress
+= ImageContext
.SectionAlignment
- 1;
779 ImageContext
.ImageAddress
&= ~(ImageContext
.SectionAlignment
- 1);
782 Status
= PeCoffLoaderLoadImage (&ImageContext
);
783 if (EFI_ERROR (Status
)) {
787 SecPeCoffRelocateImageExtraAction (&ImageContext
);
790 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
793 *ImageAddress
= ImageContext
.ImageAddress
;
794 *ImageSize
= ImageContext
.ImageSize
;
795 *EntryPoint
= ImageContext
.EntryPoint
;
803 SecPeCoffGetEntryPoint (
805 IN OUT VOID
**EntryPoint
809 EFI_PHYSICAL_ADDRESS ImageAddress
;
811 EFI_PHYSICAL_ADDRESS PhysEntryPoint
;
813 Status
= SecUnixPeiLoadFile (Pe32Data
, &ImageAddress
, &ImageSize
, &PhysEntryPoint
);
815 *EntryPoint
= (VOID
*)(UINTN
)PhysEntryPoint
;
825 IN OUT EFI_PHYSICAL_ADDRESS
*FdBase
,
826 IN OUT UINT64
*FdSize
831 Return the FD Size and base address. Since the FD is loaded from a
832 file into host memory only the SEC will know it's address.
835 Index - Which FD, starts at zero.
836 FdSize - Size of the FD in bytes
837 FdBase - Start address of the FD. Assume it points to an FV Header
840 EFI_SUCCESS - Return the Base address and size of the FV
841 EFI_UNSUPPORTED - Index does nto map to an FD in the system
845 if (Index
>= gFdInfoCount
) {
846 return EFI_UNSUPPORTED
;
849 *FdBase
= gFdInfo
[Index
].Address
;
850 *FdSize
= gFdInfo
[Index
].Size
;
852 if (*FdBase
== 0 && *FdSize
== 0) {
853 return EFI_UNSUPPORTED
;
864 IN OUT UINTN
*ReadSize
,
870 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
873 FileHandle - The handle to the PE/COFF file
874 FileOffset - The offset, in bytes, into the file to read
875 ReadSize - The number of bytes to read from the file starting at FileOffset
876 Buffer - A pointer to the buffer to read the data into.
879 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
887 Destination8
= Buffer
;
888 Source8
= (CHAR8
*) ((UINTN
) FileHandle
+ FileOffset
);
891 *(Destination8
++) = *(Source8
++);
898 CountSeperatorsInString (
899 IN
const CHAR16
*String
,
905 Count the number of seperators in String
908 String - String to process
909 Seperator - Item to count
912 Number of Seperator in String
918 for (Count
= 0; *String
!= '\0'; String
++) {
919 if (*String
== Seperator
) {
930 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
,
936 Store the ModHandle in an array indexed by the Pdb File name.
937 The ModHandle is needed to unload the image.
940 ImageContext - Input data returned from PE Laoder Library. Used to find the
941 .PDB file name of the PE Image.
942 ModHandle - Returned from LoadLibraryEx() and stored for call to
946 EFI_SUCCESS - ModHandle was stored.
951 IMAGE_CONTEXT_TO_MOD_HANDLE
*Array
;
955 Array
= mImageContextModHandleArray
;
956 for (Index
= 0; Index
< mImageContextModHandleArraySize
; Index
++, Array
++) {
957 if (Array
->ImageContext
== NULL
) {
959 // Make a copy of the stirng and store the ModHandle
961 Array
->ImageContext
= ImageContext
;
962 Array
->ModHandle
= ModHandle
;
968 // No free space in mImageContextModHandleArray so grow it by
969 // IMAGE_CONTEXT_TO_MOD_HANDLE entires. realloc will
970 // copy the old values to the new locaiton. But it does
971 // not zero the new memory area.
973 PreviousSize
= mImageContextModHandleArraySize
* sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE
);
974 mImageContextModHandleArraySize
+= MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE
;
976 mImageContextModHandleArray
= realloc (mImageContextModHandleArray
, mImageContextModHandleArraySize
* sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE
));
977 if (mImageContextModHandleArray
== NULL
) {
979 return EFI_OUT_OF_RESOURCES
;
982 memset (mImageContextModHandleArray
+ PreviousSize
, 0, MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE
* sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE
));
984 return AddHandle (ImageContext
, ModHandle
);
990 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
995 Return the ModHandle and delete the entry in the array.
998 ImageContext - Input data returned from PE Laoder Library. Used to find the
999 .PDB file name of the PE Image.
1002 ModHandle - ModHandle assoicated with ImageContext is returned
1003 NULL - No ModHandle associated with ImageContext
1008 IMAGE_CONTEXT_TO_MOD_HANDLE
*Array
;
1010 if (ImageContext
->PdbPointer
== NULL
) {
1012 // If no PDB pointer there is no ModHandle so return NULL
1017 Array
= mImageContextModHandleArray
;
1018 for (Index
= 0; Index
< mImageContextModHandleArraySize
; Index
++, Array
++) {
1019 if ((Array
->ImageContext
== ImageContext
)) {
1021 // If you find a match return it and delete the entry
1023 Array
->ImageContext
= NULL
;
1024 return Array
->ModHandle
;
1034 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to source a
1035 // add-symbol-file command. Hey what can you say scripting in gdb is not that great....
1037 // Put .gdbinit in the CWD where you do gdb SecMain.dll for source level debug
1040 // b SecGdbScriptBreak
1043 // source SecMain.dll.gdb
1055 SecUnixLoaderBreak (
1063 IN CHAR8
*PdbFileName
1068 if (PdbFileName
== NULL
) {
1072 Len
= strlen (PdbFileName
);
1073 if ((Len
< 5)|| (PdbFileName
[Len
- 4] != '.')) {
1077 if ((PdbFileName
[Len
- 3] == 'P' || PdbFileName
[Len
- 3] == 'p') &&
1078 (PdbFileName
[Len
- 2] == 'D' || PdbFileName
[Len
- 2] == 'd') &&
1079 (PdbFileName
[Len
- 1] == 'B' || PdbFileName
[Len
- 1] == 'b')) {
1087 #define MAX_SPRINT_BUFFER_SIZE 0x200
1091 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
1095 "0x%08lx Loading %s with entry point 0x%08lx\n",
1096 (unsigned long)ImageContext
->ImageAddress
+ ImageContext
->SizeOfHeaders
,
1097 ImageContext
->PdbPointer
,
1098 (unsigned long)ImageContext
->EntryPoint
1101 // Keep output synced up
1108 SecPeCoffRelocateImageExtraAction (
1109 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
1114 Status
= PeCoffLoaderRelocateImage (ImageContext
);
1115 if (EFI_ERROR (Status
)) {
1116 PrintLoadAddress (ImageContext
);
1121 PrintLoadAddress (ImageContext
);
1124 // In mach-o (OS X executable) dlopen() can only load files in the MH_DYLIB of MH_BUNDLE format.
1125 // To convert to PE/COFF we need to construct a mach-o with the MH_PRELOAD format. We create
1126 // .dSYM files for the PE/COFF images that can be used by gdb for source level debugging.
1131 // In the Mach-O to PE/COFF conversion the size of the PE/COFF headers is not accounted for.
1132 // Thus we need to skip over the PE/COFF header when giving load addresses for our symbol table.
1134 if (ImageContext
->PdbPointer
!= NULL
&& !IsPdbFile (ImageContext
->PdbPointer
)) {
1136 // Now we have a database of the images that are currently loaded
1140 // 'symbol-file' will clear out currnet symbol mappings in gdb.
1141 // you can do a 'add-symbol-file filename address' for every image we loaded to get source
1142 // level debug in gdb. Note Sec, being a true application will work differently.
1144 // We add the PE/COFF header size into the image as the mach-O does not have a header in
1145 // loaded into system memory.
1147 // This gives us a data base of gdb commands and after something is unloaded that entry will be
1148 // removed. We don't yet have the scheme of how to comunicate with gdb, but we have the
1149 // data base of info ready to roll.
1151 // We could use qXfer:libraries:read, but OS X GDB does not currently support it.
1153 // <library name="/lib/libc.so.6"> // ImageContext->PdbPointer
1154 // <segment address="0x10000000"/> // ImageContext->ImageAddress + ImageContext->SizeOfHeaders
1160 // Write the file we need for the gdb script
1162 GdbTempFile
= fopen (gGdbWorkingFileName
, "w");
1163 if (GdbTempFile
!= NULL
) {
1164 fprintf (GdbTempFile
, "add-symbol-file %s 0x%x\n", ImageContext
->PdbPointer
, (UINTN
)(ImageContext
->ImageAddress
+ ImageContext
->SizeOfHeaders
));
1165 fclose (GdbTempFile
);
1168 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1169 // Hey what can you say scripting in gdb is not that great....
1171 SecGdbScriptBreak ();
1174 AddHandle (ImageContext
, ImageContext
->PdbPointer
);
1180 void *Handle
= NULL
;
1184 "Loading %s 0x%08lx - entry point 0x%08lx\n",
1185 ImageContext
->PdbPointer
,
1186 (unsigned long)ImageContext
->ImageAddress
,
1187 (unsigned long)ImageContext
->EntryPoint
);
1189 Handle
= dlopen(ImageContext
->PdbPointer
, RTLD_NOW
);
1192 Entry
= dlsym(Handle
, "_ModuleEntryPoint");
1194 printf("%s\n", dlerror());
1197 if (Entry
!= NULL
) {
1198 ImageContext
->EntryPoint
= (UINTN
)Entry
;
1199 printf("Change %s Entrypoint to :0x%08lx\n", ImageContext
->PdbPointer
, (unsigned long)Entry
);
1202 SecUnixLoaderBreak ();
1212 SecPeCoffLoaderUnloadImageExtraAction (
1213 IN PE_COFF_LOADER_IMAGE_CONTEXT
*ImageContext
1218 Handle
= RemoveHandle (ImageContext
);
1223 if (Handle
!= NULL
) {
1225 // Need to skip .PDB files created from VC++
1227 if (!IsPdbFile (ImageContext
->PdbPointer
)) {
1229 // Write the file we need for the gdb script
1231 GdbTempFile
= fopen (gGdbWorkingFileName
, "w");
1232 if (GdbTempFile
!= NULL
) {
1233 fprintf (GdbTempFile
, "remove-symbol-file %s\n", ImageContext
->PdbPointer
);
1234 fclose (GdbTempFile
);
1237 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1238 // Hey what can you say scripting in gdb is not that great....
1240 SecGdbScriptBreak ();
1247 // Don't want to confuse gdb with symbols for something that got unloaded
1249 if (Handle
!= NULL
) {
1266 SecTemporaryRamSupport (
1267 IN CONST EFI_PEI_SERVICES
**PeiServices
,
1268 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase
,
1269 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase
,
1274 // Migrate the whole temporary memory to permenent memory.
1277 (VOID
*)(UINTN
)PermanentMemoryBase
,
1278 (VOID
*)(UINTN
)TemporaryMemoryBase
,
1283 // SecSwitchStack function must be invoked after the memory migration
1284 // immediatly, also we need fixup the stack change caused by new call into
1285 // permenent memory.
1288 (UINT32
) TemporaryMemoryBase
,
1289 (UINT32
) PermanentMemoryBase
1293 // We need *not* fix the return address because currently,
1294 // The PeiCore is excuted in flash.
1298 // Simulate to invalid temporary memory, terminate temporary memory
1300 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);