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