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