]> git.proxmox.com Git - mirror_edk2.git/blob - Tools/Source/TianoTools/PeiRebase/PeiRebaseExe.c
7b48b67d2464c54927421f098ce4454716b52ba5
[mirror_edk2.git] / Tools / Source / TianoTools / PeiRebase / PeiRebaseExe.c
1 /*++
2
3 Copyright (c) 1999 - 2005 Intel Corporation. All rights reserved
4 This software and associated documentation (if any) is furnished
5 under a license and may only be used or copied in accordance
6 with the terms of the license. Except as permitted by such
7 license, no part of this software or documentation may be
8 reproduced, stored in a retrieval system, or transmitted in any
9 form or by any means without the express written consent of
10 Intel Corporation.
11
12
13 Module Name:
14
15 PeiRebaseExe.c
16
17 Abstract:
18
19 This contains all code necessary to build the PeiRebase.exe utility.
20 This utility relies heavily on the PeiRebase DLL. Definitions for both
21 can be found in the PEI Rebase Utility Specification, review draft.
22
23 --*/
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28
29 #include <Common/UefiBaseTypes.h>
30 #include <Common/FirmwareVolumeImageFormat.h>
31 #include <Common/FirmwareFileSystem.h>
32 #include <Library/PeCoffLib.h>
33
34 #include "ParseInf.h"
35 #include "FvLib.h"
36 #include "EfiUtilityMsgs.h"
37 #include "PeiRebaseExe.h"
38
39 EFI_STATUS
40 ReadHeader (
41 IN FILE *InputFile,
42 OUT UINT32 *FvSize,
43 OUT BOOLEAN *ErasePolarity
44 );
45
46 int
47 main (
48 int argc,
49 char **argv
50 )
51 /*++
52
53 Routine Description:
54
55 This utility relocates PEI XIP PE32s in a FV.
56
57 Arguments:
58
59 argc - Number of command line arguments
60 argv[]:
61 BaseAddress The base address to use for rebasing the FV. The correct
62 format is a hex number preceded by 0x.
63 InputFileName The name of the input FV file.
64 OutputFileName The name of the output FV file.
65
66 Arguments come in pair in any order.
67 -I InputFileName
68 -O OutputFileName
69 -B BaseAddress
70
71 Returns:
72
73 0 No error conditions detected.
74 1 One or more of the input parameters is invalid.
75 2 A resource required by the utility was unavailable.
76 Most commonly this will be memory allocation or file creation.
77 3 PeiRebase.dll could not be loaded.
78 4 Error executing the PEI rebase.
79
80 --*/
81 {
82 UINT8 Index;
83 CHAR8 InputFileName[_MAX_PATH];
84 CHAR8 OutputFileName[_MAX_PATH];
85 EFI_PHYSICAL_ADDRESS BaseAddress;
86 BOOLEAN BaseAddressSet;
87 EFI_STATUS Status;
88 FILE *InputFile;
89 FILE *OutputFile;
90 UINT64 FvOffset;
91 UINT32 FileCount;
92 int BytesRead;
93 EFI_FIRMWARE_VOLUME_HEADER *FvImage;
94 UINT32 FvSize;
95 EFI_FFS_FILE_HEADER *CurrentFile;
96 BOOLEAN ErasePolarity;
97 EFI_PHYSICAL_ADDRESS CurrentFileBaseAddress;
98
99 ErasePolarity = FALSE;
100 //
101 // Set utility name for error/warning reporting purposes.
102 //
103 SetUtilityName (UTILITY_NAME);
104 //
105 // Verify the correct number of arguments
106 //
107 if (argc != MAX_ARGS) {
108 PrintUsage ();
109 return STATUS_ERROR;
110 }
111 //
112 // Initialize variables
113 //
114 InputFileName[0] = 0;
115 OutputFileName[0] = 0;
116 BaseAddress = 0;
117 BaseAddressSet = FALSE;
118 FvOffset = 0;
119 FileCount = 0;
120 ErasePolarity = FALSE;
121 InputFile = NULL;
122 OutputFile = NULL;
123 FvImage = NULL;
124 //
125 // Parse the command line arguments
126 //
127 for (Index = 1; Index < MAX_ARGS; Index += 2) {
128 //
129 // Make sure argument pair begin with - or /
130 //
131 if (argv[Index][0] != '-' && argv[Index][0] != '/') {
132 PrintUsage ();
133 Error (NULL, 0, 0, argv[Index], "unrecognized option");
134 return STATUS_ERROR;
135 }
136 //
137 // Make sure argument specifier is only one letter
138 //
139 if (argv[Index][2] != 0) {
140 PrintUsage ();
141 Error (NULL, 0, 0, argv[Index], "unrecognized option");
142 return STATUS_ERROR;
143 }
144 //
145 // Determine argument to read
146 //
147 switch (argv[Index][1]) {
148 case 'I':
149 case 'i':
150 if (strlen (InputFileName) == 0) {
151 strcpy (InputFileName, argv[Index + 1]);
152 } else {
153 PrintUsage ();
154 Error (NULL, 0, 0, argv[Index + 1], "only one -i InputFileName may be specified");
155 return STATUS_ERROR;
156 }
157 break;
158
159 case 'O':
160 case 'o':
161 if (strlen (OutputFileName) == 0) {
162 strcpy (OutputFileName, argv[Index + 1]);
163 } else {
164 PrintUsage ();
165 Error (NULL, 0, 0, argv[Index + 1], "only one -o OutputFileName may be specified");
166 return STATUS_ERROR;
167 }
168 break;
169
170 case 'B':
171 case 'b':
172 if (!BaseAddressSet) {
173 Status = AsciiStringToUint64 (argv[Index + 1], FALSE, &BaseAddress);
174 if (EFI_ERROR (Status)) {
175 PrintUsage ();
176 Error (NULL, 0, 0, argv[Index + 1], "invalid hex digit given for the base address");
177 return STATUS_ERROR;
178 }
179
180 BaseAddressSet = TRUE;
181 } else {
182 PrintUsage ();
183 Error (NULL, 0, 0, argv[Index + 1], "-b BaseAddress may only be specified once");
184 return STATUS_ERROR;
185 }
186 break;
187
188 default:
189 PrintUsage ();
190 Error (NULL, 0, 0, argv[Index], "unrecognized argument");
191 return STATUS_ERROR;
192 break;
193 }
194 }
195 //
196 // Open the file containing the FV
197 //
198 InputFile = fopen (InputFileName, "rb");
199 if (InputFile == NULL) {
200 Error (NULL, 0, 0, InputFileName, "could not open input file for reading");
201 return STATUS_ERROR;
202 }
203 //
204 // Determine size of FV
205 //
206 Status = ReadHeader (InputFile, &FvSize, &ErasePolarity);
207 if (EFI_ERROR (Status)) {
208 Error (NULL, 0, 0, "could not parse the FV header", NULL);
209 goto Finish;
210 }
211 //
212 // Allocate a buffer for the FV image
213 //
214 FvImage = malloc (FvSize);
215 if (FvImage == NULL) {
216 Error (NULL, 0, 0, "application error", "memory allocation failed");
217 goto Finish;
218 }
219 //
220 // Read the entire FV to the buffer
221 //
222 BytesRead = fread (FvImage, 1, FvSize, InputFile);
223 fclose (InputFile);
224 InputFile = NULL;
225 if ((unsigned int) BytesRead != FvSize) {
226 Error (NULL, 0, 0, InputFileName, "failed to read from file");
227 goto Finish;
228 }
229 //
230 // Prepare to walk the FV image
231 //
232 InitializeFvLib (FvImage, FvSize);
233 //
234 // Get the first file
235 //
236 Status = GetNextFile (NULL, &CurrentFile);
237 if (EFI_ERROR (Status)) {
238 Error (NULL, 0, 0, "cannot find the first file in the FV image", NULL);
239 goto Finish;
240 }
241 //
242 // Check if each file should be rebased
243 //
244 while (CurrentFile != NULL) {
245 //
246 // Rebase this file
247 //
248 CurrentFileBaseAddress = BaseAddress + ((UINTN) CurrentFile - (UINTN) FvImage);
249 Status = FfsRebase (CurrentFile, CurrentFileBaseAddress);
250
251 if (EFI_ERROR (Status)) {
252 switch (Status) {
253
254 case EFI_INVALID_PARAMETER:
255 Error (NULL, 0, 0, "invalid parameter passed to FfsRebase", NULL);
256 break;
257
258 case EFI_ABORTED:
259 Error (NULL, 0, 0, "error detected while rebasing -- aborted", NULL);
260 break;
261
262 case EFI_OUT_OF_RESOURCES:
263 Error (NULL, 0, 0, "FfsRebase could not allocate required resources", NULL);
264 break;
265
266 case EFI_NOT_FOUND:
267 Error (NULL, 0, 0, "FfsRebase could not locate a PE32 section", NULL);
268 break;
269
270 default:
271 Error (NULL, 0, 0, "FfsRebase returned unknown status", "status=0x%08X", Status);
272 break;
273 }
274
275 goto Finish;
276 }
277 //
278 // Get the next file
279 //
280 Status = GetNextFile (CurrentFile, &CurrentFile);
281 if (EFI_ERROR (Status)) {
282 Error (NULL, 0, 0, "cannot find the next file in the FV image", NULL);
283 goto Finish;
284 }
285 }
286 //
287 // Open the output file
288 //
289 OutputFile = fopen (OutputFileName, "wb");
290 if (OutputFile == NULL) {
291 Error (NULL, 0, 0, OutputFileName, "failed to open output file");
292 goto Finish;
293 }
294
295 if (fwrite (FvImage, 1, FvSize, OutputFile) != FvSize) {
296 Error (NULL, 0, 0, "failed to write to output file", 0);
297 goto Finish;
298 }
299
300 Finish:
301 if (InputFile != NULL) {
302 fclose (InputFile);
303 }
304 //
305 // If we created an output file, and there was an error, remove it so
306 // subsequent builds will rebuild it.
307 //
308 if (OutputFile != NULL) {
309 if (GetUtilityStatus () == STATUS_ERROR) {
310 remove (OutputFileName);
311 }
312
313 fclose (OutputFile);
314 }
315
316 if (FvImage != NULL) {
317 free (FvImage);
318 }
319
320 return GetUtilityStatus ();
321 }
322
323 EFI_STATUS
324 ReadHeader (
325 IN FILE *InputFile,
326 OUT UINT32 *FvSize,
327 OUT BOOLEAN *ErasePolarity
328 )
329 /*++
330
331 Routine Description:
332
333 This function determines the size of the FV and the erase polarity. The
334 erase polarity is the FALSE value for file state.
335
336 Arguments:
337
338 InputFile The file that contains the FV image.
339 FvSize The size of the FV.
340 ErasePolarity The FV erase polarity.
341
342 Returns:
343
344 EFI_SUCCESS Function completed successfully.
345 EFI_INVALID_PARAMETER A required parameter was NULL or is out of range.
346 EFI_ABORTED The function encountered an error.
347
348 --*/
349 {
350 EFI_FIRMWARE_VOLUME_HEADER VolumeHeader;
351 EFI_FV_BLOCK_MAP_ENTRY BlockMap;
352 UINTN Signature[2];
353 UINTN BytesRead;
354 UINT32 Size;
355
356 BytesRead = 0;
357 Size = 0;
358 //
359 // Check input parameters
360 //
361 if ((InputFile == NULL) || (FvSize == NULL) || (ErasePolarity == NULL)) {
362 Error (NULL, 0, 0, "ReadHeader()", "invalid input parameter");
363 return EFI_INVALID_PARAMETER;
364 }
365 //
366 // Read the header
367 //
368 fread (&VolumeHeader, sizeof (EFI_FIRMWARE_VOLUME_HEADER) - sizeof (EFI_FV_BLOCK_MAP_ENTRY), 1, InputFile);
369 BytesRead = sizeof (EFI_FIRMWARE_VOLUME_HEADER) - sizeof (EFI_FV_BLOCK_MAP_ENTRY);
370 Signature[0] = VolumeHeader.Signature;
371 Signature[1] = 0;
372
373 //
374 // Get erase polarity
375 //
376 if (VolumeHeader.Attributes & EFI_FVB_ERASE_POLARITY) {
377 *ErasePolarity = TRUE;
378 }
379
380 do {
381 fread (&BlockMap, sizeof (EFI_FV_BLOCK_MAP_ENTRY), 1, InputFile);
382 BytesRead += sizeof (EFI_FV_BLOCK_MAP_ENTRY);
383
384 if (BlockMap.NumBlocks != 0) {
385 Size += BlockMap.NumBlocks * BlockMap.BlockLength;
386 }
387
388 } while (!(BlockMap.NumBlocks == 0 && BlockMap.BlockLength == 0));
389
390 if (VolumeHeader.FvLength != Size) {
391 Error (NULL, 0, 0, "volume size not consistant with block maps", NULL);
392 return EFI_ABORTED;
393 }
394
395 *FvSize = Size;
396
397 rewind (InputFile);
398
399 return EFI_SUCCESS;
400 }
401
402 VOID
403 PrintUtilityInfo (
404 VOID
405 )
406 /*++
407
408 Routine Description:
409
410 Displays the standard utility information to SDTOUT
411
412 Arguments:
413
414 None
415
416 Returns:
417
418 None
419
420 --*/
421 {
422 printf (
423 "%s, PEI Rebase Utility. Version %i.%i, %s.\n\n",
424 UTILITY_NAME,
425 UTILITY_MAJOR_VERSION,
426 UTILITY_MINOR_VERSION,
427 UTILITY_DATE
428 );
429 }
430
431 VOID
432 PrintUsage (
433 VOID
434 )
435 /*++
436
437 Routine Description:
438
439 Displays the utility usage syntax to STDOUT
440
441 Arguments:
442
443 None
444
445 Returns:
446
447 None
448
449 --*/
450 {
451 printf (
452 "Usage: %s -I InputFileName -O OutputFileName -B BaseAddress\n",
453 UTILITY_NAME
454 );
455 printf (" Where:\n");
456 printf (" InputFileName is the name of the EFI FV file to rebase.\n");
457 printf (" OutputFileName is the desired output file name.\n");
458 printf (" BaseAddress is the FV base address to rebase agains.\n");
459 printf (" Argument pair may be in any order.\n\n");
460 }
461
462 EFI_STATUS
463 FfsRebase (
464 IN OUT EFI_FFS_FILE_HEADER *FfsFile,
465 IN EFI_PHYSICAL_ADDRESS BaseAddress
466 )
467 /*++
468
469 Routine Description:
470
471 This function determines if a file is XIP and should be rebased. It will
472 rebase any PE32 sections found in the file using the base address.
473
474 Arguments:
475
476 FfsFile A pointer to Ffs file image.
477 BaseAddress The base address to use for rebasing the file image.
478
479 Returns:
480
481 EFI_SUCCESS The image was properly rebased.
482 EFI_INVALID_PARAMETER An input parameter is invalid.
483 EFI_ABORTED An error occurred while rebasing the input file image.
484 EFI_OUT_OF_RESOURCES Could not allocate a required resource.
485 EFI_NOT_FOUND No compressed sections could be found.
486
487 --*/
488 {
489 EFI_STATUS Status;
490 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
491 UINTN MemoryImagePointer;
492 UINTN MemoryImagePointerAligned;
493 EFI_PHYSICAL_ADDRESS ImageAddress;
494 UINT64 ImageSize;
495 EFI_PHYSICAL_ADDRESS EntryPoint;
496 UINT32 Pe32ImageSize;
497 UINT32 NewPe32BaseAddress;
498 UINTN Index;
499 EFI_FILE_SECTION_POINTER CurrentPe32Section;
500 EFI_FFS_FILE_STATE SavedState;
501 EFI_IMAGE_NT_HEADERS *PeHdr;
502 UINT32 *PeHdrSizeOfImage;
503 UINT32 *PeHdrChecksum;
504 UINT32 FoundCount;
505 EFI_TE_IMAGE_HEADER *TEImageHeader;
506 UINT8 *TEBuffer;
507 EFI_IMAGE_DOS_HEADER *DosHeader;
508 UINT8 FileGuidString[80];
509 UINT32 TailSize;
510 EFI_FFS_FILE_TAIL TailValue;
511
512 //
513 // Verify input parameters
514 //
515 if (FfsFile == NULL) {
516 return EFI_INVALID_PARAMETER;
517 }
518 //
519 // Convert the GUID to a string so we can at least report which file
520 // if we find an error.
521 //
522 PrintGuidToBuffer (&FfsFile->Name, FileGuidString, sizeof (FileGuidString), TRUE);
523 if (FfsFile->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
524 TailSize = sizeof (EFI_FFS_FILE_TAIL);
525 } else {
526 TailSize = 0;
527 }
528 //
529 // Do some cursory checks on the FFS file contents
530 //
531 Status = VerifyFfsFile (FfsFile);
532 if (EFI_ERROR (Status)) {
533 Error (NULL, 0, 0, "file does not appear to be a valid FFS file, cannot be rebased", FileGuidString);
534 return EFI_INVALID_PARAMETER;
535 }
536 //
537 // Check if XIP file type. If not XIP, don't rebase.
538 //
539 if (FfsFile->Type != EFI_FV_FILETYPE_PEI_CORE &&
540 FfsFile->Type != EFI_FV_FILETYPE_PEIM &&
541 FfsFile->Type != EFI_FV_FILETYPE_SECURITY_CORE &&
542 FfsFile->Type != EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER
543 ) {
544 return EFI_SUCCESS;
545 }
546 //
547 // Rebase each PE32 section
548 //
549 Status = EFI_SUCCESS;
550 FoundCount = 0;
551 for (Index = 1;; Index++) {
552 Status = GetSectionByType (FfsFile, EFI_SECTION_PE32, Index, &CurrentPe32Section);
553 if (EFI_ERROR (Status)) {
554 break;
555 }
556
557 FoundCount++;
558
559 //
560 // Calculate the PE32 base address, the FFS file base plus the offset of the PE32 section
561 //
562 NewPe32BaseAddress = ((UINT32) BaseAddress) + ((UINTN) CurrentPe32Section.Pe32Section + sizeof (EFI_COMMON_SECTION_HEADER) - (UINTN) FfsFile);
563
564 //
565 // Initialize context
566 //
567 memset (&ImageContext, 0, sizeof (ImageContext));
568 ImageContext.Handle = (VOID *) ((UINTN) CurrentPe32Section.Pe32Section + sizeof (EFI_PE32_SECTION));
569 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) FfsRebaseImageRead;
570
571 Status = PeCoffLoaderGetImageInfo (&ImageContext);
572
573 if (EFI_ERROR (Status)) {
574 Error (NULL, 0, 0, "GetImageInfo() call failed on rebase", FileGuidString);
575 return Status;
576 }
577 //
578 // Allocate a buffer for the image to be loaded into.
579 //
580 Pe32ImageSize = GetLength (CurrentPe32Section.Pe32Section->CommonHeader.Size) - sizeof (EFI_PE32_SECTION);
581 MemoryImagePointer = (UINTN) (malloc (Pe32ImageSize + 0x1000));
582 if (MemoryImagePointer == 0) {
583 Error (NULL, 0, 0, "memory allocation failure", NULL);
584 return EFI_OUT_OF_RESOURCES;
585 }
586 memset ((void *) MemoryImagePointer, 0, Pe32ImageSize + 0x1000);
587 MemoryImagePointerAligned = (MemoryImagePointer + 0x0FFF) & (-1 << 12);
588
589
590 ImageContext.ImageAddress = MemoryImagePointerAligned;
591
592 Status = PeCoffLoaderLoadImage (&ImageContext);
593 if (EFI_ERROR (Status)) {
594 Error (NULL, 0, 0, "LoadImage() call failed on rebase", FileGuidString);
595 free ((VOID *) MemoryImagePointer);
596 return Status;
597 }
598
599 ImageContext.DestinationAddress = NewPe32BaseAddress;
600 Status = PeCoffLoaderRelocateImage (&ImageContext);
601 if (EFI_ERROR (Status)) {
602 Error (NULL, 0, 0, "RelocateImage() call failed on rebase", FileGuidString);
603 free ((VOID *) MemoryImagePointer);
604 return Status;
605 }
606
607 ImageAddress = ImageContext.ImageAddress;
608 ImageSize = ImageContext.ImageSize;
609 EntryPoint = ImageContext.EntryPoint;
610
611 if (ImageSize > Pe32ImageSize) {
612 Error (
613 NULL,
614 0,
615 0,
616 "rebased image is larger than original PE32 image",
617 "0x%X > 0x%X, file %s",
618 ImageSize,
619 Pe32ImageSize,
620 FileGuidString
621 );
622 free ((VOID *) MemoryImagePointer);
623 return EFI_ABORTED;
624 }
625 //
626 // Since we may have updated the Codeview RVA, we need to insure the PE
627 // header indicates the image is large enough to contain the Codeview data
628 // so it will be loaded properly later if the PEIM is reloaded into memory...
629 //
630 PeHdr = (VOID *) ((UINTN) ImageAddress + ImageContext.PeCoffHeaderOffset);
631 if (PeHdr->FileHeader.Machine == EFI_IMAGE_MACHINE_IA32) {
632 PeHdrSizeOfImage = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER32 *) &PeHdr->OptionalHeader).SizeOfImage);
633 PeHdrChecksum = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER32 *) &PeHdr->OptionalHeader).CheckSum);
634 } else if (PeHdr->FileHeader.Machine == EFI_IMAGE_MACHINE_IA64) {
635 PeHdrSizeOfImage = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER64 *) &PeHdr->OptionalHeader).SizeOfImage);
636 PeHdrChecksum = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER64 *) &PeHdr->OptionalHeader).CheckSum);
637 } else if (PeHdr->FileHeader.Machine == EFI_IMAGE_MACHINE_X64) {
638 PeHdrSizeOfImage = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER64 *) &PeHdr->OptionalHeader).SizeOfImage);
639 PeHdrChecksum = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER64 *) &PeHdr->OptionalHeader).CheckSum);
640 } else {
641 Error (
642 NULL,
643 0,
644 0,
645 "unknown machine type in PE32 image",
646 "machine type=0x%X, file=%s",
647 (UINT32) PeHdr->FileHeader.Machine,
648 FileGuidString
649 );
650 free ((VOID *) MemoryImagePointer);
651 return EFI_ABORTED;
652 }
653
654 if (*PeHdrSizeOfImage != ImageContext.ImageSize) {
655 *PeHdrSizeOfImage = (UINT32) ImageContext.ImageSize;
656 if (*PeHdrChecksum) {
657 *PeHdrChecksum = 0;
658 }
659 }
660
661 memcpy (CurrentPe32Section.Pe32Section + 1, (VOID *) MemoryImagePointerAligned, (UINT32) ImageSize);
662
663 free ((VOID *) MemoryImagePointer);
664
665 //
666 // Now update file checksum
667 //
668 if (FfsFile->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
669 TailSize = sizeof (EFI_FFS_FILE_TAIL);
670 } else {
671 TailSize = 0;
672 }
673
674 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
675 SavedState = FfsFile->State;
676 FfsFile->IntegrityCheck.Checksum.File = 0;
677 FfsFile->State = 0;
678 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
679 FfsFile->IntegrityCheck.Checksum.File = CalculateChecksum8 (
680 (UINT8 *) FfsFile,
681 GetLength (FfsFile->Size) - TailSize
682 );
683 } else {
684 FfsFile->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
685 }
686
687 FfsFile->State = SavedState;
688 }
689 //
690 // Update tail if present
691 //
692 if (FfsFile->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
693 TailValue = (EFI_FFS_FILE_TAIL) (~(FfsFile->IntegrityCheck.TailReference));
694 *(EFI_FFS_FILE_TAIL *) (((UINTN) FfsFile + GetLength (FfsFile->Size) - sizeof (EFI_FFS_FILE_TAIL))) = TailValue;
695 }
696 }
697 //
698 // Now process TE sections
699 //
700 for (Index = 1;; Index++) {
701 Status = GetSectionByType (FfsFile, EFI_SECTION_TE, Index, &CurrentPe32Section);
702 if (EFI_ERROR (Status)) {
703 break;
704 }
705
706 FoundCount++;
707
708 //
709 // Calculate the TE base address, the FFS file base plus the offset of the TE section less the size stripped off
710 // by GenTEImage
711 //
712 TEImageHeader = (EFI_TE_IMAGE_HEADER *) ((UINT8 *) CurrentPe32Section.Pe32Section + sizeof (EFI_COMMON_SECTION_HEADER));
713
714 NewPe32BaseAddress = ((UINT32) BaseAddress) +
715 (
716 (UINTN) CurrentPe32Section.Pe32Section +
717 sizeof (EFI_COMMON_SECTION_HEADER) +
718 sizeof (EFI_TE_IMAGE_HEADER) -
719 TEImageHeader->StrippedSize -
720 (UINTN) FfsFile
721 );
722
723 //
724 // Allocate a buffer to unshrink the image into.
725 //
726 Pe32ImageSize = GetLength (CurrentPe32Section.Pe32Section->CommonHeader.Size) - sizeof (EFI_PE32_SECTION) -
727 sizeof (EFI_TE_IMAGE_HEADER);
728 Pe32ImageSize += TEImageHeader->StrippedSize;
729 TEBuffer = (UINT8 *) malloc (Pe32ImageSize);
730 if (TEBuffer == NULL) {
731 Error (NULL, 0, 0, "failed to allocate memory", NULL);
732 return EFI_OUT_OF_RESOURCES;
733 }
734 //
735 // Expand the image into our buffer and fill in critical fields in the DOS header
736 // Fill in fields required by the loader.
737 // At offset 0x3C is the offset to the PE signature. We'll put it immediately following the offset value
738 // itself.
739 //
740 memset (TEBuffer, 0, Pe32ImageSize);
741 DosHeader = (EFI_IMAGE_DOS_HEADER *) TEBuffer;
742 DosHeader->e_magic = EFI_IMAGE_DOS_SIGNATURE;
743 *(UINT32 *) (TEBuffer + 0x3C) = 0x40;
744 PeHdr = (EFI_IMAGE_NT_HEADERS *) (TEBuffer + 0x40);
745 PeHdr->Signature = EFI_IMAGE_NT_SIGNATURE;
746 PeHdr->FileHeader.Machine = TEImageHeader->Machine;
747 PeHdr->FileHeader.NumberOfSections = TEImageHeader->NumberOfSections;
748
749 //
750 // Say the size of the optional header is the total we stripped off less the size of a PE file header and PE signature and
751 // the 0x40 bytes for our DOS header.
752 //
753 PeHdr->FileHeader.SizeOfOptionalHeader = (UINT16) (TEImageHeader->StrippedSize - 0x40 - sizeof (UINT32) - sizeof (EFI_IMAGE_FILE_HEADER));
754 PeHdr->OptionalHeader.ImageBase = (UINTN) (TEImageHeader->ImageBase - TEImageHeader->StrippedSize + sizeof (EFI_TE_IMAGE_HEADER));
755 PeHdr->OptionalHeader.SizeOfImage = Pe32ImageSize;
756 PeHdr->OptionalHeader.Subsystem = TEImageHeader->Subsystem;
757 PeHdr->OptionalHeader.SizeOfImage = Pe32ImageSize;
758 PeHdr->OptionalHeader.SizeOfHeaders = TEImageHeader->StrippedSize + TEImageHeader->NumberOfSections *
759 sizeof (EFI_IMAGE_SECTION_HEADER) - 12;
760
761 //
762 // Set NumberOfRvaAndSizes in the optional header to what we had available in the original image
763 //
764 if ((TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress != 0) ||
765 (TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size != 0)
766 ) {
767 PeHdr->OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC + 1;
768 PeHdr->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
769 PeHdr->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
770 }
771
772 if ((TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress != 0) ||
773 (TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size != 0)
774 ) {
775 PeHdr->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
776 PeHdr->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = TEImageHeader->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
777 if (PeHdr->OptionalHeader.NumberOfRvaAndSizes < EFI_IMAGE_DIRECTORY_ENTRY_DEBUG + 1) {
778 PeHdr->OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_DIRECTORY_ENTRY_DEBUG + 1;
779 }
780 }
781 //
782 // NOTE: These values are defaults, and should be verified to be correct in the GenTE utility
783 //
784 PeHdr->OptionalHeader.SectionAlignment = 0x10;
785
786 //
787 // Copy the rest of the image to its original offset
788 //
789 memcpy (
790 TEBuffer + TEImageHeader->StrippedSize,
791 (UINT8 *) CurrentPe32Section.Pe32Section + sizeof (EFI_PE32_SECTION) + sizeof (EFI_TE_IMAGE_HEADER),
792 GetLength (CurrentPe32Section.Pe32Section->CommonHeader.Size) - sizeof (EFI_PE32_SECTION) -
793 sizeof (EFI_TE_IMAGE_HEADER)
794 );
795
796 //
797 // Initialize context
798 //
799 memset (&ImageContext, 0, sizeof (ImageContext));
800 ImageContext.Handle = (VOID *) TEBuffer;
801 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) FfsRebaseImageRead;
802
803 Status = PeCoffLoaderGetImageInfo (&ImageContext);
804
805 if (EFI_ERROR (Status)) {
806 Error (NULL, 0, 0, "GetImageInfo() call failed on rebase of TE image", FileGuidString);
807 free (TEBuffer);
808 return Status;
809 }
810 //
811 // Allocate a buffer for the image to be loaded into.
812 //
813 MemoryImagePointer = (UINTN) (malloc (Pe32ImageSize + 0x1000));
814 if (MemoryImagePointer == 0) {
815 Error (NULL, 0, 0, "memory allocation error on rebase of TE image", FileGuidString);
816 free (TEBuffer);
817 return EFI_OUT_OF_RESOURCES;
818 }
819 memset ((void *) MemoryImagePointer, 0, Pe32ImageSize + 0x1000);
820 MemoryImagePointerAligned = (MemoryImagePointer + 0x0FFF) & (-1 << 12);
821
822
823 ImageContext.ImageAddress = MemoryImagePointerAligned;
824 Status = PeCoffLoaderLoadImage (&ImageContext);
825 if (EFI_ERROR (Status)) {
826 Error (NULL, 0, 0, "LoadImage() call failed on rebase of TE image", FileGuidString);
827 free (TEBuffer);
828 free ((VOID *) MemoryImagePointer);
829 return Status;
830 }
831
832 ImageContext.DestinationAddress = NewPe32BaseAddress;
833 Status = PeCoffLoaderRelocateImage (&ImageContext);
834 if (EFI_ERROR (Status)) {
835 Error (NULL, 0, 0, "RelocateImage() call failed on rebase of TE image", FileGuidString);
836 free ((VOID *) MemoryImagePointer);
837 free (TEBuffer);
838 return Status;
839 }
840
841 ImageAddress = ImageContext.ImageAddress;
842 ImageSize = ImageContext.ImageSize;
843 EntryPoint = ImageContext.EntryPoint;
844
845 //
846 // Since we may have updated the Codeview RVA, we need to insure the PE
847 // header indicates the image is large enough to contain the Codeview data
848 // so it will be loaded properly later if the PEIM is reloaded into memory...
849 //
850 PeHdr = (VOID *) ((UINTN) ImageAddress + ImageContext.PeCoffHeaderOffset);
851 if (PeHdr->FileHeader.Machine == EFI_IMAGE_MACHINE_IA32) {
852 PeHdrSizeOfImage = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER32 *) &PeHdr->OptionalHeader).SizeOfImage);
853 PeHdrChecksum = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER32 *) &PeHdr->OptionalHeader).CheckSum);
854 } else if (PeHdr->FileHeader.Machine == EFI_IMAGE_MACHINE_IA64) {
855 PeHdrSizeOfImage = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER64 *) &PeHdr->OptionalHeader).SizeOfImage);
856 PeHdrChecksum = (UINT32 *) (&(*(EFI_IMAGE_OPTIONAL_HEADER64 *) &PeHdr->OptionalHeader).CheckSum);
857 } else {
858 Error (
859 NULL,
860 0,
861 0,
862 "unknown machine type in TE image",
863 "machine type=0x%X, file=%s",
864 (UINT32) PeHdr->FileHeader.Machine,
865 FileGuidString
866 );
867 free ((VOID *) MemoryImagePointer);
868 free (TEBuffer);
869 return EFI_ABORTED;
870 }
871
872 if (*PeHdrSizeOfImage != ImageContext.ImageSize) {
873 *PeHdrSizeOfImage = (UINT32) ImageContext.ImageSize;
874 if (*PeHdrChecksum) {
875 *PeHdrChecksum = 0;
876 }
877 }
878
879 TEImageHeader->ImageBase = (UINT64) (NewPe32BaseAddress + TEImageHeader->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER));
880 memcpy (
881 (UINT8 *) (CurrentPe32Section.Pe32Section + 1) + sizeof (EFI_TE_IMAGE_HEADER),
882 (VOID *) ((UINT8 *) MemoryImagePointerAligned + TEImageHeader->StrippedSize),
883 GetLength (CurrentPe32Section.Pe32Section->CommonHeader.Size) - sizeof (EFI_PE32_SECTION) -
884 sizeof (EFI_TE_IMAGE_HEADER)
885 );
886 free ((VOID *) MemoryImagePointer);
887 free (TEBuffer);
888 if (FfsFile->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
889 TailSize = sizeof (EFI_FFS_FILE_TAIL);
890 } else {
891 TailSize = 0;
892 }
893 //
894 // Now update file checksum
895 //
896 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
897 SavedState = FfsFile->State;
898 FfsFile->IntegrityCheck.Checksum.File = 0;
899 FfsFile->State = 0;
900 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
901 FfsFile->IntegrityCheck.Checksum.File = CalculateChecksum8 (
902 (UINT8 *) FfsFile,
903 GetLength (FfsFile->Size) - TailSize
904 );
905 } else {
906 FfsFile->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
907 }
908
909 FfsFile->State = SavedState;
910 }
911 //
912 // Update tail if present
913 //
914 if (FfsFile->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
915 TailValue = (EFI_FFS_FILE_TAIL) (~(FfsFile->IntegrityCheck.TailReference));
916 *(EFI_FFS_FILE_TAIL *) (((UINTN) FfsFile + GetLength (FfsFile->Size) - sizeof (EFI_FFS_FILE_TAIL))) = TailValue;
917 }
918 }
919 //
920 // If we found no files, then emit an error if no compressed sections either
921 //
922 if (FoundCount == 0) {
923 Status = GetSectionByType (FfsFile, EFI_SECTION_COMPRESSION, Index, &CurrentPe32Section);
924 if (EFI_ERROR (Status)) {
925 Error (NULL, 0, 0, "no PE32, TE, nor compressed section found in FV file", FileGuidString);
926 return EFI_NOT_FOUND;
927 }
928 }
929
930 return EFI_SUCCESS;
931 }
932
933 EFI_STATUS
934 FfsRebaseImageRead (
935 IN VOID *FileHandle,
936 IN UINTN FileOffset,
937 IN OUT UINT32 *ReadSize,
938 OUT VOID *Buffer
939 )
940 /*++
941
942 Routine Description:
943
944 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
945
946 Arguments:
947
948 FileHandle - The handle to the PE/COFF file
949
950 FileOffset - The offset, in bytes, into the file to read
951
952 ReadSize - The number of bytes to read from the file starting at FileOffset
953
954 Buffer - A pointer to the buffer to read the data into.
955
956 Returns:
957
958 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
959
960 --*/
961 {
962 CHAR8 *Destination8;
963 CHAR8 *Source8;
964 UINT32 Length;
965
966 Destination8 = Buffer;
967 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
968 Length = *ReadSize;
969 while (Length--) {
970 *(Destination8++) = *(Source8++);
971 }
972
973 return EFI_SUCCESS;
974 }