Unix version of EFI emulator
[mirror_edk2.git] / EdkUnixPkg / Sec / SecMain.c
1 /*++
2
3 Copyright (c) 2006, Intel Corporation
4 All rights reserved. This program and the accompanying materials
5 are licensed and made available under the terms and conditions of the BSD License
6 which accompanies this distribution. The full text of the license may be found at
7 http://opensource.org/licenses/bsd-license.php
8
9 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11
12 Module Name:
13
14 SecMain.c
15
16 Abstract:
17 WinNt emulator of SEC phase. It's really a Win32 application, but this is
18 Ok since all the other modules for NT32 are NOT Win32 applications.
19
20 This program processes Windows environment variables and figures out
21 what the memory layout will be, how may FD's will be loaded and also
22 what the boot mode is.
23
24 The SEC registers a set of services with the SEC core. gPrivateDispatchTable
25 is a list of PPI's produced by the SEC that are availble for usage in PEI.
26
27 This code produces 128 K of temporary memory for the PEI stack by opening a
28 Windows file and mapping it directly to memory addresses.
29
30 The system.cmd script is used to set windows environment variables that drive
31 the configuration opitons of the SEC.
32
33 --*/
34
35 #include "SecMain.h"
36 #include <stdlib.h>
37 #include <sys/mman.h>
38 #include <sys/fcntl.h>
39 #include <unistd.h>
40
41 //
42 // Globals
43 //
44 EFI_PEI_PE_COFF_LOADER_PROTOCOL_INSTANCE mPeiEfiPeiPeCoffLoaderInstance = {
45 {
46 SecNt32PeCoffGetImageInfo,
47 SecNt32PeCoffLoadImage,
48 SecNt32PeCoffRelocateImage,
49 SecNt32PeCoffUnloadimage
50 },
51 NULL
52 };
53
54
55
56 EFI_PEI_PE_COFF_LOADER_PROTOCOL *gPeiEfiPeiPeCoffLoader = &mPeiEfiPeiPeCoffLoaderInstance.PeCoff;
57
58 UNIX_PEI_LOAD_FILE_PPI mSecNtLoadFilePpi = { SecWinNtPeiLoadFile };
59
60 PEI_UNIX_AUTOSCAN_PPI mSecNtAutoScanPpi = { SecWinNtPeiAutoScan };
61
62 PEI_UNIX_THUNK_PPI mSecWinNtThunkPpi = { SecWinNtWinNtThunkAddress };
63
64 EFI_PEI_PROGRESS_CODE_PPI mSecStatusCodePpi = { SecPeiReportStatusCode };
65
66 UNIX_FWH_PPI mSecFwhInformationPpi = { SecWinNtFdAddress };
67
68
69 EFI_PEI_PPI_DESCRIPTOR gPrivateDispatchTable[] = {
70 {
71 EFI_PEI_PPI_DESCRIPTOR_PPI,
72 &gEfiPeiPeCoffLoaderGuid,
73 NULL
74 },
75 {
76 EFI_PEI_PPI_DESCRIPTOR_PPI,
77 &gUnixPeiLoadFilePpiGuid,
78 &mSecNtLoadFilePpi
79 },
80 {
81 EFI_PEI_PPI_DESCRIPTOR_PPI,
82 &gPeiUnixAutoScanPpiGuid,
83 &mSecNtAutoScanPpi
84 },
85 {
86 EFI_PEI_PPI_DESCRIPTOR_PPI,
87 &gPeiUnixThunkPpiGuid,
88 &mSecWinNtThunkPpi
89 },
90 {
91 EFI_PEI_PPI_DESCRIPTOR_PPI,
92 &gEfiPeiStatusCodePpiGuid,
93 &mSecStatusCodePpi
94 },
95 {
96 EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
97 &gUnixFwhPpiGuid,
98 &mSecFwhInformationPpi
99 }
100 };
101
102
103 //
104 // Default information about where the FD is located.
105 // This array gets filled in with information from EFI_FIRMWARE_VOLUMES
106 // EFI_FIRMWARE_VOLUMES is a Windows environment variable set by system.cmd.
107 // The number of array elements is allocated base on parsing
108 // EFI_FIRMWARE_VOLUMES and the memory is never freed.
109 //
110 UINTN gFdInfoCount = 0;
111 UNIX_FD_INFO *gFdInfo;
112
113 //
114 // Array that supports seperate memory rantes.
115 // The memory ranges are set in system.cmd via the EFI_MEMORY_SIZE variable.
116 // The number of array elements is allocated base on parsing
117 // EFI_MEMORY_SIZE and the memory is never freed.
118 //
119 UINTN gSystemMemoryCount = 0;
120 UNIX_SYSTEM_MEMORY *gSystemMemory;
121
122
123 STATIC
124 EFI_PHYSICAL_ADDRESS *
125 MapMemory (
126 INTN fd,
127 UINT64 length,
128 INTN prot,
129 INTN flags);
130
131 STATIC
132 EFI_STATUS
133 MapFile (
134 IN CHAR8 *FileName,
135 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
136 OUT UINT64 *Length
137 );
138
139
140 INTN
141 EFIAPI
142 main (
143 IN INTN Argc,
144 IN CHAR8 **Argv,
145 IN CHAR8 **Envp
146 )
147 /*++
148
149 Routine Description:
150 Main entry point to SEC for WinNt. This is a Windows program
151
152 Arguments:
153 Argc - Number of command line arguments
154 Argv - Array of command line argument strings
155 Envp - Array of environmemt variable strings
156
157 Returns:
158 0 - Normal exit
159 1 - Abnormal exit
160
161 --*/
162 {
163 EFI_STATUS Status;
164 EFI_PHYSICAL_ADDRESS InitialStackMemory;
165 UINT64 InitialStackMemorySize;
166 UINTN Index;
167 UINTN Index1;
168 UINTN Index2;
169 UINTN PeiIndex;
170 CHAR8 *FileName;
171 BOOLEAN Done;
172 VOID *PeiCoreFile;
173 CHAR16 *MemorySizeStr;
174 CHAR16 *FirmwareVolumesStr;
175
176 MemorySizeStr = (CHAR16 *)PcdGetPtr (PcdUnixMemorySizeForSecMain);
177 FirmwareVolumesStr = (CHAR16 *)PcdGetPtr (PcdUnixFirmwareVolume);
178
179 printf ("\nEDK SEC Main NT Emulation Environment from www.TianoCore.org\n");
180
181 //
182 // Allocate space for gSystemMemory Array
183 //
184 gSystemMemoryCount = CountSeperatorsInString (MemorySizeStr, '!') + 1;
185 gSystemMemory = calloc (gSystemMemoryCount, sizeof (UNIX_SYSTEM_MEMORY));
186 if (gSystemMemory == NULL) {
187 printf ("ERROR : Can not allocate memory for system. Exiting.\n");
188 exit (1);
189 }
190 //
191 // Allocate space for gSystemMemory Array
192 //
193 gFdInfoCount = CountSeperatorsInString (FirmwareVolumesStr, '!') + 1;
194 gFdInfo = calloc (gFdInfoCount, sizeof (UNIX_FD_INFO));
195 if (gFdInfo == NULL) {
196 printf ("ERROR : Can not allocate memory for fd info. Exiting.\n");
197 exit (1);
198 }
199 //
200 // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)
201 //
202 printf (" BootMode 0x%02x\n", FixedPcdGet32 (PcdUnixBootMode));
203
204 //
205 // Open up a 128K file to emulate temp memory for PEI.
206 // on a real platform this would be SRAM, or using the cache as RAM.
207 // Set InitialStackMemory to zero so WinNtOpenFile will allocate a new mapping
208 //
209 InitialStackMemorySize = 0x20000;
210 InitialStackMemory = (UINTN)MapMemory(0,
211 (UINT32) InitialStackMemorySize,
212 PROT_READ | PROT_WRITE,
213 MAP_ANONYMOUS | MAP_PRIVATE);
214 if (InitialStackMemory == 0) {
215 printf ("ERROR : Can not open SecStack Exiting\n");
216 exit (1);
217 }
218
219 printf (" SEC passing in %u KB of temp RAM at 0x%08lx to PEI\n",
220 (UINTN)(InitialStackMemorySize / 1024),
221 (unsigned long)InitialStackMemory);
222
223 //
224 // Open All the firmware volumes and remember the info in the gFdInfo global
225 //
226 FileName = (CHAR8 *)malloc (StrLen (FirmwareVolumesStr) + 1);
227 if (FileName == NULL) {
228 printf ("ERROR : Can not allocate memory for firmware volume string\n");
229 exit (1);
230 }
231
232 Index2 = 0;
233 for (Done = FALSE, Index = 0, PeiIndex = 0, PeiCoreFile = NULL;
234 FirmwareVolumesStr[Index2] != 0;
235 Index++) {
236 for (Index1 = 0; (FirmwareVolumesStr[Index2] != '!') && (FirmwareVolumesStr[Index2] != 0); Index2++)
237 FileName[Index1++] = FirmwareVolumesStr[Index2];
238 if (FirmwareVolumesStr[Index2] == '!')
239 Index2++;
240 FileName[Index1] = '\0';
241
242 //
243 // Open the FD and remmeber where it got mapped into our processes address space
244 //
245 Status = MapFile (
246 FileName,
247 &gFdInfo[Index].Address,
248 &gFdInfo[Index].Size
249 );
250 if (EFI_ERROR (Status)) {
251 printf ("ERROR : Can not open Firmware Device File %s (%x). Exiting.\n", FileName, Status);
252 exit (1);
253 }
254
255 printf (" FD loaded from %s at 0x%08lx",
256 FileName, (unsigned long)gFdInfo[Index].Address);
257
258 if (PeiCoreFile == NULL) {
259 //
260 // Assume the beginning of the FD is an FV and look for the PEI Core.
261 // Load the first one we find.
262 //
263 Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);
264 if (!EFI_ERROR (Status)) {
265 PeiIndex = Index;
266 printf (" contains SEC Core");
267 }
268 }
269
270 printf ("\n");
271 }
272 //
273 // Calculate memory regions and store the information in the gSystemMemory
274 // global for later use. The autosizing code will use this data to
275 // map this memory into the SEC process memory space.
276 //
277 Index1 = 0;
278 Index = 0;
279 while (1) {
280 UINTN val = 0;
281 //
282 // Save the size of the memory.
283 //
284 while (MemorySizeStr[Index1] >= '0' && MemorySizeStr[Index1] <= '9') {
285 val = val * 10 + MemorySizeStr[Index1] - '0';
286 Index1++;
287 }
288 gSystemMemory[Index++].Size = val * 0x100000;
289 if (MemorySizeStr[Index1] == 0)
290 break;
291 Index1++;
292 }
293
294 printf ("\n");
295
296 //
297 // Hand off to PEI Core
298 //
299 SecLoadFromCore ((UINTN) InitialStackMemory, (UINTN) InitialStackMemorySize, (UINTN) gFdInfo[0].Address, PeiCoreFile);
300
301 //
302 // If we get here, then the PEI Core returned. This is an error as PEI should
303 // always hand off to DXE.
304 //
305 printf ("ERROR : PEI Core returned\n");
306 exit (1);
307 }
308
309 EFI_PHYSICAL_ADDRESS *
310 MapMemory (
311 INTN fd,
312 UINT64 length,
313 INTN prot,
314 INTN flags)
315 {
316 static UINTN base = 0x40000000;
317 const UINTN align = (1 << 24);
318 void *res;
319
320 res = mmap ((void *)base, length, prot, flags, fd, 0);
321 if (res == MAP_FAILED)
322 return NULL;
323
324 // Guard page.
325 base += length + 4096;
326 base = (base + align - 1) & ~(align - 1);
327
328 return res;
329 }
330
331 EFI_STATUS
332 MapFile (
333 IN CHAR8 *FileName,
334 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
335 OUT UINT64 *Length
336 )
337 /*++
338
339 Routine Description:
340 Opens and memory maps a file using WinNt services. If BaseAddress is non zero
341 the process will try and allocate the memory starting at BaseAddress.
342
343 Arguments:
344 FileName - The name of the file to open and map
345 MapSize - The amount of the file to map in bytes
346 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
347 memory emulation, and exiting files for firmware volume emulation
348 BaseAddress - The base address of the mapped file in the user address space.
349 If passed in as NULL the a new memory region is used.
350 If passed in as non NULL the request memory region is used for
351 the mapping of the file into the process space.
352 Length - The size of the mapped region in bytes
353
354 Returns:
355 EFI_SUCCESS - The file was opened and mapped.
356 EFI_NOT_FOUND - FileName was not found in the current directory
357 EFI_DEVICE_ERROR - An error occured attempting to map the opened file
358
359 --*/
360 {
361 int fd;
362 VOID *res;
363 UINTN FileSize;
364
365 fd = open (FileName, O_RDONLY);
366 if (fd < 0)
367 return EFI_NOT_FOUND;
368 FileSize = lseek (fd, 0, SEEK_END);
369
370 #if 0
371 if (IsMain)
372 {
373 /* Read entry address. */
374 lseek (fd, FileSize - 0x20, SEEK_SET);
375 if (read (fd, &EntryAddress, 4) != 4)
376 {
377 close (fd);
378 return EFI_DEVICE_ERROR;
379 }
380 }
381 #endif
382
383 res = MapMemory(fd, FileSize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE);
384
385 close (fd);
386
387 if (res == MAP_FAILED)
388 return EFI_DEVICE_ERROR;
389
390 *Length = (UINT64) FileSize;
391 *BaseAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) res;
392
393 return EFI_SUCCESS;
394 }
395
396 #define BYTES_PER_RECORD 512
397
398 /**
399 Extracts ASSERT() information from a status code structure.
400
401 Converts the status code specified by CodeType, Value, and Data to the ASSERT()
402 arguments specified by Filename, Description, and LineNumber. If CodeType is
403 an EFI_ERROR_CODE, and CodeType has a severity of EFI_ERROR_UNRECOVERED, and
404 Value has an operation mask of EFI_SW_EC_ILLEGAL_SOFTWARE_STATE, extract
405 Filename, Description, and LineNumber from the optional data area of the
406 status code buffer specified by Data. The optional data area of Data contains
407 a Null-terminated ASCII string for the FileName, followed by a Null-terminated
408 ASCII string for the Description, followed by a 32-bit LineNumber. If the
409 ASSERT() information could be extracted from Data, then return TRUE.
410 Otherwise, FALSE is returned.
411
412 If Data is NULL, then ASSERT().
413 If Filename is NULL, then ASSERT().
414 If Description is NULL, then ASSERT().
415 If LineNumber is NULL, then ASSERT().
416
417 @param CodeType The type of status code being converted.
418 @param Value The status code value being converted.
419 @param Data Pointer to status code data buffer.
420 @param Filename Pointer to the source file name that generated the ASSERT().
421 @param Description Pointer to the description of the ASSERT().
422 @param LineNumber Pointer to source line number that generated the ASSERT().
423
424 @retval TRUE The status code specified by CodeType, Value, and Data was
425 converted ASSERT() arguments specified by Filename, Description,
426 and LineNumber.
427 @retval FALSE The status code specified by CodeType, Value, and Data could
428 not be converted to ASSERT() arguments.
429
430 **/
431 STATIC
432 BOOLEAN
433 ReportStatusCodeExtractAssertInfo (
434 IN EFI_STATUS_CODE_TYPE CodeType,
435 IN EFI_STATUS_CODE_VALUE Value,
436 IN CONST EFI_STATUS_CODE_DATA *Data,
437 OUT CHAR8 **Filename,
438 OUT CHAR8 **Description,
439 OUT UINT32 *LineNumber
440 )
441 {
442 EFI_DEBUG_ASSERT_DATA *AssertData;
443
444 ASSERT (Data != NULL);
445 ASSERT (Filename != NULL);
446 ASSERT (Description != NULL);
447 ASSERT (LineNumber != NULL);
448
449 if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
450 ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) &&
451 ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) {
452 AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1);
453 *Filename = (CHAR8 *)(AssertData + 1);
454 *Description = *Filename + AsciiStrLen (*Filename) + 1;
455 *LineNumber = AssertData->LineNumber;
456 return TRUE;
457 }
458 return FALSE;
459 }
460
461 EFI_STATUS
462 EFIAPI
463 SecPeiReportStatusCode (
464 IN EFI_PEI_SERVICES **PeiServices,
465 IN EFI_STATUS_CODE_TYPE CodeType,
466 IN EFI_STATUS_CODE_VALUE Value,
467 IN UINT32 Instance,
468 IN EFI_GUID * CallerId,
469 IN EFI_STATUS_CODE_DATA * Data OPTIONAL
470 )
471 /*++
472
473 Routine Description:
474
475 This routine produces the ReportStatusCode PEI service. It's passed
476 up to the PEI Core via a PPI. T
477
478 This code currently uses the NT clib printf. This does not work the same way
479 as the EFI Print (), as %t, %g, %s as Unicode are not supported.
480
481 Arguments:
482 (see EFI_PEI_REPORT_STATUS_CODE)
483
484 Returns:
485 EFI_SUCCESS - Always return success
486
487 --*/
488 // TODO: PeiServices - add argument and description to function comment
489 // TODO: CodeType - add argument and description to function comment
490 // TODO: Value - add argument and description to function comment
491 // TODO: Instance - add argument and description to function comment
492 // TODO: CallerId - add argument and description to function comment
493 // TODO: Data - add argument and description to function comment
494 {
495 CHAR8 *Format;
496 EFI_DEBUG_INFO *DebugInfo;
497 VA_LIST Marker;
498 CHAR8 PrintBuffer[BYTES_PER_RECORD * 2];
499 CHAR8 *Filename;
500 CHAR8 *Description;
501 UINT32 LineNumber;
502
503 if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
504 //
505 // This supports DEBUG () marcos
506 // Data format
507 // EFI_STATUS_CODE_DATA
508 // EFI_DEBUG_INFO
509 //
510 // The first 12 * UINT64 bytes of the string are really an
511 // arguement stack to support varargs on the Format string.
512 //
513 if (Data != NULL) {
514 DebugInfo = (EFI_DEBUG_INFO *) (Data + 1);
515 Marker = (VA_LIST) (DebugInfo + 1);
516 Format = (CHAR8 *) (((UINT64 *) Marker) + 12);
517
518 AsciiVSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
519 printf (PrintBuffer);
520 } else {
521 printf ("DEBUG <null>\n");
522 }
523 }
524
525 if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
526 ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED)
527 ) {
528 if (Data != NULL && ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
529 //
530 // Support ASSERT () macro
531 //
532 printf ("ASSERT %s(%d): %s\n", Filename, LineNumber, Description);
533 } else {
534 printf ("ASSERT <null>\n");
535 }
536 CpuBreakpoint ();
537 }
538
539 return EFI_SUCCESS;
540 }
541
542
543 VOID
544 SecLoadFromCore (
545 IN UINTN LargestRegion,
546 IN UINTN LargestRegionSize,
547 IN UINTN BootFirmwareVolumeBase,
548 IN VOID *PeiCorePe32File
549 )
550 /*++
551
552 Routine Description:
553 This is the service to load the PEI Core from the Firmware Volume
554
555 Arguments:
556 LargestRegion - Memory to use for PEI.
557 LargestRegionSize - Size of Memory to use for PEI
558 BootFirmwareVolumeBase - Start of the Boot FV
559 PeiCorePe32File - PEI Core PE32
560
561 Returns:
562 Success means control is transfered and thus we should never return
563
564 --*/
565 {
566 EFI_STATUS Status;
567 EFI_PHYSICAL_ADDRESS TopOfMemory;
568 VOID *TopOfStack;
569 UINT64 PeiCoreSize;
570 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
571 EFI_PHYSICAL_ADDRESS PeiImageAddress;
572 EFI_PEI_STARTUP_DESCRIPTOR *PeiStartup;
573
574 //
575 // Compute Top Of Memory for Stack and PEI Core Allocations
576 //
577 TopOfMemory = LargestRegion + LargestRegionSize;
578
579 //
580 // Allocate 128KB for the Stack
581 //
582 TopOfStack = (VOID *)((UINTN)TopOfMemory - sizeof (EFI_PEI_STARTUP_DESCRIPTOR) - CPU_STACK_ALIGNMENT);
583 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
584 TopOfMemory = TopOfMemory - STACK_SIZE;
585
586 //
587 // Patch value in dispatch table values
588 //
589 gPrivateDispatchTable[0].Ppi = gPeiEfiPeiPeCoffLoader;
590
591 //
592 // Bind this information into the SEC hand-off state
593 //
594 PeiStartup = (EFI_PEI_STARTUP_DESCRIPTOR *) (UINTN) TopOfStack;
595 PeiStartup->DispatchTable = (EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable;
596 PeiStartup->SizeOfCacheAsRam = STACK_SIZE;
597 PeiStartup->BootFirmwareVolume = BootFirmwareVolumeBase;
598
599 //
600 // Load the PEI Core from a Firmware Volume
601 //
602 Status = SecWinNtPeiLoadFile (
603 PeiCorePe32File,
604 &PeiImageAddress,
605 &PeiCoreSize,
606 &PeiCoreEntryPoint
607 );
608 if (EFI_ERROR (Status)) {
609 return ;
610 }
611 printf ("Jump to 0x%08lx\n", (unsigned long)PeiCoreEntryPoint);
612 //
613 // Transfer control to the PEI Core
614 //
615 SwitchStack (
616 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
617 PeiStartup,
618 NULL,
619 TopOfStack
620 );
621 //
622 // If we get here, then the PEI Core returned. This is an error
623 //
624 return ;
625 }
626
627 EFI_STATUS
628 EFIAPI
629 SecWinNtPeiAutoScan (
630 IN UINTN Index,
631 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
632 OUT UINT64 *MemorySize
633 )
634 /*++
635
636 Routine Description:
637 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
638 It allows discontiguous memory regions to be supported by the emulator.
639 It uses gSystemMemory[] and gSystemMemoryCount that were created by
640 parsing the Windows environment variable EFI_MEMORY_SIZE.
641 The size comes from the varaible and the address comes from the call to
642 WinNtOpenFile.
643
644 Arguments:
645 Index - Which memory region to use
646 MemoryBase - Return Base address of memory region
647 MemorySize - Return size in bytes of the memory region
648
649 Returns:
650 EFI_SUCCESS - If memory region was mapped
651 EFI_UNSUPPORTED - If Index is not supported
652
653 --*/
654 {
655 void *res;
656
657 if (Index >= gSystemMemoryCount) {
658 return EFI_UNSUPPORTED;
659 }
660
661 *MemoryBase = 0;
662 res = MapMemory(0, gSystemMemory[Index].Size,
663 PROT_READ | PROT_WRITE | PROT_EXEC,
664 MAP_PRIVATE | MAP_ANONYMOUS);
665 if (res == MAP_FAILED)
666 return EFI_DEVICE_ERROR;
667 *MemorySize = gSystemMemory[Index].Size;
668 *MemoryBase = (UINTN)res;
669 gSystemMemory[Index].Memory = *MemoryBase;
670
671 return EFI_SUCCESS;
672 }
673
674 VOID *
675 EFIAPI
676 SecWinNtWinNtThunkAddress (
677 VOID
678 )
679 /*++
680
681 Routine Description:
682 Since the SEC is the only Windows program in stack it must export
683 an interface to do Win API calls. That's what the WinNtThunk address
684 is for. gWinNt is initailized in WinNtThunk.c.
685
686 Arguments:
687 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
688 InterfaceBase - Address of the gWinNt global
689
690 Returns:
691 EFI_SUCCESS - Data returned
692
693 --*/
694 {
695 return gUnix;
696 }
697
698
699 EFI_STATUS
700 EFIAPI
701 SecWinNtPeiLoadFile (
702 IN VOID *Pe32Data,
703 IN EFI_PHYSICAL_ADDRESS *ImageAddress,
704 IN UINT64 *ImageSize,
705 IN EFI_PHYSICAL_ADDRESS *EntryPoint
706 )
707 /*++
708
709 Routine Description:
710 Loads and relocates a PE/COFF image into memory.
711
712 Arguments:
713 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
714 ImageAddress - The base address of the relocated PE/COFF image
715 ImageSize - The size of the relocated PE/COFF image
716 EntryPoint - The entry point of the relocated PE/COFF image
717
718 Returns:
719 EFI_SUCCESS - The file was loaded and relocated
720 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
721
722 --*/
723 {
724 EFI_STATUS Status;
725 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
726
727 ZeroMem (&ImageContext, sizeof (ImageContext));
728 ImageContext.Handle = Pe32Data;
729
730 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
731
732 Status = gPeiEfiPeiPeCoffLoader->GetImageInfo (gPeiEfiPeiPeCoffLoader, &ImageContext);
733 if (EFI_ERROR (Status)) {
734 return Status;
735 }
736 //
737 // Allocate space in NT (not emulator) memory. Extra space is for alignment
738 //
739 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) malloc ((UINTN) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)));
740 if (ImageContext.ImageAddress == 0) {
741 return EFI_OUT_OF_RESOURCES;
742 }
743 //
744 // Align buffer on section boundry
745 //
746 ImageContext.ImageAddress += ImageContext.SectionAlignment;
747 ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);
748
749
750 Status = gPeiEfiPeiPeCoffLoader->LoadImage (gPeiEfiPeiPeCoffLoader, &ImageContext);
751 if (EFI_ERROR (Status)) {
752 return Status;
753 }
754
755 Status = gPeiEfiPeiPeCoffLoader->RelocateImage (gPeiEfiPeiPeCoffLoader, &ImageContext);
756 if (EFI_ERROR (Status)) {
757 return Status;
758 }
759
760 //
761 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
762 //
763
764 *ImageAddress = ImageContext.ImageAddress;
765 *ImageSize = ImageContext.ImageSize;
766 *EntryPoint = ImageContext.EntryPoint;
767
768 return EFI_SUCCESS;
769 }
770
771 EFI_STATUS
772 EFIAPI
773 SecWinNtFdAddress (
774 IN UINTN Index,
775 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
776 IN OUT UINT64 *FdSize
777 )
778 /*++
779
780 Routine Description:
781 Return the FD Size and base address. Since the FD is loaded from a
782 file into Windows memory only the SEC will know it's address.
783
784 Arguments:
785 Index - Which FD, starts at zero.
786 FdSize - Size of the FD in bytes
787 FdBase - Start address of the FD. Assume it points to an FV Header
788
789 Returns:
790 EFI_SUCCESS - Return the Base address and size of the FV
791 EFI_UNSUPPORTED - Index does nto map to an FD in the system
792
793 --*/
794 {
795 if (Index >= gFdInfoCount) {
796 return EFI_UNSUPPORTED;
797 }
798
799 *FdBase = gFdInfo[Index].Address;
800 *FdSize = gFdInfo[Index].Size;
801
802 if (*FdBase == 0 && *FdSize == 0) {
803 return EFI_UNSUPPORTED;
804 }
805
806 return EFI_SUCCESS;
807 }
808
809 EFI_STATUS
810 EFIAPI
811 SecImageRead (
812 IN VOID *FileHandle,
813 IN UINTN FileOffset,
814 IN OUT UINTN *ReadSize,
815 OUT VOID *Buffer
816 )
817 /*++
818
819 Routine Description:
820 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
821
822 Arguments:
823 FileHandle - The handle to the PE/COFF file
824 FileOffset - The offset, in bytes, into the file to read
825 ReadSize - The number of bytes to read from the file starting at FileOffset
826 Buffer - A pointer to the buffer to read the data into.
827
828 Returns:
829 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
830
831 --*/
832 {
833 CHAR8 *Destination8;
834 CHAR8 *Source8;
835 UINTN Length;
836
837 Destination8 = Buffer;
838 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
839 Length = *ReadSize;
840 while (Length--) {
841 *(Destination8++) = *(Source8++);
842 }
843
844 return EFI_SUCCESS;
845 }
846
847 UINTN
848 CountSeperatorsInString (
849 IN const CHAR16 *String,
850 IN CHAR16 Seperator
851 )
852 /*++
853
854 Routine Description:
855 Count the number of seperators in String
856
857 Arguments:
858 String - String to process
859 Seperator - Item to count
860
861 Returns:
862 Number of Seperator in String
863
864 --*/
865 {
866 UINTN Count;
867
868 for (Count = 0; *String != '\0'; String++) {
869 if (*String == Seperator) {
870 Count++;
871 }
872 }
873
874 return Count;
875 }
876
877
878
879 EFI_STATUS
880 EFIAPI
881 SecNt32PeCoffGetImageInfo (
882 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
883 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
884 )
885 {
886 EFI_STATUS Status;
887
888 Status = PeCoffLoaderGetImageInfo (ImageContext);
889 if (EFI_ERROR (Status)) {
890 return Status;
891 }
892
893 switch (ImageContext->ImageType) {
894
895 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
896 ImageContext->ImageCodeMemoryType = EfiLoaderCode;
897 ImageContext->ImageDataMemoryType = EfiLoaderData;
898 break;
899
900 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
901 ImageContext->ImageCodeMemoryType = EfiBootServicesCode;
902 ImageContext->ImageDataMemoryType = EfiBootServicesData;
903 break;
904
905 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
906 case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
907 ImageContext->ImageCodeMemoryType = EfiRuntimeServicesCode;
908 ImageContext->ImageDataMemoryType = EfiRuntimeServicesData;
909 break;
910
911 default:
912 ImageContext->ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM;
913 return RETURN_UNSUPPORTED;
914 }
915
916 return Status;
917 }
918
919 EFI_STATUS
920 EFIAPI
921 SecNt32PeCoffLoadImage (
922 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
923 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
924 )
925 {
926 EFI_STATUS Status;
927
928 Status = PeCoffLoaderLoadImage (ImageContext);
929 return Status;
930 }
931
932 VOID
933 SecUnixLoaderBreak (
934 VOID
935 )
936 {
937 }
938
939 EFI_STATUS
940 EFIAPI
941 SecNt32PeCoffRelocateImage (
942 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
943 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
944 )
945 {
946
947 #if 0
948 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
949 EFI_IMAGE_SECTION_HEADER *Sec;
950 INTN i;
951 #endif
952
953 fprintf (stderr,
954 "Loading %s 0x%08lx - entry point 0x%08lx\n",
955 ImageContext->PdbPointer,
956 (unsigned long)ImageContext->ImageAddress,
957 (unsigned long)ImageContext->EntryPoint);
958
959 #if 0
960 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)
961 ((UINTN)ImageContext->ImageAddress + ImageContext->PeCoffHeaderOffset);
962 Sec = (EFI_IMAGE_SECTION_HEADER*)
963 ((UINTN)ImageContext->ImageAddress
964 + ImageContext->PeCoffHeaderOffset
965 + sizeof(UINT32)
966 + sizeof(EFI_IMAGE_FILE_HEADER)
967 + Hdr.Pe32->FileHeader.SizeOfOptionalHeader);
968 for (i = 0; i < Hdr.Pe32->FileHeader.NumberOfSections; i++)
969 fprintf (stderr, " %s 0x%08lx\n",
970 Sec[i].Name, (unsigned long)Sec[i].VirtualAddress);
971 #endif
972
973 SecUnixLoaderBreak ();
974
975 return PeCoffLoaderRelocateImage (ImageContext);
976 }
977
978
979 EFI_STATUS
980 EFIAPI
981 SecNt32PeCoffUnloadimage (
982 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
983 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
984 )
985 {
986 return EFI_SUCCESS;
987 }
988
989 VOID
990 _ModuleEntryPoint (
991 VOID
992 )
993 {
994 }
995