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