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