]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/Pei/Image/Image.c
92fe798cd6750ffcc8e3bf24421c68f7972adcf1
[mirror_edk2.git] / MdeModulePkg / Core / Pei / Image / Image.c
1 /** @file
2 Pei Core Load Image Support
3
4 Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.<BR>
5 SPDX-License-Identifier: BSD-2-Clause-Patent
6
7 **/
8
9 #include "PeiMain.h"
10
11
12 EFI_PEI_LOAD_FILE_PPI mPeiLoadImagePpi = {
13 PeiLoadImageLoadImageWrapper
14 };
15
16
17 EFI_PEI_PPI_DESCRIPTOR gPpiLoadFilePpiList = {
18 (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
19 &gEfiPeiLoadFilePpiGuid,
20 &mPeiLoadImagePpi
21 };
22
23 /**
24
25 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file.
26 The function is used for XIP code to have optimized memory copy.
27
28 @param FileHandle - The handle to the PE/COFF file
29 @param FileOffset - The offset, in bytes, into the file to read
30 @param ReadSize - The number of bytes to read from the file starting at FileOffset
31 @param Buffer - A pointer to the buffer to read the data into.
32
33 @return EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
34
35 **/
36 EFI_STATUS
37 EFIAPI
38 PeiImageRead (
39 IN VOID *FileHandle,
40 IN UINTN FileOffset,
41 IN UINTN *ReadSize,
42 OUT VOID *Buffer
43 )
44 {
45 CHAR8 *Destination8;
46 CHAR8 *Source8;
47
48 Destination8 = Buffer;
49 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
50 if (Destination8 != Source8) {
51 CopyMem (Destination8, Source8, *ReadSize);
52 }
53
54 return EFI_SUCCESS;
55 }
56
57 /**
58 To check memory usage bit map array to figure out if the memory range the image will be loaded in is available or not. If
59 memory range is available, the function will mark the corresponding bits to 1 which indicates the memory range is used.
60 The function is only invoked when load modules at fixed address feature is enabled.
61
62 @param Private Pointer to the private data passed in from caller
63 @param ImageBase The base address the image will be loaded at.
64 @param ImageSize The size of the image
65
66 @retval EFI_SUCCESS The memory range the image will be loaded in is available
67 @retval EFI_NOT_FOUND The memory range the image will be loaded in is not available
68 **/
69 EFI_STATUS
70 CheckAndMarkFixLoadingMemoryUsageBitMap (
71 IN PEI_CORE_INSTANCE *Private,
72 IN EFI_PHYSICAL_ADDRESS ImageBase,
73 IN UINT32 ImageSize
74 )
75 {
76 UINT32 DxeCodePageNumber;
77 UINT64 ReservedCodeSize;
78 EFI_PHYSICAL_ADDRESS PeiCodeBase;
79 UINT32 BaseOffsetPageNumber;
80 UINT32 TopOffsetPageNumber;
81 UINT32 Index;
82 UINT64 *MemoryUsageBitMap;
83
84
85 //
86 // The reserved code range includes RuntimeCodePage range, Boot time code range and PEI code range.
87 //
88 DxeCodePageNumber = PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber);
89 DxeCodePageNumber += PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber);
90 ReservedCodeSize = EFI_PAGES_TO_SIZE(DxeCodePageNumber + PcdGet32(PcdLoadFixAddressPeiCodePageNumber));
91 PeiCodeBase = Private->LoadModuleAtFixAddressTopAddress - ReservedCodeSize;
92
93 //
94 // Test the memory range for loading the image in the PEI code range.
95 //
96 if ((Private->LoadModuleAtFixAddressTopAddress - EFI_PAGES_TO_SIZE(DxeCodePageNumber)) < (ImageBase + ImageSize) ||
97 (PeiCodeBase > ImageBase)) {
98 return EFI_NOT_FOUND;
99 }
100
101 //
102 // Test if the memory is available or not.
103 //
104 MemoryUsageBitMap = Private->PeiCodeMemoryRangeUsageBitMap;
105 BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - PeiCodeBase));
106 TopOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - PeiCodeBase));
107 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
108 if ((MemoryUsageBitMap[Index / 64] & LShiftU64(1, (Index % 64))) != 0) {
109 //
110 // This page is already used.
111 //
112 return EFI_NOT_FOUND;
113 }
114 }
115
116 //
117 // Being here means the memory range is available. So mark the bits for the memory range
118 //
119 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
120 MemoryUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64));
121 }
122 return EFI_SUCCESS;
123 }
124 /**
125
126 Get the fixed loading address from image header assigned by build tool. This function only be called
127 when Loading module at Fixed address feature enabled.
128
129 @param ImageContext Pointer to the image context structure that describes the PE/COFF
130 image that needs to be examined by this function.
131 @param Private Pointer to the private data passed in from caller
132
133 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
134 @retval EFI_NOT_FOUND The image has no assigned fixed loading address.
135
136 **/
137 EFI_STATUS
138 GetPeCoffImageFixLoadingAssignedAddress(
139 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
140 IN PEI_CORE_INSTANCE *Private
141 )
142 {
143 UINTN SectionHeaderOffset;
144 EFI_STATUS Status;
145 EFI_IMAGE_SECTION_HEADER SectionHeader;
146 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
147 EFI_PHYSICAL_ADDRESS FixLoadingAddress;
148 UINT16 Index;
149 UINTN Size;
150 UINT16 NumberOfSections;
151 UINT64 ValueInSectionHeader;
152
153
154 FixLoadingAddress = 0;
155 Status = EFI_NOT_FOUND;
156
157 //
158 // Get PeHeader pointer
159 //
160 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);
161 if (ImageContext->IsTeImage) {
162 //
163 // for TE image, the fix loading address is saved in first section header that doesn't point
164 // to code section.
165 //
166 SectionHeaderOffset = sizeof (EFI_TE_IMAGE_HEADER);
167 NumberOfSections = ImgHdr->Te.NumberOfSections;
168 } else {
169 SectionHeaderOffset = ImageContext->PeCoffHeaderOffset +
170 sizeof (UINT32) +
171 sizeof (EFI_IMAGE_FILE_HEADER) +
172 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader;
173 NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;
174 }
175 //
176 // Get base address from the first section header that doesn't point to code section.
177 //
178 for (Index = 0; Index < NumberOfSections; Index++) {
179 //
180 // Read section header from file
181 //
182 Size = sizeof (EFI_IMAGE_SECTION_HEADER);
183 Status = ImageContext->ImageRead (
184 ImageContext->Handle,
185 SectionHeaderOffset,
186 &Size,
187 &SectionHeader
188 );
189 if (EFI_ERROR (Status)) {
190 return Status;
191 }
192
193 Status = EFI_NOT_FOUND;
194
195 if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
196 //
197 // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header
198 // that doesn't point to code section in image header, as well as ImageBase field of image header. A notable thing is
199 // that for PEIM, the value in ImageBase field may not be equal to the value in PointerToRelocations & PointerToLineNumbers because
200 // for XIP PEIM, ImageBase field holds the image base address running on the Flash. And PointerToRelocations & PointerToLineNumbers
201 // hold the image base address when it is shadow to the memory. And there is an assumption that when the feature is enabled, if a
202 // module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers fields should NOT be Zero, or
203 // else, these 2 fields should be set to Zero
204 //
205 ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations);
206 if (ValueInSectionHeader != 0) {
207 //
208 // Found first section header that doesn't point to code section.
209 //
210 if ((INT64)PcdGet64(PcdLoadModuleAtFixAddressEnable) > 0) {
211 //
212 // When LMFA feature is configured as Load Module at Fixed Absolute Address mode, PointerToRelocations & PointerToLineNumbers field
213 // hold the absolute address of image base running in memory
214 //
215 FixLoadingAddress = ValueInSectionHeader;
216 } else {
217 //
218 // When LMFA feature is configured as Load Module at Fixed offset mode, PointerToRelocations & PointerToLineNumbers field
219 // hold the offset relative to a platform-specific top address.
220 //
221 FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(Private->LoadModuleAtFixAddressTopAddress + (INT64)ValueInSectionHeader);
222 }
223 //
224 // Check if the memory range is available.
225 //
226 Status = CheckAndMarkFixLoadingMemoryUsageBitMap (Private, FixLoadingAddress, (UINT32) ImageContext->ImageSize);
227 if (!EFI_ERROR(Status)) {
228 //
229 // The assigned address is valid. Return the specified loading address
230 //
231 ImageContext->ImageAddress = FixLoadingAddress;
232 }
233 }
234 break;
235 }
236 SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
237 }
238 DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status= %r \n", (VOID *)(UINTN)FixLoadingAddress, Status));
239 return Status;
240 }
241 /**
242
243 Loads and relocates a PE/COFF image into memory.
244 If the image is not relocatable, it will not be loaded into memory and be loaded as XIP image.
245
246 @param FileHandle - Pointer to the FFS file header of the image.
247 @param Pe32Data - The base address of the PE/COFF file that is to be loaded and relocated
248 @param ImageAddress - The base address of the relocated PE/COFF image
249 @param ImageSize - The size of the relocated PE/COFF image
250 @param EntryPoint - The entry point of the relocated PE/COFF image
251
252 @retval EFI_SUCCESS The file was loaded and relocated
253 @retval EFI_OUT_OF_RESOURCES There was not enough memory to load and relocate the PE/COFF file
254 @retval EFI_WARN_BUFFER_TOO_SMALL
255 There is not enough heap to allocate the requested size.
256 This will not prevent the XIP image from being invoked.
257
258 **/
259 EFI_STATUS
260 LoadAndRelocatePeCoffImage (
261 IN EFI_PEI_FILE_HANDLE FileHandle,
262 IN VOID *Pe32Data,
263 OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
264 OUT UINT64 *ImageSize,
265 OUT EFI_PHYSICAL_ADDRESS *EntryPoint
266 )
267 {
268 EFI_STATUS Status;
269 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
270 PEI_CORE_INSTANCE *Private;
271 UINT64 AlignImageSize;
272 BOOLEAN IsXipImage;
273 EFI_STATUS ReturnStatus;
274 BOOLEAN IsS3Boot;
275 BOOLEAN IsPeiModule;
276 BOOLEAN IsRegisterForShadow;
277 EFI_FV_FILE_INFO FileInfo;
278
279 Private = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ());
280
281 ReturnStatus = EFI_SUCCESS;
282 IsXipImage = FALSE;
283 ZeroMem (&ImageContext, sizeof (ImageContext));
284 ImageContext.Handle = Pe32Data;
285 ImageContext.ImageRead = PeiImageRead;
286
287 Status = PeCoffLoaderGetImageInfo (&ImageContext);
288 if (EFI_ERROR (Status)) {
289 return Status;
290 }
291
292 //
293 // Initialize local IsS3Boot and IsRegisterForShadow variable
294 //
295 IsS3Boot = FALSE;
296 if (Private->HobList.HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME) {
297 IsS3Boot = TRUE;
298 }
299 IsRegisterForShadow = FALSE;
300 if ((Private->CurrentFileHandle == FileHandle)
301 && (Private->Fv[Private->CurrentPeimFvCount].PeimState[Private->CurrentPeimCount] == PEIM_STATE_REGISTER_FOR_SHADOW)) {
302 IsRegisterForShadow = TRUE;
303 }
304
305 //
306 // XIP image that ImageAddress is same to Image handle.
307 //
308 if (ImageContext.ImageAddress == (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) {
309 IsXipImage = TRUE;
310 }
311
312 //
313 // Get file type first
314 //
315 Status = PeiServicesFfsGetFileInfo (FileHandle, &FileInfo);
316 ASSERT_EFI_ERROR (Status);
317
318 //
319 // Check whether the file type is PEI module.
320 //
321 IsPeiModule = FALSE;
322 if (FileInfo.FileType == EFI_FV_FILETYPE_PEI_CORE ||
323 FileInfo.FileType == EFI_FV_FILETYPE_PEIM ||
324 FileInfo.FileType == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER) {
325 IsPeiModule = TRUE;
326 }
327
328 //
329 // When Image has no reloc section, it can't be relocated into memory.
330 //
331 if (ImageContext.RelocationsStripped && (Private->PeiMemoryInstalled) &&
332 ((!IsPeiModule) || PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) ||
333 (!IsS3Boot && (PcdGetBool (PcdShadowPeimOnBoot) || IsRegisterForShadow)) ||
334 (IsS3Boot && PcdGetBool (PcdShadowPeimOnS3Boot)))
335 ) {
336 DEBUG ((DEBUG_INFO|DEBUG_LOAD, "The image at 0x%08x without reloc section can't be loaded into memory\n", (UINTN) Pe32Data));
337 }
338
339 //
340 // Set default base address to current image address.
341 //
342 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data;
343
344 //
345 // Allocate Memory for the image when memory is ready, and image is relocatable.
346 // On normal boot, PcdShadowPeimOnBoot decides whether load PEIM or PeiCore into memory.
347 // On S3 boot, PcdShadowPeimOnS3Boot decides whether load PEIM or PeiCore into memory.
348 //
349 if ((!ImageContext.RelocationsStripped) && (Private->PeiMemoryInstalled) &&
350 ((!IsPeiModule) || PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) ||
351 (!IsS3Boot && (PcdGetBool (PcdShadowPeimOnBoot) || IsRegisterForShadow)) ||
352 (IsS3Boot && PcdGetBool (PcdShadowPeimOnS3Boot)))
353 ) {
354 //
355 // Allocate more buffer to avoid buffer overflow.
356 //
357 if (ImageContext.IsTeImage) {
358 AlignImageSize = ImageContext.ImageSize + ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);
359 } else {
360 AlignImageSize = ImageContext.ImageSize;
361 }
362
363 if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) {
364 AlignImageSize += ImageContext.SectionAlignment;
365 }
366
367 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) {
368 Status = GetPeCoffImageFixLoadingAssignedAddress(&ImageContext, Private);
369 if (EFI_ERROR (Status)){
370 DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n"));
371 //
372 // The PEIM is not assigned valid address, try to allocate page to load it.
373 //
374 Status = PeiServicesAllocatePages (EfiBootServicesCode,
375 EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize),
376 &ImageContext.ImageAddress);
377 }
378 } else {
379 Status = PeiServicesAllocatePages (EfiBootServicesCode,
380 EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize),
381 &ImageContext.ImageAddress);
382 }
383 if (!EFI_ERROR (Status)) {
384 //
385 // Adjust the Image Address to make sure it is section alignment.
386 //
387 if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) {
388 ImageContext.ImageAddress =
389 (ImageContext.ImageAddress + ImageContext.SectionAlignment - 1) &
390 ~((UINTN)ImageContext.SectionAlignment - 1);
391 }
392 //
393 // Fix alignment requirement when Load IPF TeImage into memory.
394 // Skip the reserved space for the stripped PeHeader when load TeImage into memory.
395 //
396 if (ImageContext.IsTeImage) {
397 ImageContext.ImageAddress = ImageContext.ImageAddress +
398 ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize -
399 sizeof (EFI_TE_IMAGE_HEADER);
400 }
401 } else {
402 //
403 // No enough memory resource.
404 //
405 if (IsXipImage) {
406 //
407 // XIP image can still be invoked.
408 //
409 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data;
410 ReturnStatus = EFI_WARN_BUFFER_TOO_SMALL;
411 } else {
412 //
413 // Non XIP image can't be loaded because no enough memory is allocated.
414 //
415 ASSERT (FALSE);
416 return EFI_OUT_OF_RESOURCES;
417 }
418 }
419 }
420
421 //
422 // Load the image to our new buffer
423 //
424 Status = PeCoffLoaderLoadImage (&ImageContext);
425 if (EFI_ERROR (Status)) {
426 if (ImageContext.ImageError == IMAGE_ERROR_INVALID_SECTION_ALIGNMENT) {
427 DEBUG ((DEBUG_ERROR, "PEIM Image Address 0x%11p doesn't meet with section alignment 0x%x.\n", (VOID*)(UINTN)ImageContext.ImageAddress, ImageContext.SectionAlignment));
428 }
429 return Status;
430 }
431 //
432 // Relocate the image in our new buffer
433 //
434 Status = PeCoffLoaderRelocateImage (&ImageContext);
435 if (EFI_ERROR (Status)) {
436 return Status;
437 }
438
439 //
440 // Flush the instruction cache so the image data is written before we execute it
441 //
442 if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) {
443 InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize);
444 }
445
446 *ImageAddress = ImageContext.ImageAddress;
447 *ImageSize = ImageContext.ImageSize;
448 *EntryPoint = ImageContext.EntryPoint;
449
450 return ReturnStatus;
451 }
452
453 /**
454 Loads and relocates a PE/COFF image in place.
455
456 @param Pe32Data The base address of the PE/COFF file that is to be loaded and relocated
457 @param ImageAddress The base address of the relocated PE/COFF image
458
459 @retval EFI_SUCCESS The file was loaded and relocated.
460 @retval Others The file not be loaded and error occurred.
461
462 **/
463 EFI_STATUS
464 LoadAndRelocatePeCoffImageInPlace (
465 IN VOID *Pe32Data,
466 IN VOID *ImageAddress
467 )
468 {
469 EFI_STATUS Status;
470 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
471
472 ZeroMem (&ImageContext, sizeof (ImageContext));
473 ImageContext.Handle = Pe32Data;
474 ImageContext.ImageRead = PeiImageRead;
475
476 Status = PeCoffLoaderGetImageInfo (&ImageContext);
477 if (EFI_ERROR (Status)) {
478 ASSERT_EFI_ERROR (Status);
479 return Status;
480 }
481
482 ImageContext.ImageAddress = (PHYSICAL_ADDRESS)(UINTN) ImageAddress;
483
484 //
485 // Load the image in place
486 //
487 Status = PeCoffLoaderLoadImage (&ImageContext);
488 if (EFI_ERROR (Status)) {
489 ASSERT_EFI_ERROR (Status);
490 return Status;
491 }
492
493 //
494 // Relocate the image in place
495 //
496 Status = PeCoffLoaderRelocateImage (&ImageContext);
497 if (EFI_ERROR (Status)) {
498 ASSERT_EFI_ERROR (Status);
499 return Status;
500 }
501
502 //
503 // Flush the instruction cache so the image data is written before we execute it
504 //
505 if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) {
506 InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize);
507 }
508
509 return Status;
510 }
511
512 /**
513 Find the PE32 Data for an FFS file.
514
515 @param FileHandle Pointer to the FFS file header of the image.
516 @param Pe32Data Pointer to a (VOID *) PE32 Data pointer.
517
518 @retval EFI_SUCCESS Image is successfully loaded.
519 @retval EFI_NOT_FOUND Fail to locate PE32 Data.
520
521 **/
522 EFI_STATUS
523 PeiGetPe32Data (
524 IN EFI_PEI_FILE_HANDLE FileHandle,
525 OUT VOID **Pe32Data
526 )
527 {
528 EFI_STATUS Status;
529 EFI_SECTION_TYPE SearchType1;
530 EFI_SECTION_TYPE SearchType2;
531 UINT32 AuthenticationState;
532
533 *Pe32Data = NULL;
534
535 if (FeaturePcdGet (PcdPeiCoreImageLoaderSearchTeSectionFirst)) {
536 SearchType1 = EFI_SECTION_TE;
537 SearchType2 = EFI_SECTION_PE32;
538 } else {
539 SearchType1 = EFI_SECTION_PE32;
540 SearchType2 = EFI_SECTION_TE;
541 }
542
543 //
544 // Try to find a first exe section (if PcdPeiCoreImageLoaderSearchTeSectionFirst
545 // is true, TE will be searched first).
546 //
547 Status = PeiServicesFfsFindSectionData3 (
548 SearchType1,
549 0,
550 FileHandle,
551 Pe32Data,
552 &AuthenticationState
553 );
554 //
555 // If we didn't find a first exe section, try to find the second exe section.
556 //
557 if (EFI_ERROR (Status)) {
558 Status = PeiServicesFfsFindSectionData3 (
559 SearchType2,
560 0,
561 FileHandle,
562 Pe32Data,
563 &AuthenticationState
564 );
565 }
566 return Status;
567 }
568
569 /**
570 Loads a PEIM into memory for subsequent execution. If there are compressed
571 images or images that need to be relocated into memory for performance reasons,
572 this service performs that transformation.
573
574 @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation
575 @param FileHandle Pointer to the FFS file header of the image.
576 @param ImageAddressArg Pointer to PE/TE image.
577 @param ImageSizeArg Size of PE/TE image.
578 @param EntryPoint Pointer to entry point of specified image file for output.
579 @param AuthenticationState - Pointer to attestation authentication state of image.
580
581 @retval EFI_SUCCESS Image is successfully loaded.
582 @retval EFI_NOT_FOUND Fail to locate necessary PPI.
583 @retval EFI_UNSUPPORTED Image Machine Type is not supported.
584 @retval EFI_WARN_BUFFER_TOO_SMALL
585 There is not enough heap to allocate the requested size.
586 This will not prevent the XIP image from being invoked.
587
588 **/
589 EFI_STATUS
590 PeiLoadImageLoadImage (
591 IN CONST EFI_PEI_SERVICES **PeiServices,
592 IN EFI_PEI_FILE_HANDLE FileHandle,
593 OUT EFI_PHYSICAL_ADDRESS *ImageAddressArg, OPTIONAL
594 OUT UINT64 *ImageSizeArg, OPTIONAL
595 OUT EFI_PHYSICAL_ADDRESS *EntryPoint,
596 OUT UINT32 *AuthenticationState
597 )
598 {
599 EFI_STATUS Status;
600 VOID *Pe32Data;
601 EFI_PHYSICAL_ADDRESS ImageAddress;
602 UINT64 ImageSize;
603 EFI_PHYSICAL_ADDRESS ImageEntryPoint;
604 UINT16 Machine;
605 EFI_SECTION_TYPE SearchType1;
606 EFI_SECTION_TYPE SearchType2;
607
608 *EntryPoint = 0;
609 ImageSize = 0;
610 *AuthenticationState = 0;
611
612 if (FeaturePcdGet (PcdPeiCoreImageLoaderSearchTeSectionFirst)) {
613 SearchType1 = EFI_SECTION_TE;
614 SearchType2 = EFI_SECTION_PE32;
615 } else {
616 SearchType1 = EFI_SECTION_PE32;
617 SearchType2 = EFI_SECTION_TE;
618 }
619
620 //
621 // Try to find a first exe section (if PcdPeiCoreImageLoaderSearchTeSectionFirst
622 // is true, TE will be searched first).
623 //
624 Status = PeiServicesFfsFindSectionData3 (
625 SearchType1,
626 0,
627 FileHandle,
628 &Pe32Data,
629 AuthenticationState
630 );
631 //
632 // If we didn't find a first exe section, try to find the second exe section.
633 //
634 if (EFI_ERROR (Status)) {
635 Status = PeiServicesFfsFindSectionData3 (
636 SearchType2,
637 0,
638 FileHandle,
639 &Pe32Data,
640 AuthenticationState
641 );
642 if (EFI_ERROR (Status)) {
643 //
644 // PEI core only carry the loader function for TE and PE32 executables
645 // If this two section does not exist, just return.
646 //
647 return Status;
648 }
649 }
650
651 DEBUG ((DEBUG_INFO, "Loading PEIM %g\n", FileHandle));
652
653 //
654 // If memory is installed, perform the shadow operations
655 //
656 Status = LoadAndRelocatePeCoffImage (
657 FileHandle,
658 Pe32Data,
659 &ImageAddress,
660 &ImageSize,
661 &ImageEntryPoint
662 );
663
664 if (EFI_ERROR (Status)) {
665 return Status;
666 }
667
668 //
669 // Got the entry point from the loaded Pe32Data
670 //
671 Pe32Data = (VOID *) ((UINTN) ImageAddress);
672 *EntryPoint = ImageEntryPoint;
673
674 Machine = PeCoffLoaderGetMachineType (Pe32Data);
675
676 if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Machine)) {
677 if (!EFI_IMAGE_MACHINE_CROSS_TYPE_SUPPORTED (Machine)) {
678 return EFI_UNSUPPORTED;
679 }
680 }
681
682 if (ImageAddressArg != NULL) {
683 *ImageAddressArg = ImageAddress;
684 }
685
686 if (ImageSizeArg != NULL) {
687 *ImageSizeArg = ImageSize;
688 }
689
690 DEBUG_CODE_BEGIN ();
691 CHAR8 *AsciiString;
692 CHAR8 EfiFileName[512];
693 INT32 Index;
694 INT32 StartIndex;
695
696 //
697 // Print debug message: Loading PEIM at 0x12345678 EntryPoint=0x12345688 Driver.efi
698 //
699 if (Machine != EFI_IMAGE_MACHINE_IA64) {
700 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Loading PEIM at 0x%11p EntryPoint=0x%11p ", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)*EntryPoint));
701 } else {
702 //
703 // For IPF Image, the real entry point should be print.
704 //
705 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Loading PEIM at 0x%11p EntryPoint=0x%11p ", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)(*(UINT64 *)(UINTN)*EntryPoint)));
706 }
707
708 //
709 // Print Module Name by PeImage PDB file name.
710 //
711 AsciiString = PeCoffLoaderGetPdbPointer (Pe32Data);
712
713 if (AsciiString != NULL) {
714 StartIndex = 0;
715 for (Index = 0; AsciiString[Index] != 0; Index++) {
716 if (AsciiString[Index] == '\\' || AsciiString[Index] == '/') {
717 StartIndex = Index + 1;
718 }
719 }
720
721 //
722 // Copy the PDB file name to our temporary string, and replace .pdb with .efi
723 // The PDB file name is limited in the range of 0~511.
724 // If the length is bigger than 511, trim the redundant characters to avoid overflow in array boundary.
725 //
726 for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {
727 EfiFileName[Index] = AsciiString[Index + StartIndex];
728 if (EfiFileName[Index] == 0) {
729 EfiFileName[Index] = '.';
730 }
731 if (EfiFileName[Index] == '.') {
732 EfiFileName[Index + 1] = 'e';
733 EfiFileName[Index + 2] = 'f';
734 EfiFileName[Index + 3] = 'i';
735 EfiFileName[Index + 4] = 0;
736 break;
737 }
738 }
739
740 if (Index == sizeof (EfiFileName) - 4) {
741 EfiFileName[Index] = 0;
742 }
743
744 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName));
745 }
746
747 DEBUG_CODE_END ();
748
749 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n"));
750
751 return EFI_SUCCESS;
752
753 }
754
755
756 /**
757 The wrapper function of PeiLoadImageLoadImage().
758
759 @param This - Pointer to EFI_PEI_LOAD_FILE_PPI.
760 @param FileHandle - Pointer to the FFS file header of the image.
761 @param ImageAddressArg - Pointer to PE/TE image.
762 @param ImageSizeArg - Size of PE/TE image.
763 @param EntryPoint - Pointer to entry point of specified image file for output.
764 @param AuthenticationState - Pointer to attestation authentication state of image.
765
766 @return Status of PeiLoadImageLoadImage().
767
768 **/
769 EFI_STATUS
770 EFIAPI
771 PeiLoadImageLoadImageWrapper (
772 IN CONST EFI_PEI_LOAD_FILE_PPI *This,
773 IN EFI_PEI_FILE_HANDLE FileHandle,
774 OUT EFI_PHYSICAL_ADDRESS *ImageAddressArg, OPTIONAL
775 OUT UINT64 *ImageSizeArg, OPTIONAL
776 OUT EFI_PHYSICAL_ADDRESS *EntryPoint,
777 OUT UINT32 *AuthenticationState
778 )
779 {
780 return PeiLoadImageLoadImage (
781 GetPeiServicesTablePointer (),
782 FileHandle,
783 ImageAddressArg,
784 ImageSizeArg,
785 EntryPoint,
786 AuthenticationState
787 );
788 }
789
790 /**
791 Check whether the input image has the relocation.
792
793 @param Pe32Data Pointer to the PE/COFF or TE image.
794
795 @retval TRUE Relocation is stripped.
796 @retval FALSE Relocation is not stripped.
797
798 **/
799 BOOLEAN
800 RelocationIsStrip (
801 IN VOID *Pe32Data
802 )
803 {
804 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
805 EFI_IMAGE_DOS_HEADER *DosHdr;
806
807 ASSERT (Pe32Data != NULL);
808
809 DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data;
810 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
811 //
812 // DOS image header is present, so read the PE header after the DOS image header.
813 //
814 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff));
815 } else {
816 //
817 // DOS image header is not present, so PE header is at the image base.
818 //
819 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data;
820 }
821
822 //
823 // Three cases with regards to relocations:
824 // - Image has base relocs, RELOCS_STRIPPED==0 => image is relocatable
825 // - Image has no base relocs, RELOCS_STRIPPED==1 => Image is not relocatable
826 // - Image has no base relocs, RELOCS_STRIPPED==0 => Image is relocatable but
827 // has no base relocs to apply
828 // Obviously having base relocations with RELOCS_STRIPPED==1 is invalid.
829 //
830 // Look at the file header to determine if relocations have been stripped, and
831 // save this info in the image context for later use.
832 //
833 if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
834 if ((Hdr.Te->DataDirectory[0].Size == 0) && (Hdr.Te->DataDirectory[0].VirtualAddress == 0)) {
835 return TRUE;
836 } else {
837 return FALSE;
838 }
839 } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) {
840 if ((Hdr.Pe32->FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) != 0) {
841 return TRUE;
842 } else {
843 return FALSE;
844 }
845 }
846
847 return FALSE;
848 }
849
850 /**
851 Routine to load image file for subsequent execution by LoadFile Ppi.
852 If any LoadFile Ppi is not found, the build-in support function for the PE32+/TE
853 XIP image format is used.
854
855 @param PeiServices - An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation
856 @param FileHandle - Pointer to the FFS file header of the image.
857 @param PeimState - The dispatch state of the input PEIM handle.
858 @param EntryPoint - Pointer to entry point of specified image file for output.
859 @param AuthenticationState - Pointer to attestation authentication state of image.
860
861 @retval EFI_SUCCESS - Image is successfully loaded.
862 @retval EFI_NOT_FOUND - Fail to locate necessary PPI
863 @retval Others - Fail to load file.
864
865 **/
866 EFI_STATUS
867 PeiLoadImage (
868 IN CONST EFI_PEI_SERVICES **PeiServices,
869 IN EFI_PEI_FILE_HANDLE FileHandle,
870 IN UINT8 PeimState,
871 OUT EFI_PHYSICAL_ADDRESS *EntryPoint,
872 OUT UINT32 *AuthenticationState
873 )
874 {
875 EFI_STATUS PpiStatus;
876 EFI_STATUS Status;
877 UINTN Index;
878 EFI_PEI_LOAD_FILE_PPI *LoadFile;
879 EFI_PHYSICAL_ADDRESS ImageAddress;
880 UINT64 ImageSize;
881 BOOLEAN IsStrip;
882
883 IsStrip = FALSE;
884 //
885 // If any instances of PEI_LOAD_FILE_PPI are installed, they are called.
886 // one at a time, until one reports EFI_SUCCESS.
887 //
888 Index = 0;
889 do {
890 PpiStatus = PeiServicesLocatePpi (
891 &gEfiPeiLoadFilePpiGuid,
892 Index,
893 NULL,
894 (VOID **)&LoadFile
895 );
896 if (!EFI_ERROR (PpiStatus)) {
897 Status = LoadFile->LoadFile (
898 LoadFile,
899 FileHandle,
900 &ImageAddress,
901 &ImageSize,
902 EntryPoint,
903 AuthenticationState
904 );
905 if (!EFI_ERROR (Status) || Status == EFI_WARN_BUFFER_TOO_SMALL) {
906 //
907 // The shadowed PEIM must be relocatable.
908 //
909 if (PeimState == PEIM_STATE_REGISTER_FOR_SHADOW) {
910 IsStrip = RelocationIsStrip ((VOID *) (UINTN) ImageAddress);
911 ASSERT (!IsStrip);
912 if (IsStrip) {
913 return EFI_UNSUPPORTED;
914 }
915 }
916
917 //
918 // The image to be started must have the machine type supported by PeiCore.
919 //
920 ASSERT (EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *) (UINTN) ImageAddress)));
921 if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *) (UINTN) ImageAddress))) {
922 return EFI_UNSUPPORTED;
923 }
924 return EFI_SUCCESS;
925 }
926 }
927 Index++;
928 } while (!EFI_ERROR (PpiStatus));
929
930 return PpiStatus;
931 }
932
933
934 /**
935
936 Install Pei Load File PPI.
937
938
939 @param PrivateData - Pointer to PEI_CORE_INSTANCE.
940 @param OldCoreData - Pointer to PEI_CORE_INSTANCE.
941
942 **/
943 VOID
944 InitializeImageServices (
945 IN PEI_CORE_INSTANCE *PrivateData,
946 IN PEI_CORE_INSTANCE *OldCoreData
947 )
948 {
949 if (OldCoreData == NULL) {
950 //
951 // The first time we are XIP (running from FLASH). We need to remember the
952 // FLASH address so we can reinstall the memory version that runs faster
953 //
954 PrivateData->XipLoadFile = &gPpiLoadFilePpiList;
955 PeiServicesInstallPpi (PrivateData->XipLoadFile);
956 } else {
957 //
958 // 2nd time we are running from memory so replace the XIP version with the
959 // new memory version.
960 //
961 PeiServicesReInstallPpi (PrivateData->XipLoadFile, &gPpiLoadFilePpiList);
962 }
963 }