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