]> git.proxmox.com Git - mirror_edk2.git/blame - UnixPkg/Sec/SecMain.c
Integrate patch from Andrew Fish to make it run on OS X.
[mirror_edk2.git] / UnixPkg / Sec / SecMain.c
CommitLineData
804405e7 1/*++
2
ccd55824 3Copyright (c) 2006 - 2009 Intel Corporation.
4Portions copyright (c) 2008-2009 Apple Inc.
804405e7 5All rights reserved. This program and the accompanying materials
6are licensed and made available under the terms and conditions of the BSD License
7which accompanies this distribution. The full text of the license may be found at
8http://opensource.org/licenses/bsd-license.php
9
10THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13Module Name:
14
15 SecMain.c
16
17Abstract:
ccd55824 18 Unix emulator of SEC phase. It's really a Posix application, but this is
804405e7 19 Ok since all the other modules for NT32 are NOT Posix applications.
20
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.
24
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.
27
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.
30
31 The system.cmd script is used to set host environment variables that drive
32 the configuration opitons of the SEC.
33
34--*/
35
36#include "SecMain.h"
37#include <sys/mman.h>
38#include <Ppi/UnixPeiLoadFile.h>
ccd55824 39#include <Framework/StatusCode.h>
804405e7 40#include <Ppi/TemporaryRamSupport.h>
41#include <dlfcn.h>
ccd55824 42
43#ifdef __APPLE__
44#define MAP_ANONYMOUS MAP_ANON
45char *gGdbWorkingFileName = NULL;
46#endif
47
48
804405e7 49//
50// Globals
51//
804405e7 52
ccd55824 53UNIX_PEI_LOAD_FILE_PPI mSecUnixLoadFilePpi = { SecUnixPeiLoadFile };
804405e7 54
ccd55824 55PEI_UNIX_AUTOSCAN_PPI mSecUnixAutoScanPpi = { SecUnixPeiAutoScan };
804405e7 56
ccd55824 57PEI_UNIX_THUNK_PPI mSecUnixThunkPpi = { SecUnixUnixThunkAddress };
804405e7 58
73aa7f04 59EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { SecPeiReportStatusCode };
804405e7 60
ccd55824 61UNIX_FWH_PPI mSecFwhInformationPpi = { SecUnixFdAddress };
804405e7 62
63TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi = {SecTemporaryRamSupport};
64
65EFI_PEI_PPI_DESCRIPTOR gPrivateDispatchTable[] = {
804405e7 66 {
67 EFI_PEI_PPI_DESCRIPTOR_PPI,
68 &gUnixPeiLoadFilePpiGuid,
ccd55824 69 &mSecUnixLoadFilePpi
804405e7 70 },
71 {
72 EFI_PEI_PPI_DESCRIPTOR_PPI,
73 &gPeiUnixAutoScanPpiGuid,
ccd55824 74 &mSecUnixAutoScanPpi
804405e7 75 },
76 {
77 EFI_PEI_PPI_DESCRIPTOR_PPI,
78 &gPeiUnixThunkPpiGuid,
ccd55824 79 &mSecUnixThunkPpi
804405e7 80 },
81 {
82 EFI_PEI_PPI_DESCRIPTOR_PPI,
83 &gEfiPeiStatusCodePpiGuid,
84 &mSecStatusCodePpi
85 },
86 {
87 EFI_PEI_PPI_DESCRIPTOR_PPI,
88 &gEfiTemporaryRamSupportPpiGuid,
89 &mSecTemporaryRamSupportPpi
90 },
91 {
92
93 EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
94 &gUnixFwhPpiGuid,
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 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.
106//
107UINTN gFdInfoCount = 0;
108UNIX_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//
116UINTN gSystemMemoryCount = 0;
117UNIX_SYSTEM_MEMORY *gSystemMemory;
118
ccd55824 119
120
121UINTN mImageContextModHandleArraySize = 0;
122IMAGE_CONTEXT_TO_MOD_HANDLE *mImageContextModHandleArray = NULL;
123
124
804405e7 125VOID
126EFIAPI
127SecSwitchStack (
128 UINT32 TemporaryMemoryBase,
129 UINT32 PermenentMemoryBase
130 );
131
804405e7 132EFI_PHYSICAL_ADDRESS *
133MapMemory (
134 INTN fd,
135 UINT64 length,
136 INTN prot,
137 INTN flags);
138
804405e7 139EFI_STATUS
140MapFile (
141 IN CHAR8 *FileName,
142 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
143 OUT UINT64 *Length
144 );
398b646f 145EFI_STATUS
146EFIAPI
147SecNt32PeCoffRelocateImage (
148 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
149 );
804405e7 150
151
ccd55824 152int
804405e7 153main (
ccd55824 154 IN int Argc,
155 IN char **Argv,
156 IN char **Envp
804405e7 157 )
158/*++
159
160Routine Description:
ccd55824 161 Main entry point to SEC for Unix. This is a unix program
804405e7 162
163Arguments:
164 Argc - Number of command line arguments
165 Argv - Array of command line argument strings
166 Envp - Array of environmemt variable strings
167
168Returns:
169 0 - Normal exit
170 1 - Abnormal exit
171
172--*/
173{
174 EFI_STATUS Status;
175 EFI_PHYSICAL_ADDRESS InitialStackMemory;
176 UINT64 InitialStackMemorySize;
177 UINTN Index;
178 UINTN Index1;
179 UINTN Index2;
180 UINTN PeiIndex;
181 CHAR8 *FileName;
182 BOOLEAN Done;
183 VOID *PeiCoreFile;
184 CHAR16 *MemorySizeStr;
185 CHAR16 *FirmwareVolumesStr;
186 UINTN *StackPointer;
187
188 setbuf(stdout, 0);
189 setbuf(stderr, 0);
190
191 MemorySizeStr = (CHAR16 *) FixedPcdGetPtr (PcdUnixMemorySizeForSecMain);
192 FirmwareVolumesStr = (CHAR16 *) FixedPcdGetPtr (PcdUnixFirmwareVolume);
193
194 printf ("\nEDK SEC Main UNIX Emulation Environment from www.TianoCore.org\n");
195
ccd55824 196#ifdef __APPLE__
197 //
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.
201 //
202 Index = strlen (*Argv);
203 gGdbWorkingFileName = malloc (Index + strlen(".gdb"));
204 strcpy (gGdbWorkingFileName, *Argv);
205 strcat (gGdbWorkingFileName, ".gdb");
206#endif
207
208
804405e7 209 //
210 // Allocate space for gSystemMemory Array
211 //
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");
216 exit (1);
217 }
218 //
219 // Allocate space for gSystemMemory Array
220 //
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");
225 exit (1);
226 }
227 //
228 // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)
229 //
ccd55824 230 printf (" BootMode 0x%02x\n", (unsigned int)FixedPcdGet32 (PcdUnixBootMode));
804405e7 231
232 //
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.
ccd55824 235 // Set InitialStackMemory to zero so UnixOpenFile will allocate a new mapping
804405e7 236 //
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");
244 exit (1);
245 }
246
247 printf (" SEC passing in %u KB of temp RAM at 0x%08lx to PEI\n",
ccd55824 248 (unsigned int)(InitialStackMemorySize / 1024),
804405e7 249 (unsigned long)InitialStackMemory);
250
251 for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;
ccd55824 252 StackPointer < (UINTN*)(UINTN)((UINTN) InitialStackMemory + (UINT64) InitialStackMemorySize);
804405e7 253 StackPointer ++) {
254 *StackPointer = 0x5AA55AA5;
255 }
256
257 //
258 // Open All the firmware volumes and remember the info in the gFdInfo global
259 //
260 FileName = (CHAR8 *)malloc (StrLen (FirmwareVolumesStr) + 1);
261 if (FileName == NULL) {
262 printf ("ERROR : Can not allocate memory for firmware volume string\n");
263 exit (1);
264 }
265
266 Index2 = 0;
267 for (Done = FALSE, Index = 0, PeiIndex = 0, PeiCoreFile = NULL;
268 FirmwareVolumesStr[Index2] != 0;
269 Index++) {
270 for (Index1 = 0; (FirmwareVolumesStr[Index2] != '!') && (FirmwareVolumesStr[Index2] != 0); Index2++)
271 FileName[Index1++] = FirmwareVolumesStr[Index2];
272 if (FirmwareVolumesStr[Index2] == '!')
273 Index2++;
274 FileName[Index1] = '\0';
275
276 //
277 // Open the FD and remmeber where it got mapped into our processes address space
278 //
279 Status = MapFile (
280 FileName,
281 &gFdInfo[Index].Address,
282 &gFdInfo[Index].Size
283 );
284 if (EFI_ERROR (Status)) {
ccd55824 285 printf ("ERROR : Can not open Firmware Device File %s (%x). Exiting.\n", FileName, (unsigned int)Status);
804405e7 286 exit (1);
287 }
288
289 printf (" FD loaded from %s at 0x%08lx",
290 FileName, (unsigned long)gFdInfo[Index].Address);
291
292 if (PeiCoreFile == NULL) {
293 //
294 // Assume the beginning of the FD is an FV and look for the PEI Core.
295 // Load the first one we find.
296 //
297 Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);
298 if (!EFI_ERROR (Status)) {
299 PeiIndex = Index;
300 printf (" contains SEC Core");
301 }
302 }
303
304 printf ("\n");
305 }
306 //
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.
310 //
311 Index1 = 0;
312 Index = 0;
313 while (1) {
314 UINTN val = 0;
315 //
316 // Save the size of the memory.
317 //
318 while (MemorySizeStr[Index1] >= '0' && MemorySizeStr[Index1] <= '9') {
319 val = val * 10 + MemorySizeStr[Index1] - '0';
320 Index1++;
321 }
322 gSystemMemory[Index++].Size = val * 0x100000;
323 if (MemorySizeStr[Index1] == 0)
324 break;
325 Index1++;
326 }
327
328 printf ("\n");
329
330 //
331 // Hand off to PEI Core
332 //
333 SecLoadFromCore ((UINTN) InitialStackMemory, (UINTN) InitialStackMemorySize, (UINTN) gFdInfo[0].Address, PeiCoreFile);
334
335 //
336 // If we get here, then the PEI Core returned. This is an error as PEI should
337 // always hand off to DXE.
338 //
339 printf ("ERROR : PEI Core returned\n");
340 exit (1);
341}
342
343EFI_PHYSICAL_ADDRESS *
344MapMemory (
345 INTN fd,
346 UINT64 length,
347 INTN prot,
348 INTN flags)
349{
350 STATIC UINTN base = 0x40000000;
351 CONST UINTN align = (1 << 24);
352 VOID *res = NULL;
353 BOOLEAN isAligned = 0;
354
355 //
356 // Try to get an aligned block somewhere in the address space of this
357 // process.
358 //
359 while((!isAligned) && (base != 0)) {
360 res = mmap ((void *)base, length, prot, flags, fd, 0);
361 if (res == MAP_FAILED) {
362 return NULL;
363 }
364 if ((((UINTN)res) & ~(align-1)) == (UINTN)res) {
365 isAligned=1;
366 }
367 else {
368 munmap(res, length);
369 base += align;
370 }
371 }
372 return res;
373}
374
375EFI_STATUS
376MapFile (
377 IN CHAR8 *FileName,
378 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
379 OUT UINT64 *Length
380 )
381/*++
382
383Routine Description:
ccd55824 384 Opens and memory maps a file using Unix services. If BaseAddress is non zero
804405e7 385 the process will try and allocate the memory starting at BaseAddress.
386
387Arguments:
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
397
398Returns:
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
402
403--*/
404{
405 int fd;
406 VOID *res;
407 UINTN FileSize;
408
409 fd = open (FileName, O_RDONLY);
410 if (fd < 0)
411 return EFI_NOT_FOUND;
412 FileSize = lseek (fd, 0, SEEK_END);
413
414#if 0
415 if (IsMain)
416 {
417 /* Read entry address. */
418 lseek (fd, FileSize - 0x20, SEEK_SET);
419 if (read (fd, &EntryAddress, 4) != 4)
420 {
421 close (fd);
422 return EFI_DEVICE_ERROR;
423 }
424 }
425#endif
426
427 res = MapMemory(fd, FileSize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE);
428
429 close (fd);
430
431 if (res == MAP_FAILED)
432 return EFI_DEVICE_ERROR;
433
434 *Length = (UINT64) FileSize;
435 *BaseAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) res;
436
437 return EFI_SUCCESS;
438}
439
440#define BYTES_PER_RECORD 512
441
442EFI_STATUS
443EFIAPI
444SecPeiReportStatusCode (
ccd55824 445 IN CONST EFI_PEI_SERVICES **PeiServices,
804405e7 446 IN EFI_STATUS_CODE_TYPE CodeType,
447 IN EFI_STATUS_CODE_VALUE Value,
448 IN UINT32 Instance,
ccd55824 449 IN CONST EFI_GUID *CallerId,
450 IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
804405e7 451 )
452/*++
453
454Routine Description:
455
456 This routine produces the ReportStatusCode PEI service. It's passed
457 up to the PEI Core via a PPI. T
458
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.
461
462Arguments:
463 (see EFI_PEI_REPORT_STATUS_CODE)
464
465Returns:
466 EFI_SUCCESS - Always return success
467
468--*/
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
475{
476 CHAR8 *Format;
9c98c8e1 477 BASE_LIST Marker;
804405e7 478 CHAR8 PrintBuffer[BYTES_PER_RECORD * 2];
479 CHAR8 *Filename;
480 CHAR8 *Description;
481 UINT32 LineNumber;
482 UINT32 ErrorLevel;
483
484
485 if (Data == NULL) {
486 } else if (ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
487 //
488 // Processes ASSERT ()
489 //
ccd55824 490 printf ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);
804405e7 491
492 } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
493 //
494 // Process DEBUG () macro
495 //
9c98c8e1 496 AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
804405e7 497 printf (PrintBuffer);
498 }
499
500 return EFI_SUCCESS;
501}
502
503/**
504 Transfers control to a function starting with a new stack.
505
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.
510
511 If EntryPoint is NULL, then ASSERT().
512 If NewStack is NULL, then ASSERT().
513
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
516 function.
517 @param Context2 A pointer to the context to pass into the EntryPoint
518 function.
519 @param NewStack A pointer to the new stack to use for the EntryPoint
520 function.
521 @param NewBsp A pointer to the new BSP for the EntryPoint on IPF. It's
522 Reserved on other architectures.
523
524**/
525VOID
526EFIAPI
527PeiSwitchStacks (
528 IN SWITCH_STACK_ENTRY_POINT EntryPoint,
529 IN VOID *Context1, OPTIONAL
530 IN VOID *Context2, OPTIONAL
531 IN VOID *Context3, OPTIONAL
532 IN VOID *NewStack
533 )
534{
535 BASE_LIBRARY_JUMP_BUFFER JumpBuffer;
536
537 ASSERT (EntryPoint != NULL);
538 ASSERT (NewStack != NULL);
539
540 //
541 // Stack should be aligned with CPU_STACK_ALIGNMENT
542 //
543 ASSERT (((UINTN)NewStack & (CPU_STACK_ALIGNMENT - 1)) == 0);
544
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;
551
552 LongJump (&JumpBuffer, (UINTN)-1);
553
554
555 //
556 // InternalSwitchStack () will never return
557 //
558 ASSERT (FALSE);
559}
560
561VOID
562SecLoadFromCore (
563 IN UINTN LargestRegion,
564 IN UINTN LargestRegionSize,
565 IN UINTN BootFirmwareVolumeBase,
566 IN VOID *PeiCorePe32File
567 )
568/*++
569
570Routine Description:
571 This is the service to load the PEI Core from the Firmware Volume
572
573Arguments:
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
578
579Returns:
580 Success means control is transfered and thus we should never return
581
582--*/
583{
584 EFI_STATUS Status;
585 EFI_PHYSICAL_ADDRESS TopOfMemory;
586 VOID *TopOfStack;
587 UINT64 PeiCoreSize;
588 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
589 EFI_PHYSICAL_ADDRESS PeiImageAddress;
590 EFI_SEC_PEI_HAND_OFF *SecCoreData;
591 UINTN PeiStackSize;
592
593 //
594 // Compute Top Of Memory for Stack and PEI Core Allocations
595 //
596 TopOfMemory = LargestRegion + LargestRegionSize;
597 PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);
598
599 //
600 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
601 // | Heap |
602 // | |
603 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
604 // | |
605 // | Stack |
606 // |-----------| <---- TemporaryRamBase
607 //
608 TopOfStack = (VOID *)(LargestRegion + PeiStackSize);
609 TopOfMemory = LargestRegion + PeiStackSize;
610
611 //
612 // Reservet space for storing PeiCore's parament in stack.
613 //
614 TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
615 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
616
398b646f 617
804405e7 618 //
619 // Bind this information into the SEC hand-off state
620 //
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;
631
632 //
633 // Load the PEI Core from a Firmware Volume
634 //
ccd55824 635 Status = SecUnixPeiLoadFile (
804405e7 636 PeiCorePe32File,
637 &PeiImageAddress,
638 &PeiCoreSize,
639 &PeiCoreEntryPoint
640 );
641 if (EFI_ERROR (Status)) {
642 return ;
643 }
644
645 //
646 // Transfer control to the PEI Core
647 //
648 PeiSwitchStacks (
649 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
650 SecCoreData,
651 (VOID *) (UINTN) ((EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable),
652 NULL,
653 TopOfStack
654 );
655 //
656 // If we get here, then the PEI Core returned. This is an error
657 //
658 return ;
659}
660
661EFI_STATUS
662EFIAPI
ccd55824 663SecUnixPeiAutoScan (
804405e7 664 IN UINTN Index,
665 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
666 OUT UINT64 *MemorySize
667 )
668/*++
669
670Routine Description:
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
ccd55824 676 UnixOpenFile.
804405e7 677
678Arguments:
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
682
683Returns:
684 EFI_SUCCESS - If memory region was mapped
685 EFI_UNSUPPORTED - If Index is not supported
686
687--*/
688{
689 void *res;
690
691 if (Index >= gSystemMemoryCount) {
692 return EFI_UNSUPPORTED;
693 }
694
695 *MemoryBase = 0;
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;
704
705 return EFI_SUCCESS;
706}
707
708VOID *
709EFIAPI
ccd55824 710SecUnixUnixThunkAddress (
804405e7 711 VOID
712 )
713/*++
714
715Routine Description:
716 Since the SEC is the only Unix program in stack it must export
ccd55824 717 an interface to do POSIX calls. gUnix is initailized in UnixThunk.c.
804405e7 718
719Arguments:
720 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
ccd55824 721 InterfaceBase - Address of the gUnix global
804405e7 722
723Returns:
724 EFI_SUCCESS - Data returned
725
726--*/
727{
728 return gUnix;
729}
730
731
732EFI_STATUS
ccd55824 733SecUnixPeiLoadFile (
804405e7 734 IN VOID *Pe32Data,
ccd55824 735 OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
736 OUT UINT64 *ImageSize,
737 OUT EFI_PHYSICAL_ADDRESS *EntryPoint
804405e7 738 )
739/*++
740
741Routine Description:
742 Loads and relocates a PE/COFF image into memory.
743
744Arguments:
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
749
750Returns:
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
753
754--*/
755{
756 EFI_STATUS Status;
757 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
758
759 ZeroMem (&ImageContext, sizeof (ImageContext));
760 ImageContext.Handle = Pe32Data;
761
762 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
763
398b646f 764 Status = PeCoffLoaderGetImageInfo (&ImageContext);
804405e7 765 if (EFI_ERROR (Status)) {
766 return Status;
767 }
768 //
769 // Allocate space in UNIX (not emulator) memory. Extra space is for alignment
770 //
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;
774 }
775 //
776 // Align buffer on section boundry
777 //
f7bef78c 778 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
804405e7 779 ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);
780
781
398b646f 782 Status = PeCoffLoaderLoadImage (&ImageContext);
804405e7 783 if (EFI_ERROR (Status)) {
784 return Status;
785 }
786
ccd55824 787 SecPeCoffRelocateImageExtraAction (&ImageContext);
804405e7 788
789 //
790 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
791 //
792
793 *ImageAddress = ImageContext.ImageAddress;
794 *ImageSize = ImageContext.ImageSize;
795 *EntryPoint = ImageContext.EntryPoint;
796
797 return EFI_SUCCESS;
798}
799
ccd55824 800
801RETURN_STATUS
802EFIAPI
803SecPeCoffGetEntryPoint (
804 IN VOID *Pe32Data,
805 IN OUT VOID **EntryPoint
806 )
807{
808 EFI_STATUS Status;
809 EFI_PHYSICAL_ADDRESS ImageAddress;
810 UINT64 ImageSize;
811 EFI_PHYSICAL_ADDRESS PhysEntryPoint;
812
813 Status = SecUnixPeiLoadFile (Pe32Data, &ImageAddress, &ImageSize, &PhysEntryPoint);
814
815 *EntryPoint = (VOID *)(UINTN)PhysEntryPoint;
816 return Status;
817}
818
819
820
804405e7 821EFI_STATUS
822EFIAPI
ccd55824 823SecUnixFdAddress (
804405e7 824 IN UINTN Index,
825 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
826 IN OUT UINT64 *FdSize
827 )
828/*++
829
830Routine Description:
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.
833
834Arguments:
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
838
839Returns:
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
842
843--*/
844{
845 if (Index >= gFdInfoCount) {
846 return EFI_UNSUPPORTED;
847 }
848
849 *FdBase = gFdInfo[Index].Address;
850 *FdSize = gFdInfo[Index].Size;
851
852 if (*FdBase == 0 && *FdSize == 0) {
853 return EFI_UNSUPPORTED;
854 }
855
856 return EFI_SUCCESS;
857}
858
859EFI_STATUS
860EFIAPI
861SecImageRead (
862 IN VOID *FileHandle,
863 IN UINTN FileOffset,
864 IN OUT UINTN *ReadSize,
865 OUT VOID *Buffer
866 )
867/*++
868
869Routine Description:
870 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
871
872Arguments:
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.
877
878Returns:
879 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
880
881--*/
882{
883 CHAR8 *Destination8;
884 CHAR8 *Source8;
885 UINTN Length;
886
887 Destination8 = Buffer;
888 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
889 Length = *ReadSize;
890 while (Length--) {
891 *(Destination8++) = *(Source8++);
892 }
893
894 return EFI_SUCCESS;
895}
896
897UINTN
898CountSeperatorsInString (
899 IN const CHAR16 *String,
900 IN CHAR16 Seperator
901 )
902/*++
903
904Routine Description:
905 Count the number of seperators in String
906
907Arguments:
908 String - String to process
909 Seperator - Item to count
910
911Returns:
912 Number of Seperator in String
913
914--*/
915{
916 UINTN Count;
917
918 for (Count = 0; *String != '\0'; String++) {
919 if (*String == Seperator) {
920 Count++;
921 }
922 }
923
924 return Count;
925}
926
927
ccd55824 928EFI_STATUS
929AddHandle (
930 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
931 IN VOID *ModHandle
932 )
933/*++
934
935Routine Description:
936 Store the ModHandle in an array indexed by the Pdb File name.
937 The ModHandle is needed to unload the image.
938
939Arguments:
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
943 FreeLibrary().
944
945Returns:
946 EFI_SUCCESS - ModHandle was stored.
947
948--*/
949{
950 UINTN Index;
951 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
952 UINTN PreviousSize;
953
954
955 Array = mImageContextModHandleArray;
956 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
957 if (Array->ImageContext == NULL) {
958 //
959 // Make a copy of the stirng and store the ModHandle
960 //
961 Array->ImageContext = ImageContext;
962 Array->ModHandle = ModHandle;
963 return EFI_SUCCESS;
964 }
965 }
966
967 //
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.
972 //
973 PreviousSize = mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE);
974 mImageContextModHandleArraySize += MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE;
975
976 mImageContextModHandleArray = realloc (mImageContextModHandleArray, mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
977 if (mImageContextModHandleArray == NULL) {
978 ASSERT (FALSE);
979 return EFI_OUT_OF_RESOURCES;
980 }
981
982 memset (mImageContextModHandleArray + PreviousSize, 0, MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
983
984 return AddHandle (ImageContext, ModHandle);
985}
986
987
988VOID *
989RemoveHandle (
990 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
991 )
992/*++
993
994Routine Description:
995 Return the ModHandle and delete the entry in the array.
996
997Arguments:
998 ImageContext - Input data returned from PE Laoder Library. Used to find the
999 .PDB file name of the PE Image.
1000
1001Returns:
1002 ModHandle - ModHandle assoicated with ImageContext is returned
1003 NULL - No ModHandle associated with ImageContext
1004
1005--*/
1006{
1007 UINTN Index;
1008 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
1009
1010 if (ImageContext->PdbPointer == NULL) {
1011 //
1012 // If no PDB pointer there is no ModHandle so return NULL
1013 //
1014 return NULL;
1015 }
1016
1017 Array = mImageContextModHandleArray;
1018 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
1019 if ((Array->ImageContext == ImageContext)) {
1020 //
1021 // If you find a match return it and delete the entry
1022 //
1023 Array->ImageContext = NULL;
1024 return Array->ModHandle;
1025 }
1026 }
1027
1028 return NULL;
1029}
1030
1031
1032
1033//
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....
1036//
1037// Put .gdbinit in the CWD where you do gdb SecMain.dll for source level debug
1038//
1039// cat .gdbinit
1040// b SecGdbScriptBreak
1041// command
1042// silent
1043// source SecMain.dll.gdb
1044// c
1045// end
1046//
1047VOID
1048SecGdbScriptBreak (
1049 VOID
1050 )
1051{
1052}
804405e7 1053
804405e7 1054VOID
1055SecUnixLoaderBreak (
1056 VOID
1057 )
1058{
1059}
1060
ccd55824 1061BOOLEAN
1062IsPdbFile (
1063 IN CHAR8 *PdbFileName
1064 )
1065{
1066 UINTN Len;
1067
1068 if (PdbFileName == NULL) {
1069 return FALSE;
1070 }
1071
1072 Len = strlen (PdbFileName);
1073 if ((Len < 5)|| (PdbFileName[Len - 4] != '.')) {
1074 return FALSE;
1075 }
1076
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')) {
1080 return TRUE;
1081 }
1082
1083 return FALSE;
1084}
1085
1086
1087#define MAX_SPRINT_BUFFER_SIZE 0x200
1088
1089void
1090PrintLoadAddress (
1091 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1092 )
1093{
1094 fprintf (stderr,
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
1099 );
1100
1101 // Keep output synced up
1102 fflush (stderr);
1103}
1104
1105
1106VOID
804405e7 1107EFIAPI
ccd55824 1108SecPeCoffRelocateImageExtraAction (
804405e7 1109 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1110 )
1111{
804405e7 1112 EFI_STATUS Status;
1113
804405e7 1114 Status = PeCoffLoaderRelocateImage (ImageContext);
ccd55824 1115 if (EFI_ERROR (Status)) {
1116 PrintLoadAddress (ImageContext);
1117 return;
1118 }
1119
1120#ifdef __APPLE__
1121 PrintLoadAddress (ImageContext);
1122
1123 //
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.
1127 //
1128 FILE *GdbTempFile;
1129
1130 //
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.
1133 //
1134 if (ImageContext->PdbPointer != NULL && !IsPdbFile (ImageContext->PdbPointer)) {
1135 //
1136 // Now we have a database of the images that are currently loaded
1137 //
1138
1139 //
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.
1143 //
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.
1146 //
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.
1150 //
1151 // We could use qXfer:libraries:read, but OS X GDB does not currently support it.
1152 // <library-list>
1153 // <library name="/lib/libc.so.6"> // ImageContext->PdbPointer
1154 // <segment address="0x10000000"/> // ImageContext->ImageAddress + ImageContext->SizeOfHeaders
1155 // </library>
1156 // </library-list>
1157 //
1158
1159 //
1160 // Write the file we need for the gdb script
1161 //
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);
1166
1167 //
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....
1170 //
1171 SecGdbScriptBreak ();
1172 }
1173
1174 AddHandle (ImageContext, ImageContext->PdbPointer);
1175
1176 }
1177
1178#else
1179
1180 void *Handle = NULL;
1181 void *Entry = NULL;
1182
804405e7 1183 fprintf (stderr,
1184 "Loading %s 0x%08lx - entry point 0x%08lx\n",
1185 ImageContext->PdbPointer,
1186 (unsigned long)ImageContext->ImageAddress,
1187 (unsigned long)ImageContext->EntryPoint);
1188
865c7e17 1189 Handle = dlopen(ImageContext->PdbPointer, RTLD_NOW);
1190
1191 if (Handle) {
1192 Entry = dlsym(Handle, "_ModuleEntryPoint");
1193 } else {
1194 printf("%s\n", dlerror());
1195 }
1196
1197 if (Entry != NULL) {
ccd55824 1198 ImageContext->EntryPoint = (UINTN)Entry;
1199 printf("Change %s Entrypoint to :0x%08lx\n", ImageContext->PdbPointer, (unsigned long)Entry);
865c7e17 1200 }
1201
804405e7 1202 SecUnixLoaderBreak ();
1203
ccd55824 1204#endif
1205
1206 return;
804405e7 1207}
1208
1209
ccd55824 1210VOID
804405e7 1211EFIAPI
ccd55824 1212SecPeCoffLoaderUnloadImageExtraAction (
804405e7 1213 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1214 )
1215{
ccd55824 1216 VOID *Handle;
1217
1218 Handle = RemoveHandle (ImageContext);
1219
1220#ifdef __APPLE__
1221 FILE *GdbTempFile;
1222
1223 if (Handle != NULL) {
1224 //
1225 // Need to skip .PDB files created from VC++
1226 //
1227 if (!IsPdbFile (ImageContext->PdbPointer)) {
1228 //
1229 // Write the file we need for the gdb script
1230 //
1231 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1232 if (GdbTempFile != NULL) {
1233 fprintf (GdbTempFile, "remove-symbol-file %s\n", ImageContext->PdbPointer);
1234 fclose (GdbTempFile);
1235
1236 //
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....
1239 //
1240 SecGdbScriptBreak ();
1241 }
1242 }
1243 }
1244
1245#else
1246 //
1247 // Don't want to confuse gdb with symbols for something that got unloaded
1248 //
1249 if (Handle != NULL) {
1250 dlclose (Handle);
1251 }
1252
1253#endif
1254 return;
804405e7 1255}
1256
1257VOID
1258ModuleEntryPoint (
1259 VOID
1260 )
1261{
1262}
1263
1264EFI_STATUS
1265EFIAPI
1266SecTemporaryRamSupport (
1267 IN CONST EFI_PEI_SERVICES **PeiServices,
1268 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,
1269 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,
1270 IN UINTN CopySize
1271 )
1272{
1273 //
1274 // Migrate the whole temporary memory to permenent memory.
1275 //
1276 CopyMem (
1277 (VOID*)(UINTN)PermanentMemoryBase,
1278 (VOID*)(UINTN)TemporaryMemoryBase,
1279 CopySize
1280 );
1281
1282 //
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.
1286 //
1287 SecSwitchStack (
1288 (UINT32) TemporaryMemoryBase,
1289 (UINT32) PermanentMemoryBase
1290 );
1291
1292 //
1293 // We need *not* fix the return address because currently,
1294 // The PeiCore is excuted in flash.
1295 //
1296
1297 //
1fd8c31a 1298 // Simulate to invalid temporary memory, terminate temporary memory
804405e7 1299 //
1300 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);
1301
1302 return EFI_SUCCESS;
1303}