]> git.proxmox.com Git - mirror_edk2.git/blame - UnixPkg/Sec/SecMain.c
Added support for Xcode on Snow Leopard. Upaded with bug fixes for Snow Leopard.
[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 {
804405e7 92 EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
93 &gUnixFwhPpiGuid,
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 host 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//
106UINTN gFdInfoCount = 0;
107UNIX_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//
115UINTN gSystemMemoryCount = 0;
116UNIX_SYSTEM_MEMORY *gSystemMemory;
117
ccd55824 118
119
120UINTN mImageContextModHandleArraySize = 0;
121IMAGE_CONTEXT_TO_MOD_HANDLE *mImageContextModHandleArray = NULL;
122
123
804405e7 124VOID
125EFIAPI
126SecSwitchStack (
127 UINT32 TemporaryMemoryBase,
128 UINT32 PermenentMemoryBase
129 );
130
804405e7 131EFI_PHYSICAL_ADDRESS *
132MapMemory (
133 INTN fd,
134 UINT64 length,
135 INTN prot,
136 INTN flags);
137
804405e7 138EFI_STATUS
139MapFile (
140 IN CHAR8 *FileName,
141 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
142 OUT UINT64 *Length
143 );
7ee3b613 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);
7ee3b613 203 gGdbWorkingFileName = malloc (Index + strlen(".gdb") + 1);
ccd55824 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);
b7f76514 497 printf ("%s", PrintBuffer);
804405e7 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 }
7ee3b613
A
786
787 Status = PeCoffLoaderRelocateImage (&ImageContext);
788 if (EFI_ERROR (Status)) {
789 return Status;
790 }
791
804405e7 792
ccd55824 793 SecPeCoffRelocateImageExtraAction (&ImageContext);
804405e7 794
795 //
796 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
797 //
798
799 *ImageAddress = ImageContext.ImageAddress;
800 *ImageSize = ImageContext.ImageSize;
801 *EntryPoint = ImageContext.EntryPoint;
802
803 return EFI_SUCCESS;
804}
805
ccd55824 806
807RETURN_STATUS
808EFIAPI
809SecPeCoffGetEntryPoint (
810 IN VOID *Pe32Data,
811 IN OUT VOID **EntryPoint
812 )
813{
814 EFI_STATUS Status;
815 EFI_PHYSICAL_ADDRESS ImageAddress;
816 UINT64 ImageSize;
817 EFI_PHYSICAL_ADDRESS PhysEntryPoint;
818
819 Status = SecUnixPeiLoadFile (Pe32Data, &ImageAddress, &ImageSize, &PhysEntryPoint);
820
821 *EntryPoint = (VOID *)(UINTN)PhysEntryPoint;
822 return Status;
823}
824
825
826
804405e7 827EFI_STATUS
828EFIAPI
ccd55824 829SecUnixFdAddress (
804405e7 830 IN UINTN Index,
831 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
7ee3b613
A
832 IN OUT UINT64 *FdSize,
833 IN OUT EFI_PHYSICAL_ADDRESS *FixUp
804405e7 834 )
835/*++
836
837Routine Description:
838 Return the FD Size and base address. Since the FD is loaded from a
839 file into host memory only the SEC will know it's address.
840
841Arguments:
842 Index - Which FD, starts at zero.
843 FdSize - Size of the FD in bytes
844 FdBase - Start address of the FD. Assume it points to an FV Header
7ee3b613 845 FixUp - Difference between actual FD address and build address
804405e7 846
847Returns:
848 EFI_SUCCESS - Return the Base address and size of the FV
849 EFI_UNSUPPORTED - Index does nto map to an FD in the system
850
851--*/
852{
853 if (Index >= gFdInfoCount) {
854 return EFI_UNSUPPORTED;
855 }
856
857 *FdBase = gFdInfo[Index].Address;
858 *FdSize = gFdInfo[Index].Size;
7ee3b613 859 *FixUp = 0;
804405e7 860
861 if (*FdBase == 0 && *FdSize == 0) {
862 return EFI_UNSUPPORTED;
863 }
864
7ee3b613
A
865 if (Index == 0) {
866 //
867 // FD 0 has XIP code and well known PCD values
868 // If the memory buffer could not be allocated at the FD build address
869 // the Fixup is the difference.
870 //
871 *FixUp = *FdBase - FixedPcdGet32 (PcdUnixFdBaseAddress);
872 }
873
804405e7 874 return EFI_SUCCESS;
875}
876
877EFI_STATUS
878EFIAPI
879SecImageRead (
880 IN VOID *FileHandle,
881 IN UINTN FileOffset,
882 IN OUT UINTN *ReadSize,
883 OUT VOID *Buffer
884 )
885/*++
886
887Routine Description:
888 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
889
890Arguments:
891 FileHandle - The handle to the PE/COFF file
892 FileOffset - The offset, in bytes, into the file to read
893 ReadSize - The number of bytes to read from the file starting at FileOffset
894 Buffer - A pointer to the buffer to read the data into.
895
896Returns:
897 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
898
899--*/
900{
901 CHAR8 *Destination8;
902 CHAR8 *Source8;
903 UINTN Length;
904
905 Destination8 = Buffer;
906 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
907 Length = *ReadSize;
908 while (Length--) {
909 *(Destination8++) = *(Source8++);
910 }
911
912 return EFI_SUCCESS;
913}
914
915UINTN
916CountSeperatorsInString (
917 IN const CHAR16 *String,
918 IN CHAR16 Seperator
919 )
920/*++
921
922Routine Description:
923 Count the number of seperators in String
924
925Arguments:
926 String - String to process
927 Seperator - Item to count
928
929Returns:
930 Number of Seperator in String
931
932--*/
933{
934 UINTN Count;
935
936 for (Count = 0; *String != '\0'; String++) {
937 if (*String == Seperator) {
938 Count++;
939 }
940 }
941
942 return Count;
943}
944
945
ccd55824 946EFI_STATUS
947AddHandle (
948 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
949 IN VOID *ModHandle
950 )
951/*++
952
953Routine Description:
954 Store the ModHandle in an array indexed by the Pdb File name.
955 The ModHandle is needed to unload the image.
956
957Arguments:
958 ImageContext - Input data returned from PE Laoder Library. Used to find the
959 .PDB file name of the PE Image.
960 ModHandle - Returned from LoadLibraryEx() and stored for call to
961 FreeLibrary().
962
963Returns:
964 EFI_SUCCESS - ModHandle was stored.
965
966--*/
967{
968 UINTN Index;
969 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
970 UINTN PreviousSize;
971
972
973 Array = mImageContextModHandleArray;
974 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
975 if (Array->ImageContext == NULL) {
976 //
977 // Make a copy of the stirng and store the ModHandle
978 //
979 Array->ImageContext = ImageContext;
980 Array->ModHandle = ModHandle;
981 return EFI_SUCCESS;
982 }
983 }
984
985 //
986 // No free space in mImageContextModHandleArray so grow it by
987 // IMAGE_CONTEXT_TO_MOD_HANDLE entires. realloc will
988 // copy the old values to the new locaiton. But it does
989 // not zero the new memory area.
990 //
991 PreviousSize = mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE);
992 mImageContextModHandleArraySize += MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE;
993
994 mImageContextModHandleArray = realloc (mImageContextModHandleArray, mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
995 if (mImageContextModHandleArray == NULL) {
996 ASSERT (FALSE);
997 return EFI_OUT_OF_RESOURCES;
998 }
999
1000 memset (mImageContextModHandleArray + PreviousSize, 0, MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
1001
1002 return AddHandle (ImageContext, ModHandle);
1003}
1004
1005
1006VOID *
1007RemoveHandle (
1008 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1009 )
1010/*++
1011
1012Routine Description:
1013 Return the ModHandle and delete the entry in the array.
1014
1015Arguments:
1016 ImageContext - Input data returned from PE Laoder Library. Used to find the
1017 .PDB file name of the PE Image.
1018
1019Returns:
1020 ModHandle - ModHandle assoicated with ImageContext is returned
1021 NULL - No ModHandle associated with ImageContext
1022
1023--*/
1024{
1025 UINTN Index;
1026 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
1027
1028 if (ImageContext->PdbPointer == NULL) {
1029 //
1030 // If no PDB pointer there is no ModHandle so return NULL
1031 //
1032 return NULL;
1033 }
1034
1035 Array = mImageContextModHandleArray;
1036 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
1037 if ((Array->ImageContext == ImageContext)) {
1038 //
1039 // If you find a match return it and delete the entry
1040 //
1041 Array->ImageContext = NULL;
1042 return Array->ModHandle;
1043 }
1044 }
1045
1046 return NULL;
1047}
1048
1049
1050
1051//
1052// Target for gdb breakpoint in a script that uses gGdbWorkingFileName to source a
1053// add-symbol-file command. Hey what can you say scripting in gdb is not that great....
1054//
1055// Put .gdbinit in the CWD where you do gdb SecMain.dll for source level debug
1056//
1057// cat .gdbinit
1058// b SecGdbScriptBreak
1059// command
1060// silent
1061// source SecMain.dll.gdb
1062// c
1063// end
1064//
1065VOID
1066SecGdbScriptBreak (
1067 VOID
1068 )
1069{
1070}
804405e7 1071
804405e7 1072VOID
1073SecUnixLoaderBreak (
1074 VOID
1075 )
1076{
1077}
1078
ccd55824 1079BOOLEAN
1080IsPdbFile (
1081 IN CHAR8 *PdbFileName
1082 )
1083{
1084 UINTN Len;
1085
1086 if (PdbFileName == NULL) {
1087 return FALSE;
1088 }
1089
1090 Len = strlen (PdbFileName);
1091 if ((Len < 5)|| (PdbFileName[Len - 4] != '.')) {
1092 return FALSE;
1093 }
1094
1095 if ((PdbFileName[Len - 3] == 'P' || PdbFileName[Len - 3] == 'p') &&
1096 (PdbFileName[Len - 2] == 'D' || PdbFileName[Len - 2] == 'd') &&
1097 (PdbFileName[Len - 1] == 'B' || PdbFileName[Len - 1] == 'b')) {
1098 return TRUE;
1099 }
1100
1101 return FALSE;
1102}
1103
1104
1105#define MAX_SPRINT_BUFFER_SIZE 0x200
1106
1107void
1108PrintLoadAddress (
1109 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1110 )
1111{
1112 fprintf (stderr,
1113 "0x%08lx Loading %s with entry point 0x%08lx\n",
1114 (unsigned long)ImageContext->ImageAddress + ImageContext->SizeOfHeaders,
1115 ImageContext->PdbPointer,
1116 (unsigned long)ImageContext->EntryPoint
1117 );
1118
1119 // Keep output synced up
1120 fflush (stderr);
1121}
1122
1123
1124VOID
804405e7 1125EFIAPI
ccd55824 1126SecPeCoffRelocateImageExtraAction (
804405e7 1127 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1128 )
1129{
ccd55824 1130
1131#ifdef __APPLE__
1132 PrintLoadAddress (ImageContext);
1133
1134 //
1135 // In mach-o (OS X executable) dlopen() can only load files in the MH_DYLIB of MH_BUNDLE format.
1136 // To convert to PE/COFF we need to construct a mach-o with the MH_PRELOAD format. We create
1137 // .dSYM files for the PE/COFF images that can be used by gdb for source level debugging.
1138 //
1139 FILE *GdbTempFile;
1140
1141 //
1142 // In the Mach-O to PE/COFF conversion the size of the PE/COFF headers is not accounted for.
1143 // Thus we need to skip over the PE/COFF header when giving load addresses for our symbol table.
1144 //
1145 if (ImageContext->PdbPointer != NULL && !IsPdbFile (ImageContext->PdbPointer)) {
1146 //
1147 // Now we have a database of the images that are currently loaded
1148 //
1149
1150 //
1151 // 'symbol-file' will clear out currnet symbol mappings in gdb.
1152 // you can do a 'add-symbol-file filename address' for every image we loaded to get source
1153 // level debug in gdb. Note Sec, being a true application will work differently.
1154 //
1155 // We add the PE/COFF header size into the image as the mach-O does not have a header in
1156 // loaded into system memory.
1157 //
1158 // This gives us a data base of gdb commands and after something is unloaded that entry will be
1159 // removed. We don't yet have the scheme of how to comunicate with gdb, but we have the
1160 // data base of info ready to roll.
1161 //
1162 // We could use qXfer:libraries:read, but OS X GDB does not currently support it.
1163 // <library-list>
1164 // <library name="/lib/libc.so.6"> // ImageContext->PdbPointer
1165 // <segment address="0x10000000"/> // ImageContext->ImageAddress + ImageContext->SizeOfHeaders
1166 // </library>
1167 // </library-list>
1168 //
1169
1170 //
1171 // Write the file we need for the gdb script
1172 //
1173 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1174 if (GdbTempFile != NULL) {
1175 fprintf (GdbTempFile, "add-symbol-file %s 0x%x\n", ImageContext->PdbPointer, (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders));
1176 fclose (GdbTempFile);
1177
1178 //
1179 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1180 // Hey what can you say scripting in gdb is not that great....
1181 //
1182 SecGdbScriptBreak ();
1183 }
1184
1185 AddHandle (ImageContext, ImageContext->PdbPointer);
1186
1187 }
1188
1189#else
1190
1191 void *Handle = NULL;
1192 void *Entry = NULL;
1193
804405e7 1194 fprintf (stderr,
1195 "Loading %s 0x%08lx - entry point 0x%08lx\n",
1196 ImageContext->PdbPointer,
1197 (unsigned long)ImageContext->ImageAddress,
1198 (unsigned long)ImageContext->EntryPoint);
1199
7ee3b613 1200 Handle = dlopen (ImageContext->PdbPointer, RTLD_NOW);
865c7e17 1201
1202 if (Handle) {
7ee3b613 1203 Entry = dlsym (Handle, "_ModuleEntryPoint");
865c7e17 1204 } else {
1205 printf("%s\n", dlerror());
1206 }
1207
1208 if (Entry != NULL) {
ccd55824 1209 ImageContext->EntryPoint = (UINTN)Entry;
1210 printf("Change %s Entrypoint to :0x%08lx\n", ImageContext->PdbPointer, (unsigned long)Entry);
865c7e17 1211 }
1212
804405e7 1213 SecUnixLoaderBreak ();
1214
ccd55824 1215#endif
1216
1217 return;
804405e7 1218}
1219
1220
ccd55824 1221VOID
804405e7 1222EFIAPI
ccd55824 1223SecPeCoffLoaderUnloadImageExtraAction (
804405e7 1224 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1225 )
1226{
ccd55824 1227 VOID *Handle;
1228
1229 Handle = RemoveHandle (ImageContext);
1230
1231#ifdef __APPLE__
1232 FILE *GdbTempFile;
1233
1234 if (Handle != NULL) {
1235 //
1236 // Need to skip .PDB files created from VC++
1237 //
1238 if (!IsPdbFile (ImageContext->PdbPointer)) {
1239 //
1240 // Write the file we need for the gdb script
1241 //
1242 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1243 if (GdbTempFile != NULL) {
1244 fprintf (GdbTempFile, "remove-symbol-file %s\n", ImageContext->PdbPointer);
1245 fclose (GdbTempFile);
1246
1247 //
1248 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1249 // Hey what can you say scripting in gdb is not that great....
1250 //
1251 SecGdbScriptBreak ();
1252 }
1253 }
1254 }
1255
1256#else
1257 //
1258 // Don't want to confuse gdb with symbols for something that got unloaded
1259 //
1260 if (Handle != NULL) {
1261 dlclose (Handle);
1262 }
1263
1264#endif
1265 return;
804405e7 1266}
1267
1268VOID
1269ModuleEntryPoint (
1270 VOID
1271 )
1272{
1273}
1274
1275EFI_STATUS
1276EFIAPI
1277SecTemporaryRamSupport (
1278 IN CONST EFI_PEI_SERVICES **PeiServices,
1279 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,
1280 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,
1281 IN UINTN CopySize
1282 )
1283{
1284 //
1285 // Migrate the whole temporary memory to permenent memory.
1286 //
1287 CopyMem (
1288 (VOID*)(UINTN)PermanentMemoryBase,
1289 (VOID*)(UINTN)TemporaryMemoryBase,
1290 CopySize
1291 );
1292
1293 //
1294 // SecSwitchStack function must be invoked after the memory migration
1295 // immediatly, also we need fixup the stack change caused by new call into
1296 // permenent memory.
1297 //
1298 SecSwitchStack (
1299 (UINT32) TemporaryMemoryBase,
1300 (UINT32) PermanentMemoryBase
1301 );
1302
1303 //
1304 // We need *not* fix the return address because currently,
1305 // The PeiCore is excuted in flash.
1306 //
1307
1308 //
1fd8c31a 1309 // Simulate to invalid temporary memory, terminate temporary memory
804405e7 1310 //
1311 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);
1312
1313 return EFI_SUCCESS;
1314}