]> git.proxmox.com Git - mirror_edk2.git/blame - UnixPkg/Sec/SecMain.c
The patch acknowledges the TCP zero window probe message, either the format with...
[mirror_edk2.git] / UnixPkg / Sec / SecMain.c
CommitLineData
804405e7 1/*++
2
f9b8ab56
HT
3Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
4Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
5This program and the accompanying materials
804405e7 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>
804405e7 39#include <Ppi/TemporaryRamSupport.h>
40#include <dlfcn.h>
ccd55824 41
42#ifdef __APPLE__
43#define MAP_ANONYMOUS MAP_ANON
44char *gGdbWorkingFileName = NULL;
45#endif
46
47
804405e7 48//
49// Globals
50//
bb111c23 51#ifdef __APPLE__
52UNIX_PEI_LOAD_FILE_PPI mSecUnixLoadFilePpi = { GasketSecUnixPeiLoadFile };
53PEI_UNIX_AUTOSCAN_PPI mSecUnixAutoScanPpi = { GasketSecUnixPeiAutoScan };
54PEI_UNIX_THUNK_PPI mSecUnixThunkPpi = { GasketSecUnixUnixThunkAddress };
55EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { GasketSecPeiReportStatusCode };
56UNIX_FWH_PPI mSecFwhInformationPpi = { GasketSecUnixFdAddress };
57TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi = { GasketSecTemporaryRamSupport };
58#else
59UNIX_PEI_LOAD_FILE_PPI mSecUnixLoadFilePpi = { SecUnixPeiLoadFile };
60PEI_UNIX_AUTOSCAN_PPI mSecUnixAutoScanPpi = { SecUnixPeiAutoScan };
61PEI_UNIX_THUNK_PPI mSecUnixThunkPpi = { SecUnixUnixThunkAddress };
73aa7f04 62EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { SecPeiReportStatusCode };
ccd55824 63UNIX_FWH_PPI mSecFwhInformationPpi = { SecUnixFdAddress };
bb111c23 64TEMPORARY_RAM_SUPPORT_PPI mSecTemporaryRamSupportPpi = { SecTemporaryRamSupport };
65#endif
804405e7 66
67EFI_PEI_PPI_DESCRIPTOR gPrivateDispatchTable[] = {
804405e7 68 {
69 EFI_PEI_PPI_DESCRIPTOR_PPI,
70 &gUnixPeiLoadFilePpiGuid,
ccd55824 71 &mSecUnixLoadFilePpi
804405e7 72 },
73 {
74 EFI_PEI_PPI_DESCRIPTOR_PPI,
75 &gPeiUnixAutoScanPpiGuid,
ccd55824 76 &mSecUnixAutoScanPpi
804405e7 77 },
78 {
79 EFI_PEI_PPI_DESCRIPTOR_PPI,
80 &gPeiUnixThunkPpiGuid,
ccd55824 81 &mSecUnixThunkPpi
804405e7 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 {
804405e7 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//
108UINTN gFdInfoCount = 0;
109UNIX_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//
117UINTN gSystemMemoryCount = 0;
118UNIX_SYSTEM_MEMORY *gSystemMemory;
119
ccd55824 120
121
122UINTN mImageContextModHandleArraySize = 0;
123IMAGE_CONTEXT_TO_MOD_HANDLE *mImageContextModHandleArray = NULL;
124
125
804405e7 126VOID
127EFIAPI
128SecSwitchStack (
129 UINT32 TemporaryMemoryBase,
130 UINT32 PermenentMemoryBase
131 );
132
804405e7 133EFI_PHYSICAL_ADDRESS *
134MapMemory (
135 INTN fd,
136 UINT64 length,
137 INTN prot,
138 INTN flags);
139
804405e7 140EFI_STATUS
141MapFile (
142 IN CHAR8 *FileName,
143 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
144 OUT UINT64 *Length
145 );
7ee3b613 146
398b646f 147EFI_STATUS
148EFIAPI
149SecNt32PeCoffRelocateImage (
150 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
151 );
804405e7 152
153
ccd55824 154int
804405e7 155main (
ccd55824 156 IN int Argc,
157 IN char **Argv,
158 IN char **Envp
804405e7 159 )
160/*++
161
162Routine Description:
ccd55824 163 Main entry point to SEC for Unix. This is a unix program
804405e7 164
165Arguments:
166 Argc - Number of command line arguments
167 Argv - Array of command line argument strings
168 Envp - Array of environmemt variable strings
169
170Returns:
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
cdccd99e 193 MemorySizeStr = (CHAR16 *) PcdGetPtr (PcdUnixMemorySizeForSecMain);
194 FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdUnixFirmwareVolume);
804405e7 195
d5cdd257 196 printf ("\nEDK SEC Main UNIX Emulation Environment from edk2.sourceforge.net\n");
804405e7 197
ccd55824 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);
7ee3b613 205 gGdbWorkingFileName = malloc (Index + strlen(".gdb") + 1);
ccd55824 206 strcpy (gGdbWorkingFileName, *Argv);
207 strcat (gGdbWorkingFileName, ".gdb");
208#endif
209
210
804405e7 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 //
cdccd99e 232 printf (" BootMode 0x%02x\n", (unsigned int)PcdGet32 (PcdUnixBootMode));
804405e7 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.
ccd55824 237 // Set InitialStackMemory to zero so UnixOpenFile will allocate a new mapping
804405e7 238 //
239 InitialStackMemorySize = STACK_SIZE;
240 InitialStackMemory = (UINTN)MapMemory(0,
241 (UINT32) InitialStackMemorySize,
d34689b4 242 PROT_READ | PROT_WRITE | PROT_EXEC,
804405e7 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",
ccd55824 250 (unsigned int)(InitialStackMemorySize / 1024),
804405e7 251 (unsigned long)InitialStackMemory);
252
253 for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;
ccd55824 254 StackPointer < (UINTN*)(UINTN)((UINTN) InitialStackMemory + (UINT64) InitialStackMemorySize);
804405e7 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)) {
ccd55824 287 printf ("ERROR : Can not open Firmware Device File %s (%x). Exiting.\n", FileName, (unsigned int)Status);
804405e7 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
345EFI_PHYSICAL_ADDRESS *
346MapMemory (
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
377EFI_STATUS
378MapFile (
379 IN CHAR8 *FileName,
380 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
381 OUT UINT64 *Length
382 )
383/*++
384
385Routine Description:
ccd55824 386 Opens and memory maps a file using Unix services. If BaseAddress is non zero
804405e7 387 the process will try and allocate the memory starting at BaseAddress.
388
389Arguments:
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
400Returns:
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
444EFI_STATUS
445EFIAPI
446SecPeiReportStatusCode (
ccd55824 447 IN CONST EFI_PEI_SERVICES **PeiServices,
804405e7 448 IN EFI_STATUS_CODE_TYPE CodeType,
449 IN EFI_STATUS_CODE_VALUE Value,
450 IN UINT32 Instance,
ccd55824 451 IN CONST EFI_GUID *CallerId,
452 IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
804405e7 453 )
454/*++
455
456Routine 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
464Arguments:
465 (see EFI_PEI_REPORT_STATUS_CODE)
466
467Returns:
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;
9c98c8e1 479 BASE_LIST Marker;
804405e7 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 //
ccd55824 492 printf ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);
804405e7 493
494 } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
495 //
496 // Process DEBUG () macro
497 //
9c98c8e1 498 AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
b7f76514 499 printf ("%s", PrintBuffer);
804405e7 500 }
501
502 return EFI_SUCCESS;
503}
504
804405e7 505VOID
506EFIAPI
507PeiSwitchStacks (
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
67f86803 513 );
804405e7 514
515VOID
516SecLoadFromCore (
517 IN UINTN LargestRegion,
518 IN UINTN LargestRegionSize,
519 IN UINTN BootFirmwareVolumeBase,
520 IN VOID *PeiCorePe32File
521 )
522/*++
523
524Routine Description:
525 This is the service to load the PEI Core from the Firmware Volume
526
527Arguments:
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
533Returns:
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
547 //
548 // Compute Top Of Memory for Stack and PEI Core Allocations
549 //
550 TopOfMemory = LargestRegion + LargestRegionSize;
551 PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);
552
553 //
554 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
555 // | Heap |
556 // | |
557 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
558 // | |
559 // | Stack |
560 // |-----------| <---- TemporaryRamBase
561 //
562 TopOfStack = (VOID *)(LargestRegion + PeiStackSize);
563 TopOfMemory = LargestRegion + PeiStackSize;
564
565 //
566 // Reservet space for storing PeiCore's parament in stack.
567 //
568 TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
569 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
570
398b646f 571
804405e7 572 //
573 // Bind this information into the SEC hand-off state
574 //
575 SecCoreData = (EFI_SEC_PEI_HAND_OFF*)(UINTN) TopOfStack;
576 SecCoreData->DataSize = sizeof(EFI_SEC_PEI_HAND_OFF);
577 SecCoreData->BootFirmwareVolumeBase = (VOID*)BootFirmwareVolumeBase;
cdccd99e 578 SecCoreData->BootFirmwareVolumeSize = PcdGet32 (PcdUnixFirmwareFdSize);
804405e7 579 SecCoreData->TemporaryRamBase = (VOID*)(UINTN)LargestRegion;
580 SecCoreData->TemporaryRamSize = STACK_SIZE;
581 SecCoreData->StackBase = SecCoreData->TemporaryRamBase;
582 SecCoreData->StackSize = PeiStackSize;
583 SecCoreData->PeiTemporaryRamBase = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + PeiStackSize);
584 SecCoreData->PeiTemporaryRamSize = STACK_SIZE - PeiStackSize;
585
586 //
587 // Load the PEI Core from a Firmware Volume
588 //
ccd55824 589 Status = SecUnixPeiLoadFile (
804405e7 590 PeiCorePe32File,
591 &PeiImageAddress,
592 &PeiCoreSize,
593 &PeiCoreEntryPoint
594 );
595 if (EFI_ERROR (Status)) {
596 return ;
597 }
598
599 //
600 // Transfer control to the PEI Core
601 //
602 PeiSwitchStacks (
603 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
604 SecCoreData,
605 (VOID *) (UINTN) ((EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable),
606 NULL,
607 TopOfStack
608 );
609 //
610 // If we get here, then the PEI Core returned. This is an error
611 //
612 return ;
613}
614
615EFI_STATUS
616EFIAPI
ccd55824 617SecUnixPeiAutoScan (
804405e7 618 IN UINTN Index,
619 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
620 OUT UINT64 *MemorySize
621 )
622/*++
623
624Routine Description:
625 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
626 It allows discontiguous memory regions to be supported by the emulator.
627 It uses gSystemMemory[] and gSystemMemoryCount that were created by
628 parsing the host environment variable EFI_MEMORY_SIZE.
629 The size comes from the varaible and the address comes from the call to
ccd55824 630 UnixOpenFile.
804405e7 631
632Arguments:
633 Index - Which memory region to use
634 MemoryBase - Return Base address of memory region
635 MemorySize - Return size in bytes of the memory region
636
637Returns:
638 EFI_SUCCESS - If memory region was mapped
639 EFI_UNSUPPORTED - If Index is not supported
640
641--*/
642{
643 void *res;
644
645 if (Index >= gSystemMemoryCount) {
646 return EFI_UNSUPPORTED;
647 }
648
649 *MemoryBase = 0;
650 res = MapMemory(0, gSystemMemory[Index].Size,
651 PROT_READ | PROT_WRITE | PROT_EXEC,
652 MAP_PRIVATE | MAP_ANONYMOUS);
653 if (res == MAP_FAILED)
654 return EFI_DEVICE_ERROR;
655 *MemorySize = gSystemMemory[Index].Size;
656 *MemoryBase = (UINTN)res;
657 gSystemMemory[Index].Memory = *MemoryBase;
658
659 return EFI_SUCCESS;
660}
661
662VOID *
663EFIAPI
ccd55824 664SecUnixUnixThunkAddress (
804405e7 665 VOID
666 )
667/*++
668
669Routine Description:
670 Since the SEC is the only Unix program in stack it must export
ccd55824 671 an interface to do POSIX calls. gUnix is initailized in UnixThunk.c.
804405e7 672
673Arguments:
674 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
ccd55824 675 InterfaceBase - Address of the gUnix global
804405e7 676
677Returns:
678 EFI_SUCCESS - Data returned
679
680--*/
681{
682 return gUnix;
683}
684
685
686EFI_STATUS
ccd55824 687SecUnixPeiLoadFile (
804405e7 688 IN VOID *Pe32Data,
ccd55824 689 OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
690 OUT UINT64 *ImageSize,
691 OUT EFI_PHYSICAL_ADDRESS *EntryPoint
804405e7 692 )
693/*++
694
695Routine Description:
696 Loads and relocates a PE/COFF image into memory.
697
698Arguments:
699 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
700 ImageAddress - The base address of the relocated PE/COFF image
701 ImageSize - The size of the relocated PE/COFF image
702 EntryPoint - The entry point of the relocated PE/COFF image
703
704Returns:
705 EFI_SUCCESS - The file was loaded and relocated
706 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
707
708--*/
709{
710 EFI_STATUS Status;
711 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
712
713 ZeroMem (&ImageContext, sizeof (ImageContext));
714 ImageContext.Handle = Pe32Data;
715
716 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
717
398b646f 718 Status = PeCoffLoaderGetImageInfo (&ImageContext);
804405e7 719 if (EFI_ERROR (Status)) {
720 return Status;
721 }
d34689b4 722
723
804405e7 724 //
725 // Allocate space in UNIX (not emulator) memory. Extra space is for alignment
726 //
d34689b4 727 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) MapMemory (
728 0,
729 (UINT32) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)),
730 PROT_READ | PROT_WRITE | PROT_EXEC,
731 MAP_ANONYMOUS | MAP_PRIVATE
732 );
804405e7 733 if (ImageContext.ImageAddress == 0) {
734 return EFI_OUT_OF_RESOURCES;
735 }
d34689b4 736
804405e7 737 //
738 // Align buffer on section boundry
739 //
f7bef78c 740 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
d34689b4 741 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)(ImageContext.SectionAlignment - 1));
804405e7 742
743
398b646f 744 Status = PeCoffLoaderLoadImage (&ImageContext);
804405e7 745 if (EFI_ERROR (Status)) {
746 return Status;
747 }
7ee3b613
A
748
749 Status = PeCoffLoaderRelocateImage (&ImageContext);
750 if (EFI_ERROR (Status)) {
751 return Status;
752 }
753
804405e7 754
ccd55824 755 SecPeCoffRelocateImageExtraAction (&ImageContext);
804405e7 756
757 //
758 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
759 //
760
761 *ImageAddress = ImageContext.ImageAddress;
762 *ImageSize = ImageContext.ImageSize;
763 *EntryPoint = ImageContext.EntryPoint;
764
765 return EFI_SUCCESS;
766}
767
ccd55824 768
769RETURN_STATUS
770EFIAPI
771SecPeCoffGetEntryPoint (
772 IN VOID *Pe32Data,
773 IN OUT VOID **EntryPoint
774 )
775{
776 EFI_STATUS Status;
777 EFI_PHYSICAL_ADDRESS ImageAddress;
778 UINT64 ImageSize;
779 EFI_PHYSICAL_ADDRESS PhysEntryPoint;
780
781 Status = SecUnixPeiLoadFile (Pe32Data, &ImageAddress, &ImageSize, &PhysEntryPoint);
782
783 *EntryPoint = (VOID *)(UINTN)PhysEntryPoint;
784 return Status;
785}
786
787
788
804405e7 789EFI_STATUS
790EFIAPI
ccd55824 791SecUnixFdAddress (
804405e7 792 IN UINTN Index,
793 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
7ee3b613
A
794 IN OUT UINT64 *FdSize,
795 IN OUT EFI_PHYSICAL_ADDRESS *FixUp
804405e7 796 )
797/*++
798
799Routine Description:
800 Return the FD Size and base address. Since the FD is loaded from a
801 file into host memory only the SEC will know it's address.
802
803Arguments:
804 Index - Which FD, starts at zero.
805 FdSize - Size of the FD in bytes
806 FdBase - Start address of the FD. Assume it points to an FV Header
7ee3b613 807 FixUp - Difference between actual FD address and build address
804405e7 808
809Returns:
810 EFI_SUCCESS - Return the Base address and size of the FV
811 EFI_UNSUPPORTED - Index does nto map to an FD in the system
812
813--*/
814{
815 if (Index >= gFdInfoCount) {
816 return EFI_UNSUPPORTED;
817 }
818
819 *FdBase = gFdInfo[Index].Address;
820 *FdSize = gFdInfo[Index].Size;
7ee3b613 821 *FixUp = 0;
804405e7 822
823 if (*FdBase == 0 && *FdSize == 0) {
824 return EFI_UNSUPPORTED;
825 }
826
7ee3b613
A
827 if (Index == 0) {
828 //
829 // FD 0 has XIP code and well known PCD values
830 // If the memory buffer could not be allocated at the FD build address
831 // the Fixup is the difference.
832 //
b9c8e50e 833 *FixUp = *FdBase - PcdGet64 (PcdUnixFdBaseAddress);
7ee3b613
A
834 }
835
804405e7 836 return EFI_SUCCESS;
837}
838
839EFI_STATUS
840EFIAPI
841SecImageRead (
842 IN VOID *FileHandle,
843 IN UINTN FileOffset,
844 IN OUT UINTN *ReadSize,
845 OUT VOID *Buffer
846 )
847/*++
848
849Routine Description:
850 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
851
852Arguments:
853 FileHandle - The handle to the PE/COFF file
854 FileOffset - The offset, in bytes, into the file to read
855 ReadSize - The number of bytes to read from the file starting at FileOffset
856 Buffer - A pointer to the buffer to read the data into.
857
858Returns:
859 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
860
861--*/
862{
863 CHAR8 *Destination8;
864 CHAR8 *Source8;
865 UINTN Length;
866
867 Destination8 = Buffer;
868 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
869 Length = *ReadSize;
870 while (Length--) {
871 *(Destination8++) = *(Source8++);
872 }
873
874 return EFI_SUCCESS;
875}
876
877UINTN
878CountSeperatorsInString (
879 IN const CHAR16 *String,
880 IN CHAR16 Seperator
881 )
882/*++
883
884Routine Description:
885 Count the number of seperators in String
886
887Arguments:
888 String - String to process
889 Seperator - Item to count
890
891Returns:
892 Number of Seperator in String
893
894--*/
895{
896 UINTN Count;
897
898 for (Count = 0; *String != '\0'; String++) {
899 if (*String == Seperator) {
900 Count++;
901 }
902 }
903
904 return Count;
905}
906
907
ccd55824 908EFI_STATUS
909AddHandle (
910 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
911 IN VOID *ModHandle
912 )
913/*++
914
915Routine Description:
916 Store the ModHandle in an array indexed by the Pdb File name.
917 The ModHandle is needed to unload the image.
918
919Arguments:
920 ImageContext - Input data returned from PE Laoder Library. Used to find the
921 .PDB file name of the PE Image.
922 ModHandle - Returned from LoadLibraryEx() and stored for call to
923 FreeLibrary().
924
925Returns:
926 EFI_SUCCESS - ModHandle was stored.
927
928--*/
929{
930 UINTN Index;
931 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
932 UINTN PreviousSize;
933
934
935 Array = mImageContextModHandleArray;
936 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
937 if (Array->ImageContext == NULL) {
938 //
939 // Make a copy of the stirng and store the ModHandle
940 //
941 Array->ImageContext = ImageContext;
942 Array->ModHandle = ModHandle;
943 return EFI_SUCCESS;
944 }
945 }
946
947 //
948 // No free space in mImageContextModHandleArray so grow it by
949 // IMAGE_CONTEXT_TO_MOD_HANDLE entires. realloc will
950 // copy the old values to the new locaiton. But it does
951 // not zero the new memory area.
952 //
953 PreviousSize = mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE);
954 mImageContextModHandleArraySize += MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE;
955
956 mImageContextModHandleArray = realloc (mImageContextModHandleArray, mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
957 if (mImageContextModHandleArray == NULL) {
958 ASSERT (FALSE);
959 return EFI_OUT_OF_RESOURCES;
960 }
961
962 memset (mImageContextModHandleArray + PreviousSize, 0, MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
963
964 return AddHandle (ImageContext, ModHandle);
965}
966
967
968VOID *
969RemoveHandle (
970 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
971 )
972/*++
973
974Routine Description:
975 Return the ModHandle and delete the entry in the array.
976
977Arguments:
978 ImageContext - Input data returned from PE Laoder Library. Used to find the
979 .PDB file name of the PE Image.
980
981Returns:
982 ModHandle - ModHandle assoicated with ImageContext is returned
983 NULL - No ModHandle associated with ImageContext
984
985--*/
986{
987 UINTN Index;
988 IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
989
990 if (ImageContext->PdbPointer == NULL) {
991 //
992 // If no PDB pointer there is no ModHandle so return NULL
993 //
994 return NULL;
995 }
996
997 Array = mImageContextModHandleArray;
998 for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
999 if ((Array->ImageContext == ImageContext)) {
1000 //
1001 // If you find a match return it and delete the entry
1002 //
1003 Array->ImageContext = NULL;
1004 return Array->ModHandle;
1005 }
1006 }
1007
1008 return NULL;
1009}
1010
1011
1012
1013//
1014// Target for gdb breakpoint in a script that uses gGdbWorkingFileName to source a
1015// add-symbol-file command. Hey what can you say scripting in gdb is not that great....
1016//
1017// Put .gdbinit in the CWD where you do gdb SecMain.dll for source level debug
1018//
1019// cat .gdbinit
1020// b SecGdbScriptBreak
1021// command
1022// silent
1023// source SecMain.dll.gdb
1024// c
1025// end
1026//
1027VOID
1028SecGdbScriptBreak (
1029 VOID
1030 )
1031{
1032}
804405e7 1033
804405e7 1034VOID
1035SecUnixLoaderBreak (
1036 VOID
1037 )
1038{
1039}
1040
ccd55824 1041BOOLEAN
1042IsPdbFile (
1043 IN CHAR8 *PdbFileName
1044 )
1045{
1046 UINTN Len;
1047
1048 if (PdbFileName == NULL) {
1049 return FALSE;
1050 }
1051
1052 Len = strlen (PdbFileName);
1053 if ((Len < 5)|| (PdbFileName[Len - 4] != '.')) {
1054 return FALSE;
1055 }
1056
1057 if ((PdbFileName[Len - 3] == 'P' || PdbFileName[Len - 3] == 'p') &&
1058 (PdbFileName[Len - 2] == 'D' || PdbFileName[Len - 2] == 'd') &&
1059 (PdbFileName[Len - 1] == 'B' || PdbFileName[Len - 1] == 'b')) {
1060 return TRUE;
1061 }
1062
1063 return FALSE;
1064}
1065
1066
1067#define MAX_SPRINT_BUFFER_SIZE 0x200
1068
1069void
1070PrintLoadAddress (
1071 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1072 )
1073{
bb111c23 1074 if (ImageContext->PdbPointer == NULL) {
1075 fprintf (stderr,
1076 "0x%08lx Loading NO DEBUG with entry point 0x%08lx\n",
1077 (unsigned long)(ImageContext->ImageAddress),
1078 (unsigned long)ImageContext->EntryPoint
1079 );
1080 } else {
1081 fprintf (stderr,
1082 "0x%08lx Loading %s with entry point 0x%08lx\n",
1083 (unsigned long)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders),
1084 ImageContext->PdbPointer,
1085 (unsigned long)ImageContext->EntryPoint
1086 );
1087 }
ccd55824 1088 // Keep output synced up
1089 fflush (stderr);
1090}
1091
1092
1093VOID
804405e7 1094EFIAPI
ccd55824 1095SecPeCoffRelocateImageExtraAction (
804405e7 1096 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1097 )
1098{
ccd55824 1099
1100#ifdef __APPLE__
1101 PrintLoadAddress (ImageContext);
1102
1103 //
1104 // In mach-o (OS X executable) dlopen() can only load files in the MH_DYLIB of MH_BUNDLE format.
1105 // To convert to PE/COFF we need to construct a mach-o with the MH_PRELOAD format. We create
1106 // .dSYM files for the PE/COFF images that can be used by gdb for source level debugging.
1107 //
1108 FILE *GdbTempFile;
1109
1110 //
1111 // In the Mach-O to PE/COFF conversion the size of the PE/COFF headers is not accounted for.
1112 // Thus we need to skip over the PE/COFF header when giving load addresses for our symbol table.
1113 //
1114 if (ImageContext->PdbPointer != NULL && !IsPdbFile (ImageContext->PdbPointer)) {
1115 //
1116 // Now we have a database of the images that are currently loaded
1117 //
1118
1119 //
1120 // 'symbol-file' will clear out currnet symbol mappings in gdb.
1121 // you can do a 'add-symbol-file filename address' for every image we loaded to get source
1122 // level debug in gdb. Note Sec, being a true application will work differently.
1123 //
1124 // We add the PE/COFF header size into the image as the mach-O does not have a header in
1125 // loaded into system memory.
1126 //
1127 // This gives us a data base of gdb commands and after something is unloaded that entry will be
1128 // removed. We don't yet have the scheme of how to comunicate with gdb, but we have the
1129 // data base of info ready to roll.
1130 //
1131 // We could use qXfer:libraries:read, but OS X GDB does not currently support it.
1132 // <library-list>
1133 // <library name="/lib/libc.so.6"> // ImageContext->PdbPointer
1134 // <segment address="0x10000000"/> // ImageContext->ImageAddress + ImageContext->SizeOfHeaders
1135 // </library>
1136 // </library-list>
1137 //
1138
1139 //
1140 // Write the file we need for the gdb script
1141 //
1142 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1143 if (GdbTempFile != NULL) {
d34689b4 1144 fprintf (GdbTempFile, "add-symbol-file %s 0x%08lx\n", ImageContext->PdbPointer, (long unsigned int)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders));
ccd55824 1145 fclose (GdbTempFile);
1146
1147 //
1148 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1149 // Hey what can you say scripting in gdb is not that great....
1150 //
1151 SecGdbScriptBreak ();
1152 }
1153
1154 AddHandle (ImageContext, ImageContext->PdbPointer);
1155
1156 }
1157
1158#else
1159
1160 void *Handle = NULL;
1161 void *Entry = NULL;
1162
804405e7 1163 fprintf (stderr,
1164 "Loading %s 0x%08lx - entry point 0x%08lx\n",
1165 ImageContext->PdbPointer,
1166 (unsigned long)ImageContext->ImageAddress,
1167 (unsigned long)ImageContext->EntryPoint);
1168
7ee3b613 1169 Handle = dlopen (ImageContext->PdbPointer, RTLD_NOW);
865c7e17 1170
1171 if (Handle) {
7ee3b613 1172 Entry = dlsym (Handle, "_ModuleEntryPoint");
865c7e17 1173 } else {
1174 printf("%s\n", dlerror());
1175 }
1176
1177 if (Entry != NULL) {
ccd55824 1178 ImageContext->EntryPoint = (UINTN)Entry;
1179 printf("Change %s Entrypoint to :0x%08lx\n", ImageContext->PdbPointer, (unsigned long)Entry);
865c7e17 1180 }
1181
804405e7 1182 SecUnixLoaderBreak ();
1183
ccd55824 1184#endif
1185
1186 return;
804405e7 1187}
1188
1189
ccd55824 1190VOID
804405e7 1191EFIAPI
ccd55824 1192SecPeCoffLoaderUnloadImageExtraAction (
804405e7 1193 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
1194 )
1195{
ccd55824 1196 VOID *Handle;
1197
1198 Handle = RemoveHandle (ImageContext);
1199
1200#ifdef __APPLE__
1201 FILE *GdbTempFile;
1202
1203 if (Handle != NULL) {
1204 //
1205 // Need to skip .PDB files created from VC++
1206 //
1207 if (!IsPdbFile (ImageContext->PdbPointer)) {
1208 //
1209 // Write the file we need for the gdb script
1210 //
1211 GdbTempFile = fopen (gGdbWorkingFileName, "w");
1212 if (GdbTempFile != NULL) {
1213 fprintf (GdbTempFile, "remove-symbol-file %s\n", ImageContext->PdbPointer);
1214 fclose (GdbTempFile);
1215
1216 //
1217 // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
1218 // Hey what can you say scripting in gdb is not that great....
1219 //
1220 SecGdbScriptBreak ();
1221 }
1222 }
1223 }
1224
1225#else
1226 //
1227 // Don't want to confuse gdb with symbols for something that got unloaded
1228 //
1229 if (Handle != NULL) {
1230 dlclose (Handle);
1231 }
1232
1233#endif
1234 return;
804405e7 1235}
1236
1237VOID
1238ModuleEntryPoint (
1239 VOID
1240 )
1241{
1242}
1243
1244EFI_STATUS
1245EFIAPI
1246SecTemporaryRamSupport (
1247 IN CONST EFI_PEI_SERVICES **PeiServices,
1248 IN EFI_PHYSICAL_ADDRESS TemporaryMemoryBase,
1249 IN EFI_PHYSICAL_ADDRESS PermanentMemoryBase,
1250 IN UINTN CopySize
1251 )
1252{
1253 //
1254 // Migrate the whole temporary memory to permenent memory.
1255 //
1256 CopyMem (
1257 (VOID*)(UINTN)PermanentMemoryBase,
1258 (VOID*)(UINTN)TemporaryMemoryBase,
1259 CopySize
1260 );
1261
1262 //
1263 // SecSwitchStack function must be invoked after the memory migration
1264 // immediatly, also we need fixup the stack change caused by new call into
1265 // permenent memory.
1266 //
1267 SecSwitchStack (
1268 (UINT32) TemporaryMemoryBase,
1269 (UINT32) PermanentMemoryBase
1270 );
1271
1272 //
1273 // We need *not* fix the return address because currently,
1274 // The PeiCore is excuted in flash.
1275 //
1276
1277 //
1fd8c31a 1278 // Simulate to invalid temporary memory, terminate temporary memory
804405e7 1279 //
1280 //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);
1281
1282 return EFI_SUCCESS;
1283}