Always return an aligned block when mapping memory.
[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 BOOLEAN isAligned = 0;
320
321 //
322 // Try to get an aligned block somewhere in the address space of this
323 // process.
324 //
325 while((!isAligned) && (base != 0)) {
326 res = mmap ((void *)base, length, prot, flags, fd, 0);
327 if (res == MAP_FAILED) {
328 return NULL;
329 }
330 if ((((UINTN)res) & ~(align-1)) == (UINTN)res) {
331 isAligned=1;
332 }
333 else {
334 munmap(res, length);
335 base += align;
336 }
337 }
338 return res;
339 }
340
341 EFI_STATUS
342 MapFile (
343 IN CHAR8 *FileName,
344 IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
345 OUT UINT64 *Length
346 )
347 /*++
348
349 Routine Description:
350 Opens and memory maps a file using WinNt services. If BaseAddress is non zero
351 the process will try and allocate the memory starting at BaseAddress.
352
353 Arguments:
354 FileName - The name of the file to open and map
355 MapSize - The amount of the file to map in bytes
356 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
357 memory emulation, and exiting files for firmware volume emulation
358 BaseAddress - The base address of the mapped file in the user address space.
359 If passed in as NULL the a new memory region is used.
360 If passed in as non NULL the request memory region is used for
361 the mapping of the file into the process space.
362 Length - The size of the mapped region in bytes
363
364 Returns:
365 EFI_SUCCESS - The file was opened and mapped.
366 EFI_NOT_FOUND - FileName was not found in the current directory
367 EFI_DEVICE_ERROR - An error occured attempting to map the opened file
368
369 --*/
370 {
371 int fd;
372 VOID *res;
373 UINTN FileSize;
374
375 fd = open (FileName, O_RDONLY);
376 if (fd < 0)
377 return EFI_NOT_FOUND;
378 FileSize = lseek (fd, 0, SEEK_END);
379
380 #if 0
381 if (IsMain)
382 {
383 /* Read entry address. */
384 lseek (fd, FileSize - 0x20, SEEK_SET);
385 if (read (fd, &EntryAddress, 4) != 4)
386 {
387 close (fd);
388 return EFI_DEVICE_ERROR;
389 }
390 }
391 #endif
392
393 res = MapMemory(fd, FileSize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE);
394
395 close (fd);
396
397 if (res == MAP_FAILED)
398 return EFI_DEVICE_ERROR;
399
400 *Length = (UINT64) FileSize;
401 *BaseAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) res;
402
403 return EFI_SUCCESS;
404 }
405
406 #define BYTES_PER_RECORD 512
407
408 /**
409 Extracts ASSERT() information from a status code structure.
410
411 Converts the status code specified by CodeType, Value, and Data to the ASSERT()
412 arguments specified by Filename, Description, and LineNumber. If CodeType is
413 an EFI_ERROR_CODE, and CodeType has a severity of EFI_ERROR_UNRECOVERED, and
414 Value has an operation mask of EFI_SW_EC_ILLEGAL_SOFTWARE_STATE, extract
415 Filename, Description, and LineNumber from the optional data area of the
416 status code buffer specified by Data. The optional data area of Data contains
417 a Null-terminated ASCII string for the FileName, followed by a Null-terminated
418 ASCII string for the Description, followed by a 32-bit LineNumber. If the
419 ASSERT() information could be extracted from Data, then return TRUE.
420 Otherwise, FALSE is returned.
421
422 If Data is NULL, then ASSERT().
423 If Filename is NULL, then ASSERT().
424 If Description is NULL, then ASSERT().
425 If LineNumber is NULL, then ASSERT().
426
427 @param CodeType The type of status code being converted.
428 @param Value The status code value being converted.
429 @param Data Pointer to status code data buffer.
430 @param Filename Pointer to the source file name that generated the ASSERT().
431 @param Description Pointer to the description of the ASSERT().
432 @param LineNumber Pointer to source line number that generated the ASSERT().
433
434 @retval TRUE The status code specified by CodeType, Value, and Data was
435 converted ASSERT() arguments specified by Filename, Description,
436 and LineNumber.
437 @retval FALSE The status code specified by CodeType, Value, and Data could
438 not be converted to ASSERT() arguments.
439
440 **/
441 STATIC
442 BOOLEAN
443 ReportStatusCodeExtractAssertInfo (
444 IN EFI_STATUS_CODE_TYPE CodeType,
445 IN EFI_STATUS_CODE_VALUE Value,
446 IN CONST EFI_STATUS_CODE_DATA *Data,
447 OUT CHAR8 **Filename,
448 OUT CHAR8 **Description,
449 OUT UINT32 *LineNumber
450 )
451 {
452 EFI_DEBUG_ASSERT_DATA *AssertData;
453
454 ASSERT (Data != NULL);
455 ASSERT (Filename != NULL);
456 ASSERT (Description != NULL);
457 ASSERT (LineNumber != NULL);
458
459 if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
460 ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) &&
461 ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) {
462 AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1);
463 *Filename = (CHAR8 *)(AssertData + 1);
464 *Description = *Filename + AsciiStrLen (*Filename) + 1;
465 *LineNumber = AssertData->LineNumber;
466 return TRUE;
467 }
468 return FALSE;
469 }
470
471 EFI_STATUS
472 EFIAPI
473 SecPeiReportStatusCode (
474 IN EFI_PEI_SERVICES **PeiServices,
475 IN EFI_STATUS_CODE_TYPE CodeType,
476 IN EFI_STATUS_CODE_VALUE Value,
477 IN UINT32 Instance,
478 IN EFI_GUID * CallerId,
479 IN EFI_STATUS_CODE_DATA * Data OPTIONAL
480 )
481 /*++
482
483 Routine Description:
484
485 This routine produces the ReportStatusCode PEI service. It's passed
486 up to the PEI Core via a PPI. T
487
488 This code currently uses the NT clib printf. This does not work the same way
489 as the EFI Print (), as %t, %g, %s as Unicode are not supported.
490
491 Arguments:
492 (see EFI_PEI_REPORT_STATUS_CODE)
493
494 Returns:
495 EFI_SUCCESS - Always return success
496
497 --*/
498 // TODO: PeiServices - add argument and description to function comment
499 // TODO: CodeType - add argument and description to function comment
500 // TODO: Value - add argument and description to function comment
501 // TODO: Instance - add argument and description to function comment
502 // TODO: CallerId - add argument and description to function comment
503 // TODO: Data - add argument and description to function comment
504 {
505 CHAR8 *Format;
506 EFI_DEBUG_INFO *DebugInfo;
507 VA_LIST Marker;
508 CHAR8 PrintBuffer[BYTES_PER_RECORD * 2];
509 CHAR8 *Filename;
510 CHAR8 *Description;
511 UINT32 LineNumber;
512
513 if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
514 //
515 // This supports DEBUG () marcos
516 // Data format
517 // EFI_STATUS_CODE_DATA
518 // EFI_DEBUG_INFO
519 //
520 // The first 12 * UINT64 bytes of the string are really an
521 // arguement stack to support varargs on the Format string.
522 //
523 if (Data != NULL) {
524 DebugInfo = (EFI_DEBUG_INFO *) (Data + 1);
525 Marker = (VA_LIST) (DebugInfo + 1);
526 Format = (CHAR8 *) (((UINT64 *) Marker) + 12);
527
528 AsciiVSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
529 printf (PrintBuffer);
530 } else {
531 printf ("DEBUG <null>\n");
532 }
533 }
534
535 if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
536 ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED)
537 ) {
538 if (Data != NULL && ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
539 //
540 // Support ASSERT () macro
541 //
542 printf ("ASSERT %s(%d): %s\n", Filename, LineNumber, Description);
543 } else {
544 printf ("ASSERT <null>\n");
545 }
546 CpuBreakpoint ();
547 }
548
549 return EFI_SUCCESS;
550 }
551
552
553 VOID
554 SecLoadFromCore (
555 IN UINTN LargestRegion,
556 IN UINTN LargestRegionSize,
557 IN UINTN BootFirmwareVolumeBase,
558 IN VOID *PeiCorePe32File
559 )
560 /*++
561
562 Routine Description:
563 This is the service to load the PEI Core from the Firmware Volume
564
565 Arguments:
566 LargestRegion - Memory to use for PEI.
567 LargestRegionSize - Size of Memory to use for PEI
568 BootFirmwareVolumeBase - Start of the Boot FV
569 PeiCorePe32File - PEI Core PE32
570
571 Returns:
572 Success means control is transfered and thus we should never return
573
574 --*/
575 {
576 EFI_STATUS Status;
577 EFI_PHYSICAL_ADDRESS TopOfMemory;
578 VOID *TopOfStack;
579 UINT64 PeiCoreSize;
580 EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
581 EFI_PHYSICAL_ADDRESS PeiImageAddress;
582 EFI_PEI_STARTUP_DESCRIPTOR *PeiStartup;
583
584 //
585 // Compute Top Of Memory for Stack and PEI Core Allocations
586 //
587 TopOfMemory = LargestRegion + LargestRegionSize;
588
589 //
590 // Allocate 128KB for the Stack
591 //
592 TopOfStack = (VOID *)((UINTN)TopOfMemory - sizeof (EFI_PEI_STARTUP_DESCRIPTOR) - CPU_STACK_ALIGNMENT);
593 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
594 TopOfMemory = TopOfMemory - STACK_SIZE;
595
596 //
597 // Patch value in dispatch table values
598 //
599 gPrivateDispatchTable[0].Ppi = gPeiEfiPeiPeCoffLoader;
600
601 //
602 // Bind this information into the SEC hand-off state
603 //
604 PeiStartup = (EFI_PEI_STARTUP_DESCRIPTOR *) (UINTN) TopOfStack;
605 PeiStartup->DispatchTable = (EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable;
606 PeiStartup->SizeOfCacheAsRam = STACK_SIZE;
607 PeiStartup->BootFirmwareVolume = BootFirmwareVolumeBase;
608
609 //
610 // Load the PEI Core from a Firmware Volume
611 //
612 Status = SecWinNtPeiLoadFile (
613 PeiCorePe32File,
614 &PeiImageAddress,
615 &PeiCoreSize,
616 &PeiCoreEntryPoint
617 );
618 if (EFI_ERROR (Status)) {
619 return ;
620 }
621 printf ("Jump to 0x%08lx\n", (unsigned long)PeiCoreEntryPoint);
622 //
623 // Transfer control to the PEI Core
624 //
625 SwitchStack (
626 (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
627 PeiStartup,
628 NULL,
629 TopOfStack
630 );
631 //
632 // If we get here, then the PEI Core returned. This is an error
633 //
634 return ;
635 }
636
637 EFI_STATUS
638 EFIAPI
639 SecWinNtPeiAutoScan (
640 IN UINTN Index,
641 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
642 OUT UINT64 *MemorySize
643 )
644 /*++
645
646 Routine Description:
647 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
648 It allows discontiguous memory regions to be supported by the emulator.
649 It uses gSystemMemory[] and gSystemMemoryCount that were created by
650 parsing the Windows environment variable EFI_MEMORY_SIZE.
651 The size comes from the varaible and the address comes from the call to
652 WinNtOpenFile.
653
654 Arguments:
655 Index - Which memory region to use
656 MemoryBase - Return Base address of memory region
657 MemorySize - Return size in bytes of the memory region
658
659 Returns:
660 EFI_SUCCESS - If memory region was mapped
661 EFI_UNSUPPORTED - If Index is not supported
662
663 --*/
664 {
665 void *res;
666
667 if (Index >= gSystemMemoryCount) {
668 return EFI_UNSUPPORTED;
669 }
670
671 *MemoryBase = 0;
672 res = MapMemory(0, gSystemMemory[Index].Size,
673 PROT_READ | PROT_WRITE | PROT_EXEC,
674 MAP_PRIVATE | MAP_ANONYMOUS);
675 if (res == MAP_FAILED)
676 return EFI_DEVICE_ERROR;
677 *MemorySize = gSystemMemory[Index].Size;
678 *MemoryBase = (UINTN)res;
679 gSystemMemory[Index].Memory = *MemoryBase;
680
681 return EFI_SUCCESS;
682 }
683
684 VOID *
685 EFIAPI
686 SecWinNtWinNtThunkAddress (
687 VOID
688 )
689 /*++
690
691 Routine Description:
692 Since the SEC is the only Windows program in stack it must export
693 an interface to do Win API calls. That's what the WinNtThunk address
694 is for. gWinNt is initailized in WinNtThunk.c.
695
696 Arguments:
697 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
698 InterfaceBase - Address of the gWinNt global
699
700 Returns:
701 EFI_SUCCESS - Data returned
702
703 --*/
704 {
705 return gUnix;
706 }
707
708
709 EFI_STATUS
710 EFIAPI
711 SecWinNtPeiLoadFile (
712 IN VOID *Pe32Data,
713 IN EFI_PHYSICAL_ADDRESS *ImageAddress,
714 IN UINT64 *ImageSize,
715 IN EFI_PHYSICAL_ADDRESS *EntryPoint
716 )
717 /*++
718
719 Routine Description:
720 Loads and relocates a PE/COFF image into memory.
721
722 Arguments:
723 Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
724 ImageAddress - The base address of the relocated PE/COFF image
725 ImageSize - The size of the relocated PE/COFF image
726 EntryPoint - The entry point of the relocated PE/COFF image
727
728 Returns:
729 EFI_SUCCESS - The file was loaded and relocated
730 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
731
732 --*/
733 {
734 EFI_STATUS Status;
735 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
736
737 ZeroMem (&ImageContext, sizeof (ImageContext));
738 ImageContext.Handle = Pe32Data;
739
740 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
741
742 Status = gPeiEfiPeiPeCoffLoader->GetImageInfo (gPeiEfiPeiPeCoffLoader, &ImageContext);
743 if (EFI_ERROR (Status)) {
744 return Status;
745 }
746 //
747 // Allocate space in NT (not emulator) memory. Extra space is for alignment
748 //
749 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) malloc ((UINTN) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)));
750 if (ImageContext.ImageAddress == 0) {
751 return EFI_OUT_OF_RESOURCES;
752 }
753 //
754 // Align buffer on section boundry
755 //
756 ImageContext.ImageAddress += ImageContext.SectionAlignment;
757 ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);
758
759
760 Status = gPeiEfiPeiPeCoffLoader->LoadImage (gPeiEfiPeiPeCoffLoader, &ImageContext);
761 if (EFI_ERROR (Status)) {
762 return Status;
763 }
764
765 Status = gPeiEfiPeiPeCoffLoader->RelocateImage (gPeiEfiPeiPeCoffLoader, &ImageContext);
766 if (EFI_ERROR (Status)) {
767 return Status;
768 }
769
770 //
771 // BugBug: Flush Instruction Cache Here when CPU Lib is ready
772 //
773
774 *ImageAddress = ImageContext.ImageAddress;
775 *ImageSize = ImageContext.ImageSize;
776 *EntryPoint = ImageContext.EntryPoint;
777
778 return EFI_SUCCESS;
779 }
780
781 EFI_STATUS
782 EFIAPI
783 SecWinNtFdAddress (
784 IN UINTN Index,
785 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
786 IN OUT UINT64 *FdSize
787 )
788 /*++
789
790 Routine Description:
791 Return the FD Size and base address. Since the FD is loaded from a
792 file into Windows memory only the SEC will know it's address.
793
794 Arguments:
795 Index - Which FD, starts at zero.
796 FdSize - Size of the FD in bytes
797 FdBase - Start address of the FD. Assume it points to an FV Header
798
799 Returns:
800 EFI_SUCCESS - Return the Base address and size of the FV
801 EFI_UNSUPPORTED - Index does nto map to an FD in the system
802
803 --*/
804 {
805 if (Index >= gFdInfoCount) {
806 return EFI_UNSUPPORTED;
807 }
808
809 *FdBase = gFdInfo[Index].Address;
810 *FdSize = gFdInfo[Index].Size;
811
812 if (*FdBase == 0 && *FdSize == 0) {
813 return EFI_UNSUPPORTED;
814 }
815
816 return EFI_SUCCESS;
817 }
818
819 EFI_STATUS
820 EFIAPI
821 SecImageRead (
822 IN VOID *FileHandle,
823 IN UINTN FileOffset,
824 IN OUT UINTN *ReadSize,
825 OUT VOID *Buffer
826 )
827 /*++
828
829 Routine Description:
830 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
831
832 Arguments:
833 FileHandle - The handle to the PE/COFF file
834 FileOffset - The offset, in bytes, into the file to read
835 ReadSize - The number of bytes to read from the file starting at FileOffset
836 Buffer - A pointer to the buffer to read the data into.
837
838 Returns:
839 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
840
841 --*/
842 {
843 CHAR8 *Destination8;
844 CHAR8 *Source8;
845 UINTN Length;
846
847 Destination8 = Buffer;
848 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
849 Length = *ReadSize;
850 while (Length--) {
851 *(Destination8++) = *(Source8++);
852 }
853
854 return EFI_SUCCESS;
855 }
856
857 UINTN
858 CountSeperatorsInString (
859 IN const CHAR16 *String,
860 IN CHAR16 Seperator
861 )
862 /*++
863
864 Routine Description:
865 Count the number of seperators in String
866
867 Arguments:
868 String - String to process
869 Seperator - Item to count
870
871 Returns:
872 Number of Seperator in String
873
874 --*/
875 {
876 UINTN Count;
877
878 for (Count = 0; *String != '\0'; String++) {
879 if (*String == Seperator) {
880 Count++;
881 }
882 }
883
884 return Count;
885 }
886
887
888
889 EFI_STATUS
890 EFIAPI
891 SecNt32PeCoffGetImageInfo (
892 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
893 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
894 )
895 {
896 EFI_STATUS Status;
897
898 Status = PeCoffLoaderGetImageInfo (ImageContext);
899 if (EFI_ERROR (Status)) {
900 return Status;
901 }
902
903 switch (ImageContext->ImageType) {
904
905 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
906 ImageContext->ImageCodeMemoryType = EfiLoaderCode;
907 ImageContext->ImageDataMemoryType = EfiLoaderData;
908 break;
909
910 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
911 ImageContext->ImageCodeMemoryType = EfiBootServicesCode;
912 ImageContext->ImageDataMemoryType = EfiBootServicesData;
913 break;
914
915 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
916 case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
917 ImageContext->ImageCodeMemoryType = EfiRuntimeServicesCode;
918 ImageContext->ImageDataMemoryType = EfiRuntimeServicesData;
919 break;
920
921 default:
922 ImageContext->ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM;
923 return RETURN_UNSUPPORTED;
924 }
925
926 return Status;
927 }
928
929 EFI_STATUS
930 EFIAPI
931 SecNt32PeCoffLoadImage (
932 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
933 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
934 )
935 {
936 EFI_STATUS Status;
937
938 Status = PeCoffLoaderLoadImage (ImageContext);
939 return Status;
940 }
941
942 VOID
943 SecUnixLoaderBreak (
944 VOID
945 )
946 {
947 }
948
949 EFI_STATUS
950 EFIAPI
951 SecNt32PeCoffRelocateImage (
952 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
953 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
954 )
955 {
956
957 #if 0
958 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
959 EFI_IMAGE_SECTION_HEADER *Sec;
960 INTN i;
961 #endif
962
963 fprintf (stderr,
964 "Loading %s 0x%08lx - entry point 0x%08lx\n",
965 ImageContext->PdbPointer,
966 (unsigned long)ImageContext->ImageAddress,
967 (unsigned long)ImageContext->EntryPoint);
968
969 #if 0
970 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)
971 ((UINTN)ImageContext->ImageAddress + ImageContext->PeCoffHeaderOffset);
972 Sec = (EFI_IMAGE_SECTION_HEADER*)
973 ((UINTN)ImageContext->ImageAddress
974 + ImageContext->PeCoffHeaderOffset
975 + sizeof(UINT32)
976 + sizeof(EFI_IMAGE_FILE_HEADER)
977 + Hdr.Pe32->FileHeader.SizeOfOptionalHeader);
978 for (i = 0; i < Hdr.Pe32->FileHeader.NumberOfSections; i++)
979 fprintf (stderr, " %s 0x%08lx\n",
980 Sec[i].Name, (unsigned long)Sec[i].VirtualAddress);
981 #endif
982
983 SecUnixLoaderBreak ();
984
985 return PeCoffLoaderRelocateImage (ImageContext);
986 }
987
988
989 EFI_STATUS
990 EFIAPI
991 SecNt32PeCoffUnloadimage (
992 IN EFI_PEI_PE_COFF_LOADER_PROTOCOL *This,
993 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
994 )
995 {
996 return EFI_SUCCESS;
997 }
998
999 VOID
1000 _ModuleEntryPoint (
1001 VOID
1002 )
1003 {
1004 }
1005