]> git.proxmox.com Git - mirror_edk2.git/blob - EmulatorPkg/Win/Host/WinHost.c
EmulatorPkg: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / EmulatorPkg / Win / Host / WinHost.c
1 /**@file
2 WinNt emulator of pre-SEC phase. It's really a Win32 application, but this is
3 Ok since all the other modules for NT32 are NOT Win32 applications.
4
5 This program gets NT32 PCD setting and figures out what the memory layout
6 will be, how may FD's will be loaded and also what the boot mode is.
7
8 This code produces 128 K of temporary memory for the SEC stack by directly
9 allocate memory space with ReadWrite and Execute attribute.
10
11 Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
12 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
13 SPDX-License-Identifier: BSD-2-Clause-Patent
14 **/
15
16 #include "WinHost.h"
17
18 #ifndef SE_TIME_ZONE_NAME
19 #define SE_TIME_ZONE_NAME TEXT("SeTimeZonePrivilege")
20 #endif
21
22 //
23 // Default information about where the FD is located.
24 // This array gets filled in with information from PcdWinNtFirmwareVolume
25 // The number of array elements is allocated base on parsing
26 // PcdWinNtFirmwareVolume and the memory is never freed.
27 //
28 UINTN gFdInfoCount = 0;
29 NT_FD_INFO *gFdInfo;
30
31 //
32 // Array that supports seperate memory rantes.
33 // The memory ranges are set by PcdWinNtMemorySizeForSecMain.
34 // The number of array elements is allocated base on parsing
35 // PcdWinNtMemorySizeForSecMain value and the memory is never freed.
36 //
37 UINTN gSystemMemoryCount = 0;
38 NT_SYSTEM_MEMORY *gSystemMemory;
39
40 /*++
41
42 Routine Description:
43 This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
44 It allows discontinuous memory regions to be supported by the emulator.
45 It uses gSystemMemory[] and gSystemMemoryCount that were created by
46 parsing the host environment variable EFI_MEMORY_SIZE.
47 The size comes from the varaible and the address comes from the call to
48 UnixOpenFile.
49
50 Arguments:
51 Index - Which memory region to use
52 MemoryBase - Return Base address of memory region
53 MemorySize - Return size in bytes of the memory region
54
55 Returns:
56 EFI_SUCCESS - If memory region was mapped
57 EFI_UNSUPPORTED - If Index is not supported
58
59 **/
60 EFI_STATUS
61 WinPeiAutoScan (
62 IN UINTN Index,
63 OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
64 OUT UINT64 *MemorySize
65 )
66 {
67 if (Index >= gSystemMemoryCount) {
68 return EFI_UNSUPPORTED;
69 }
70
71 //
72 // Allocate enough memory space for emulator
73 //
74 gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
75 if (gSystemMemory[Index].Memory == 0) {
76 return EFI_OUT_OF_RESOURCES;
77 }
78
79 *MemoryBase = gSystemMemory[Index].Memory;
80 *MemorySize = gSystemMemory[Index].Size;
81
82 return EFI_SUCCESS;
83 }
84
85 /*++
86
87 Routine Description:
88 Return the FD Size and base address. Since the FD is loaded from a
89 file into host memory only the SEC will know it's address.
90
91 Arguments:
92 Index - Which FD, starts at zero.
93 FdSize - Size of the FD in bytes
94 FdBase - Start address of the FD. Assume it points to an FV Header
95 FixUp - Difference between actual FD address and build address
96
97 Returns:
98 EFI_SUCCESS - Return the Base address and size of the FV
99 EFI_UNSUPPORTED - Index does nto map to an FD in the system
100
101 **/
102 EFI_STATUS
103 WinFdAddress (
104 IN UINTN Index,
105 IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
106 IN OUT UINT64 *FdSize,
107 IN OUT EFI_PHYSICAL_ADDRESS *FixUp
108 )
109 {
110 if (Index >= gFdInfoCount) {
111 return EFI_UNSUPPORTED;
112 }
113
114
115 *FdBase = (EFI_PHYSICAL_ADDRESS)(UINTN)gFdInfo[Index].Address;
116 *FdSize = (UINT64)gFdInfo[Index].Size;
117 *FixUp = 0;
118
119 if (*FdBase == 0 && *FdSize == 0) {
120 return EFI_UNSUPPORTED;
121 }
122
123 if (Index == 0) {
124 //
125 // FD 0 has XIP code and well known PCD values
126 // If the memory buffer could not be allocated at the FD build address
127 // the Fixup is the difference.
128 //
129 *FixUp = *FdBase - PcdGet64 (PcdEmuFdBaseAddress);
130 }
131
132 return EFI_SUCCESS;
133 }
134
135 /*++
136
137 Routine Description:
138 Since the SEC is the only Unix program in stack it must export
139 an interface to do POSIX calls. gUnix is initialized in UnixThunk.c.
140
141 Arguments:
142 InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
143 InterfaceBase - Address of the gUnix global
144
145 Returns:
146 EFI_SUCCESS - Data returned
147
148 **/
149 VOID *
150 WinThunk (
151 VOID
152 )
153 {
154 return &gEmuThunkProtocol;
155 }
156
157
158 EMU_THUNK_PPI mSecEmuThunkPpi = {
159 WinPeiAutoScan,
160 WinFdAddress,
161 WinThunk
162 };
163
164 VOID
165 SecPrint (
166 CHAR8 *Format,
167 ...
168 )
169 {
170 va_list Marker;
171 UINTN CharCount;
172 CHAR8 Buffer[0x1000];
173
174 va_start (Marker, Format);
175
176 _vsnprintf (Buffer, sizeof (Buffer), Format, Marker);
177
178 va_end (Marker);
179
180 CharCount = strlen (Buffer);
181 WriteFile (
182 GetStdHandle (STD_OUTPUT_HANDLE),
183 Buffer,
184 (DWORD)CharCount,
185 (LPDWORD)&CharCount,
186 NULL
187 );
188 }
189
190 /*++
191
192 Routine Description:
193 Check to see if an address range is in the EFI GCD memory map.
194
195 This is all of GCD for system memory passed to DXE Core. FV
196 mapping and other device mapped into system memory are not
197 inlcuded in the check.
198
199 Arguments:
200 Index - Which memory region to use
201 MemoryBase - Return Base address of memory region
202 MemorySize - Return size in bytes of the memory region
203
204 Returns:
205 TRUE - Address is in the EFI GCD memory map
206 FALSE - Address is NOT in memory map
207
208 **/
209 BOOLEAN
210 EfiSystemMemoryRange (
211 IN VOID *MemoryAddress
212 )
213 {
214 UINTN Index;
215 EFI_PHYSICAL_ADDRESS MemoryBase;
216
217 MemoryBase = (EFI_PHYSICAL_ADDRESS)(UINTN)MemoryAddress;
218 for (Index = 0; Index < gSystemMemoryCount; Index++) {
219 if ((MemoryBase >= gSystemMemory[Index].Memory) &&
220 (MemoryBase < (gSystemMemory[Index].Memory + gSystemMemory[Index].Size)) ) {
221 return TRUE;
222 }
223 }
224
225 return FALSE;
226 }
227
228
229 EFI_STATUS
230 WinNtOpenFile (
231 IN CHAR16 *FileName, OPTIONAL
232 IN UINT32 MapSize,
233 IN DWORD CreationDisposition,
234 IN OUT VOID **BaseAddress,
235 OUT UINTN *Length
236 )
237 /*++
238
239 Routine Description:
240 Opens and memory maps a file using WinNt services. If *BaseAddress is non zero
241 the process will try and allocate the memory starting at BaseAddress.
242
243 Arguments:
244 FileName - The name of the file to open and map
245 MapSize - The amount of the file to map in bytes
246 CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
247 memory emulation, and exiting files for firmware volume emulation
248 BaseAddress - The base address of the mapped file in the user address space.
249 If *BaseAddress is 0, the new memory region is used.
250 If *BaseAddress is not 0, the request memory region is used for
251 the mapping of the file into the process space.
252 Length - The size of the mapped region in bytes
253
254 Returns:
255 EFI_SUCCESS - The file was opened and mapped.
256 EFI_NOT_FOUND - FileName was not found in the current directory
257 EFI_DEVICE_ERROR - An error occured attempting to map the opened file
258
259 --*/
260 {
261 HANDLE NtFileHandle;
262 HANDLE NtMapHandle;
263 VOID *VirtualAddress;
264 UINTN FileSize;
265
266 //
267 // Use Win API to open/create a file
268 //
269 NtFileHandle = INVALID_HANDLE_VALUE;
270 if (FileName != NULL) {
271 NtFileHandle = CreateFile (
272 FileName,
273 GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE,
274 FILE_SHARE_READ,
275 NULL,
276 CreationDisposition,
277 FILE_ATTRIBUTE_NORMAL,
278 NULL
279 );
280 if (NtFileHandle == INVALID_HANDLE_VALUE) {
281 return EFI_NOT_FOUND;
282 }
283 }
284 //
285 // Map the open file into a memory range
286 //
287 NtMapHandle = CreateFileMapping (
288 NtFileHandle,
289 NULL,
290 PAGE_EXECUTE_READWRITE,
291 0,
292 MapSize,
293 NULL
294 );
295 if (NtMapHandle == NULL) {
296 return EFI_DEVICE_ERROR;
297 }
298 //
299 // Get the virtual address (address in the emulator) of the mapped file
300 //
301 VirtualAddress = MapViewOfFileEx (
302 NtMapHandle,
303 FILE_MAP_EXECUTE | FILE_MAP_ALL_ACCESS,
304 0,
305 0,
306 MapSize,
307 *BaseAddress
308 );
309 if (VirtualAddress == NULL) {
310 return EFI_DEVICE_ERROR;
311 }
312
313 if (MapSize == 0) {
314 //
315 // Seek to the end of the file to figure out the true file size.
316 //
317 FileSize = SetFilePointer (
318 NtFileHandle,
319 0,
320 NULL,
321 FILE_END
322 );
323 if (FileSize == -1) {
324 return EFI_DEVICE_ERROR;
325 }
326
327 *Length = FileSize;
328 } else {
329 *Length = MapSize;
330 }
331
332 *BaseAddress = VirtualAddress;
333
334 return EFI_SUCCESS;
335 }
336
337 INTN
338 EFIAPI
339 main (
340 IN INTN Argc,
341 IN CHAR8 **Argv,
342 IN CHAR8 **Envp
343 )
344 /*++
345
346 Routine Description:
347 Main entry point to SEC for WinNt. This is a Windows program
348
349 Arguments:
350 Argc - Number of command line arguments
351 Argv - Array of command line argument strings
352 Envp - Array of environment variable strings
353
354 Returns:
355 0 - Normal exit
356 1 - Abnormal exit
357
358 --*/
359 {
360 EFI_STATUS Status;
361 HANDLE Token;
362 TOKEN_PRIVILEGES TokenPrivileges;
363 VOID *TemporaryRam;
364 UINT32 TemporaryRamSize;
365 VOID *EmuMagicPage;
366 UINTN Index;
367 UINTN Index1;
368 CHAR16 *FileName;
369 CHAR16 *FileNamePtr;
370 BOOLEAN Done;
371 EFI_PEI_FILE_HANDLE FileHandle;
372 VOID *SecFile;
373 CHAR16 *MemorySizeStr;
374 CHAR16 *FirmwareVolumesStr;
375 UINT32 ProcessAffinityMask;
376 UINT32 SystemAffinityMask;
377 INT32 LowBit;
378
379 //
380 // Enable the privilege so that RTC driver can successfully run SetTime()
381 //
382 OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &Token);
383 if (LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &TokenPrivileges.Privileges[0].Luid)) {
384 TokenPrivileges.PrivilegeCount = 1;
385 TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
386 AdjustTokenPrivileges(Token, FALSE, &TokenPrivileges, 0, (PTOKEN_PRIVILEGES) NULL, 0);
387 }
388
389 MemorySizeStr = (CHAR16 *) PcdGetPtr (PcdEmuMemorySize);
390 FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdEmuFirmwareVolume);
391
392 SecPrint ("\nEDK II WIN Host Emulation Environment from http://www.tianocore.org/edk2/\n");
393
394 //
395 // Determine the first thread available to this process.
396 //
397 if (GetProcessAffinityMask (GetCurrentProcess (), &ProcessAffinityMask, &SystemAffinityMask)) {
398 LowBit = (INT32)LowBitSet32 (ProcessAffinityMask);
399 if (LowBit != -1) {
400 //
401 // Force the system to bind the process to a single thread to work
402 // around odd semaphore type crashes.
403 //
404 SetProcessAffinityMask (GetCurrentProcess (), (INTN)(BIT0 << LowBit));
405 }
406 }
407
408 //
409 // Make some Windows calls to Set the process to the highest priority in the
410 // idle class. We need this to have good performance.
411 //
412 SetPriorityClass (GetCurrentProcess (), IDLE_PRIORITY_CLASS);
413 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);
414
415 SecInitializeThunk ();
416 //
417 // PPIs pased into PEI_CORE
418 //
419 AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, &mSecEmuThunkPpi);
420
421 //
422 // Emulator Bus Driver Thunks
423 //
424 AddThunkProtocol (&mWinNtWndThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuGop), TRUE);
425 AddThunkProtocol (&mWinNtFileSystemThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuFileSystem), TRUE);
426 AddThunkProtocol (&mWinNtBlockIoThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuVirtualDisk), TRUE);
427
428 //
429 // Allocate space for gSystemMemory Array
430 //
431 gSystemMemoryCount = CountSeparatorsInString (MemorySizeStr, '!') + 1;
432 gSystemMemory = calloc (gSystemMemoryCount, sizeof (NT_SYSTEM_MEMORY));
433 if (gSystemMemory == NULL) {
434 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n", MemorySizeStr);
435 exit (1);
436 }
437
438 //
439 // Allocate space for gSystemMemory Array
440 //
441 gFdInfoCount = CountSeparatorsInString (FirmwareVolumesStr, '!') + 1;
442 gFdInfo = calloc (gFdInfoCount, sizeof (NT_FD_INFO));
443 if (gFdInfo == NULL) {
444 SecPrint ("ERROR : Can not allocate memory for %S. Exiting.\n", FirmwareVolumesStr);
445 exit (1);
446 }
447 //
448 // Setup Boot Mode.
449 //
450 SecPrint (" BootMode 0x%02x\n", PcdGet32 (PcdEmuBootMode));
451
452 //
453 // Allocate 128K memory to emulate temp memory for PEI.
454 // on a real platform this would be SRAM, or using the cache as RAM.
455 // Set TemporaryRam to zero so WinNtOpenFile will allocate a new mapping
456 //
457 TemporaryRamSize = TEMPORARY_RAM_SIZE;
458 TemporaryRam = VirtualAlloc (NULL, (SIZE_T) (TemporaryRamSize), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
459 if (TemporaryRam == NULL) {
460 SecPrint ("ERROR : Can not allocate enough space for SecStack\n");
461 exit (1);
462 }
463 SetMem32 (TemporaryRam, TemporaryRamSize, PcdGet32 (PcdInitValueInTempStack));
464
465 SecPrint (" OS Emulator passing in %u KB of temp RAM at 0x%08lx to SEC\n",
466 TemporaryRamSize / SIZE_1KB,
467 TemporaryRam
468 );
469
470 //
471 // If enabled use the magic page to communicate between modules
472 // This replaces the PI PeiServicesTable pointer mechanism that
473 // deos not work in the emulator. It also allows the removal of
474 // writable globals from SEC, PEI_CORE (libraries), PEIMs
475 //
476 EmuMagicPage = (VOID *)(UINTN)(FixedPcdGet64 (PcdPeiServicesTablePage) & MAX_UINTN);
477 if (EmuMagicPage != NULL) {
478 UINT64 Size;
479 Status = WinNtOpenFile (
480 NULL,
481 SIZE_4KB,
482 0,
483 &EmuMagicPage,
484 &Size
485 );
486 if (EFI_ERROR (Status)) {
487 SecPrint ("ERROR : Could not allocate PeiServicesTablePage @ %p\n", EmuMagicPage);
488 return EFI_DEVICE_ERROR;
489 }
490 }
491
492 //
493 // Open All the firmware volumes and remember the info in the gFdInfo global
494 // Meanwhile, find the SEC Core.
495 //
496 FileNamePtr = AllocateCopyPool (StrSize (FirmwareVolumesStr), FirmwareVolumesStr);
497 if (FileNamePtr == NULL) {
498 SecPrint ("ERROR : Can not allocate memory for firmware volume string\n");
499 exit (1);
500 }
501
502 for (Done = FALSE, Index = 0, SecFile = NULL; !Done; Index++) {
503 FileName = FileNamePtr;
504 for (Index1 = 0; (FileNamePtr[Index1] != '!') && (FileNamePtr[Index1] != 0); Index1++)
505 ;
506 if (FileNamePtr[Index1] == 0) {
507 Done = TRUE;
508 } else {
509 FileNamePtr[Index1] = '\0';
510 FileNamePtr = &FileNamePtr[Index1 + 1];
511 }
512
513 //
514 // Open the FD and remember where it got mapped into our processes address space
515 //
516 Status = WinNtOpenFile (
517 FileName,
518 0,
519 OPEN_EXISTING,
520 &gFdInfo[Index].Address,
521 &gFdInfo[Index].Size
522 );
523 if (EFI_ERROR (Status)) {
524 SecPrint ("ERROR : Can not open Firmware Device File %S (0x%X). Exiting.\n", FileName, Status);
525 exit (1);
526 }
527
528 SecPrint (" FD loaded from %S\n", FileName);
529
530 if (SecFile == NULL) {
531 //
532 // Assume the beginning of the FD is an FV and look for the SEC Core.
533 // Load the first one we find.
534 //
535 FileHandle = NULL;
536 Status = PeiServicesFfsFindNextFile (
537 EFI_FV_FILETYPE_SECURITY_CORE,
538 (EFI_PEI_FV_HANDLE)gFdInfo[Index].Address,
539 &FileHandle
540 );
541 if (!EFI_ERROR (Status)) {
542 Status = PeiServicesFfsFindSectionData (EFI_SECTION_PE32, FileHandle, &SecFile);
543 if (!EFI_ERROR (Status)) {
544 SecPrint (" contains SEC Core");
545 }
546 }
547 }
548
549 SecPrint ("\n");
550 }
551 //
552 // Calculate memory regions and store the information in the gSystemMemory
553 // global for later use. The autosizing code will use this data to
554 // map this memory into the SEC process memory space.
555 //
556 for (Index = 0, Done = FALSE; !Done; Index++) {
557 //
558 // Save the size of the memory and make a Unicode filename SystemMemory00, ...
559 //
560 gSystemMemory[Index].Size = _wtoi (MemorySizeStr) * SIZE_1MB;
561
562 //
563 // Find the next region
564 //
565 for (Index1 = 0; MemorySizeStr[Index1] != '!' && MemorySizeStr[Index1] != 0; Index1++)
566 ;
567 if (MemorySizeStr[Index1] == 0) {
568 Done = TRUE;
569 }
570
571 MemorySizeStr = MemorySizeStr + Index1 + 1;
572 }
573
574 SecPrint ("\n");
575
576 //
577 // Hand off to SEC Core
578 //
579 SecLoadSecCore ((UINTN)TemporaryRam, TemporaryRamSize, gFdInfo[0].Address, gFdInfo[0].Size, SecFile);
580
581 //
582 // If we get here, then the SEC Core returned. This is an error as SEC should
583 // always hand off to PEI Core and then on to DXE Core.
584 //
585 SecPrint ("ERROR : SEC returned\n");
586 exit (1);
587 }
588
589 VOID
590 SecLoadSecCore (
591 IN UINTN TemporaryRam,
592 IN UINTN TemporaryRamSize,
593 IN VOID *BootFirmwareVolumeBase,
594 IN UINTN BootFirmwareVolumeSize,
595 IN VOID *SecCorePe32File
596 )
597 /*++
598
599 Routine Description:
600 This is the service to load the SEC Core from the Firmware Volume
601
602 Arguments:
603 TemporaryRam - Memory to use for SEC.
604 TemporaryRamSize - Size of Memory to use for SEC
605 BootFirmwareVolumeBase - Start of the Boot FV
606 SecCorePe32File - SEC Core PE32
607
608 Returns:
609 Success means control is transfered and thus we should never return
610
611 --*/
612 {
613 EFI_STATUS Status;
614 VOID *TopOfStack;
615 VOID *SecCoreEntryPoint;
616 EFI_SEC_PEI_HAND_OFF *SecCoreData;
617 UINTN SecStackSize;
618
619 //
620 // Compute Top Of Memory for Stack and PEI Core Allocations
621 //
622 SecStackSize = TemporaryRamSize >> 1;
623
624 //
625 // |-----------| <---- TemporaryRamBase + TemporaryRamSize
626 // | Heap |
627 // | |
628 // |-----------| <---- StackBase / PeiTemporaryMemoryBase
629 // | |
630 // | Stack |
631 // |-----------| <---- TemporaryRamBase
632 //
633 TopOfStack = (VOID *)(TemporaryRam + SecStackSize);
634
635 //
636 // Reservet space for storing PeiCore's parament in stack.
637 //
638 TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
639 TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
640
641 //
642 // Bind this information into the SEC hand-off state
643 //
644 SecCoreData = (EFI_SEC_PEI_HAND_OFF*)(UINTN)TopOfStack;
645 SecCoreData->DataSize = sizeof (EFI_SEC_PEI_HAND_OFF);
646 SecCoreData->BootFirmwareVolumeBase = BootFirmwareVolumeBase;
647 SecCoreData->BootFirmwareVolumeSize = BootFirmwareVolumeSize;
648 SecCoreData->TemporaryRamBase = (VOID*)TemporaryRam;
649 SecCoreData->TemporaryRamSize = TemporaryRamSize;
650 SecCoreData->StackBase = SecCoreData->TemporaryRamBase;
651 SecCoreData->StackSize = SecStackSize;
652 SecCoreData->PeiTemporaryRamBase = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + SecStackSize);
653 SecCoreData->PeiTemporaryRamSize = TemporaryRamSize - SecStackSize;
654
655 //
656 // Load the PEI Core from a Firmware Volume
657 //
658 Status = SecPeCoffGetEntryPoint (
659 SecCorePe32File,
660 &SecCoreEntryPoint
661 );
662 if (EFI_ERROR (Status)) {
663 return ;
664 }
665
666 //
667 // Transfer control to the SEC Core
668 //
669 SwitchStack (
670 (SWITCH_STACK_ENTRY_POINT)(UINTN)SecCoreEntryPoint,
671 SecCoreData,
672 GetThunkPpiList (),
673 TopOfStack
674 );
675 //
676 // If we get here, then the SEC Core returned. This is an error
677 //
678 return ;
679 }
680
681 RETURN_STATUS
682 EFIAPI
683 SecPeCoffGetEntryPoint (
684 IN VOID *Pe32Data,
685 IN OUT VOID **EntryPoint
686 )
687 {
688 EFI_STATUS Status;
689 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
690
691 ZeroMem (&ImageContext, sizeof (ImageContext));
692 ImageContext.Handle = Pe32Data;
693
694 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) SecImageRead;
695
696 Status = PeCoffLoaderGetImageInfo (&ImageContext);
697 if (EFI_ERROR (Status)) {
698 return Status;
699 }
700 //
701 // Allocate space in NT (not emulator) memory with ReadWrite and Execute attribute.
702 // Extra space is for alignment
703 //
704 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
705 if (ImageContext.ImageAddress == 0) {
706 return EFI_OUT_OF_RESOURCES;
707 }
708 //
709 // Align buffer on section boundary
710 //
711 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
712 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);
713
714 Status = PeCoffLoaderLoadImage (&ImageContext);
715 if (EFI_ERROR (Status)) {
716 return Status;
717 }
718
719 Status = PeCoffLoaderRelocateImage (&ImageContext);
720 if (EFI_ERROR (Status)) {
721 return Status;
722 }
723
724 *EntryPoint = (VOID *)(UINTN)ImageContext.EntryPoint;
725
726 return EFI_SUCCESS;
727 }
728
729 EFI_STATUS
730 EFIAPI
731 SecImageRead (
732 IN VOID *FileHandle,
733 IN UINTN FileOffset,
734 IN OUT UINTN *ReadSize,
735 OUT VOID *Buffer
736 )
737 /*++
738
739 Routine Description:
740 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
741
742 Arguments:
743 FileHandle - The handle to the PE/COFF file
744 FileOffset - The offset, in bytes, into the file to read
745 ReadSize - The number of bytes to read from the file starting at FileOffset
746 Buffer - A pointer to the buffer to read the data into.
747
748 Returns:
749 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
750
751 --*/
752 {
753 CHAR8 *Destination8;
754 CHAR8 *Source8;
755 UINTN Length;
756
757 Destination8 = Buffer;
758 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
759 Length = *ReadSize;
760 while (Length--) {
761 *(Destination8++) = *(Source8++);
762 }
763
764 return EFI_SUCCESS;
765 }
766
767 CHAR16 *
768 AsciiToUnicode (
769 IN CHAR8 *Ascii,
770 IN UINTN *StrLen OPTIONAL
771 )
772 /*++
773
774 Routine Description:
775 Convert the passed in Ascii string to Unicode.
776 Optionally return the length of the strings.
777
778 Arguments:
779 Ascii - Ascii string to convert
780 StrLen - Length of string
781
782 Returns:
783 Pointer to malloc'ed Unicode version of Ascii
784
785 --*/
786 {
787 UINTN Index;
788 CHAR16 *Unicode;
789
790 //
791 // Allocate a buffer for unicode string
792 //
793 for (Index = 0; Ascii[Index] != '\0'; Index++)
794 ;
795 Unicode = malloc ((Index + 1) * sizeof (CHAR16));
796 if (Unicode == NULL) {
797 return NULL;
798 }
799
800 for (Index = 0; Ascii[Index] != '\0'; Index++) {
801 Unicode[Index] = (CHAR16) Ascii[Index];
802 }
803
804 Unicode[Index] = '\0';
805
806 if (StrLen != NULL) {
807 *StrLen = Index;
808 }
809
810 return Unicode;
811 }
812
813 UINTN
814 CountSeparatorsInString (
815 IN CONST CHAR16 *String,
816 IN CHAR16 Separator
817 )
818 /*++
819
820 Routine Description:
821 Count the number of separators in String
822
823 Arguments:
824 String - String to process
825 Separator - Item to count
826
827 Returns:
828 Number of Separator in String
829
830 --*/
831 {
832 UINTN Count;
833
834 for (Count = 0; *String != '\0'; String++) {
835 if (*String == Separator) {
836 Count++;
837 }
838 }
839
840 return Count;
841 }
842
843
844 VOID
845 EFIAPI
846 PeCoffLoaderRelocateImageExtraAction (
847 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
848 )
849 {
850 VOID *DllEntryPoint;
851 CHAR16 *DllFileName;
852 HMODULE Library;
853 UINTN Index;
854
855 ASSERT (ImageContext != NULL);
856 //
857 // If we load our own PE COFF images the Windows debugger can not source
858 // level debug our code. If a valid PDB pointer exists usw it to load
859 // the *.dll file as a library using Windows* APIs. This allows
860 // source level debug. The image is still loaded and relocated
861 // in the Framework memory space like on a real system (by the code above),
862 // but the entry point points into the DLL loaded by the code bellow.
863 //
864
865 DllEntryPoint = NULL;
866
867 //
868 // Load the DLL if it's not an EBC image.
869 //
870 if ((ImageContext->PdbPointer != NULL) &&
871 (ImageContext->Machine != EFI_IMAGE_MACHINE_EBC)) {
872 //
873 // Convert filename from ASCII to Unicode
874 //
875 DllFileName = AsciiToUnicode (ImageContext->PdbPointer, &Index);
876
877 //
878 // Check that we have a valid filename
879 //
880 if (Index < 5 || DllFileName[Index - 4] != '.') {
881 free (DllFileName);
882
883 //
884 // Never return an error if PeCoffLoaderRelocateImage() succeeded.
885 // The image will run, but we just can't source level debug. If we
886 // return an error the image will not run.
887 //
888 return;
889 }
890 //
891 // Replace .PDB with .DLL on the filename
892 //
893 DllFileName[Index - 3] = 'D';
894 DllFileName[Index - 2] = 'L';
895 DllFileName[Index - 1] = 'L';
896
897 //
898 // Load the .DLL file into the user process's address space for source
899 // level debug
900 //
901 Library = LoadLibraryEx (DllFileName, NULL, DONT_RESOLVE_DLL_REFERENCES);
902 if (Library != NULL) {
903 //
904 // InitializeDriver is the entry point we put in all our EFI DLL's. The
905 // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() suppresses the
906 // normal DLL entry point of DllMain, and prevents other modules that are
907 // referenced in side the DllFileName from being loaded. There is no error
908 // checking as the we can point to the PE32 image loaded by Tiano. This
909 // step is only needed for source level debugging
910 //
911 DllEntryPoint = (VOID *) (UINTN) GetProcAddress (Library, "InitializeDriver");
912
913 }
914
915 if ((Library != NULL) && (DllEntryPoint != NULL)) {
916 ImageContext->EntryPoint = (EFI_PHYSICAL_ADDRESS) (UINTN) DllEntryPoint;
917 SecPrint ("LoadLibraryEx (%S,\n NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);
918 } else {
919 SecPrint ("WARNING: No source level debug %S. \n", DllFileName);
920 }
921
922 free (DllFileName);
923 }
924 }
925
926 VOID
927 EFIAPI
928 PeCoffLoaderUnloadImageExtraAction (
929 IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
930 )
931 {
932 ASSERT (ImageContext != NULL);
933 }
934
935
936 VOID
937 _ModuleEntryPoint (
938 VOID
939 )
940 {
941 }