]> git.proxmox.com Git - mirror_edk2.git/blob - UnixPkg/Sec/SecMain.c
Added SecDispatchTable library to allow custom PPIs to be passed up to into PEI Core...
[mirror_edk2.git] / UnixPkg / Sec / SecMain.c
1 /*++
2
3 Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
4 Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
5 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
9
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.
12
13 Module Name:
14
15 SecMain.c
16
17 Abstract:
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.
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>
39 #include <Ppi/TemporaryRamSupport.h>
40 #include <dlfcn.h>
41
42 #ifdef __APPLE__
43 #define MAP_ANONYMOUS MAP_ANON
44 char *gGdbWorkingFileName = NULL;
45 #endif
46
47
48 //
49 // Globals
50 //
51 #ifdef __APPLE__
52 UNIX_PEI_LOAD_FILE_PPI mSecUnixLoadFilePpi = { GasketSecUnixPeiLoadFile };
53 PEI_UNIX_AUTOSCAN_PPI mSecUnixAutoScanPpi = { GasketSecUnixPeiAutoScan };
54 PEI_UNIX_THUNK_PPI mSecUnixThunkPpi = { GasketSecUnixUnixThunkAddress };
55 EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { GasketSecPeiReportStatusCode };
56 UNIX_FWH_PPI mSecFwhInformationPpi = { GasketSecUnixFdAddress };
57 TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi = { GasketSecTemporaryRamSupport };
58 #else
59 UNIX_PEI_LOAD_FILE_PPI mSecUnixLoadFilePpi = { SecUnixPeiLoadFile };
60 PEI_UNIX_AUTOSCAN_PPI mSecUnixAutoScanPpi = { SecUnixPeiAutoScan };
61 PEI_UNIX_THUNK_PPI mSecUnixThunkPpi = { SecUnixUnixThunkAddress };
62 EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { SecPeiReportStatusCode };
63 UNIX_FWH_PPI mSecFwhInformationPpi = { SecUnixFdAddress };
64 TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi = { SecTemporaryRamSupport };
65 #endif
66
67 EFI_PEI_PPI_DESCRIPTOR gPrivateDispatchTable[] = {
68 {
69 EFI_PEI_PPI_DESCRIPTOR_PPI,
70 &gUnixPeiLoadFilePpiGuid,
71 &mSecUnixLoadFilePpi
72 },
73 {
74 EFI_PEI_PPI_DESCRIPTOR_PPI,
75 &gPeiUnixAutoScanPpiGuid,
76 &mSecUnixAutoScanPpi
77 },
78 {
79 EFI_PEI_PPI_DESCRIPTOR_PPI,
80 &gPeiUnixThunkPpiGuid,
81 &mSecUnixThunkPpi
82 },
83 {
84 EFI_PEI_PPI_DESCRIPTOR_PPI,
85 &gEfiPeiStatusCodePpiGuid,
86 &mSecStatusCodePpi
87 },
88 {
89 EFI_PEI_PPI_DESCRIPTOR_PPI,
90 &gEfiTemporaryRamSupportPpiGuid,
91 &mSecTemporaryRamSupportPpi
92 },
93 {
94 EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
95 &gUnixFwhPpiGuid,
96 &mSecFwhInformationPpi
97 }
98 };
99
100
101 //
102 // Default information about where the FD is located.
103 // This array gets filled in with information from EFI_FIRMWARE_VOLUMES
104 // EFI_FIRMWARE_VOLUMES is a host environment variable set by system.cmd.
105 // The number of array elements is allocated base on parsing
106 // EFI_FIRMWARE_VOLUMES and the memory is never freed.
107 //
108 UINTN gFdInfoCount = 0;
109 UNIX_FD_INFO *gFdInfo;
110
111 //
112 // Array that supports seperate memory rantes.
113 // The memory ranges are set in system.cmd via the EFI_MEMORY_SIZE variable.
114 // The number of array elements is allocated base on parsing
115 // EFI_MEMORY_SIZE and the memory is never freed.
116 //
117 UINTN gSystemMemoryCount = 0;
118 UNIX_SYSTEM_MEMORY *gSystemMemory;
119
120
121
122 UINTN mImageContextModHandleArraySize = 0;
123 IMAGE_CONTEXT_TO_MOD_HANDLE *mImageContextModHandleArray = NULL;
124
125
126 VOID
127 EFIAPI
128 SecSwitchStack (
129 UINT32 TemporaryMemoryBase,
130 UINT32 PermenentMemoryBase
131 );
132
133 EFI_PHYSICAL_ADDRESS *
134 MapMemory (
135 INTN fd,
136 UINT64 length,
137 INTN prot,
138 INTN flags);
139
140 EFI_STATUS
141 MapFile (
142 IN CHAR8 *FileName,
143 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
144 OUT UINT64 *Length
145 );
146
147 EFI_STATUS
148 EFIAPI
149 SecNt32PeCoffRelocateImage (
150 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
151 );
152
153
154 int
155 main (
156 IN int Argc,
157 IN char **Argv,
158 IN char **Envp
159 )
160 /*++
161
162 Routine Description:
163 Main entry point to SEC for Unix. This is a unix program
164
165 Arguments:
166 Argc - Number of command line arguments
167 Argv - Array of command line argument strings
168 Envp - Array of environmemt variable strings
169
170 Returns:
171 0 - Normal exit
172 1 - Abnormal exit
173
174 --*/
175 {
176 EFI_STATUS Status;
177 EFI_PHYSICAL_ADDRESS InitialStackMemory;
178 UINT64 InitialStackMemorySize;
179 UINTN Index;
180 UINTN Index1;
181 UINTN Index2;
182 UINTN PeiIndex;
183 CHAR8 *FileName;
184 BOOLEAN Done;
185 VOID *PeiCoreFile;
186 CHAR16 *MemorySizeStr;
187 CHAR16 *FirmwareVolumesStr;
188 UINTN *StackPointer;
189
190 setbuf(stdout, 0);
191 setbuf(stderr, 0);
192
193 MemorySizeStr = (CHAR16 *) PcdGetPtr (PcdUnixMemorySizeForSecMain);
194 FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdUnixFirmwareVolume);
195
196 printf ("\nEDK SEC Main UNIX Emulation Environment from edk2.sourceforge.net\n");
197
198 #ifdef __APPLE__
199 //
200 // We can't use dlopen on OS X, so we need a scheme to get symboles into gdb
201 // We need to create a temp file that contains gdb commands so we can load
202 // symbols when we load every PE/COFF image.
203 //
204 Index = strlen (*Argv);
205 gGdbWorkingFileName = malloc (Index + strlen(".gdb") + 1);
206 strcpy (gGdbWorkingFileName, *Argv);
207 strcat (gGdbWorkingFileName, ".gdb");
208 #endif
209
210
211 //
212 // Allocate space for gSystemMemory Array
213 //
214 gSystemMemoryCount = CountSeperatorsInString (MemorySizeStr, '!') + 1;
215 gSystemMemory = calloc (gSystemMemoryCount, sizeof (UNIX_SYSTEM_MEMORY));
216 if (gSystemMemory == NULL) {
217 printf ("ERROR : Can not allocate memory for system. Exiting.\n");
218 exit (1);
219 }
220 //
221 // Allocate space for gSystemMemory Array
222 //
223 gFdInfoCount = CountSeperatorsInString (FirmwareVolumesStr, '!') + 1;
224 gFdInfo = calloc (gFdInfoCount, sizeof (UNIX_FD_INFO));
225 if (gFdInfo == NULL) {
226 printf ("ERROR : Can not allocate memory for fd info. Exiting.\n");
227 exit (1);
228 }
229 //
230 // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)
231 //
232 printf (" BootMode 0x%02x\n", (unsigned int)PcdGet32 (PcdUnixBootMode));
233
234 //
235 // Open up a 128K file to emulate temp memory for PEI.
236 // on a real platform this would be SRAM, or using the cache as RAM.
237 // Set InitialStackMemory to zero so UnixOpenFile will allocate a new mapping
238 //
239 InitialStackMemorySize = STACK_SIZE;
240 InitialStackMemory = (UINTN)MapMemory(0,
241 (UINT32) InitialStackMemorySize,
242 PROT_READ | PROT_WRITE | PROT_EXEC,
243 MAP_ANONYMOUS | MAP_PRIVATE);
244 if (InitialStackMemory == 0) {
245 printf ("ERROR : Can not open SecStack Exiting\n");
246 exit (1);
247 }
248
249 printf (" SEC passing in %u KB of temp RAM at 0x%08lx to PEI\n",
250 (unsigned int)(InitialStackMemorySize / 1024),
251 (unsigned long)InitialStackMemory);
252
253 for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;
254 StackPointer < (UINTN*)(UINTN)((UINTN) InitialStackMemory + (UINT64) InitialStackMemorySize);
255 StackPointer ++) {
256 *StackPointer = 0x5AA55AA5;
257 }
258
259 //
260 // Open All the firmware volumes and remember the info in the gFdInfo global
261 //
262 FileName = (CHAR8 *)malloc (StrLen (FirmwareVolumesStr) + 1);
263 if (FileName == NULL) {
264 printf ("ERROR : Can not allocate memory for firmware volume string\n");
265 exit (1);
266 }
267
268 Index2 = 0;
269 for (Done = FALSE, Index = 0, PeiIndex = 0, PeiCoreFile = NULL;
270 FirmwareVolumesStr[Index2] != 0;
271 Index++) {
272 for (Index1 = 0; (FirmwareVolumesStr[Index2] != '!') && (FirmwareVolumesStr[Index2] != 0); Index2++)
273 FileName[Index1++] = FirmwareVolumesStr[Index2];
274 if (FirmwareVolumesStr[Index2] == '!')
275 Index2++;
276 FileName[Index1] = '\0';
277
278 //
279 // Open the FD and remmeber where it got mapped into our processes address space
280 //
281 Status = MapFile (
282 FileName,
283 &gFdInfo[Index].Address,
284 &gFdInfo[Index].Size
285 );
286 if (EFI_ERROR (Status)) {
287 printf ("ERROR : Can not open Firmware Device File %s (%x). Exiting.\n", FileName, (unsigned int)Status);
288 exit (1);
289 }
290
291 printf (" FD loaded from %s at 0x%08lx",
292 FileName, (unsigned long)gFdInfo[Index].Address);
293
294 if (PeiCoreFile == NULL) {
295 //
296 // Assume the beginning of the FD is an FV and look for the PEI Core.
297 // Load the first one we find.
298 //
299 Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);
300 if (!EFI_ERROR (Status)) {
301 PeiIndex = Index;
302 printf (" contains SEC Core");
303 }
304 }
305
306 printf ("\n");
307 }
308 //
309 // Calculate memory regions and store the information in the gSystemMemory
310 // global for later use. The autosizing code will use this data to
311 // map this memory into the SEC process memory space.
312 //
313 Index1 = 0;
314 Index = 0;
315 while (1) {
316 UINTN val = 0;
317 //
318 // Save the size of the memory.
319 //
320 while (MemorySizeStr[Index1] >= '0' && MemorySizeStr[Index1] <= '9') {
321 val = val * 10 + MemorySizeStr[Index1] - '0';
322 Index1++;
323 }
324 gSystemMemory[Index++].Size = val * 0x100000;
325 if (MemorySizeStr[Index1] == 0)
326 break;
327 Index1++;
328 }
329
330 printf ("\n");
331
332 //
333 // Hand off to PEI Core
334 //
335 SecLoadFromCore ((UINTN) InitialStackMemory, (UINTN) InitialStackMemorySize, (UINTN) gFdInfo[0].Address, PeiCoreFile);
336
337 //
338 // If we get here, then the PEI Core returned. This is an error as PEI should
339 // always hand off to DXE.
340 //
341 printf ("ERROR : PEI Core returned\n");
342 exit (1);
343 }
344
345 EFI_PHYSICAL_ADDRESS *
346 MapMemory (
347 INTN fd,
348 UINT64 length,
349 INTN prot,
350 INTN flags)
351 {
352 STATIC UINTN base = 0x40000000;
353 CONST UINTN align = (1 << 24);
354 VOID *res = NULL;
355 BOOLEAN isAligned = 0;
356
357 //
358 // Try to get an aligned block somewhere in the address space of this
359 // process.
360 //
361 while((!isAligned) && (base != 0)) {
362 res = mmap ((void *)base, length, prot, flags, fd, 0);
363 if (res == MAP_FAILED) {
364 return NULL;
365 }
366 if ((((UINTN)res) & ~(align-1)) == (UINTN)res) {
367 isAligned=1;
368 }
369 else {
370 munmap(res, length);
371 base += align;
372 }
373 }
374 return res;
375 }
376
377 EFI_STATUS
378 MapFile (
379 IN CHAR8 *FileName,
380 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
381 OUT UINT64 *Length
382 )
383 /*++
384
385 Routine Description:
386 Opens and memory maps a file using Unix services. If BaseAddress is non zero
387 the process will try and allocate the memory starting at BaseAddress.
388
389 Arguments:
390 FileName - The name of the file to open and map
391 MapSize - The amount of the file to map in bytes
392 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
393 memory emulation, and exiting files for firmware volume emulation
394 BaseAddress - The base address of the mapped file in the user address space.
395 If passed in as NULL the a new memory region is used.
396 If passed in as non NULL the request memory region is used for
397 the mapping of the file into the process space.
398 Length - The size of the mapped region in bytes
399
400 Returns:
401 EFI_SUCCESS - The file was opened and mapped.
402 EFI_NOT_FOUND - FileName was not found in the current directory
403 EFI_DEVICE_ERROR - An error occured attempting to map the opened file
404
405 --*/
406 {
407 int fd;
408 VOID *res;
409 UINTN FileSize;
410
411 fd = open (FileName, O_RDONLY);
412 if (fd < 0)
413 return EFI_NOT_FOUND;
414 FileSize = lseek (fd, 0, SEEK_END);
415
416 #if 0
417 if (IsMain)
418 {
419 /* Read entry address. */
420 lseek (fd, FileSize - 0x20, SEEK_SET);
421 if (read (fd, &EntryAddress, 4) != 4)
422 {
423 close (fd);
424 return EFI_DEVICE_ERROR;
425 }
426 }
427 #endif
428
429 res = MapMemory(fd, FileSize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE);
430
431 close (fd);
432
433 if (res == MAP_FAILED)
434 return EFI_DEVICE_ERROR;
435
436 *Length = (UINT64) FileSize;
437 *BaseAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) res;
438
439 return EFI_SUCCESS;
440 }
441
442 #define BYTES_PER_RECORD 512
443
444 EFI_STATUS
445 EFIAPI
446 SecPeiReportStatusCode (
447 IN CONST EFI_PEI_SERVICES **PeiServices,
448 IN EFI_STATUS_CODE_TYPE CodeType,
449 IN EFI_STATUS_CODE_VALUE Value,
450 IN UINT32 Instance,
451 IN CONST EFI_GUID *CallerId,
452 IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
453 )
454 /*++
455
456 Routine Description:
457
458 This routine produces the ReportStatusCode PEI service. It's passed
459 up to the PEI Core via a PPI. T
460
461 This code currently uses the UNIX clib printf. This does not work the same way
462 as the EFI Print (), as %t, %g, %s as Unicode are not supported.
463
464 Arguments:
465 (see EFI_PEI_REPORT_STATUS_CODE)
466
467 Returns:
468 EFI_SUCCESS - Always return success
469
470 --*/
471 // TODO: PeiServices - add argument and description to function comment
472 // TODO: CodeType - add argument and description to function comment
473 // TODO: Value - add argument and description to function comment
474 // TODO: Instance - add argument and description to function comment
475 // TODO: CallerId - add argument and description to function comment
476 // TODO: Data - add argument and description to function comment
477 {
478 CHAR8 *Format;
479 BASE_LIST Marker;
480 CHAR8 PrintBuffer[BYTES_PER_RECORD * 2];
481 CHAR8 *Filename;
482 CHAR8 *Description;
483 UINT32 LineNumber;
484 UINT32 ErrorLevel;
485
486
487 if (Data == NULL) {
488 } else if (ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
489 //
490 // Processes ASSERT ()
491 //
492 printf ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);
493
494 } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
495 //
496 // Process DEBUG () macro
497 //
498 AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
499 printf ("%s", PrintBuffer);
500 }
501
502 return EFI_SUCCESS;
503 }
504
505 VOID
506 EFIAPI
507 PeiSwitchStacks (
508 IN SWITCH_STACK_ENTRY_POINT EntryPoint,
509 IN VOID *Context1, OPTIONAL
510 IN VOID *Context2, OPTIONAL
511 IN VOID *Context3, OPTIONAL
512 IN VOID *NewStack
513 );
514
515 VOID
516 SecLoadFromCore (
517 IN UINTN LargestRegion,
518 IN UINTN LargestRegionSize,
519 IN UINTN BootFirmwareVolumeBase,
520 IN VOID *PeiCorePe32File
521 )
522 /*++
523
524 Routine Description:
525 This is the service to load the PEI Core from the Firmware Volume
526
527 Arguments:
528 LargestRegion - Memory to use for PEI.
529 LargestRegionSize - Size of Memory to use for PEI
530 BootFirmwareVolumeBase - Start of the Boot FV
531 PeiCorePe32File - PEI Core PE32
532
533 Returns:
534 Success means control is transfered and thus we should never return
535
536 --*/
537 {
538 EFI_STATUS Status;
539 EFI_PHYSICAL_ADDRESS TopOfMemory;
540 VOID *TopOfStack;
541 UINT64 PeiCoreSize;
542 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
543 EFI_PHYSICAL_ADDRESS PeiImageAddress;
544 EFI_SEC_PEI_HAND_OFF *SecCoreData;
545 UINTN PeiStackSize;
546 EFI_PEI_PPI_DESCRIPTOR *DispatchTable;
547
548 //
549 // Compute Top Of Memory for Stack and PEI Core Allocations
550 //
551 TopOfMemory = LargestRegion + LargestRegionSize;
552 PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);
553
554 //
555 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
556 // | Heap |
557 // | |
558 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
559 // | |
560 // | Stack |
561 // |-----------| <---- TemporaryRamBase
562 //
563 TopOfStack = (VOID *)(LargestRegion + PeiStackSize);
564 TopOfMemory = LargestRegion + PeiStackSize;
565
566 //
567 // Reservet space for storing PeiCore's parament in stack.
568 //
569 TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
570 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
571
572
573 //
574 // Bind this information into the SEC hand-off state
575 //
576 SecCoreData = (EFI_SEC_PEI_HAND_OFF*)(UINTN) TopOfStack;
577 SecCoreData->DataSize = sizeof(EFI_SEC_PEI_HAND_OFF);
578 SecCoreData->BootFirmwareVolumeBase = (VOID*)BootFirmwareVolumeBase;
579 SecCoreData->BootFirmwareVolumeSize = PcdGet32 (PcdUnixFirmwareFdSize);
580 SecCoreData->TemporaryRamBase = (VOID*)(UINTN)LargestRegion;
581 SecCoreData->TemporaryRamSize = STACK_SIZE;
582 SecCoreData->StackBase = SecCoreData->TemporaryRamBase;
583 SecCoreData->StackSize = PeiStackSize;
584 SecCoreData->PeiTemporaryRamBase = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + PeiStackSize);
585 SecCoreData->PeiTemporaryRamSize = STACK_SIZE - PeiStackSize;
586
587 //
588 // Load the PEI Core from a Firmware Volume
589 //
590 Status = SecUnixPeiLoadFile (
591 PeiCorePe32File,
592 &PeiImageAddress,
593 &PeiCoreSize,
594 &PeiCoreEntryPoint
595 );
596 if (EFI_ERROR (Status)) {
597 return ;
598 }
599
600 //
601 // Allow an override for extra PPIs to be passed up to PEI
602 // This is an easy way to enable OS specific customizations
603 //
604 DispatchTable = OverrideDispatchTable (&gPrivateDispatchTable[0]);
605
606 //
607 // Transfer control to the PEI Core
608 //
609 PeiSwitchStacks (
610 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
611 SecCoreData,
612 (VOID *)DispatchTable,
613 NULL,
614 TopOfStack
615 );
616 //
617 // If we get here, then the PEI Core returned. This is an error
618 //
619 return ;
620 }
621
622 EFI_STATUS
623 EFIAPI
624 SecUnixPeiAutoScan (
625 IN UINTN Index,
626 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
627 OUT UINT64 *MemorySize
628 )
629 /*++
630
631 Routine Description:
632 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
633 It allows discontiguous memory regions to be supported by the emulator.
634 It uses gSystemMemory[] and gSystemMemoryCount that were created by
635 parsing the host environment variable EFI_MEMORY_SIZE.
636 The size comes from the varaible and the address comes from the call to
637 UnixOpenFile.
638
639 Arguments:
640 Index - Which memory region to use
641 MemoryBase - Return Base address of memory region
642 MemorySize - Return size in bytes of the memory region
643
644 Returns:
645 EFI_SUCCESS - If memory region was mapped
646 EFI_UNSUPPORTED - If Index is not supported
647
648 --*/
649 {
650 void *res;
651
652 if (Index >= gSystemMemoryCount) {
653 return EFI_UNSUPPORTED;
654 }
655
656 *MemoryBase = 0;
657 res = MapMemory(0, gSystemMemory[Index].Size,
658 PROT_READ | PROT_WRITE | PROT_EXEC,
659 MAP_PRIVATE | MAP_ANONYMOUS);
660 if (res == MAP_FAILED)
661 return EFI_DEVICE_ERROR;
662 *MemorySize = gSystemMemory[Index].Size;
663 *MemoryBase = (UINTN)res;
664 gSystemMemory[Index].Memory = *MemoryBase;
665
666 return EFI_SUCCESS;
667 }
668
669 VOID *
670 EFIAPI
671 SecUnixUnixThunkAddress (
672 VOID
673 )
674 /*++
675
676 Routine Description:
677 Since the SEC is the only Unix program in stack it must export
678 an interface to do POSIX calls. gUnix is initailized in UnixThunk.c.
679
680 Arguments:
681 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
682 InterfaceBase - Address of the gUnix global
683
684 Returns:
685 EFI_SUCCESS - Data returned
686
687 --*/
688 {
689 return gUnix;
690 }
691
692
693 EFI_STATUS
694 SecUnixPeiLoadFile (
695 IN VOID *Pe32Data,
696 OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
697 OUT UINT64 *ImageSize,
698 OUT EFI_PHYSICAL_ADDRESS *EntryPoint
699 )
700 /*++
701
702 Routine Description:
703 Loads and relocates a PE/COFF image into memory.
704
705 Arguments:
706 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
707 ImageAddress - The base address of the relocated PE/COFF image
708 ImageSize - The size of the relocated PE/COFF image
709 EntryPoint - The entry point of the relocated PE/COFF image
710
711 Returns:
712 EFI_SUCCESS - The file was loaded and relocated
713 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
714
715 --*/
716 {
717 EFI_STATUS Status;
718 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
719
720 ZeroMem (&ImageContext, sizeof (ImageContext));
721 ImageContext.Handle = Pe32Data;
722
723 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
724
725 Status = PeCoffLoaderGetImageInfo (&ImageContext);
726 if (EFI_ERROR (Status)) {
727 return Status;
728 }
729
730
731 //
732 // Allocate space in UNIX (not emulator) memory. Extra space is for alignment
733 //
734 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) MapMemory (
735 0,
736 (UINT32) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)),
737 PROT_READ | PROT_WRITE | PROT_EXEC,
738 MAP_ANONYMOUS | MAP_PRIVATE
739 );
740 if (ImageContext.ImageAddress == 0) {
741 return EFI_OUT_OF_RESOURCES;
742 }
743
744 //
745 // Align buffer on section boundry
746 //
747 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
748 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)(ImageContext.SectionAlignment - 1));
749
750
751 Status = PeCoffLoaderLoadImage (&ImageContext);
752 if (EFI_ERROR (Status)) {
753 return Status;
754 }
755
756 Status = PeCoffLoaderRelocateImage (&ImageContext);
757 if (EFI_ERROR (Status)) {
758 return Status;
759 }
760
761
762 SecPeCoffRelocateImageExtraAction (&ImageContext);
763
764 //
765 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
766 //
767
768 *ImageAddress = ImageContext.ImageAddress;
769 *ImageSize = ImageContext.ImageSize;
770 *EntryPoint = ImageContext.EntryPoint;
771
772 return EFI_SUCCESS;
773 }
774
775
776 RETURN_STATUS
777 EFIAPI
778 SecPeCoffGetEntryPoint (
779 IN VOID *Pe32Data,
780 IN OUT VOID **EntryPoint
781 )
782 {
783 EFI_STATUS Status;
784 EFI_PHYSICAL_ADDRESS ImageAddress;
785 UINT64 ImageSize;
786 EFI_PHYSICAL_ADDRESS PhysEntryPoint;
787
788 Status = SecUnixPeiLoadFile (Pe32Data, &ImageAddress, &ImageSize, &PhysEntryPoint);
789
790 *EntryPoint = (VOID *)(UINTN)PhysEntryPoint;
791 return Status;
792 }
793
794
795
796 EFI_STATUS
797 EFIAPI
798 SecUnixFdAddress (
799 IN UINTN Index,
800 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
801 IN OUT UINT64 *FdSize,
802 IN OUT EFI_PHYSICAL_ADDRESS *FixUp
803 )
804 /*++
805
806 Routine Description:
807 Return the FD Size and base address. Since the FD is loaded from a
808 file into host memory only the SEC will know it's address.
809
810 Arguments:
811 Index - Which FD, starts at zero.
812 FdSize - Size of the FD in bytes
813 FdBase - Start address of the FD. Assume it points to an FV Header
814 FixUp - Difference between actual FD address and build address
815
816 Returns:
817 EFI_SUCCESS - Return the Base address and size of the FV
818 EFI_UNSUPPORTED - Index does nto map to an FD in the system
819
820 --*/
821 {
822 if (Index >= gFdInfoCount) {
823 return EFI_UNSUPPORTED;
824 }
825
826 *FdBase = gFdInfo[Index].Address;
827 *FdSize = gFdInfo[Index].Size;
828 *FixUp = 0;
829
830 if (*FdBase == 0 && *FdSize == 0) {
831 return EFI_UNSUPPORTED;
832 }
833
834 if (Index == 0) {
835 //
836 // FD 0 has XIP code and well known PCD values
837 // If the memory buffer could not be allocated at the FD build address
838 // the Fixup is the difference.
839 //
840 *FixUp = *FdBase - PcdGet64 (PcdUnixFdBaseAddress);
841 }
842
843 return EFI_SUCCESS;
844 }
845
846 EFI_STATUS
847 EFIAPI
848 SecImageRead (
849 IN VOID *FileHandle,
850 IN UINTN FileOffset,
851 IN OUT UINTN *ReadSize,
852 OUT VOID *Buffer
853 )
854 /*++
855
856 Routine Description:
857 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
858
859 Arguments:
860 FileHandle - The handle to the PE/COFF file
861 FileOffset - The offset, in bytes, into the file to read
862 ReadSize - The number of bytes to read from the file starting at FileOffset
863 Buffer - A pointer to the buffer to read the data into.
864
865 Returns:
866 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
867
868 --*/
869 {
870 CHAR8 *Destination8;
871 CHAR8 *Source8;
872 UINTN Length;
873
874 Destination8 = Buffer;
875 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
876 Length = *ReadSize;
877 while (Length--) {
878 *(Destination8++) = *(Source8++);
879 }
880
881 return EFI_SUCCESS;
882 }
883
884 UINTN
885 CountSeperatorsInString (
886 IN const CHAR16 *String,
887 IN CHAR16 Seperator
888 )
889 /*++
890
891 Routine Description:
892 Count the number of seperators in String
893
894 Arguments:
895 String - String to process
896 Seperator - Item to count
897
898 Returns:
899 Number of Seperator in String
900
901 --*/
902 {
903 UINTN Count;
904
905 for (Count = 0; *String != '\0'; String++) {
906 if (*String == Seperator) {
907 Count++;
908 }
909 }
910
911 return Count;
912 }
913
914
915 EFI_STATUS
916 AddHandle (
917 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
918 IN VOID *ModHandle
919 )
920 /*++
921
922 Routine Description:
923 Store the ModHandle in an array indexed by the Pdb File name.
924 The ModHandle is needed to unload the image.
925
926 Arguments:
927 ImageContext - Input data returned from PE Laoder Library. Used to find the
928 .PDB file name of the PE Image.
929 ModHandle - Returned from LoadLibraryEx() and stored for call to
930 FreeLibrary().
931
932 Returns:
933 EFI_SUCCESS - ModHandle was stored.
934
935 --*/
936 {
937 UINTN Index;
938 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
939 UINTN PreviousSize;
940
941
942 Array = mImageContextModHandleArray;
943 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
944 if (Array->ImageContext == NULL) {
945 //
946 // Make a copy of the stirng and store the ModHandle
947 //
948 Array->ImageContext = ImageContext;
949 Array->ModHandle = ModHandle;
950 return EFI_SUCCESS;
951 }
952 }
953
954 //
955 // No free space in mImageContextModHandleArray so grow it by
956 // IMAGE_CONTEXT_TO_MOD_HANDLE entires. realloc will
957 // copy the old values to the new locaiton. But it does
958 // not zero the new memory area.
959 //
960 PreviousSize = mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE);
961 mImageContextModHandleArraySize += MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE;
962
963 mImageContextModHandleArray = realloc (mImageContextModHandleArray, mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
964 if (mImageContextModHandleArray == NULL) {
965 ASSERT (FALSE);
966 return EFI_OUT_OF_RESOURCES;
967 }
968
969 memset (mImageContextModHandleArray + PreviousSize, 0, MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
970
971 return AddHandle (ImageContext, ModHandle);
972 }
973
974
975 VOID *
976 RemoveHandle (
977 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
978 )
979 /*++
980
981 Routine Description:
982 Return the ModHandle and delete the entry in the array.
983
984 Arguments:
985 ImageContext - Input data returned from PE Laoder Library. Used to find the
986 .PDB file name of the PE Image.
987
988 Returns:
989 ModHandle - ModHandle assoicated with ImageContext is returned
990 NULL - No ModHandle associated with ImageContext
991
992 --*/
993 {
994 UINTN Index;
995 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
996
997 if (ImageContext->PdbPointer == NULL) {
998 //
999 // If no PDB pointer there is no ModHandle so return NULL
1000 //
1001 return NULL;
1002 }
1003
1004 Array = mImageContextModHandleArray;
1005 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
1006 if ((Array->ImageContext == ImageContext)) {
1007 //
1008 // If you find a match return it and delete the entry
1009 //
1010 Array->ImageContext = NULL;
1011 return Array->ModHandle;
1012 }
1013 }
1014
1015 return NULL;
1016 }
1017
1018
1019
1020 //
1021 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to source a
1022 // add-symbol-file command. Hey what can you say scripting in gdb is not that great....
1023 //
1024 // Put .gdbinit in the CWD where you do gdb SecMain.dll for source level debug
1025 //
1026 // cat .gdbinit
1027 // b SecGdbScriptBreak
1028 // command
1029 // silent
1030 // source SecMain.dll.gdb
1031 // c
1032 // end
1033 //
1034 VOID
1035 SecGdbScriptBreak (
1036 VOID
1037 )
1038 {
1039 }
1040
1041 VOID
1042 SecUnixLoaderBreak (
1043 VOID
1044 )
1045 {
1046 }
1047
1048 BOOLEAN
1049 IsPdbFile (
1050 IN CHAR8 *PdbFileName
1051 )
1052 {
1053 UINTN Len;
1054
1055 if (PdbFileName == NULL) {
1056 return FALSE;
1057 }
1058
1059 Len = strlen (PdbFileName);
1060 if ((Len < 5)|| (PdbFileName[Len - 4] != '.')) {
1061 return FALSE;
1062 }
1063
1064 if ((PdbFileName[Len - 3] == 'P' || PdbFileName[Len - 3] == 'p') &&
1065 (PdbFileName[Len - 2] == 'D' || PdbFileName[Len - 2] == 'd') &&
1066 (PdbFileName[Len - 1] == 'B' || PdbFileName[Len - 1] == 'b')) {
1067 return TRUE;
1068 }
1069
1070 return FALSE;
1071 }
1072
1073
1074 #define MAX_SPRINT_BUFFER_SIZE 0x200
1075
1076 void
1077 PrintLoadAddress (
1078 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1079 )
1080 {
1081 if (ImageContext->PdbPointer == NULL) {
1082 fprintf (stderr,
1083 "0x%08lx Loading NO DEBUG with entry point 0x%08lx\n",
1084 (unsigned long)(ImageContext->ImageAddress),
1085 (unsigned long)ImageContext->EntryPoint
1086 );
1087 } else {
1088 fprintf (stderr,
1089 "0x%08lx Loading %s with entry point 0x%08lx\n",
1090 (unsigned long)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders),
1091 ImageContext->PdbPointer,
1092 (unsigned long)ImageContext->EntryPoint
1093 );
1094 }
1095 // Keep output synced up
1096 fflush (stderr);
1097 }
1098
1099
1100 VOID
1101 EFIAPI
1102 SecPeCoffRelocateImageExtraAction (
1103 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1104 )
1105 {
1106
1107 #ifdef __APPLE__
1108 PrintLoadAddress (ImageContext);
1109
1110 //
1111 // In mach-o (OS X executable) dlopen() can only load files in the MH_DYLIB of MH_BUNDLE format.
1112 // To convert to PE/COFF we need to construct a mach-o with the MH_PRELOAD format. We create
1113 // .dSYM files for the PE/COFF images that can be used by gdb for source level debugging.
1114 //
1115 FILE *GdbTempFile;
1116
1117 //
1118 // In the Mach-O to PE/COFF conversion the size of the PE/COFF headers is not accounted for.
1119 // Thus we need to skip over the PE/COFF header when giving load addresses for our symbol table.
1120 //
1121 if (ImageContext->PdbPointer != NULL && !IsPdbFile (ImageContext->PdbPointer)) {
1122 //
1123 // Now we have a database of the images that are currently loaded
1124 //
1125
1126 //
1127 // 'symbol-file' will clear out currnet symbol mappings in gdb.
1128 // you can do a 'add-symbol-file filename address' for every image we loaded to get source
1129 // level debug in gdb. Note Sec, being a true application will work differently.
1130 //
1131 // We add the PE/COFF header size into the image as the mach-O does not have a header in
1132 // loaded into system memory.
1133 //
1134 // This gives us a data base of gdb commands and after something is unloaded that entry will be
1135 // removed. We don't yet have the scheme of how to comunicate with gdb, but we have the
1136 // data base of info ready to roll.
1137 //
1138 // We could use qXfer:libraries:read, but OS X GDB does not currently support it.
1139 // <library-list>
1140 // <library name="/lib/libc.so.6"> // ImageContext->PdbPointer
1141 // <segment address="0x10000000"/> // ImageContext->ImageAddress + ImageContext->SizeOfHeaders
1142 // </library>
1143 // </library-list>
1144 //
1145
1146 //
1147 // Write the file we need for the gdb script
1148 //
1149 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1150 if (GdbTempFile != NULL) {
1151 fprintf (GdbTempFile, "add-symbol-file %s 0x%08lx\n", ImageContext->PdbPointer, (long unsigned int)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders));
1152 fclose (GdbTempFile);
1153
1154 //
1155 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1156 // Hey what can you say scripting in gdb is not that great....
1157 //
1158 SecGdbScriptBreak ();
1159 }
1160
1161 AddHandle (ImageContext, ImageContext->PdbPointer);
1162
1163 }
1164
1165 #else
1166
1167 void *Handle = NULL;
1168 void *Entry = NULL;
1169
1170 fprintf (stderr,
1171 "Loading %s 0x%08lx - entry point 0x%08lx\n",
1172 ImageContext->PdbPointer,
1173 (unsigned long)ImageContext->ImageAddress,
1174 (unsigned long)ImageContext->EntryPoint);
1175
1176 Handle = dlopen (ImageContext->PdbPointer, RTLD_NOW);
1177
1178 if (Handle) {
1179 Entry = dlsym (Handle, "_ModuleEntryPoint");
1180 } else {
1181 printf("%s\n", dlerror());
1182 }
1183
1184 if (Entry != NULL) {
1185 ImageContext->EntryPoint = (UINTN)Entry;
1186 printf("Change %s Entrypoint to :0x%08lx\n", ImageContext->PdbPointer, (unsigned long)Entry);
1187 }
1188
1189 SecUnixLoaderBreak ();
1190
1191 #endif
1192
1193 return;
1194 }
1195
1196
1197 VOID
1198 EFIAPI
1199 SecPeCoffLoaderUnloadImageExtraAction (
1200 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1201 )
1202 {
1203 VOID *Handle;
1204
1205 Handle = RemoveHandle (ImageContext);
1206
1207 #ifdef __APPLE__
1208 FILE *GdbTempFile;
1209
1210 if (Handle != NULL) {
1211 //
1212 // Need to skip .PDB files created from VC++
1213 //
1214 if (!IsPdbFile (ImageContext->PdbPointer)) {
1215 //
1216 // Write the file we need for the gdb script
1217 //
1218 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1219 if (GdbTempFile != NULL) {
1220 fprintf (GdbTempFile, "remove-symbol-file %s\n", ImageContext->PdbPointer);
1221 fclose (GdbTempFile);
1222
1223 //
1224 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1225 // Hey what can you say scripting in gdb is not that great....
1226 //
1227 SecGdbScriptBreak ();
1228 }
1229 }
1230 }
1231
1232 #else
1233 //
1234 // Don't want to confuse gdb with symbols for something that got unloaded
1235 //
1236 if (Handle != NULL) {
1237 dlclose (Handle);
1238 }
1239
1240 #endif
1241 return;
1242 }
1243
1244 VOID
1245 ModuleEntryPoint (
1246 VOID
1247 )
1248 {
1249 }
1250
1251 EFI_STATUS
1252 EFIAPI
1253 SecTemporaryRamSupport (
1254 IN CONST EFI_PEI_SERVICES **PeiServices,
1255 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,
1256 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,
1257 IN UINTN CopySize
1258 )
1259 {
1260 //
1261 // Migrate the whole temporary memory to permenent memory.
1262 //
1263 CopyMem (
1264 (VOID*)(UINTN)PermanentMemoryBase,
1265 (VOID*)(UINTN)TemporaryMemoryBase,
1266 CopySize
1267 );
1268
1269 //
1270 // SecSwitchStack function must be invoked after the memory migration
1271 // immediatly, also we need fixup the stack change caused by new call into
1272 // permenent memory.
1273 //
1274 SecSwitchStack (
1275 (UINT32) TemporaryMemoryBase,
1276 (UINT32) PermanentMemoryBase
1277 );
1278
1279 //
1280 // We need *not* fix the return address because currently,
1281 // The PeiCore is excuted in flash.
1282 //
1283
1284 //
1285 // Simulate to invalid temporary memory, terminate temporary memory
1286 //
1287 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);
1288
1289 return EFI_SUCCESS;
1290 }