]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/GenFw.c
d511834fc0aaaa7d1ff4cf62397eeef261299d19
[mirror_edk2.git] / BaseTools / Source / C / GenFw / GenFw.c
1 /** @file
2
3 Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
4 This program and the accompanying materials
5 are licensed and made available under the terms and conditions of the BSD License
6 which accompanies this distribution. The full text of the license may be found at
7 http://opensource.org/licenses/bsd-license.php
8
9 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11
12 Module Name:
13
14 GenFw.c
15
16 Abstract:
17
18 Converts a pe32+ image to an FW, Te image type, or other specific image.
19
20 **/
21
22 #include "WinNtInclude.h"
23
24 #ifndef __GNUC__
25 #include <windows.h>
26 #include <io.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #endif
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <time.h>
34 #include <ctype.h>
35
36 #include <Common/UefiBaseTypes.h>
37 #include <IndustryStandard/PeImage.h>
38 #include <Common/UefiInternalFormRepresentation.h>
39
40 //
41 // Acpi Table definition
42 //
43 #include <IndustryStandard/Acpi.h>
44 #include <IndustryStandard/Acpi1_0.h>
45 #include <IndustryStandard/Acpi2_0.h>
46 #include <IndustryStandard/Acpi3_0.h>
47 #include <IndustryStandard/MemoryMappedConfigurationSpaceAccessTable.h>
48
49 #include "CommonLib.h"
50 #include "PeCoffLib.h"
51 #include "ParseInf.h"
52 #include "EfiUtilityMsgs.h"
53
54 #include "GenFw.h"
55
56 //
57 // Version of this utility
58 //
59 #define UTILITY_NAME "GenFw"
60 #define UTILITY_MAJOR_VERSION 0
61 #define UTILITY_MINOR_VERSION 2
62
63 #define HII_RESOURCE_SECTION_INDEX 1
64 #define HII_RESOURCE_SECTION_NAME "HII"
65
66 #define DEFAULT_MC_PAD_BYTE_VALUE 0xFF
67 #define DEFAULT_MC_ALIGNMENT 16
68
69 #ifndef _MAX_PATH
70 #define _MAX_PATH 500
71 #endif
72
73 #define STATUS_IGNORE 0xA
74 //
75 // Structure definition for a microcode header
76 //
77 typedef struct {
78 UINT32 HeaderVersion;
79 UINT32 PatchId;
80 UINT32 Date;
81 UINT32 CpuId;
82 UINT32 Checksum;
83 UINT32 LoaderVersion;
84 UINT32 PlatformId;
85 UINT32 DataSize; // if 0, then TotalSize = 2048, and TotalSize field is invalid
86 UINT32 TotalSize; // number of bytes
87 UINT32 Reserved[3];
88 } MICROCODE_IMAGE_HEADER;
89
90 static EFI_GUID mZeroGuid = {0x0, 0x0, 0x0, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
91
92 static const char *gHiiPackageRCFileHeader[] = {
93 "//",
94 "// DO NOT EDIT -- auto-generated file",
95 "//",
96 NULL
97 };
98
99 //
100 // Module image information
101 //
102 CHAR8 *mInImageName;
103 UINT32 mImageTimeStamp = 0;
104 UINT32 mImageSize = 0;
105 UINT32 mOutImageType = FW_DUMMY_IMAGE;
106
107
108 STATIC
109 EFI_STATUS
110 ZeroDebugData (
111 IN OUT UINT8 *FileBuffer,
112 BOOLEAN ZeroDebug
113 );
114
115 STATIC
116 EFI_STATUS
117 SetStamp (
118 IN OUT UINT8 *FileBuffer,
119 IN CHAR8 *TimeStamp
120 );
121
122 STATIC
123 STATUS
124 MicrocodeReadData (
125 FILE *InFptr,
126 UINT32 *Data
127 );
128
129 STATIC
130 VOID
131 Version (
132 VOID
133 )
134 /*++
135
136 Routine Description:
137
138 Print out version information for this utility.
139
140 Arguments:
141
142 None
143
144 Returns:
145
146 None
147
148 --*/
149 {
150 fprintf (stdout, "%s Version %d.%d %s \n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION, __BUILD_VERSION);
151 }
152
153 STATIC
154 VOID
155 Usage (
156 VOID
157 )
158 /*++
159
160 Routine Description:
161
162 Print Help message.
163
164 Arguments:
165
166 VOID
167
168 Returns:
169
170 None
171
172 --*/
173 {
174 //
175 // Summary usage
176 //
177 fprintf (stdout, "\nUsage: %s [options] <input_file>\n\n", UTILITY_NAME);
178
179 //
180 // Copyright declaration
181 //
182 fprintf (stdout, "Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.\n\n");
183
184 //
185 // Details Option
186 //
187 fprintf (stdout, "Options:\n");
188 fprintf (stdout, " -o FileName, --outputfile FileName\n\
189 File will be created to store the ouput content.\n");
190 fprintf (stdout, " -e EFI_FILETYPE, --efiImage EFI_FILETYPE\n\
191 Create Efi Image. EFI_FILETYPE is one of BASE,SMM_CORE,\n\
192 PEI_CORE, PEIM, DXE_CORE, DXE_DRIVER, UEFI_APPLICATION,\n\
193 SEC, DXE_SAL_DRIVER, UEFI_DRIVER, DXE_RUNTIME_DRIVER,\n\
194 DXE_SMM_DRIVER, SECURITY_CORE, COMBINED_PEIM_DRIVER,\n\
195 PIC_PEIM, RELOCATABLE_PEIM, BS_DRIVER, RT_DRIVER,\n\
196 APPLICATION, SAL_RT_DRIVER to support all module types\n\
197 It can only be used together with --keepexceptiontable,\n\
198 --keepzeropending, -r, -o option.It is a action option.\n\
199 If it is combined with other action options, the later\n\
200 input action option will override the previous one.\n");
201 fprintf (stdout, " -c, --acpi Create Acpi table.\n\
202 It can't be combined with other action options\n\
203 except for -o, -r option. It is a action option.\n\
204 If it is combined with other action options, the later\n\
205 input action option will override the previous one.\n");
206 fprintf (stdout, " -t, --terse Create Te Image.\n\
207 It can only be used together with --keepexceptiontable,\n\
208 --keepzeropending, -r, -o option.It is a action option.\n\
209 If it is combined with other action options, the later\n\
210 input action option will override the previous one.\n");
211 fprintf (stdout, " -u, --dump Dump TeImage Header.\n\
212 It can't be combined with other action options\n\
213 except for -o, -r option. It is a action option.\n\
214 If it is combined with other action options, the later\n\
215 input action option will override the previous one.\n");
216 fprintf (stdout, " -z, --zero Zero the Debug Data Fields in the PE input image file.\n\
217 It also zeros the time stamp fields.\n\
218 This option can be used to compare the binary efi image.\n\
219 It can't be combined with other action options\n\
220 except for -o, -r option. It is a action option.\n\
221 If it is combined with other action options, the later\n\
222 input action option will override the previous one.\n");
223 fprintf (stdout, " -b, --exe2bin Convert the input EXE to the output BIN file.\n\
224 It can't be combined with other action options\n\
225 except for -o, -r option. It is a action option.\n\
226 If it is combined with other action options, the later\n\
227 input action option will override the previous one.\n");;
228 fprintf (stdout, " -l, --stripped Strip off the relocation info from PE or TE image.\n\
229 It can't be combined with other action options\n\
230 except for -o, -r option. It is a action option.\n\
231 If it is combined with other action options, the later\n\
232 input action option will override the previous one.\n");
233 fprintf (stdout, " -s timedate, --stamp timedate\n\
234 timedate format is \"yyyy-mm-dd 00:00:00\". if timedata \n\
235 is set to NOW, current system time is used. The support\n\
236 date scope is 1970-01-01 00+timezone:00:00\n\
237 ~ 2038-01-19 03+timezone:14:07\n\
238 The scope is adjusted according to the different zones.\n\
239 It can't be combined with other action options\n\
240 except for -o, -r option. It is a action option.\n\
241 If it is combined with other action options, the later\n\
242 input action option will override the previous one.\n");
243 fprintf (stdout, " -m, --mcifile Convert input microcode txt file to microcode bin file.\n\
244 It can't be combined with other action options\n\
245 except for -o option. It is a action option.\n\
246 If it is combined with other action options, the later\n\
247 input action option will override the previous one.\n");
248 fprintf (stdout, " -j, --join Combine multi microcode bin files to one file.\n\
249 It can be specified with -a, -p, -o option.\n\
250 No other options can be combined with it.\n\
251 If it is combined with other action options, the later\n\
252 input action option will override the previous one.\n");
253 fprintf (stdout, " -a NUM, --align NUM NUM is one HEX or DEC format alignment value.\n\
254 This option is only used together with -j option.\n");
255 fprintf (stdout, " -p NUM, --pad NUM NUM is one HEX or DEC format padding value.\n\
256 This option is only used together with -j option.\n");
257 fprintf (stdout, " --keepexceptiontable Don't clear exception table.\n\
258 This option can be used together with -e or -t.\n\
259 It doesn't work for other options.\n");
260 fprintf (stdout, " --keepzeropending Don't strip zero pending of .reloc.\n\
261 This option can be used together with -e or -t.\n\
262 It doesn't work for other options.\n");
263 fprintf (stdout, " -r, --replace Overwrite the input file with the output content.\n\
264 If more input files are specified,\n\
265 the last input file will be as the output file.\n");
266 fprintf (stdout, " -g HiiPackageListGuid, --hiiguid HiiPackageListGuid\n\
267 Guid is used to specify hii package list guid.\n\
268 Its format is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n\
269 If not specified, the first Form FormSet guid is used.\n");
270 fprintf (stdout, " --hiipackage Combine all input binary hii pacakges into \n\
271 a single package list as the text resource data(RC).\n\
272 It can't be combined with other action options\n\
273 except for -o option. It is a action option.\n\
274 If it is combined with other action options, the later\n\
275 input action option will override the previous one.\n");
276 fprintf (stdout, " --hiibinpackage Combine all input binary hii pacakges into \n\
277 a single package list as the binary resource section.\n\
278 It can't be combined with other action options\n\
279 except for -o option. It is a action option.\n\
280 If it is combined with other action options, the later\n\
281 input action option will override the previous one.\n");
282 fprintf (stdout, " --rebase NewAddress Rebase image to new base address. New address \n\
283 is also set to the first none code section header.\n\
284 It can't be combined with other action options\n\
285 except for -o or -r option. It is a action option.\n\
286 If it is combined with other action options, the later\n\
287 input action option will override the previous one.\n");
288 fprintf (stdout, " --address NewAddress Set new address into the first none code \n\
289 section header of the input image.\n\
290 It can't be combined with other action options\n\
291 except for -o or -r option. It is a action option.\n\
292 If it is combined with other action options, the later\n\
293 input action option will override the previous one.\n");
294 fprintf (stdout, " -v, --verbose Turn on verbose output with informational messages.\n");
295 fprintf (stdout, " -q, --quiet Disable all messages except key message and fatal error\n");
296 fprintf (stdout, " -d, --debug level Enable debug messages, at input debug level.\n");
297 fprintf (stdout, " --version Show program's version number and exit\n");
298 fprintf (stdout, " -h, --help Show this help message and exit\n");
299 }
300
301 STATIC
302 STATUS
303 CheckAcpiTable (
304 VOID *AcpiTable,
305 UINT32 Length
306 )
307 /*++
308
309 Routine Description:
310
311 Check Acpi Table
312
313 Arguments:
314
315 AcpiTable Buffer for AcpiSection
316 Length AcpiSection Length
317
318 Returns:
319
320 0 success
321 non-zero otherwise
322
323 --*/
324 {
325 EFI_ACPI_DESCRIPTION_HEADER *AcpiHeader;
326 EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *Facs;
327 UINT32 ExpectedLength;
328
329 AcpiHeader = (EFI_ACPI_DESCRIPTION_HEADER *)AcpiTable;
330
331 //
332 // Generic check for AcpiTable length.
333 //
334 if (AcpiHeader->Length > Length) {
335 Error (NULL, 0, 3000, "Invalid", "AcpiTable length check failed.", NULL);
336 return STATUS_ERROR;
337 }
338
339 //
340 // Currently, we only check must-have tables: FADT, FACS, DSDT,
341 // and some important tables: MADT, MCFG.
342 //
343 switch (AcpiHeader->Signature) {
344
345 //
346 // "FACP" Fixed ACPI Description Table
347 //
348 case EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE:
349 switch (AcpiHeader->Revision) {
350 case EFI_ACPI_1_0_FIXED_ACPI_DESCRIPTION_TABLE_REVISION:
351 ExpectedLength = sizeof(EFI_ACPI_1_0_FIXED_ACPI_DESCRIPTION_TABLE);
352 break;
353 case EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE_REVISION:
354 ExpectedLength = sizeof(EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE);
355 break;
356 case EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_REVISION:
357 ExpectedLength = sizeof(EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE);
358 break;
359 default:
360 if (AcpiHeader->Revision > EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_REVISION) {
361 ExpectedLength = AcpiHeader->Length;
362 break;
363 }
364 Error (NULL, 0, 3000, "Invalid", "FACP revision check failed.");
365 return STATUS_ERROR;
366 }
367 if (ExpectedLength != AcpiHeader->Length) {
368 Error (NULL, 0, 3000, "Invalid", "FACP length check failed.");
369 return STATUS_ERROR;
370 }
371 break;
372
373 //
374 // "FACS" Firmware ACPI Control Structure
375 //
376 case EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE:
377 Facs = (EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *)AcpiTable;
378 if (Facs->Version > EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_VERSION) {
379 break;
380 }
381 if ((Facs->Version != EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_VERSION) &&
382 (Facs->Version != EFI_ACPI_2_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_VERSION) &&
383 (Facs->Version != EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_VERSION)){
384 Error (NULL, 0, 3000, "Invalid", "FACS version check failed.");
385 return STATUS_ERROR;
386 }
387 if ((Facs->Length != sizeof(EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE)) &&
388 (Facs->Length != sizeof(EFI_ACPI_2_0_FIRMWARE_ACPI_CONTROL_STRUCTURE)) &&
389 (Facs->Length != sizeof(EFI_ACPI_3_0_FIRMWARE_ACPI_CONTROL_STRUCTURE))) {
390 Error (NULL, 0, 3000, "Invalid", "FACS length check failed.");
391 return STATUS_ERROR;
392 }
393 break;
394
395 //
396 // "DSDT" Differentiated System Description Table
397 //
398 case EFI_ACPI_3_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE:
399 if (AcpiHeader->Revision > EFI_ACPI_3_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_REVISION) {
400 break;
401 }
402 if (AcpiHeader->Length <= sizeof(EFI_ACPI_DESCRIPTION_HEADER)) {
403 Error (NULL, 0, 3000, "Invalid", "DSDT length check failed.");
404 return STATUS_ERROR;
405 }
406 break;
407
408 //
409 // "APIC" Multiple APIC Description Table
410 //
411 case EFI_ACPI_3_0_MULTIPLE_APIC_DESCRIPTION_TABLE_SIGNATURE:
412 if (AcpiHeader->Revision > EFI_ACPI_3_0_MULTIPLE_APIC_DESCRIPTION_TABLE_REVISION) {
413 break;
414 }
415 if ((AcpiHeader->Revision != EFI_ACPI_1_0_MULTIPLE_APIC_DESCRIPTION_TABLE_REVISION) &&
416 (AcpiHeader->Revision != EFI_ACPI_2_0_MULTIPLE_APIC_DESCRIPTION_TABLE_REVISION) &&
417 (AcpiHeader->Revision != EFI_ACPI_3_0_MULTIPLE_APIC_DESCRIPTION_TABLE_REVISION)) {
418 Error (NULL, 0, 3000, "Invalid", "APIC revision check failed.");
419 return STATUS_ERROR;
420 }
421 if (AcpiHeader->Length <= sizeof(EFI_ACPI_DESCRIPTION_HEADER) + sizeof(UINT32) + sizeof(UINT32)) {
422 Error (NULL, 0, 3000, "Invalid", "APIC length check failed.");
423 return STATUS_ERROR;
424 }
425 break;
426
427 //
428 // "MCFG" PCI Express Memory Mapped Configuration Space Base Address Description Table
429 //
430 case EFI_ACPI_3_0_PCI_EXPRESS_MEMORY_MAPPED_CONFIGURATION_SPACE_BASE_ADDRESS_DESCRIPTION_TABLE_SIGNATURE:
431 if (AcpiHeader->Revision > EFI_ACPI_MEMORY_MAPPED_CONFIGURATION_SPACE_ACCESS_TABLE_REVISION) {
432 break;
433 }
434 if (AcpiHeader->Revision != EFI_ACPI_MEMORY_MAPPED_CONFIGURATION_SPACE_ACCESS_TABLE_REVISION) {
435 Error (NULL, 0, 3000, "Invalid", "MCFG revision check failed.");
436 return STATUS_ERROR;
437 }
438 if (AcpiHeader->Length <= sizeof(EFI_ACPI_DESCRIPTION_HEADER) + sizeof(UINT64)) {
439 Error (NULL, 0, 3000, "Invalid", "MCFG length check failed.");
440 return STATUS_ERROR;
441 }
442 break;
443
444 //
445 // Other table pass check
446 //
447 default:
448 break;
449 }
450
451 return STATUS_SUCCESS;
452 }
453
454 VOID
455 SetHiiResourceHeader (
456 UINT8 *HiiBinData,
457 UINT32 OffsetToFile
458 )
459 {
460 UINT32 Index;
461 EFI_IMAGE_RESOURCE_DIRECTORY *ResourceDirectory;
462 EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *ResourceDirectoryEntry;
463 EFI_IMAGE_RESOURCE_DIRECTORY_STRING *ResourceDirectoryString;
464 EFI_IMAGE_RESOURCE_DATA_ENTRY *ResourceDataEntry;
465
466 //
467 // Fill Resource section entry
468 //
469 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (HiiBinData);
470 ResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (ResourceDirectory + 1);
471 for (Index = 0; Index < ResourceDirectory->NumberOfNamedEntries; Index ++) {
472 if (ResourceDirectoryEntry->u1.s.NameIsString) {
473 ResourceDirectoryString = (EFI_IMAGE_RESOURCE_DIRECTORY_STRING *) (HiiBinData + ResourceDirectoryEntry->u1.s.NameOffset);
474
475 if (ResourceDirectoryString->Length == 3 &&
476 ResourceDirectoryString->String[0] == L'H' &&
477 ResourceDirectoryString->String[1] == L'I' &&
478 ResourceDirectoryString->String[2] == L'I') {
479 //
480 // Resource Type "HII" found
481 //
482 if (ResourceDirectoryEntry->u2.s.DataIsDirectory) {
483 //
484 // Move to next level - resource Name
485 //
486 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (HiiBinData + ResourceDirectoryEntry->u2.s.OffsetToDirectory);
487 ResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (ResourceDirectory + 1);
488
489 if (ResourceDirectoryEntry->u2.s.DataIsDirectory) {
490 //
491 // Move to next level - resource Language
492 //
493 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (HiiBinData + ResourceDirectoryEntry->u2.s.OffsetToDirectory);
494 ResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (ResourceDirectory + 1);
495 }
496 }
497
498 //
499 // Now it ought to be resource Data and update its OffsetToData value
500 //
501 if (!ResourceDirectoryEntry->u2.s.DataIsDirectory) {
502 ResourceDataEntry = (EFI_IMAGE_RESOURCE_DATA_ENTRY *) (HiiBinData + ResourceDirectoryEntry->u2.OffsetToData);
503 ResourceDataEntry->OffsetToData = ResourceDataEntry->OffsetToData + OffsetToFile;
504 break;
505 }
506 }
507 }
508 ResourceDirectoryEntry++;
509 }
510
511 return;
512 }
513
514 EFI_IMAGE_OPTIONAL_HEADER_UNION *
515 GetPeCoffHeader (
516 void *Data
517 )
518 {
519 EFI_IMAGE_DOS_HEADER *DosHdr;
520 EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr;
521
522 //
523 // Read the dos & pe hdrs of the image
524 //
525 DosHdr = (EFI_IMAGE_DOS_HEADER *)Data;
526 if (DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
527 // NO DOS header, check for PE/COFF header
528 PeHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(Data);
529 if (PeHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
530 return NULL;
531 }
532 } else {
533
534 PeHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(((UINT8 *)Data) + DosHdr->e_lfanew);
535 if (PeHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
536 return NULL;
537 }
538 }
539
540 return PeHdr;
541 }
542
543 void
544 PeCoffConvertImageToXip (
545 UINT8 **FileBuffer,
546 UINT32 *FileLength
547 )
548 {
549 EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr;
550 EFI_IMAGE_OPTIONAL_HEADER_UNION *NewPeHdr;
551 EFI_IMAGE_SECTION_HEADER *SectionHeader;
552 UINTN TotalNecessaryFileSize;
553 UINTN SectionSize;
554 UINT8 *XipFile;
555 UINT32 XipLength;
556 UINTN Index;
557 UINTN FirstSectionOffset;
558 BOOLEAN ConversionNeeded;
559
560 PeHdr = GetPeCoffHeader ((void *) *FileBuffer);
561 if (PeHdr == NULL) {
562 return;
563 }
564
565 if (PeHdr->Pe32.OptionalHeader.SectionAlignment != PeHdr->Pe32.OptionalHeader.FileAlignment) {
566 //
567 // The only reason to expand zero fill sections is to make them compatible with XIP images.
568 // If SectionAlignment is not equal to FileAlginment then it is not an XIP type image.
569 //
570 return;
571 }
572
573 //
574 // Calculate size of XIP file, and determine if the conversion is needed.
575 //
576 ConversionNeeded = FALSE;
577 XipLength = 0;
578 FirstSectionOffset = *FileLength;
579 TotalNecessaryFileSize = 0;
580 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
581 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
582 SectionSize = MAX (SectionHeader->Misc.VirtualSize, SectionHeader->SizeOfRawData);
583 TotalNecessaryFileSize += SectionSize;
584 if (SectionSize > 0) {
585 FirstSectionOffset = MIN (FirstSectionOffset, SectionHeader->VirtualAddress);
586 XipLength = MAX (XipLength, SectionHeader->VirtualAddress + SectionSize);
587 if (SectionHeader->VirtualAddress != SectionHeader->PointerToRawData) {
588 ConversionNeeded = TRUE;
589 }
590 }
591 if (SectionHeader->Misc.VirtualSize > SectionHeader->SizeOfRawData) {
592 ConversionNeeded = TRUE;
593 }
594 }
595
596 if (FirstSectionOffset < PeHdr->Pe32.OptionalHeader.SizeOfHeaders) {
597 //
598 // If one of the sections should be loaded to an offset overlapping with
599 // the executable header, then it cannot be made into an XIP image.
600 //
601 VerboseMsg ("PE/COFF conversion to XIP is impossible due to overlap");
602 VerboseMsg ("of section data with the executable header.");
603 return;
604 }
605
606 if (FirstSectionOffset == *FileLength) {
607 //
608 // If we never found a section with a non-zero size, then we
609 // skip the conversion.
610 //
611 return;
612 }
613
614 TotalNecessaryFileSize += FirstSectionOffset;
615
616 if (!ConversionNeeded) {
617 return;
618 }
619
620 if (XipLength > (2 * TotalNecessaryFileSize)) {
621 VerboseMsg ("PE/COFF conversion to XIP appears to be larger than necessary.");
622 VerboseMsg ("The image linking process may have left unused memory ranges.");
623 }
624
625 if (PeHdr->Pe32.FileHeader.PointerToSymbolTable != 0) {
626 //
627 // This field is obsolete and should be zero
628 //
629 PeHdr->Pe32.FileHeader.PointerToSymbolTable = 0;
630 }
631
632 //
633 // Allocate the extra space that we need to grow the image
634 //
635 XipFile = malloc (XipLength);
636 memset (XipFile, 0, XipLength);
637
638 //
639 // Copy the file headers
640 //
641 memcpy (XipFile, *FileBuffer, PeHdr->Pe32.OptionalHeader.SizeOfHeaders);
642
643 NewPeHdr = GetPeCoffHeader ((void *)XipFile);
644 if (NewPeHdr == NULL) {
645 free (XipFile);
646 return;
647 }
648
649 //
650 // Copy the section data over to the appropriate XIP offsets
651 //
652 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(NewPeHdr->Pe32.OptionalHeader) + NewPeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
653 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
654 if (SectionHeader->SizeOfRawData > 0) {
655 memcpy (
656 XipFile + SectionHeader->VirtualAddress,
657 *FileBuffer + SectionHeader->PointerToRawData,
658 SectionHeader->SizeOfRawData
659 );
660 }
661 //
662 // Make the size of raw data in section header alignment.
663 //
664 SectionHeader->SizeOfRawData = (SectionHeader->Misc.VirtualSize + PeHdr->Pe32.OptionalHeader.FileAlignment - 1) & (~(PeHdr->Pe32.OptionalHeader.FileAlignment - 1));
665 SectionHeader->PointerToRawData = SectionHeader->VirtualAddress;
666 }
667
668 free (*FileBuffer);
669 *FileLength = XipLength;
670 *FileBuffer = XipFile;
671 }
672
673 UINT8 *
674 CreateHiiResouceSectionHeader (
675 UINT32 *pSectionHeaderSize,
676 UINT32 HiiDataSize
677 )
678 /*++
679
680 Routine Description:
681
682 Create COFF resource section header
683
684 Arguments:
685
686 pSectionHeaderSize - Pointer to section header size.
687 HiiDataSize - Size of the total HII data in section.
688
689 Returns:
690 The created section header buffer.
691
692 --*/
693 {
694 UINT32 HiiSectionHeaderSize;
695 UINT32 HiiSectionOffset;
696 UINT8 *HiiSectionHeader;
697 EFI_IMAGE_RESOURCE_DIRECTORY *ResourceDirectory;
698 EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *TypeResourceDirectoryEntry;
699 EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *NameResourceDirectoryEntry;
700 EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *LanguageResourceDirectoryEntry;
701 EFI_IMAGE_RESOURCE_DIRECTORY_STRING *ResourceDirectoryString;
702 EFI_IMAGE_RESOURCE_DATA_ENTRY *ResourceDataEntry;
703
704 //
705 // Calculate the total size for the resource header (include Type, Name and Language)
706 // then allocate memory for the resource header.
707 //
708 HiiSectionHeaderSize = 3 * (sizeof (EFI_IMAGE_RESOURCE_DIRECTORY) + sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY))
709 + 3 * (sizeof (UINT16) + 3 * sizeof (CHAR16))
710 + sizeof (EFI_IMAGE_RESOURCE_DATA_ENTRY);
711 HiiSectionHeader = malloc (HiiSectionHeaderSize);
712 memset (HiiSectionHeader, 0, HiiSectionHeaderSize);
713
714 HiiSectionOffset = 0;
715 //
716 // Create Type entry
717 //
718 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (HiiSectionHeader + HiiSectionOffset);
719 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DIRECTORY);
720 ResourceDirectory->NumberOfNamedEntries = 1;
721 TypeResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (HiiSectionHeader + HiiSectionOffset);
722 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY);
723 TypeResourceDirectoryEntry->u1.s.NameIsString = 1;
724 TypeResourceDirectoryEntry->u2.s.DataIsDirectory = 1;
725 TypeResourceDirectoryEntry->u2.s.OffsetToDirectory = HiiSectionOffset;
726 //
727 // Create Name entry
728 //
729 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (HiiSectionHeader + HiiSectionOffset);
730 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DIRECTORY);
731 ResourceDirectory->NumberOfNamedEntries = 1;
732 NameResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (HiiSectionHeader + HiiSectionOffset);
733 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY);
734 NameResourceDirectoryEntry->u1.s.NameIsString = 1;
735 NameResourceDirectoryEntry->u2.s.DataIsDirectory = 1;
736 NameResourceDirectoryEntry->u2.s.OffsetToDirectory = HiiSectionOffset;
737 //
738 // Create Language entry
739 //
740 ResourceDirectory = (EFI_IMAGE_RESOURCE_DIRECTORY *) (HiiSectionHeader + HiiSectionOffset);
741 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DIRECTORY);
742 ResourceDirectory->NumberOfNamedEntries = 1;
743 LanguageResourceDirectoryEntry = (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY *) (HiiSectionHeader + HiiSectionOffset);
744 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DIRECTORY_ENTRY);
745 LanguageResourceDirectoryEntry->u1.s.NameIsString = 1;
746 //
747 // Create string entry for Type
748 //
749 TypeResourceDirectoryEntry->u1.s.NameOffset = HiiSectionOffset;
750 ResourceDirectoryString = (EFI_IMAGE_RESOURCE_DIRECTORY_STRING *) (HiiSectionHeader + HiiSectionOffset);
751 ResourceDirectoryString->Length = 3;
752 ResourceDirectoryString->String[0] = L'H';
753 ResourceDirectoryString->String[1] = L'I';
754 ResourceDirectoryString->String[2] = L'I';
755 HiiSectionOffset = HiiSectionOffset + sizeof (ResourceDirectoryString->Length) + ResourceDirectoryString->Length * sizeof (ResourceDirectoryString->String[0]);
756 //
757 // Create string entry for Name
758 //
759 NameResourceDirectoryEntry->u1.s.NameOffset = HiiSectionOffset;
760 ResourceDirectoryString = (EFI_IMAGE_RESOURCE_DIRECTORY_STRING *) (HiiSectionHeader + HiiSectionOffset);
761 ResourceDirectoryString->Length = 3;
762 ResourceDirectoryString->String[0] = L'E';
763 ResourceDirectoryString->String[1] = L'F';
764 ResourceDirectoryString->String[2] = L'I';
765 HiiSectionOffset = HiiSectionOffset + sizeof (ResourceDirectoryString->Length) + ResourceDirectoryString->Length * sizeof (ResourceDirectoryString->String[0]);
766 //
767 // Create string entry for Language
768 //
769 LanguageResourceDirectoryEntry->u1.s.NameOffset = HiiSectionOffset;
770 ResourceDirectoryString = (EFI_IMAGE_RESOURCE_DIRECTORY_STRING *) (HiiSectionHeader + HiiSectionOffset);
771 ResourceDirectoryString->Length = 3;
772 ResourceDirectoryString->String[0] = L'B';
773 ResourceDirectoryString->String[1] = L'I';
774 ResourceDirectoryString->String[2] = L'N';
775 HiiSectionOffset = HiiSectionOffset + sizeof (ResourceDirectoryString->Length) + ResourceDirectoryString->Length * sizeof (ResourceDirectoryString->String[0]);
776 //
777 // Create Leaf data
778 //
779 LanguageResourceDirectoryEntry->u2.OffsetToData = HiiSectionOffset;
780 ResourceDataEntry = (EFI_IMAGE_RESOURCE_DATA_ENTRY *) (HiiSectionHeader + HiiSectionOffset);
781 HiiSectionOffset += sizeof (EFI_IMAGE_RESOURCE_DATA_ENTRY);
782 ResourceDataEntry->OffsetToData = HiiSectionOffset;
783 ResourceDataEntry->Size = HiiDataSize;
784
785 *pSectionHeaderSize = HiiSectionHeaderSize;
786 return HiiSectionHeader;
787 }
788
789 EFI_STATUS
790 RebaseImageRead (
791 IN VOID *FileHandle,
792 IN UINTN FileOffset,
793 IN OUT UINT32 *ReadSize,
794 OUT VOID *Buffer
795 )
796 /*++
797
798 Routine Description:
799
800 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
801
802 Arguments:
803
804 FileHandle - The handle to the PE/COFF file
805
806 FileOffset - The offset, in bytes, into the file to read
807
808 ReadSize - The number of bytes to read from the file starting at FileOffset
809
810 Buffer - A pointer to the buffer to read the data into.
811
812 Returns:
813
814 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
815
816 --*/
817 {
818 CHAR8 *Destination8;
819 CHAR8 *Source8;
820 UINT32 Length;
821
822 Destination8 = Buffer;
823 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
824 Length = *ReadSize;
825 while (Length--) {
826 *(Destination8++) = *(Source8++);
827 }
828
829 return EFI_SUCCESS;
830 }
831
832 EFI_STATUS
833 SetAddressToSectionHeader (
834 IN CHAR8 *FileName,
835 IN OUT UINT8 *FileBuffer,
836 IN UINT64 NewPe32BaseAddress
837 )
838 /*++
839
840 Routine Description:
841
842 Set new base address into the section header of PeImage
843
844 Arguments:
845
846 FileName - Name of file
847 FileBuffer - Pointer to PeImage.
848 NewPe32BaseAddress - New Base Address for PE image.
849
850 Returns:
851
852 EFI_SUCCESS Set new base address into this image successfully.
853
854 --*/
855 {
856 EFI_STATUS Status;
857 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
858 UINTN Index;
859 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
860 EFI_IMAGE_SECTION_HEADER *SectionHeader;
861
862 //
863 // Initialize context
864 //
865 memset (&ImageContext, 0, sizeof (ImageContext));
866 ImageContext.Handle = (VOID *) FileBuffer;
867 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) RebaseImageRead;
868 Status = PeCoffLoaderGetImageInfo (&ImageContext);
869 if (EFI_ERROR (Status)) {
870 Error (NULL, 0, 3000, "Invalid", "The input PeImage %s is not valid", FileName);
871 return Status;
872 }
873
874 if (ImageContext.RelocationsStripped) {
875 Error (NULL, 0, 3000, "Invalid", "The input PeImage %s has no relocation to be fixed up", FileName);
876 return Status;
877 }
878
879 //
880 // Get PeHeader pointer
881 //
882 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(FileBuffer + ImageContext.PeCoffHeaderOffset);
883
884 //
885 // Get section header list
886 //
887 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (
888 (UINTN) ImgHdr +
889 sizeof (UINT32) +
890 sizeof (EFI_IMAGE_FILE_HEADER) +
891 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader
892 );
893
894 //
895 // Set base address into the first section header that doesn't point to code section.
896 //
897 for (Index = 0; Index < ImgHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
898 if ((SectionHeader->Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
899 *(UINT64 *) &SectionHeader->PointerToRelocations = NewPe32BaseAddress;
900 break;
901 }
902 }
903
904 //
905 // No available section header is found.
906 //
907 if (Index == ImgHdr->Pe32.FileHeader.NumberOfSections) {
908 return EFI_NOT_FOUND;
909 }
910
911 //
912 // BaseAddress is set to section header.
913 //
914 return EFI_SUCCESS;
915 }
916
917 EFI_STATUS
918 RebaseImage (
919 IN CHAR8 *FileName,
920 IN OUT UINT8 *FileBuffer,
921 IN UINT64 NewPe32BaseAddress
922 )
923 /*++
924
925 Routine Description:
926
927 Set new base address into PeImage, and fix up PeImage based on new address.
928
929 Arguments:
930
931 FileName - Name of file
932 FileBuffer - Pointer to PeImage.
933 NewPe32BaseAddress - New Base Address for PE image.
934
935 Returns:
936
937 EFI_INVALID_PARAMETER - BaseAddress is not valid.
938 EFI_SUCCESS - Update PeImage is correctly.
939
940 --*/
941 {
942 EFI_STATUS Status;
943 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
944 UINTN Index;
945 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
946 UINT8 *MemoryImagePointer;
947 EFI_IMAGE_SECTION_HEADER *SectionHeader;
948
949 //
950 // Initialize context
951 //
952 memset (&ImageContext, 0, sizeof (ImageContext));
953 ImageContext.Handle = (VOID *) FileBuffer;
954 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) RebaseImageRead;
955 Status = PeCoffLoaderGetImageInfo (&ImageContext);
956 if (EFI_ERROR (Status)) {
957 Error (NULL, 0, 3000, "Invalid", "The input PeImage %s is not valid", FileName);
958 return Status;
959 }
960
961 if (ImageContext.RelocationsStripped) {
962 Error (NULL, 0, 3000, "Invalid", "The input PeImage %s has no relocation to be fixed up", FileName);
963 return Status;
964 }
965
966 //
967 // Get PeHeader pointer
968 //
969 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(FileBuffer + ImageContext.PeCoffHeaderOffset);
970
971 //
972 // Load and Relocate Image Data
973 //
974 MemoryImagePointer = (UINT8 *) malloc ((UINTN) ImageContext.ImageSize + ImageContext.SectionAlignment);
975 if (MemoryImagePointer == NULL) {
976 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated on rebase of %s", FileName);
977 return EFI_OUT_OF_RESOURCES;
978 }
979 memset ((VOID *) MemoryImagePointer, 0, (UINTN) ImageContext.ImageSize + ImageContext.SectionAlignment);
980 ImageContext.ImageAddress = ((UINTN) MemoryImagePointer + ImageContext.SectionAlignment - 1) & (~((INT64)ImageContext.SectionAlignment - 1));
981
982 Status = PeCoffLoaderLoadImage (&ImageContext);
983 if (EFI_ERROR (Status)) {
984 Error (NULL, 0, 3000, "Invalid", "LocateImage() call failed on rebase of %s", FileName);
985 free ((VOID *) MemoryImagePointer);
986 return Status;
987 }
988
989 ImageContext.DestinationAddress = NewPe32BaseAddress;
990 Status = PeCoffLoaderRelocateImage (&ImageContext);
991 if (EFI_ERROR (Status)) {
992 Error (NULL, 0, 3000, "Invalid", "RelocateImage() call failed on rebase of %s", FileName);
993 free ((VOID *) MemoryImagePointer);
994 return Status;
995 }
996
997 //
998 // Copy Relocated data to raw image file.
999 //
1000 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (
1001 (UINTN) ImgHdr +
1002 sizeof (UINT32) +
1003 sizeof (EFI_IMAGE_FILE_HEADER) +
1004 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader
1005 );
1006
1007 for (Index = 0; Index < ImgHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
1008 CopyMem (
1009 FileBuffer + SectionHeader->PointerToRawData,
1010 (VOID*) (UINTN) (ImageContext.ImageAddress + SectionHeader->VirtualAddress),
1011 SectionHeader->SizeOfRawData
1012 );
1013 }
1014
1015 free ((VOID *) MemoryImagePointer);
1016
1017 //
1018 // Update Image Base Address
1019 //
1020 if ((ImgHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) && (ImgHdr->Pe32.FileHeader.Machine != IMAGE_FILE_MACHINE_IA64)) {
1021 ImgHdr->Pe32.OptionalHeader.ImageBase = (UINT32) NewPe32BaseAddress;
1022 } else if (ImgHdr->Pe32Plus.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
1023 ImgHdr->Pe32Plus.OptionalHeader.ImageBase = NewPe32BaseAddress;
1024 } else {
1025 Error (NULL, 0, 3000, "Invalid", "unknown PE magic signature %X in PE32 image %s",
1026 ImgHdr->Pe32.OptionalHeader.Magic,
1027 FileName
1028 );
1029 return EFI_ABORTED;
1030 }
1031
1032 //
1033 // Set new base address into section header
1034 //
1035 Status = SetAddressToSectionHeader (FileName, FileBuffer, NewPe32BaseAddress);
1036
1037 return Status;
1038 }
1039
1040 int
1041 main (
1042 int argc,
1043 char *argv[]
1044 )
1045 /*++
1046
1047 Routine Description:
1048
1049 Main function.
1050
1051 Arguments:
1052
1053 argc - Number of command line parameters.
1054 argv - Array of pointers to command line parameter strings.
1055
1056 Returns:
1057 STATUS_SUCCESS - Utility exits successfully.
1058 STATUS_ERROR - Some error occurred during execution.
1059
1060 --*/
1061 {
1062 UINT32 Type;
1063 UINT32 InputFileNum;
1064 CHAR8 **InputFileName;
1065 char *OutImageName;
1066 char *ModuleType;
1067 CHAR8 *TimeStamp;
1068 FILE *fpIn;
1069 FILE *fpOut;
1070 FILE *fpInOut;
1071 UINT32 Data;
1072 UINT32 *DataPointer;
1073 UINT32 *OldDataPointer;
1074 UINT32 CheckSum;
1075 UINT32 Index;
1076 UINT32 Index1;
1077 UINT32 Index2;
1078 UINT64 Temp64;
1079 UINT32 MciAlignment;
1080 UINT8 MciPadValue;
1081 UINT32 AllignedRelocSize;
1082 UINT8 *FileBuffer;
1083 UINT32 FileLength;
1084 UINT8 *OutputFileBuffer;
1085 UINT32 OutputFileLength;
1086 UINT8 *InputFileBuffer;
1087 UINT32 InputFileLength;
1088 RUNTIME_FUNCTION *RuntimeFunction;
1089 UNWIND_INFO *UnwindInfo;
1090 STATUS Status;
1091 BOOLEAN ReplaceFlag;
1092 BOOLEAN KeepExceptionTableFlag;
1093 BOOLEAN KeepZeroPendingFlag;
1094 UINT64 LogLevel;
1095 EFI_TE_IMAGE_HEADER TEImageHeader;
1096 EFI_TE_IMAGE_HEADER *TeHdr;
1097 EFI_IMAGE_SECTION_HEADER *SectionHeader;
1098 EFI_IMAGE_DOS_HEADER *DosHdr;
1099 EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr;
1100 EFI_IMAGE_OPTIONAL_HEADER32 *Optional32;
1101 EFI_IMAGE_OPTIONAL_HEADER64 *Optional64;
1102 EFI_IMAGE_DOS_HEADER BackupDosHdr;
1103 MICROCODE_IMAGE_HEADER *MciHeader;
1104 UINT8 *HiiPackageListBuffer;
1105 UINT8 *HiiPackageDataPointer;
1106 EFI_GUID HiiPackageListGuid;
1107 EFI_HII_PACKAGE_LIST_HEADER HiiPackageListHeader;
1108 EFI_HII_PACKAGE_HEADER HiiPackageHeader;
1109 EFI_IFR_FORM_SET IfrFormSet;
1110 UINT8 NumberOfFormPacakge;
1111 EFI_HII_PACKAGE_HEADER EndPackage;
1112 UINT32 HiiSectionHeaderSize;
1113 UINT8 *HiiSectionHeader;
1114 UINT64 NewBaseAddress;
1115 BOOLEAN NegativeAddr;
1116 FILE *ReportFile;
1117 CHAR8 *ReportFileName;
1118 UINTN FileLen;
1119 time_t InputFileTime;
1120 time_t OutputFileTime;
1121 struct stat Stat_Buf;
1122
1123 SetUtilityName (UTILITY_NAME);
1124
1125 //
1126 // Assign to fix compile warning
1127 //
1128 FileLen = 0;
1129 InputFileNum = 0;
1130 InputFileName = NULL;
1131 mInImageName = NULL;
1132 OutImageName = NULL;
1133 ModuleType = NULL;
1134 Type = 0;
1135 Status = STATUS_SUCCESS;
1136 FileBuffer = NULL;
1137 fpIn = NULL;
1138 fpOut = NULL;
1139 fpInOut = NULL;
1140 TimeStamp = NULL;
1141 MciAlignment = DEFAULT_MC_ALIGNMENT;
1142 MciPadValue = DEFAULT_MC_PAD_BYTE_VALUE;
1143 FileLength = 0;
1144 MciHeader = NULL;
1145 CheckSum = 0;
1146 ReplaceFlag = FALSE;
1147 LogLevel = 0;
1148 OutputFileBuffer = NULL;
1149 OutputFileLength = 0;
1150 InputFileBuffer = NULL;
1151 InputFileLength = 0;
1152 Optional32 = NULL;
1153 Optional64 = NULL;
1154 KeepExceptionTableFlag = FALSE;
1155 KeepZeroPendingFlag = FALSE;
1156 NumberOfFormPacakge = 0;
1157 HiiPackageListBuffer = NULL;
1158 HiiPackageDataPointer = NULL;
1159 EndPackage.Length = sizeof (EFI_HII_PACKAGE_HEADER);
1160 EndPackage.Type = EFI_HII_PACKAGE_END;
1161 memset (&HiiPackageListGuid, 0, sizeof (HiiPackageListGuid));
1162 HiiSectionHeaderSize = 0;
1163 HiiSectionHeader = NULL;
1164 NewBaseAddress = 0;
1165 NegativeAddr = FALSE;
1166 InputFileTime = 0;
1167 OutputFileTime = 0;
1168
1169 if (argc == 1) {
1170 Error (NULL, 0, 1001, "Missing options", "No input options.");
1171 Usage ();
1172 return STATUS_ERROR;
1173 }
1174
1175 argc --;
1176 argv ++;
1177
1178 if ((stricmp (argv[0], "-h") == 0) || (stricmp (argv[0], "--help") == 0)) {
1179 Version ();
1180 Usage ();
1181 return STATUS_SUCCESS;
1182 }
1183
1184 if (stricmp (argv[0], "--version") == 0) {
1185 Version ();
1186 return STATUS_SUCCESS;
1187 }
1188
1189 while (argc > 0) {
1190 if ((stricmp (argv[0], "-o") == 0) || (stricmp (argv[0], "--outputfile") == 0)) {
1191 if (argv[1] == NULL || argv[1][0] == '-') {
1192 Error (NULL, 0, 1003, "Invalid option value", "Output file name is missing for -o option");
1193 goto Finish;
1194 }
1195 OutImageName = argv[1];
1196 argc -= 2;
1197 argv += 2;
1198 continue;
1199 }
1200
1201 if ((stricmp (argv[0], "-e") == 0) || (stricmp (argv[0], "--efiImage") == 0)) {
1202 if (argv[1] == NULL || argv[1][0] == '-') {
1203 Error (NULL, 0, 1003, "Invalid option value", "Module Type is missing for -o option");
1204 goto Finish;
1205 }
1206 ModuleType = argv[1];
1207 if (mOutImageType != FW_TE_IMAGE) {
1208 mOutImageType = FW_EFI_IMAGE;
1209 }
1210 argc -= 2;
1211 argv += 2;
1212 continue;
1213 }
1214
1215 if ((stricmp (argv[0], "-l") == 0) || (stricmp (argv[0], "--stripped") == 0)) {
1216 mOutImageType = FW_RELOC_STRIPEED_IMAGE;
1217 argc --;
1218 argv ++;
1219 continue;
1220 }
1221
1222 if ((stricmp (argv[0], "-c") == 0) || (stricmp (argv[0], "--acpi") == 0)) {
1223 mOutImageType = FW_ACPI_IMAGE;
1224 argc --;
1225 argv ++;
1226 continue;
1227 }
1228
1229 if ((stricmp (argv[0], "-t") == 0) || (stricmp (argv[0], "--terse") == 0)) {
1230 mOutImageType = FW_TE_IMAGE;
1231 argc --;
1232 argv ++;
1233 continue;
1234 }
1235
1236 if ((stricmp (argv[0], "-u") == 0) || (stricmp (argv[0], "--dump") == 0)) {
1237 mOutImageType = DUMP_TE_HEADER;
1238 argc --;
1239 argv ++;
1240 continue;
1241 }
1242
1243 if ((stricmp (argv[0], "-b") == 0) || (stricmp (argv[0], "--exe2bin") == 0)) {
1244 mOutImageType = FW_BIN_IMAGE;
1245 argc --;
1246 argv ++;
1247 continue;
1248 }
1249
1250 if ((stricmp (argv[0], "-z") == 0) || (stricmp (argv[0], "--zero") == 0)) {
1251 mOutImageType = FW_ZERO_DEBUG_IMAGE;
1252 argc --;
1253 argv ++;
1254 continue;
1255 }
1256
1257 if ((stricmp (argv[0], "-s") == 0) || (stricmp (argv[0], "--stamp") == 0)) {
1258 mOutImageType = FW_SET_STAMP_IMAGE;
1259 if (argv[1] == NULL || argv[1][0] == '-') {
1260 Error (NULL, 0, 1003, "Invalid option value", "time stamp is missing for -s option");
1261 goto Finish;
1262 }
1263 TimeStamp = argv[1];
1264 argc -= 2;
1265 argv += 2;
1266 continue;
1267 }
1268
1269 if ((stricmp (argv[0], "-r") == 0) || (stricmp (argv[0], "--replace") == 0)) {
1270 ReplaceFlag = TRUE;
1271 argc --;
1272 argv ++;
1273 continue;
1274 }
1275
1276 if (stricmp (argv[0], "--keepexceptiontable") == 0) {
1277 KeepExceptionTableFlag = TRUE;
1278 argc --;
1279 argv ++;
1280 continue;
1281 }
1282
1283 if (stricmp (argv[0], "--keepzeropending") == 0) {
1284 KeepZeroPendingFlag = TRUE;
1285 argc --;
1286 argv ++;
1287 continue;
1288 }
1289
1290 if ((stricmp (argv[0], "-m") == 0) || (stricmp (argv[0], "--mcifile") == 0)) {
1291 mOutImageType = FW_MCI_IMAGE;
1292 argc --;
1293 argv ++;
1294 continue;
1295 }
1296
1297 if ((stricmp (argv[0], "-j") == 0) || (stricmp (argv[0], "--join") == 0)) {
1298 mOutImageType = FW_MERGE_IMAGE;
1299 argc --;
1300 argv ++;
1301 continue;
1302 }
1303
1304 if ((stricmp (argv[0], "-a") == 0) || (stricmp (argv[0], "--align") == 0)) {
1305 if (AsciiStringToUint64 (argv[1], FALSE, &Temp64) != EFI_SUCCESS) {
1306 Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
1307 goto Finish;
1308 }
1309 MciAlignment = (UINT32) Temp64;
1310 argc -= 2;
1311 argv += 2;
1312 continue;
1313 }
1314
1315 if ((stricmp (argv[0], "--rebase") == 0)) {
1316 if (argv[1][0] == '-') {
1317 NegativeAddr = TRUE;
1318 Status = AsciiStringToUint64 (argv[1] + 1, FALSE, &Temp64);
1319 } else {
1320 NegativeAddr = FALSE;
1321 Status = AsciiStringToUint64 (argv[1], FALSE, &Temp64);
1322 }
1323 if (Status != EFI_SUCCESS) {
1324 Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
1325 goto Finish;
1326 }
1327 mOutImageType = FW_REBASE_IMAGE;
1328 NewBaseAddress = (UINT64) Temp64;
1329 argc -= 2;
1330 argv += 2;
1331 continue;
1332 }
1333
1334 if ((stricmp (argv[0], "--address") == 0)) {
1335 if (argv[1][0] == '-') {
1336 NegativeAddr = TRUE;
1337 Status = AsciiStringToUint64 (argv[1] + 1, FALSE, &Temp64);
1338 } else {
1339 NegativeAddr = FALSE;
1340 Status = AsciiStringToUint64 (argv[1], FALSE, &Temp64);
1341 }
1342 if (Status != EFI_SUCCESS) {
1343 Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
1344 goto Finish;
1345 }
1346 mOutImageType = FW_SET_ADDRESS_IMAGE;
1347 NewBaseAddress = (UINT64) Temp64;
1348 argc -= 2;
1349 argv += 2;
1350 continue;
1351 }
1352
1353 if ((stricmp (argv[0], "-p") == 0) || (stricmp (argv[0], "--pad") == 0)) {
1354 if (AsciiStringToUint64 (argv[1], FALSE, &Temp64) != EFI_SUCCESS) {
1355 Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
1356 goto Finish;
1357 }
1358 MciPadValue = (UINT8) Temp64;
1359 argc -= 2;
1360 argv += 2;
1361 continue;
1362 }
1363
1364 if ((stricmp (argv[0], "-v") == 0) || (stricmp (argv[0], "--verbose") == 0)) {
1365 SetPrintLevel (VERBOSE_LOG_LEVEL);
1366 VerboseMsg ("Verbose output Mode Set!");
1367 argc --;
1368 argv ++;
1369 continue;
1370 }
1371
1372 if ((stricmp (argv[0], "-q") == 0) || (stricmp (argv[0], "--quiet") == 0)) {
1373 SetPrintLevel (KEY_LOG_LEVEL);
1374 KeyMsg ("Quiet output Mode Set!");
1375 argc --;
1376 argv ++;
1377 continue;
1378 }
1379
1380 if ((stricmp (argv[0], "-d") == 0) || (stricmp (argv[0], "--debug") == 0)) {
1381 Status = AsciiStringToUint64 (argv[1], FALSE, &LogLevel);
1382 if (EFI_ERROR (Status)) {
1383 Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
1384 goto Finish;
1385 }
1386 if (LogLevel > 9) {
1387 Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, currnt input level is %d", (int) LogLevel);
1388 goto Finish;
1389 }
1390 SetPrintLevel (LogLevel);
1391 DebugMsg (NULL, 0, 9, "Debug Mode Set", "Debug Output Mode Level %s is set!", argv[1]);
1392 argc -= 2;
1393 argv += 2;
1394 continue;
1395 }
1396
1397 if ((stricmp (argv[0], "-g") == 0) || (stricmp (argv[0], "--hiiguid") == 0)) {
1398 Status = StringToGuid (argv[1], &HiiPackageListGuid);
1399 if (EFI_ERROR (Status)) {
1400 Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
1401 goto Finish;
1402 }
1403 argc -= 2;
1404 argv += 2;
1405 continue;
1406 }
1407
1408 if (stricmp (argv[0], "--hiipackage") == 0) {
1409 mOutImageType = FW_HII_PACKAGE_LIST_RCIMAGE;
1410 argc --;
1411 argv ++;
1412 continue;
1413 }
1414
1415 if (stricmp (argv[0], "--hiibinpackage") == 0) {
1416 mOutImageType = FW_HII_PACKAGE_LIST_BINIMAGE;
1417 argc --;
1418 argv ++;
1419 continue;
1420 }
1421
1422 if (argv[0][0] == '-') {
1423 Error (NULL, 0, 1000, "Unknown option", argv[0]);
1424 goto Finish;
1425 }
1426 //
1427 // Get Input file name
1428 //
1429 if ((InputFileNum == 0) && (InputFileName == NULL)) {
1430 InputFileName = (CHAR8 **) malloc (MAXIMUM_INPUT_FILE_NUM * sizeof (CHAR8 *));
1431 if (InputFileName == NULL) {
1432 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1433 goto Finish;
1434 }
1435
1436 memset (InputFileName, 0, (MAXIMUM_INPUT_FILE_NUM * sizeof (CHAR8 *)));
1437 } else if (InputFileNum % MAXIMUM_INPUT_FILE_NUM == 0) {
1438 //
1439 // InputFileName buffer too small, need to realloc
1440 //
1441 InputFileName = (CHAR8 **) realloc (
1442 InputFileName,
1443 (InputFileNum + MAXIMUM_INPUT_FILE_NUM) * sizeof (CHAR8 *)
1444 );
1445
1446 if (InputFileName == NULL) {
1447 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1448 goto Finish;
1449 }
1450
1451 memset (&(InputFileName[InputFileNum]), 0, (MAXIMUM_INPUT_FILE_NUM * sizeof (CHAR8 *)));
1452 }
1453
1454 InputFileName [InputFileNum ++] = argv[0];
1455 argc --;
1456 argv ++;
1457 }
1458
1459 VerboseMsg ("%s tool start.", UTILITY_NAME);
1460
1461 if (mOutImageType == FW_DUMMY_IMAGE) {
1462 Error (NULL, 0, 1001, "Missing option", "No create file action specified; pls specify -e, -c or -t option to create efi image, or acpi table or TeImage!");
1463 if (ReplaceFlag) {
1464 Error (NULL, 0, 1001, "Missing option", "-r option is not supported as the independent option. It can be used together with other create file option specified at the above.");
1465 }
1466 goto Finish;
1467 }
1468
1469 //
1470 // check input files
1471 //
1472 if (InputFileNum == 0) {
1473 Error (NULL, 0, 1001, "Missing option", "Input files");
1474 goto Finish;
1475 }
1476
1477 //
1478 // Combine MciBinary files to one file
1479 //
1480 if ((mOutImageType == FW_MERGE_IMAGE) && ReplaceFlag) {
1481 Error (NULL, 0, 1002, "Conflicting option", "-r replace option cannot be used with -j merge files option.");
1482 goto Finish;
1483 }
1484
1485 //
1486 // Combine HiiBinary packages to a single package list
1487 //
1488 if ((mOutImageType == FW_HII_PACKAGE_LIST_RCIMAGE) && ReplaceFlag) {
1489 Error (NULL, 0, 1002, "Conflicting option", "-r replace option cannot be used with --hiipackage merge files option.");
1490 goto Finish;
1491 }
1492
1493 if ((mOutImageType == FW_HII_PACKAGE_LIST_BINIMAGE) && ReplaceFlag) {
1494 Error (NULL, 0, 1002, "Conflicting option", "-r replace option cannot be used with --hiibinpackage merge files option.");
1495 goto Finish;
1496 }
1497
1498 //
1499 // Input image file
1500 //
1501 mInImageName = InputFileName [InputFileNum - 1];
1502 VerboseMsg ("the input file name is %s", mInImageName);
1503
1504 //
1505 // Action will be taken for the input file.
1506 //
1507 switch (mOutImageType) {
1508 case FW_EFI_IMAGE:
1509 VerboseMsg ("Create efi image on module type %s based on the input PE image.", ModuleType);
1510 break;
1511 case FW_TE_IMAGE:
1512 VerboseMsg ("Create Te Image based on the input PE image.");
1513 break;
1514 case FW_ACPI_IMAGE:
1515 VerboseMsg ("Get acpi table data from the input PE image.");
1516 break;
1517 case FW_RELOC_STRIPEED_IMAGE:
1518 VerboseMsg ("Remove relocation section from Pe or Te image.");
1519 break;
1520 case FW_BIN_IMAGE:
1521 VerboseMsg ("Convert the input EXE to the output BIN file.");
1522 break;
1523 case FW_ZERO_DEBUG_IMAGE:
1524 VerboseMsg ("Zero the Debug Data Fields and Time Stamp in input PE image.");
1525 break;
1526 case FW_SET_STAMP_IMAGE:
1527 VerboseMsg ("Set new time stamp %s in the input PE image.", TimeStamp);
1528 break;
1529 case DUMP_TE_HEADER:
1530 VerboseMsg ("Dump the TE header information of the input TE image.");
1531 break;
1532 case FW_MCI_IMAGE:
1533 VerboseMsg ("Conver input MicroCode.txt file to MicroCode.bin file.");
1534 break;
1535 case FW_MERGE_IMAGE:
1536 VerboseMsg ("Combine the input multi microcode bin files to one bin file.");
1537 break;
1538 case FW_HII_PACKAGE_LIST_RCIMAGE:
1539 VerboseMsg ("Combine the input multi hii bin packages to one text pacakge list RC file.");
1540 break;
1541 case FW_HII_PACKAGE_LIST_BINIMAGE:
1542 VerboseMsg ("Combine the input multi hii bin packages to one binary pacakge list file.");
1543 break;
1544 case FW_REBASE_IMAGE:
1545 VerboseMsg ("Rebase the input image to new base address.");
1546 break;
1547 case FW_SET_ADDRESS_IMAGE:
1548 VerboseMsg ("Set the preferred address into the section header of the input image");
1549 break;
1550 default:
1551 break;
1552 }
1553
1554 if (ReplaceFlag) {
1555 VerboseMsg ("Overwrite the input file with the output content.");
1556 }
1557
1558 //
1559 // Open output file and Write image into the output file.
1560 //
1561 if (OutImageName != NULL) {
1562 fpOut = fopen (OutImageName, "rb");
1563 if (fpOut != NULL) {
1564 //
1565 // Get Output file time stamp
1566 //
1567 fstat(fileno (fpOut), &Stat_Buf);
1568 OutputFileTime = Stat_Buf.st_mtime;
1569 //
1570 // Get Output file data
1571 //
1572 OutputFileLength = _filelength (fileno (fpOut));
1573 OutputFileBuffer = malloc (OutputFileLength);
1574 if (OutputFileBuffer == NULL) {
1575 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1576 fclose (fpOut);
1577 fpOut = NULL;
1578 goto Finish;
1579 }
1580 fread (OutputFileBuffer, 1, OutputFileLength, fpOut);
1581 fclose (fpOut);
1582 fpOut = NULL;
1583 }
1584 VerboseMsg ("Output file name is %s", OutImageName);
1585 } else if (!ReplaceFlag && mOutImageType != DUMP_TE_HEADER) {
1586 Error (NULL, 0, 1001, "Missing option", "output file");
1587 goto Finish;
1588 }
1589
1590 //
1591 // Open input file and read file data into file buffer.
1592 //
1593 fpIn = fopen (mInImageName, "rb");
1594 if (fpIn == NULL) {
1595 Error (NULL, 0, 0001, "Error opening file", mInImageName);
1596 goto Finish;
1597 }
1598 //
1599 // Get Iutput file time stamp
1600 //
1601 fstat(fileno (fpIn), &Stat_Buf);
1602 InputFileTime = Stat_Buf.st_mtime;
1603 //
1604 // Get Input file data
1605 //
1606 InputFileLength = _filelength (fileno (fpIn));
1607 InputFileBuffer = malloc (InputFileLength);
1608 if (InputFileBuffer == NULL) {
1609 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1610 fclose (fpIn);
1611 goto Finish;
1612 }
1613 fread (InputFileBuffer, 1, InputFileLength, fpIn);
1614 fclose (fpIn);
1615 DebugMsg (NULL, 0, 9, "input file info", "the input file size is %u bytes", (unsigned) InputFileLength);
1616
1617 //
1618 // Combine multi binary HII package files.
1619 //
1620 if (mOutImageType == FW_HII_PACKAGE_LIST_RCIMAGE || mOutImageType == FW_HII_PACKAGE_LIST_BINIMAGE) {
1621 //
1622 // Open output file handle.
1623 //
1624 fpOut = fopen (OutImageName, "wb");
1625 if (!fpOut) {
1626 Error (NULL, 0, 0001, "Error opening output file", OutImageName);
1627 goto Finish;
1628 }
1629 //
1630 // Get hii package list lenght
1631 //
1632 HiiPackageListHeader.PackageLength = sizeof (EFI_HII_PACKAGE_LIST_HEADER);
1633 for (Index = 0; Index < InputFileNum; Index ++) {
1634 fpIn = fopen (InputFileName [Index], "rb");
1635 if (fpIn == NULL) {
1636 Error (NULL, 0, 0001, "Error opening file", InputFileName [Index]);
1637 goto Finish;
1638 }
1639 FileLength = _filelength (fileno (fpIn));
1640 fread (&HiiPackageHeader, 1, sizeof (HiiPackageHeader), fpIn);
1641 if (HiiPackageHeader.Type == EFI_HII_PACKAGE_FORM) {
1642 if (HiiPackageHeader.Length != FileLength) {
1643 Error (NULL, 0, 3000, "Invalid", "The wrong package size is in HII package file %s", InputFileName [Index]);
1644 fclose (fpIn);
1645 goto Finish;
1646 }
1647 if (memcmp (&HiiPackageListGuid, &mZeroGuid, sizeof (EFI_GUID)) == 0) {
1648 fread (&IfrFormSet, 1, sizeof (IfrFormSet), fpIn);
1649 memcpy (&HiiPackageListGuid, &IfrFormSet.Guid, sizeof (EFI_GUID));
1650 }
1651 NumberOfFormPacakge ++;
1652 }
1653 HiiPackageListHeader.PackageLength += FileLength;
1654 fclose (fpIn);
1655 }
1656 HiiPackageListHeader.PackageLength += sizeof (EndPackage);
1657 //
1658 // Check whether hii packages are valid
1659 //
1660 if (NumberOfFormPacakge > 1) {
1661 Error (NULL, 0, 3000, "Invalid", "The input hii packages contains more than one hii form package");
1662 goto Finish;
1663 }
1664 if (memcmp (&HiiPackageListGuid, &mZeroGuid, sizeof (EFI_GUID)) == 0) {
1665 Error (NULL, 0, 3000, "Invalid", "HII pacakge list guid is not specified!");
1666 goto Finish;
1667 }
1668 memcpy (&HiiPackageListHeader.PackageListGuid, &HiiPackageListGuid, sizeof (EFI_GUID));
1669 //
1670 // read hii packages
1671 //
1672 HiiPackageListBuffer = malloc (HiiPackageListHeader.PackageLength);
1673 if (HiiPackageListBuffer == NULL) {
1674 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1675 goto Finish;
1676 }
1677 memcpy (HiiPackageListBuffer, &HiiPackageListHeader, sizeof (HiiPackageListHeader));
1678 HiiPackageDataPointer = HiiPackageListBuffer + sizeof (HiiPackageListHeader);
1679 for (Index = 0; Index < InputFileNum; Index ++) {
1680 fpIn = fopen (InputFileName [Index], "rb");
1681 if (fpIn == NULL) {
1682 Error (NULL, 0, 0001, "Error opening file", InputFileName [Index]);
1683 free (HiiPackageListBuffer);
1684 goto Finish;
1685 }
1686
1687 FileLength = _filelength (fileno (fpIn));
1688 fread (HiiPackageDataPointer, 1, FileLength, fpIn);
1689 fclose (fpIn);
1690 HiiPackageDataPointer = HiiPackageDataPointer + FileLength;
1691 }
1692 memcpy (HiiPackageDataPointer, &EndPackage, sizeof (EndPackage));
1693
1694 //
1695 // write the hii package into the binary package list file with the resource section header
1696 //
1697 if (mOutImageType == FW_HII_PACKAGE_LIST_BINIMAGE) {
1698 //
1699 // Create the resource section header
1700 //
1701 HiiSectionHeader = CreateHiiResouceSectionHeader (&HiiSectionHeaderSize, HiiPackageListHeader.PackageLength);
1702 //
1703 // Wrtie section header and HiiData into File.
1704 //
1705 fwrite (HiiSectionHeader, 1, HiiSectionHeaderSize, fpOut);
1706 fwrite (HiiPackageListBuffer, 1, HiiPackageListHeader.PackageLength, fpOut);
1707 //
1708 // Free allocated resources.
1709 //
1710 free (HiiSectionHeader);
1711 free (HiiPackageListBuffer);
1712 //
1713 // Done successfully
1714 //
1715 goto Finish;
1716 }
1717
1718 //
1719 // write the hii package into the text package list rc file.
1720 //
1721 if (mOutImageType == FW_HII_PACKAGE_LIST_RCIMAGE) {
1722 for (Index = 0; gHiiPackageRCFileHeader[Index] != NULL; Index++) {
1723 fprintf (fpOut, "%s\n", gHiiPackageRCFileHeader[Index]);
1724 }
1725 fprintf (fpOut, "\n%d %s\n{", HII_RESOURCE_SECTION_INDEX, HII_RESOURCE_SECTION_NAME);
1726
1727 HiiPackageDataPointer = HiiPackageListBuffer;
1728 for (Index = 0; Index + 2 < HiiPackageListHeader.PackageLength; Index += 2) {
1729 if (Index % 16 == 0) {
1730 fprintf (fpOut, "\n ");
1731 }
1732 fprintf (fpOut, " 0x%04X,", *(UINT16 *) HiiPackageDataPointer);
1733 HiiPackageDataPointer += 2;
1734 }
1735
1736 if (Index % 16 == 0) {
1737 fprintf (fpOut, "\n ");
1738 }
1739 if ((Index + 2) == HiiPackageListHeader.PackageLength) {
1740 fprintf (fpOut, " 0x%04X\n}\n", *(UINT16 *) HiiPackageDataPointer);
1741 }
1742 if ((Index + 1) == HiiPackageListHeader.PackageLength) {
1743 fprintf (fpOut, " 0x%04X\n}\n", *(UINT8 *) HiiPackageDataPointer);
1744 }
1745 free (HiiPackageListBuffer);
1746 //
1747 // Done successfully
1748 //
1749 goto Finish;
1750 }
1751 }
1752
1753 //
1754 // Combine MciBinary files to one file
1755 //
1756 if (mOutImageType == FW_MERGE_IMAGE) {
1757 //
1758 // Open output file handle.
1759 //
1760 fpOut = fopen (OutImageName, "wb");
1761 if (!fpOut) {
1762 Error (NULL, 0, 0001, "Error opening output file", OutImageName);
1763 goto Finish;
1764 }
1765 for (Index = 0; Index < InputFileNum; Index ++) {
1766 fpIn = fopen (InputFileName [Index], "rb");
1767 if (!fpIn) {
1768 Error (NULL, 0, 0001, "Error opening file", InputFileName [Index]);
1769 goto Finish;
1770 }
1771
1772 FileLength = _filelength (fileno (fpIn));
1773 FileBuffer = malloc (FileLength);
1774 if (FileBuffer == NULL) {
1775 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1776 fclose (fpIn);
1777 goto Finish;
1778 }
1779
1780 fread (FileBuffer, 1, FileLength, fpIn);
1781 fclose (fpIn);
1782 //
1783 // write input file to out file
1784 //
1785 fwrite (FileBuffer, 1, FileLength, fpOut);
1786 //
1787 // write pad value to out file.
1788 //
1789 while (FileLength ++ % MciAlignment != 0) {
1790 fwrite (&MciPadValue, 1, 1, fpOut);
1791 }
1792 //
1793 // free allocated memory space
1794 //
1795 free (FileBuffer);
1796 FileBuffer = NULL;
1797 }
1798 //
1799 // Done successfully
1800 //
1801 goto Finish;
1802 }
1803
1804 //
1805 // Convert MicroCode.txt file to MicroCode.bin file
1806 //
1807 if (mOutImageType == FW_MCI_IMAGE) {
1808 fpIn = fopen (mInImageName, "r");
1809 if (fpIn == NULL) {
1810 Error (NULL, 0, 0001, "Error opening file", mInImageName);
1811 goto Finish;
1812 }
1813
1814 //
1815 // The first pass is to determine
1816 // how much data is in the file so we can allocate a working buffer.
1817 //
1818 FileLength = 0;
1819 do {
1820 Status = MicrocodeReadData (fpIn, &Data);
1821 if (Status == STATUS_SUCCESS) {
1822 FileLength += sizeof (Data);
1823 }
1824 if (Status == STATUS_IGNORE) {
1825 Status = STATUS_SUCCESS;
1826 }
1827 } while (Status == STATUS_SUCCESS);
1828 //
1829 // Error if no data.
1830 //
1831 if (FileLength == 0) {
1832 Error (NULL, 0, 3000, "Invalid", "no parseable data found in file %s", mInImageName);
1833 goto Finish;
1834 }
1835 if (FileLength < sizeof (MICROCODE_IMAGE_HEADER)) {
1836 Error (NULL, 0, 3000, "Invalid", "amount of parseable data in %s is insufficient to contain a microcode header", mInImageName);
1837 goto Finish;
1838 }
1839
1840 //
1841 // Allocate a buffer for the data
1842 //
1843 FileBuffer = malloc (FileLength);
1844 if (FileBuffer == NULL) {
1845 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1846 goto Finish;
1847 }
1848 //
1849 // Re-read the file, storing the data into our buffer
1850 //
1851 fseek (fpIn, 0, SEEK_SET);
1852 DataPointer = (UINT32 *) FileBuffer;
1853 OldDataPointer = DataPointer;
1854 do {
1855 OldDataPointer = DataPointer;
1856 Status = MicrocodeReadData (fpIn, DataPointer++);
1857 if (Status == STATUS_IGNORE) {
1858 DataPointer = OldDataPointer;
1859 Status = STATUS_SUCCESS;
1860 }
1861 } while (Status == STATUS_SUCCESS);
1862 //
1863 // close input file after read data
1864 //
1865 fclose (fpIn);
1866
1867 //
1868 // Can't do much checking on the header because, per the spec, the
1869 // DataSize field may be 0, which means DataSize = 2000 and TotalSize = 2K,
1870 // and the TotalSize field is invalid (actually missing). Thus we can't
1871 // even verify the Reserved fields are 0.
1872 //
1873 MciHeader = (MICROCODE_IMAGE_HEADER *) FileBuffer;
1874 if (MciHeader->DataSize == 0) {
1875 Index = 2048;
1876 } else {
1877 Index = MciHeader->TotalSize;
1878 }
1879
1880 if (Index != FileLength) {
1881 Error (NULL, 0, 3000, "Invalid", "file length of %s (0x%x) does not equal expected TotalSize: 0x%04X.", mInImageName, (unsigned) FileLength, (unsigned) Index);
1882 goto Finish;
1883 }
1884
1885 //
1886 // Checksum the contents
1887 //
1888 DataPointer = (UINT32 *) FileBuffer;
1889 CheckSum = 0;
1890 Index = 0;
1891 while (Index < FileLength) {
1892 CheckSum += *DataPointer;
1893 DataPointer ++;
1894 Index += sizeof (*DataPointer);
1895 }
1896 if (CheckSum != 0) {
1897 Error (NULL, 0, 3000, "Invalid", "checksum (0x%x) failed on file %s.", (unsigned) CheckSum, mInImageName);
1898 goto Finish;
1899 }
1900 //
1901 // Open the output file and write the buffer contents
1902 //
1903 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
1904 goto WriteFile;
1905 }
1906
1907 //
1908 // Open input file and read file data into file buffer.
1909 //
1910 FileLength = InputFileLength;
1911 FileBuffer = malloc (FileLength);
1912 if (FileBuffer == NULL) {
1913 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
1914 goto Finish;
1915 }
1916 memcpy (FileBuffer, InputFileBuffer, InputFileLength);
1917
1918 //
1919 // Dump TeImage Header into output file.
1920 //
1921 if (mOutImageType == DUMP_TE_HEADER) {
1922 memcpy (&TEImageHeader, FileBuffer, sizeof (TEImageHeader));
1923 if (TEImageHeader.Signature != EFI_TE_IMAGE_HEADER_SIGNATURE) {
1924 Error (NULL, 0, 3000, "Invalid", "TE header signature of file %s is not correct.", mInImageName);
1925 goto Finish;
1926 }
1927 //
1928 // Open the output file handle.
1929 //
1930 if (ReplaceFlag) {
1931 fpInOut = fopen (mInImageName, "wb");
1932 if (fpInOut == NULL) {
1933 Error (NULL, 0, 0001, "Error opening file", mInImageName);
1934 goto Finish;
1935 }
1936 } else {
1937 if (OutImageName != NULL) {
1938 fpOut = fopen (OutImageName, "wb");
1939 } else {
1940 fpOut = stdout;
1941 }
1942 if (fpOut == NULL) {
1943 Error (NULL, 0, 0001, "Error opening output file", OutImageName);
1944 goto Finish;
1945 }
1946 }
1947 if (fpInOut != NULL) {
1948 fprintf (fpInOut, "Dump of file %s\n\n", mInImageName);
1949 fprintf (fpInOut, "TE IMAGE HEADER VALUES\n");
1950 fprintf (fpInOut, "%17X machine\n", TEImageHeader.Machine);
1951 fprintf (fpInOut, "%17X number of sections\n", TEImageHeader.NumberOfSections);
1952 fprintf (fpInOut, "%17X subsystems\n", TEImageHeader.Subsystem);
1953 fprintf (fpInOut, "%17X stripped size\n", TEImageHeader.StrippedSize);
1954 fprintf (fpInOut, "%17X entry point\n", (unsigned) TEImageHeader.AddressOfEntryPoint);
1955 fprintf (fpInOut, "%17X base of code\n", (unsigned) TEImageHeader.BaseOfCode);
1956 fprintf (fpInOut, "%17llX image base\n", (unsigned long long)TEImageHeader.ImageBase);
1957 fprintf (fpInOut, "%17X [%8X] RVA [size] of Base Relocation Directory\n", (unsigned) TEImageHeader.DataDirectory[0].VirtualAddress, (unsigned) TEImageHeader.DataDirectory[0].Size);
1958 fprintf (fpInOut, "%17X [%8X] RVA [size] of Debug Directory\n", (unsigned) TEImageHeader.DataDirectory[1].VirtualAddress, (unsigned) TEImageHeader.DataDirectory[1].Size);
1959 }
1960 if (fpOut != NULL) {
1961 fprintf (fpOut, "Dump of file %s\n\n", mInImageName);
1962 fprintf (fpOut, "TE IMAGE HEADER VALUES\n");
1963 fprintf (fpOut, "%17X machine\n", TEImageHeader.Machine);
1964 fprintf (fpOut, "%17X number of sections\n", TEImageHeader.NumberOfSections);
1965 fprintf (fpOut, "%17X subsystems\n", TEImageHeader.Subsystem);
1966 fprintf (fpOut, "%17X stripped size\n", TEImageHeader.StrippedSize);
1967 fprintf (fpOut, "%17X entry point\n", (unsigned) TEImageHeader.AddressOfEntryPoint);
1968 fprintf (fpOut, "%17X base of code\n", (unsigned) TEImageHeader.BaseOfCode);
1969 fprintf (fpOut, "%17llX image base\n", (unsigned long long)TEImageHeader.ImageBase);
1970 fprintf (fpOut, "%17X [%8X] RVA [size] of Base Relocation Directory\n", (unsigned) TEImageHeader.DataDirectory[0].VirtualAddress, (unsigned) TEImageHeader.DataDirectory[0].Size);
1971 fprintf (fpOut, "%17X [%8X] RVA [size] of Debug Directory\n", (unsigned) TEImageHeader.DataDirectory[1].VirtualAddress, (unsigned) TEImageHeader.DataDirectory[1].Size);
1972 }
1973 goto Finish;
1974 }
1975
1976 //
1977 // Following code to convert dll to efi image or te image.
1978 // Get new image type
1979 //
1980 if ((mOutImageType == FW_EFI_IMAGE) || (mOutImageType == FW_TE_IMAGE)) {
1981 if (ModuleType == NULL) {
1982 if (mOutImageType == FW_EFI_IMAGE) {
1983 Error (NULL, 0, 1001, "Missing option", "EFI_FILETYPE");
1984 goto Finish;
1985 } else if (mOutImageType == FW_TE_IMAGE) {
1986 //
1987 // Default TE Image Type is Boot service driver
1988 //
1989 Type = EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
1990 VerboseMsg ("Efi Image subsystem type is efi boot service driver.");
1991 }
1992 } else {
1993 if (stricmp (ModuleType, "BASE") == 0 ||
1994 stricmp (ModuleType, "SEC") == 0 ||
1995 stricmp (ModuleType, "SECURITY_CORE") == 0 ||
1996 stricmp (ModuleType, "PEI_CORE") == 0 ||
1997 stricmp (ModuleType, "PEIM") == 0 ||
1998 stricmp (ModuleType, "COMBINED_PEIM_DRIVER") == 0 ||
1999 stricmp (ModuleType, "PIC_PEIM") == 0 ||
2000 stricmp (ModuleType, "RELOCATABLE_PEIM") == 0 ||
2001 stricmp (ModuleType, "DXE_CORE") == 0 ||
2002 stricmp (ModuleType, "BS_DRIVER") == 0 ||
2003 stricmp (ModuleType, "DXE_DRIVER") == 0 ||
2004 stricmp (ModuleType, "DXE_SMM_DRIVER") == 0 ||
2005 stricmp (ModuleType, "UEFI_DRIVER") == 0 ||
2006 stricmp (ModuleType, "SMM_CORE") == 0) {
2007 Type = EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
2008 VerboseMsg ("Efi Image subsystem type is efi boot service driver.");
2009
2010 } else if (stricmp (ModuleType, "UEFI_APPLICATION") == 0 ||
2011 stricmp (ModuleType, "APPLICATION") == 0) {
2012 Type = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION;
2013 VerboseMsg ("Efi Image subsystem type is efi application.");
2014
2015 } else if (stricmp (ModuleType, "DXE_RUNTIME_DRIVER") == 0 ||
2016 stricmp (ModuleType, "RT_DRIVER") == 0) {
2017 Type = EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER;
2018 VerboseMsg ("Efi Image subsystem type is efi runtime driver.");
2019
2020 } else if (stricmp (ModuleType, "DXE_SAL_DRIVER") == 0 ||
2021 stricmp (ModuleType, "SAL_RT_DRIVER") == 0) {
2022 Type = EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER;
2023 VerboseMsg ("Efi Image subsystem type is efi sal runtime driver.");
2024
2025 } else {
2026 Error (NULL, 0, 1003, "Invalid option value", "EFI_FILETYPE = %s", ModuleType);
2027 goto Finish;
2028 }
2029 }
2030 }
2031
2032 //
2033 // Convert ELF image to PeImage
2034 //
2035 if (IsElfHeader(FileBuffer)) {
2036 VerboseMsg ("Convert %s from ELF to PE/COFF.", mInImageName);
2037 if (!ConvertElf(&FileBuffer, &FileLength)) {
2038 Error (NULL, 0, 3000, "Invalid", "Unable to convert %s from ELF to PE/COFF.", mInImageName);
2039 goto Finish;
2040 }
2041 }
2042
2043 //
2044 // Make sure File Offsets and Virtual Offsets are the same in the image so it is XIP
2045 // XIP == eXecute In Place
2046 //
2047 PeCoffConvertImageToXip (&FileBuffer, &FileLength);
2048
2049 //
2050 // Remove reloc section from PE or TE image
2051 //
2052 if (mOutImageType == FW_RELOC_STRIPEED_IMAGE) {
2053 //
2054 // Check TeImage
2055 //
2056 TeHdr = (EFI_TE_IMAGE_HEADER *) FileBuffer;
2057 if (TeHdr->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
2058 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (TeHdr + 1);
2059 for (Index = 0; Index < TeHdr->NumberOfSections; Index ++, SectionHeader ++) {
2060 if (strcmp ((char *)SectionHeader->Name, ".reloc") == 0) {
2061 //
2062 // Check the reloc section is in the end of image.
2063 //
2064 if ((SectionHeader->PointerToRawData + SectionHeader->SizeOfRawData) ==
2065 (FileLength + TeHdr->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER))) {
2066 //
2067 // Remove .reloc section and update TeImage Header
2068 //
2069 FileLength = FileLength - SectionHeader->SizeOfRawData;
2070 SectionHeader->SizeOfRawData = 0;
2071 SectionHeader->Misc.VirtualSize = 0;
2072 TeHdr->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = 0;
2073 TeHdr->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = 0;
2074 break;
2075 }
2076 }
2077 }
2078 } else {
2079 //
2080 // Check PE Image
2081 //
2082 DosHdr = (EFI_IMAGE_DOS_HEADER *) FileBuffer;
2083 if (DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
2084 PeHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(FileBuffer);
2085 if (PeHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
2086 Error (NULL, 0, 3000, "Invalid", "TE and DOS header signatures were not found in %s image.", mInImageName);
2087 goto Finish;
2088 }
2089 DosHdr = NULL;
2090 } else {
2091 PeHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(FileBuffer + DosHdr->e_lfanew);
2092 if (PeHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
2093 Error (NULL, 0, 3000, "Invalid", "PE header signature was not found in %s image.", mInImageName);
2094 goto Finish;
2095 }
2096 }
2097 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2098 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
2099 if (strcmp ((char *)SectionHeader->Name, ".reloc") == 0) {
2100 //
2101 // Check the reloc section is in the end of image.
2102 //
2103 if ((SectionHeader->PointerToRawData + SectionHeader->SizeOfRawData) == FileLength) {
2104 //
2105 // Remove .reloc section and update PeImage Header
2106 //
2107 FileLength = FileLength - SectionHeader->SizeOfRawData;
2108
2109 PeHdr->Pe32.FileHeader.Characteristics |= EFI_IMAGE_FILE_RELOCS_STRIPPED;
2110 if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
2111 Optional32 = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHdr->Pe32.OptionalHeader;
2112 Optional32->SizeOfImage -= SectionHeader->SizeOfRawData;
2113 Optional32->SizeOfInitializedData -= SectionHeader->SizeOfRawData;
2114 if (Optional32->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
2115 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = 0;
2116 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = 0;
2117 }
2118 }
2119 if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2120 Optional64 = (EFI_IMAGE_OPTIONAL_HEADER64 *)&PeHdr->Pe32.OptionalHeader;
2121 Optional64->SizeOfImage -= SectionHeader->SizeOfRawData;
2122 Optional64->SizeOfInitializedData -= SectionHeader->SizeOfRawData;
2123 if (Optional64->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
2124 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = 0;
2125 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = 0;
2126 }
2127 }
2128 SectionHeader->Misc.VirtualSize = 0;
2129 SectionHeader->SizeOfRawData = 0;
2130 break;
2131 }
2132 }
2133 }
2134 }
2135 //
2136 // Write file
2137 //
2138 goto WriteFile;
2139 }
2140 //
2141 // Read the dos & pe hdrs of the image
2142 //
2143 DosHdr = (EFI_IMAGE_DOS_HEADER *)FileBuffer;
2144 if (DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
2145 // NO DOS header, check for PE/COFF header
2146 PeHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(FileBuffer);
2147 if (PeHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
2148 Error (NULL, 0, 3000, "Invalid", "DOS header signature was not found in %s image.", mInImageName);
2149 goto Finish;
2150 }
2151 DosHdr = NULL;
2152 } else {
2153
2154 PeHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(FileBuffer + DosHdr->e_lfanew);
2155 if (PeHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
2156 Error (NULL, 0, 3000, "Invalid", "PE header signature was not found in %s image.", mInImageName);
2157 goto Finish;
2158 }
2159 }
2160
2161 if (PeHdr->Pe32.FileHeader.Machine == IMAGE_FILE_MACHINE_ARM) {
2162 // Some tools kick out IMAGE_FILE_MACHINE_ARM (0x1c0) vs IMAGE_FILE_MACHINE_ARMT (0x1c2)
2163 // so patch back to the offical UEFI value.
2164 PeHdr->Pe32.FileHeader.Machine = IMAGE_FILE_MACHINE_ARMT;
2165 }
2166
2167 //
2168 // Set new base address into image
2169 //
2170 if (mOutImageType == FW_REBASE_IMAGE || mOutImageType == FW_SET_ADDRESS_IMAGE) {
2171 if ((PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) && (PeHdr->Pe32.FileHeader.Machine != IMAGE_FILE_MACHINE_IA64)) {
2172 if (NewBaseAddress >= 0x100000000ULL) {
2173 Error (NULL, 0, 3000, "Invalid", "New base address is larger than 4G for 32bit PE image");
2174 goto Finish;
2175 }
2176 }
2177
2178 if (NegativeAddr) {
2179 //
2180 // Set Base Address to a negative value.
2181 //
2182 NewBaseAddress = (UINT64) (0 - NewBaseAddress);
2183 }
2184 if (mOutImageType == FW_REBASE_IMAGE) {
2185 Status = RebaseImage (mInImageName, FileBuffer, NewBaseAddress);
2186 } else {
2187 Status = SetAddressToSectionHeader (mInImageName, FileBuffer, NewBaseAddress);
2188 }
2189 if (EFI_ERROR (Status)) {
2190 if (NegativeAddr) {
2191 Error (NULL, 0, 3000, "Invalid", "Rebase/Set Image %s to Base address -0x%llx can't success", mInImageName, 0 - NewBaseAddress);
2192 } else {
2193 Error (NULL, 0, 3000, "Invalid", "Rebase/Set Image %s to Base address 0x%llx can't success", mInImageName, NewBaseAddress);
2194 }
2195 goto Finish;
2196 }
2197
2198 //
2199 // Write file
2200 //
2201 goto WriteFile;
2202 }
2203
2204 //
2205 // Extract bin data from Pe image.
2206 //
2207 if (mOutImageType == FW_BIN_IMAGE) {
2208 if (FileLength < PeHdr->Pe32.OptionalHeader.SizeOfHeaders) {
2209 Error (NULL, 0, 3000, "Invalid", "FileSize of %s is not a legal size.", mInImageName);
2210 goto Finish;
2211 }
2212 //
2213 // Output bin data from exe file
2214 //
2215 FileLength = FileLength - PeHdr->Pe32.OptionalHeader.SizeOfHeaders;
2216 memmove (FileBuffer, FileBuffer + PeHdr->Pe32.OptionalHeader.SizeOfHeaders, FileLength);
2217 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
2218 goto WriteFile;
2219 }
2220
2221 //
2222 // Zero Debug Information of Pe Image
2223 //
2224 if (mOutImageType == FW_ZERO_DEBUG_IMAGE) {
2225 Status = ZeroDebugData (FileBuffer, TRUE);
2226 if (EFI_ERROR (Status)) {
2227 Error (NULL, 0, 3000, "Invalid", "Zero DebugData Error status is 0x%x", (int) Status);
2228 goto Finish;
2229 }
2230
2231 //
2232 // Write the updated Image
2233 //
2234 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
2235 goto WriteFile;
2236 }
2237
2238 //
2239 // Set Time Stamp of Pe Image
2240 //
2241 if (mOutImageType == FW_SET_STAMP_IMAGE) {
2242 Status = SetStamp (FileBuffer, TimeStamp);
2243 if (EFI_ERROR (Status)) {
2244 goto Finish;
2245 }
2246
2247 //
2248 // Write the updated Image
2249 //
2250 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
2251 goto WriteFile;
2252 }
2253
2254 //
2255 // Extract acpi data from pe image.
2256 //
2257 if (mOutImageType == FW_ACPI_IMAGE) {
2258 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2259 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
2260 if (strcmp ((char *)SectionHeader->Name, ".data") == 0 || strcmp ((char *)SectionHeader->Name, ".sdata") == 0) {
2261 //
2262 // Check Acpi Table
2263 //
2264 if (SectionHeader->Misc.VirtualSize < SectionHeader->SizeOfRawData) {
2265 FileLength = SectionHeader->Misc.VirtualSize;
2266 } else {
2267 FileLength = SectionHeader->SizeOfRawData;
2268 }
2269
2270 if (CheckAcpiTable (FileBuffer + SectionHeader->PointerToRawData, FileLength) != STATUS_SUCCESS) {
2271 Error (NULL, 0, 3000, "Invalid", "ACPI table check failed in %s.", mInImageName);
2272 goto Finish;
2273 }
2274
2275 //
2276 // Output Apci data to file
2277 //
2278 memmove (FileBuffer, FileBuffer + SectionHeader->PointerToRawData, FileLength);
2279 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
2280 goto WriteFile;
2281 }
2282 }
2283 Error (NULL, 0, 3000, "Invalid", "failed to get ACPI table from %s.", mInImageName);
2284 goto Finish;
2285 }
2286 //
2287 // Zero all unused fields of the DOS header
2288 //
2289 if (DosHdr != NULL) {
2290 memcpy (&BackupDosHdr, DosHdr, sizeof (EFI_IMAGE_DOS_HEADER));
2291 memset (DosHdr, 0, sizeof (EFI_IMAGE_DOS_HEADER));
2292 DosHdr->e_magic = BackupDosHdr.e_magic;
2293 DosHdr->e_lfanew = BackupDosHdr.e_lfanew;
2294
2295 for (Index = sizeof (EFI_IMAGE_DOS_HEADER); Index < (UINT32 ) DosHdr->e_lfanew; Index++) {
2296 FileBuffer[Index] = (UINT8) DosHdr->e_cp;
2297 }
2298 }
2299
2300 //
2301 // Initialize TeImage Header
2302 //
2303 memset (&TEImageHeader, 0, sizeof (EFI_TE_IMAGE_HEADER));
2304 TEImageHeader.Signature = EFI_TE_IMAGE_HEADER_SIGNATURE;
2305 TEImageHeader.Machine = PeHdr->Pe32.FileHeader.Machine;
2306 TEImageHeader.NumberOfSections = (UINT8) PeHdr->Pe32.FileHeader.NumberOfSections;
2307 TEImageHeader.StrippedSize = (UINT16) ((UINTN) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader) - (UINTN) FileBuffer);
2308 TEImageHeader.Subsystem = (UINT8) Type;
2309
2310 //
2311 // Patch the PE header
2312 //
2313 PeHdr->Pe32.OptionalHeader.Subsystem = (UINT16) Type;
2314
2315 if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
2316 Optional32 = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHdr->Pe32.OptionalHeader;
2317 Optional32->MajorOperatingSystemVersion = 0;
2318 Optional32->MinorOperatingSystemVersion = 0;
2319 Optional32->MajorImageVersion = 0;
2320 Optional32->MinorImageVersion = 0;
2321 Optional32->MajorSubsystemVersion = 0;
2322 Optional32->MinorSubsystemVersion = 0;
2323 Optional32->Win32VersionValue = 0;
2324 Optional32->CheckSum = 0;
2325 Optional32->SizeOfStackReserve = 0;
2326 Optional32->SizeOfStackCommit = 0;
2327 Optional32->SizeOfHeapReserve = 0;
2328 Optional32->SizeOfHeapCommit = 0;
2329
2330 TEImageHeader.AddressOfEntryPoint = Optional32->AddressOfEntryPoint;
2331 TEImageHeader.BaseOfCode = Optional32->BaseOfCode;
2332 TEImageHeader.ImageBase = (UINT64) (Optional32->ImageBase);
2333
2334 if (Optional32->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
2335 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
2336 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
2337 }
2338
2339 if (Optional32->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
2340 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
2341 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
2342 }
2343
2344 //
2345 // Zero .pdata section data.
2346 //
2347 if (!KeepExceptionTableFlag && Optional32->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION &&
2348 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress != 0 &&
2349 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size != 0) {
2350 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2351 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index++, SectionHeader++) {
2352 if (SectionHeader->VirtualAddress == Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress) {
2353 //
2354 // Zero .pdata Section data
2355 //
2356 memset (FileBuffer + SectionHeader->PointerToRawData, 0, SectionHeader->SizeOfRawData);
2357 //
2358 // Zero .pdata Section header name
2359 //
2360 memset (SectionHeader->Name, 0, sizeof (SectionHeader->Name));
2361 //
2362 // Zero Execption Table
2363 //
2364 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = 0;
2365 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = 0;
2366 DebugMsg (NULL, 0, 9, "Zero the .pdata section for PE image", NULL);
2367 break;
2368 }
2369 }
2370 }
2371
2372 //
2373 // Strip zero padding at the end of the .reloc section
2374 //
2375 if (!KeepZeroPendingFlag && Optional32->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
2376 if (Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size != 0) {
2377 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2378 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index++, SectionHeader++) {
2379 //
2380 // Look for the Section Header that starts as the same virtual address as the Base Relocation Data Directory
2381 //
2382 if (SectionHeader->VirtualAddress == Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress) {
2383 SectionHeader->Misc.VirtualSize = Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
2384 AllignedRelocSize = (Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size + Optional32->FileAlignment - 1) & (~(Optional32->FileAlignment - 1));
2385 //
2386 // Check to see if there is zero padding at the end of the base relocations
2387 //
2388 if (AllignedRelocSize < SectionHeader->SizeOfRawData) {
2389 //
2390 // Check to see if the base relocations are at the end of the file
2391 //
2392 if (SectionHeader->PointerToRawData + SectionHeader->SizeOfRawData == Optional32->SizeOfImage) {
2393 //
2394 // All the required conditions are met to strip the zero padding of the end of the base relocations section
2395 //
2396 Optional32->SizeOfImage -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
2397 Optional32->SizeOfInitializedData -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
2398 SectionHeader->SizeOfRawData = AllignedRelocSize;
2399 FileLength = Optional32->SizeOfImage;
2400 DebugMsg (NULL, 0, 9, "Remove the zero padding bytes at the end of the base relocations", "The size of padding bytes is %u", (unsigned) (SectionHeader->SizeOfRawData - AllignedRelocSize));
2401 }
2402 }
2403 }
2404 }
2405 }
2406 }
2407 } else if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2408 Optional64 = (EFI_IMAGE_OPTIONAL_HEADER64 *)&PeHdr->Pe32.OptionalHeader;
2409 Optional64->MajorOperatingSystemVersion = 0;
2410 Optional64->MinorOperatingSystemVersion = 0;
2411 Optional64->MajorImageVersion = 0;
2412 Optional64->MinorImageVersion = 0;
2413 Optional64->MajorSubsystemVersion = 0;
2414 Optional64->MinorSubsystemVersion = 0;
2415 Optional64->Win32VersionValue = 0;
2416 Optional64->CheckSum = 0;
2417 Optional64->SizeOfStackReserve = 0;
2418 Optional64->SizeOfStackCommit = 0;
2419 Optional64->SizeOfHeapReserve = 0;
2420 Optional64->SizeOfHeapCommit = 0;
2421
2422 TEImageHeader.AddressOfEntryPoint = Optional64->AddressOfEntryPoint;
2423 TEImageHeader.BaseOfCode = Optional64->BaseOfCode;
2424 TEImageHeader.ImageBase = (UINT64) (Optional64->ImageBase);
2425
2426 if (Optional64->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
2427 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
2428 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
2429 }
2430
2431 if (Optional64->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
2432 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
2433 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
2434 }
2435
2436 //
2437 // Zero the .pdata section for X64 machine and don't check the Debug Directory is empty
2438 // For Itaninum and X64 Image, remove .pdata section.
2439 //
2440 if ((!KeepExceptionTableFlag && PeHdr->Pe32.FileHeader.Machine == IMAGE_FILE_MACHINE_X64) || PeHdr->Pe32.FileHeader.Machine == IMAGE_FILE_MACHINE_IA64) {
2441 if (Optional64->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION &&
2442 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress != 0 &&
2443 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size != 0) {
2444 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2445 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index++, SectionHeader++) {
2446 if (SectionHeader->VirtualAddress == Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress) {
2447 //
2448 // Zero .pdata Section header name
2449 //
2450 memset (SectionHeader->Name, 0, sizeof (SectionHeader->Name));
2451
2452 RuntimeFunction = (RUNTIME_FUNCTION *)(FileBuffer + SectionHeader->PointerToRawData);
2453 for (Index1 = 0; Index1 < Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size / sizeof (RUNTIME_FUNCTION); Index1++, RuntimeFunction++) {
2454 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2455 for (Index2 = 0; Index2 < PeHdr->Pe32.FileHeader.NumberOfSections; Index2++, SectionHeader++) {
2456 if (RuntimeFunction->UnwindInfoAddress >= SectionHeader->VirtualAddress && RuntimeFunction->UnwindInfoAddress < (SectionHeader->VirtualAddress + SectionHeader->SizeOfRawData)) {
2457 UnwindInfo = (UNWIND_INFO *)(FileBuffer + SectionHeader->PointerToRawData + (RuntimeFunction->UnwindInfoAddress - SectionHeader->VirtualAddress));
2458 if (UnwindInfo->Version == 1) {
2459 memset (UnwindInfo + 1, 0, UnwindInfo->CountOfUnwindCodes * sizeof (UINT16));
2460 memset (UnwindInfo, 0, sizeof (UNWIND_INFO));
2461 }
2462 break;
2463 }
2464 }
2465 memset (RuntimeFunction, 0, sizeof (RUNTIME_FUNCTION));
2466 }
2467 //
2468 // Zero Execption Table
2469 //
2470 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = 0;
2471 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = 0;
2472 DebugMsg (NULL, 0, 9, "Zero the .pdata section if the machine type is X64 for PE32+ image", NULL);
2473 break;
2474 }
2475 }
2476 }
2477 }
2478
2479 //
2480 // Strip zero padding at the end of the .reloc section
2481 //
2482 if (!KeepZeroPendingFlag && Optional64->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
2483 if (Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size != 0) {
2484 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2485 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index++, SectionHeader++) {
2486 //
2487 // Look for the Section Header that starts as the same virtual address as the Base Relocation Data Directory
2488 //
2489 if (SectionHeader->VirtualAddress == Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress) {
2490 SectionHeader->Misc.VirtualSize = Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
2491 AllignedRelocSize = (Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size + Optional64->FileAlignment - 1) & (~(Optional64->FileAlignment - 1));
2492 //
2493 // Check to see if there is zero padding at the end of the base relocations
2494 //
2495 if (AllignedRelocSize < SectionHeader->SizeOfRawData) {
2496 //
2497 // Check to see if the base relocations are at the end of the file
2498 //
2499 if (SectionHeader->PointerToRawData + SectionHeader->SizeOfRawData == Optional64->SizeOfImage) {
2500 //
2501 // All the required conditions are met to strip the zero padding of the end of the base relocations section
2502 //
2503 Optional64->SizeOfImage -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
2504 Optional64->SizeOfInitializedData -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
2505 SectionHeader->SizeOfRawData = AllignedRelocSize;
2506 FileLength = Optional64->SizeOfImage;
2507 DebugMsg (NULL, 0, 9, "Remove the zero padding bytes at the end of the base relocations", "The size of padding bytes is %u", (unsigned) (SectionHeader->SizeOfRawData - AllignedRelocSize));
2508 }
2509 }
2510 }
2511 }
2512 }
2513 }
2514 } else {
2515 Error (NULL, 0, 3000, "Invalid", "Magic 0x%x of PeImage %s is unknown.", PeHdr->Pe32.OptionalHeader.Magic, mInImageName);
2516 goto Finish;
2517 }
2518
2519 if (((PeHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) == 0) && \
2520 (TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress == 0) && \
2521 (TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size == 0)) {
2522 //
2523 // PeImage can be loaded into memory, but it has no relocation section.
2524 // Fix TeImage Header to set VA of relocation data directory to not zero, the size is still zero.
2525 //
2526 if (Optional32 != NULL) {
2527 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = Optional32->SizeOfImage - sizeof (EFI_IMAGE_BASE_RELOCATION);
2528 } else if (Optional64 != NULL) {
2529 TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = Optional64->SizeOfImage - sizeof (EFI_IMAGE_BASE_RELOCATION);
2530 }
2531 }
2532
2533 //
2534 // Fill HII section data
2535 //
2536 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2537 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index++) {
2538 if (stricmp ((char *)SectionHeader[Index].Name, ".hii") == 0) {
2539 //
2540 // Update resource section header offset
2541 //
2542 SetHiiResourceHeader ((UINT8*) FileBuffer + SectionHeader[Index].PointerToRawData, SectionHeader[Index].VirtualAddress);
2543 //
2544 // Update resource section name
2545 //
2546 strcpy((char *) SectionHeader[Index].Name, ".rsrc");
2547 //
2548 // Update resource data directory.
2549 //
2550 if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
2551 Optional32 = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHdr->Pe32.OptionalHeader;
2552 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = SectionHeader[Index].VirtualAddress;
2553 Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = SectionHeader[Index].Misc.VirtualSize;
2554 } else if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2555 Optional64 = (EFI_IMAGE_OPTIONAL_HEADER64 *)&PeHdr->Pe32.OptionalHeader;
2556 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = SectionHeader[Index].VirtualAddress;
2557 Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = SectionHeader[Index].Misc.VirtualSize;
2558 }
2559 break;
2560 }
2561 }
2562
2563 //
2564 // Zero ExceptionTable Xdata
2565 //
2566 if (!KeepExceptionTableFlag) {
2567 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) &(PeHdr->Pe32.OptionalHeader) + PeHdr->Pe32.FileHeader.SizeOfOptionalHeader);
2568 for (Index = 0; Index < PeHdr->Pe32.FileHeader.NumberOfSections; Index++) {
2569 if (stricmp ((char *)SectionHeader[Index].Name, ".xdata") == 0) {
2570 //
2571 // zero .xdata section
2572 //
2573 memset (FileBuffer + SectionHeader[Index].PointerToRawData, 0, SectionHeader[Index].SizeOfRawData);
2574 DebugMsg (NULL, 0, 9, NULL, "Zero the .xdata section for PE image at Offset 0x%x and Length 0x%x", (unsigned) SectionHeader[Index].PointerToRawData, (unsigned) SectionHeader[Index].SizeOfRawData);
2575 break;
2576 }
2577 }
2578 }
2579
2580 //
2581 // Zero Time/Data field
2582 //
2583 ZeroDebugData (FileBuffer, FALSE);
2584
2585 if (mOutImageType == FW_TE_IMAGE) {
2586 if ((PeHdr->Pe32.FileHeader.NumberOfSections &~0xFF) || (Type &~0xFF)) {
2587 //
2588 // Pack the subsystem and NumberOfSections into 1 byte. Make sure they fit both.
2589 //
2590 Error (NULL, 0, 3000, "Invalid", "Image's subsystem or NumberOfSections of PeImage %s cannot be packed into 1 byte.", mInImageName);
2591 goto Finish;
2592 }
2593
2594 if ((PeHdr->Pe32.OptionalHeader.SectionAlignment != PeHdr->Pe32.OptionalHeader.FileAlignment)) {
2595 //
2596 // TeImage has the same section alignment and file alignment.
2597 //
2598 Error (NULL, 0, 3000, "Invalid", "Section-Alignment and File-Alignment of PeImage %s do not match, they must be equal for a TeImage.", mInImageName);
2599 goto Finish;
2600 }
2601
2602 DebugMsg (NULL, 0, 9, "TeImage Header Info", "Machine type is %X, Number of sections is %X, Stripped size is %X, EntryPoint is %X, BaseOfCode is %X, ImageBase is %llX",
2603 TEImageHeader.Machine, TEImageHeader.NumberOfSections, TEImageHeader.StrippedSize, (unsigned) TEImageHeader.AddressOfEntryPoint, (unsigned) TEImageHeader.BaseOfCode, (unsigned long long) TEImageHeader.ImageBase);
2604 //
2605 // Update Image to TeImage
2606 //
2607 FileLength = FileLength - TEImageHeader.StrippedSize;
2608 memmove (FileBuffer + sizeof (EFI_TE_IMAGE_HEADER), FileBuffer + TEImageHeader.StrippedSize, FileLength);
2609 FileLength = FileLength + sizeof (EFI_TE_IMAGE_HEADER);
2610 memcpy (FileBuffer, &TEImageHeader, sizeof (EFI_TE_IMAGE_HEADER));
2611 VerboseMsg ("the size of output file is %u bytes", (unsigned) (FileLength));
2612 } else {
2613
2614 //
2615 // Following codes are to fix the objcopy's issue:
2616 // objcopy in binutil 2.50.18 will set PE image's charactices to "RELOC_STRIPPED" if image has no ".reloc" section
2617 // It cause issue for EFI image which has no ".reloc" sections.
2618 // Following codes will be removed when objcopy in binutil fix this problem for PE image.
2619 //
2620 if ((PeHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) != 0) {
2621 if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
2622 Optional32 = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHdr->Pe32.OptionalHeader;
2623 if (Optional32->ImageBase == 0) {
2624 PeHdr->Pe32.FileHeader.Characteristics &= ~EFI_IMAGE_FILE_RELOCS_STRIPPED;
2625 }
2626 } else if (PeHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
2627 Optional64 = (EFI_IMAGE_OPTIONAL_HEADER64 *)&PeHdr->Pe32.OptionalHeader;
2628 if (Optional64->ImageBase == 0) {
2629 PeHdr->Pe32.FileHeader.Characteristics &= ~EFI_IMAGE_FILE_RELOCS_STRIPPED;
2630 }
2631 }
2632 }
2633 }
2634
2635 WriteFile:
2636 //
2637 // Update Image to EfiImage or TE image
2638 //
2639 if (ReplaceFlag) {
2640 if ((FileLength != InputFileLength) || (memcmp (FileBuffer, InputFileBuffer, FileLength) != 0)) {
2641 //
2642 // Update File when File is changed.
2643 //
2644 fpInOut = fopen (mInImageName, "wb");
2645 if (fpInOut == NULL) {
2646 Error (NULL, 0, 0001, "Error opening file", mInImageName);
2647 goto Finish;
2648 }
2649 fwrite (FileBuffer, 1, FileLength, fpInOut);
2650 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
2651 }
2652 } else {
2653 if ((OutputFileTime < InputFileTime) || (FileLength != OutputFileLength) || (memcmp (FileBuffer, OutputFileBuffer, FileLength) != 0)) {
2654 //
2655 // Update File when File is changed or File is old.
2656 //
2657 fpOut = fopen (OutImageName, "wb");
2658 if (fpOut == NULL) {
2659 Error (NULL, 0, 0001, "Error opening output file", OutImageName);
2660 goto Finish;
2661 }
2662 fwrite (FileBuffer, 1, FileLength, fpOut);
2663 VerboseMsg ("the size of output file is %u bytes", (unsigned) FileLength);
2664 }
2665 }
2666 mImageSize = FileLength;
2667
2668 Finish:
2669 if (fpInOut != NULL) {
2670 if (GetUtilityStatus () != STATUS_SUCCESS) {
2671 //
2672 // when file updates failed, original file is still recovered.
2673 //
2674 fwrite (InputFileBuffer, 1, InputFileLength, fpInOut);
2675 }
2676 //
2677 // Write converted data into fpInOut file and close input file.
2678 //
2679 fclose (fpInOut);
2680 }
2681
2682 if (FileBuffer != NULL) {
2683 free (FileBuffer);
2684 }
2685
2686 if (InputFileName != NULL) {
2687 free (InputFileName);
2688 }
2689
2690 if (fpOut != NULL) {
2691 //
2692 // Write converted data into fpOut file and close output file.
2693 //
2694 fclose (fpOut);
2695 if (GetUtilityStatus () != STATUS_SUCCESS) {
2696 if (OutputFileBuffer == NULL) {
2697 remove (OutImageName);
2698 } else {
2699 fpOut = fopen (OutImageName, "wb");
2700 fwrite (OutputFileBuffer, 1, OutputFileLength, fpOut);
2701 fclose (fpOut);
2702 }
2703 }
2704 }
2705
2706 if (InputFileBuffer != NULL) {
2707 free (InputFileBuffer);
2708 }
2709
2710 if (OutputFileBuffer != NULL) {
2711 free (OutputFileBuffer);
2712 }
2713
2714 //
2715 // Write module size and time stamp to report file.
2716 //
2717 if (OutImageName != NULL) {
2718 FileLen = strlen (OutImageName);
2719 }
2720 if (FileLen >= 4 && strcmp (OutImageName + (FileLen - 4), ".efi") == 0) {
2721 ReportFileName = (CHAR8 *) malloc (FileLen + 1);
2722 if (ReportFileName != NULL) {
2723 strcpy (ReportFileName, OutImageName);
2724 strcpy (ReportFileName + (FileLen - 4), ".txt");
2725 ReportFile = fopen (ReportFileName, "w+");
2726 if (ReportFile != NULL) {
2727 fprintf (ReportFile, "MODULE_SIZE = %u\n", (unsigned) mImageSize);
2728 fprintf (ReportFile, "TIME_STAMP = %u\n", (unsigned) mImageTimeStamp);
2729 fclose(ReportFile);
2730 }
2731 free (ReportFileName);
2732 }
2733 }
2734 VerboseMsg ("%s tool done with return code is 0x%x.", UTILITY_NAME, GetUtilityStatus ());
2735
2736 return GetUtilityStatus ();
2737 }
2738
2739 STATIC
2740 EFI_STATUS
2741 ZeroDebugData (
2742 IN OUT UINT8 *FileBuffer,
2743 BOOLEAN ZeroDebugFlag
2744 )
2745 /*++
2746
2747 Routine Description:
2748
2749 Zero debug information in PeImage.
2750
2751 Arguments:
2752
2753 FileBuffer - Pointer to PeImage.
2754 ZeroDebugFlag - TRUE to zero Debug information, FALSE to only zero time/stamp
2755
2756 Returns:
2757
2758 EFI_ABORTED - PeImage is invalid.
2759 EFI_SUCCESS - Zero debug data successfully.
2760
2761 --*/
2762 {
2763 UINT32 Index;
2764 UINT32 DebugDirectoryEntryRva;
2765 UINT32 DebugDirectoryEntryFileOffset;
2766 UINT32 ExportDirectoryEntryRva;
2767 UINT32 ExportDirectoryEntryFileOffset;
2768 UINT32 ResourceDirectoryEntryRva;
2769 UINT32 ResourceDirectoryEntryFileOffset;
2770 EFI_IMAGE_DOS_HEADER *DosHdr;
2771 EFI_IMAGE_FILE_HEADER *FileHdr;
2772 EFI_IMAGE_OPTIONAL_HEADER32 *Optional32Hdr;
2773 EFI_IMAGE_OPTIONAL_HEADER64 *Optional64Hdr;
2774 EFI_IMAGE_SECTION_HEADER *SectionHeader;
2775 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *DebugEntry;
2776 UINT32 *NewTimeStamp;
2777
2778 //
2779 // Init variable.
2780 //
2781 DebugDirectoryEntryRva = 0;
2782 ExportDirectoryEntryRva = 0;
2783 ResourceDirectoryEntryRva = 0;
2784 DebugDirectoryEntryFileOffset = 0;
2785 ExportDirectoryEntryFileOffset = 0;
2786 ResourceDirectoryEntryFileOffset = 0;
2787 DosHdr = (EFI_IMAGE_DOS_HEADER *) FileBuffer;
2788 FileHdr = (EFI_IMAGE_FILE_HEADER *) (FileBuffer + DosHdr->e_lfanew + sizeof (UINT32));
2789
2790
2791 DosHdr = (EFI_IMAGE_DOS_HEADER *)FileBuffer;
2792 if (DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
2793 // NO DOS header, must start with PE/COFF header
2794 FileHdr = (EFI_IMAGE_FILE_HEADER *)(FileBuffer + sizeof (UINT32));
2795 } else {
2796 FileHdr = (EFI_IMAGE_FILE_HEADER *)(FileBuffer + DosHdr->e_lfanew + sizeof (UINT32));
2797 }
2798
2799 //
2800 // Get Debug, Export and Resource EntryTable RVA address.
2801 // Resource Directory entry need to review.
2802 //
2803 if (FileHdr->Machine == EFI_IMAGE_MACHINE_IA32) {
2804 Optional32Hdr = (EFI_IMAGE_OPTIONAL_HEADER32 *) ((UINT8*) FileHdr + sizeof (EFI_IMAGE_FILE_HEADER));
2805 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) Optional32Hdr + FileHdr->SizeOfOptionalHeader);
2806 if (Optional32Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_EXPORT && \
2807 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].Size != 0) {
2808 ExportDirectoryEntryRva = Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
2809 }
2810 if (Optional32Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE && \
2811 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size != 0) {
2812 ResourceDirectoryEntryRva = Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
2813 }
2814 if (Optional32Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG && \
2815 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size != 0) {
2816 DebugDirectoryEntryRva = Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
2817 if (ZeroDebugFlag) {
2818 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = 0;
2819 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = 0;
2820 }
2821 }
2822 } else {
2823 Optional64Hdr = (EFI_IMAGE_OPTIONAL_HEADER64 *) ((UINT8*) FileHdr + sizeof (EFI_IMAGE_FILE_HEADER));
2824 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) Optional64Hdr + FileHdr->SizeOfOptionalHeader);
2825 if (Optional64Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_EXPORT && \
2826 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].Size != 0) {
2827 ExportDirectoryEntryRva = Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
2828 }
2829 if (Optional64Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE && \
2830 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size != 0) {
2831 ResourceDirectoryEntryRva = Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
2832 }
2833 if (Optional64Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG && \
2834 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size != 0) {
2835 DebugDirectoryEntryRva = Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
2836 if (ZeroDebugFlag) {
2837 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = 0;
2838 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = 0;
2839 }
2840 }
2841 }
2842
2843 //
2844 // Get DirectoryEntryTable file offset.
2845 //
2846 for (Index = 0; Index < FileHdr->NumberOfSections; Index ++, SectionHeader ++) {
2847 if (DebugDirectoryEntryRva >= SectionHeader->VirtualAddress &&
2848 DebugDirectoryEntryRva < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize) {
2849 DebugDirectoryEntryFileOffset =
2850 DebugDirectoryEntryRva - SectionHeader->VirtualAddress + SectionHeader->PointerToRawData;
2851 }
2852 if (ExportDirectoryEntryRva >= SectionHeader->VirtualAddress &&
2853 ExportDirectoryEntryRva < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize) {
2854 ExportDirectoryEntryFileOffset =
2855 ExportDirectoryEntryRva - SectionHeader->VirtualAddress + SectionHeader->PointerToRawData;
2856 }
2857 if (ResourceDirectoryEntryRva >= SectionHeader->VirtualAddress &&
2858 ResourceDirectoryEntryRva < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize) {
2859 ResourceDirectoryEntryFileOffset =
2860 ResourceDirectoryEntryRva - SectionHeader->VirtualAddress + SectionHeader->PointerToRawData;
2861 }
2862 }
2863
2864 //
2865 //Zero Debug Data and TimeStamp
2866 //
2867 FileHdr->TimeDateStamp = 0;
2868 mImageTimeStamp = 0;
2869 if (ExportDirectoryEntryFileOffset != 0) {
2870 NewTimeStamp = (UINT32 *) (FileBuffer + ExportDirectoryEntryFileOffset + sizeof (UINT32));
2871 *NewTimeStamp = 0;
2872 }
2873
2874 if (ResourceDirectoryEntryFileOffset != 0) {
2875 NewTimeStamp = (UINT32 *) (FileBuffer + ResourceDirectoryEntryFileOffset + sizeof (UINT32));
2876 *NewTimeStamp = 0;
2877 }
2878
2879 if (DebugDirectoryEntryFileOffset != 0) {
2880 DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) (FileBuffer + DebugDirectoryEntryFileOffset);
2881 DebugEntry->TimeDateStamp = 0;
2882 mImageTimeStamp = 0;
2883 if (ZeroDebugFlag) {
2884 memset (FileBuffer + DebugEntry->FileOffset, 0, DebugEntry->SizeOfData);
2885 memset (DebugEntry, 0, sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY));
2886 }
2887 }
2888
2889 return EFI_SUCCESS;
2890 }
2891
2892 STATIC
2893 EFI_STATUS
2894 SetStamp (
2895 IN OUT UINT8 *FileBuffer,
2896 IN CHAR8 *TimeStamp
2897 )
2898 /*++
2899
2900 Routine Description:
2901
2902 Set new time stamp into PeImage FileHdr and Directory table:
2903 Debug, Export and Resource.
2904
2905 Arguments:
2906
2907 FileBuffer - Pointer to PeImage.
2908 TimeStamp - Time stamp string.
2909
2910 Returns:
2911
2912 EFI_INVALID_PARAMETER - TimeStamp format is not recognized.
2913 EFI_SUCCESS - Set new time stamp in this image successfully.
2914
2915 --*/
2916 {
2917 struct tm stime;
2918 struct tm *ptime;
2919 time_t newtime;
2920 UINT32 Index;
2921 UINT32 DebugDirectoryEntryRva;
2922 UINT32 DebugDirectoryEntryFileOffset;
2923 UINT32 ExportDirectoryEntryRva;
2924 UINT32 ExportDirectoryEntryFileOffset;
2925 UINT32 ResourceDirectoryEntryRva;
2926 UINT32 ResourceDirectoryEntryFileOffset;
2927 EFI_IMAGE_DOS_HEADER *DosHdr;
2928 EFI_IMAGE_FILE_HEADER *FileHdr;
2929 EFI_IMAGE_OPTIONAL_HEADER32 *Optional32Hdr;
2930 EFI_IMAGE_OPTIONAL_HEADER64 *Optional64Hdr;
2931 EFI_IMAGE_SECTION_HEADER *SectionHeader;
2932 UINT32 *NewTimeStamp;
2933
2934 //
2935 // Init variable.
2936 //
2937 DebugDirectoryEntryRva = 0;
2938 DebugDirectoryEntryFileOffset = 0;
2939 ExportDirectoryEntryRva = 0;
2940 ExportDirectoryEntryFileOffset = 0;
2941 ResourceDirectoryEntryRva = 0;
2942 ResourceDirectoryEntryFileOffset = 0;
2943 //
2944 // Get time and date that will be set.
2945 //
2946 if (TimeStamp == NULL) {
2947 Error (NULL, 0, 3000, "Invalid", "TimeStamp cannot be NULL.");
2948 return EFI_INVALID_PARAMETER;
2949 }
2950 //
2951 // compare the value with "NOW", if yes, current system time is set.
2952 //
2953 if (stricmp (TimeStamp, "NOW") == 0) {
2954 //
2955 // get system current time and date
2956 //
2957 time (&newtime);
2958 } else {
2959 //
2960 // Check Time Format strictly yyyy-mm-dd 00:00:00
2961 //
2962 for (Index = 0; TimeStamp[Index] != '\0' && Index < 20; Index ++) {
2963 if (Index == 4 || Index == 7) {
2964 if (TimeStamp[Index] == '-') {
2965 continue;
2966 }
2967 } else if (Index == 13 || Index == 16) {
2968 if (TimeStamp[Index] == ':') {
2969 continue;
2970 }
2971 } else if (Index == 10 && TimeStamp[Index] == ' ') {
2972 continue;
2973 } else if ((TimeStamp[Index] < '0') || (TimeStamp[Index] > '9')) {
2974 break;
2975 }
2976 }
2977
2978 if (Index < 19 || TimeStamp[19] != '\0') {
2979 Error (NULL, 0, 1003, "Invalid option value", "Incorrect Time \"%s\"\n Correct Format \"yyyy-mm-dd 00:00:00\"", TimeStamp);
2980 return EFI_INVALID_PARAMETER;
2981 }
2982
2983 //
2984 // get the date and time from TimeStamp
2985 //
2986 if (sscanf (TimeStamp, "%d-%d-%d %d:%d:%d",
2987 &stime.tm_year,
2988 &stime.tm_mon,
2989 &stime.tm_mday,
2990 &stime.tm_hour,
2991 &stime.tm_min,
2992 &stime.tm_sec
2993 ) != 6) {
2994 Error (NULL, 0, 1003, "Invalid option value", "Incorrect Tiem \"%s\"\n Correct Format \"yyyy-mm-dd 00:00:00\"", TimeStamp);
2995 return EFI_INVALID_PARAMETER;
2996 }
2997
2998 //
2999 // in struct, Month (0 - 11; Jan = 0). So decrease 1 from it
3000 //
3001 if (stime.tm_mon <= 0 || stime.tm_mday <=0) {
3002 Error (NULL, 0, 3000, "Invalid", "%s Invalid date!", TimeStamp);
3003 return EFI_INVALID_PARAMETER;
3004 }
3005 stime.tm_mon -= 1;
3006
3007 //
3008 // in struct, Year (current year minus 1900)
3009 // and only the dates can be handled from Jan 1, 1970 to Jan 18, 2038
3010 //
3011 //
3012 // convert 0 -> 100 (2000), 1 -> 101 (2001), ..., 38 -> 138 (2038)
3013 //
3014 if (stime.tm_year >= 1970 && stime.tm_year <= 2038) {
3015 //
3016 // convert 1970 -> 70, 2000 -> 100, ...
3017 //
3018 stime.tm_year -= 1900;
3019 } else {
3020 Error (NULL, 0, 3000, "Invalid", "%s Invalid or unsupported datetime!", TimeStamp);
3021 return EFI_INVALID_PARAMETER;
3022 }
3023
3024 //
3025 // convert the date and time to time_t format
3026 //
3027 newtime = mktime (&stime);
3028 if (newtime == (time_t) - 1) {
3029 Error (NULL, 0, 3000, "Invalid", "%s Invalid or unsupported datetime!", TimeStamp);
3030 return EFI_INVALID_PARAMETER;
3031 }
3032 }
3033
3034 ptime = localtime (&newtime);
3035 DebugMsg (NULL, 0, 9, "New Image Time Stamp", "%04d-%02d-%02d %02d:%02d:%02d",
3036 ptime->tm_year + 1900, ptime->tm_mon + 1, ptime->tm_mday, ptime->tm_hour, ptime->tm_min, ptime->tm_sec);
3037 //
3038 // Set new time and data into PeImage.
3039 //
3040 DosHdr = (EFI_IMAGE_DOS_HEADER *)FileBuffer;
3041 if (DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
3042 // NO DOS header, must start with PE/COFF header
3043 FileHdr = (EFI_IMAGE_FILE_HEADER *)(FileBuffer + sizeof (UINT32));
3044 } else {
3045 FileHdr = (EFI_IMAGE_FILE_HEADER *)(FileBuffer + DosHdr->e_lfanew + sizeof (UINT32));
3046 }
3047
3048 //
3049 // Get Debug, Export and Resource EntryTable RVA address.
3050 // Resource Directory entry need to review.
3051 //
3052 if (FileHdr->Machine == EFI_IMAGE_MACHINE_IA32) {
3053 Optional32Hdr = (EFI_IMAGE_OPTIONAL_HEADER32 *) ((UINT8*) FileHdr + sizeof (EFI_IMAGE_FILE_HEADER));
3054 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) Optional32Hdr + FileHdr->SizeOfOptionalHeader);
3055 if (Optional32Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_EXPORT && \
3056 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].Size != 0) {
3057 ExportDirectoryEntryRva = Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
3058 }
3059 if (Optional32Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE && \
3060 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size != 0) {
3061 ResourceDirectoryEntryRva = Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
3062 }
3063 if (Optional32Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG && \
3064 Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size != 0) {
3065 DebugDirectoryEntryRva = Optional32Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
3066 }
3067 } else {
3068 Optional64Hdr = (EFI_IMAGE_OPTIONAL_HEADER64 *) ((UINT8*) FileHdr + sizeof (EFI_IMAGE_FILE_HEADER));
3069 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) ((UINT8 *) Optional64Hdr + FileHdr->SizeOfOptionalHeader);
3070 if (Optional64Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_EXPORT && \
3071 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].Size != 0) {
3072 ExportDirectoryEntryRva = Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
3073 }
3074 if (Optional64Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE && \
3075 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size != 0) {
3076 ResourceDirectoryEntryRva = Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
3077 }
3078 if (Optional64Hdr->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG && \
3079 Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size != 0) {
3080 DebugDirectoryEntryRva = Optional64Hdr->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
3081 }
3082 }
3083
3084 //
3085 // Get DirectoryEntryTable file offset.
3086 //
3087 for (Index = 0; Index < FileHdr->NumberOfSections; Index ++, SectionHeader ++) {
3088 if (DebugDirectoryEntryRva >= SectionHeader->VirtualAddress &&
3089 DebugDirectoryEntryRva < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize) {
3090 DebugDirectoryEntryFileOffset =
3091 DebugDirectoryEntryRva - SectionHeader->VirtualAddress + SectionHeader->PointerToRawData;
3092 }
3093 if (ExportDirectoryEntryRva >= SectionHeader->VirtualAddress &&
3094 ExportDirectoryEntryRva < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize) {
3095 ExportDirectoryEntryFileOffset =
3096 ExportDirectoryEntryRva - SectionHeader->VirtualAddress + SectionHeader->PointerToRawData;
3097 }
3098 if (ResourceDirectoryEntryRva >= SectionHeader->VirtualAddress &&
3099 ResourceDirectoryEntryRva < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize) {
3100 ResourceDirectoryEntryFileOffset =
3101 ResourceDirectoryEntryRva - SectionHeader->VirtualAddress + SectionHeader->PointerToRawData;
3102 }
3103 }
3104
3105 //
3106 // Set new stamp
3107 //
3108 FileHdr->TimeDateStamp = (UINT32) newtime;
3109 mImageTimeStamp = (UINT32) newtime;
3110 if (ExportDirectoryEntryRva != 0) {
3111 NewTimeStamp = (UINT32 *) (FileBuffer + ExportDirectoryEntryFileOffset + sizeof (UINT32));
3112 *NewTimeStamp = (UINT32) newtime;
3113 }
3114
3115 if (ResourceDirectoryEntryRva != 0) {
3116 NewTimeStamp = (UINT32 *) (FileBuffer + ResourceDirectoryEntryFileOffset + sizeof (UINT32));
3117 *NewTimeStamp = (UINT32) newtime;
3118 }
3119
3120 if (DebugDirectoryEntryRva != 0) {
3121 NewTimeStamp = (UINT32 *) (FileBuffer + DebugDirectoryEntryFileOffset + sizeof (UINT32));
3122 *NewTimeStamp = (UINT32) newtime;
3123 }
3124
3125 return EFI_SUCCESS;
3126 }
3127
3128 STATIC
3129 STATUS
3130 MicrocodeReadData (
3131 FILE *InFptr,
3132 UINT32 *Data
3133 )
3134 /*++
3135
3136 Routine Description:
3137 Read a 32-bit microcode data value from a text file and convert to raw binary form.
3138
3139 Arguments:
3140 InFptr - file pointer to input text file
3141 Data - pointer to where to return the data parsed
3142
3143 Returns:
3144 STATUS_SUCCESS - no errors or warnings, Data contains valid information
3145 STATUS_ERROR - errors were encountered
3146
3147 --*/
3148 {
3149 CHAR8 Line[MAX_LINE_LEN];
3150 CHAR8 *cptr;
3151 unsigned ScannedData = 0;
3152
3153 Line[MAX_LINE_LEN - 1] = 0;
3154 while (1) {
3155 if (fgets (Line, MAX_LINE_LEN, InFptr) == NULL) {
3156 return STATUS_ERROR;
3157 }
3158 //
3159 // If it was a binary file, then it may have overwritten our null terminator
3160 //
3161 if (Line[MAX_LINE_LEN - 1] != 0) {
3162 return STATUS_ERROR;
3163 }
3164
3165 //
3166 // strip space
3167 //
3168 for (cptr = Line; *cptr && isspace((int)*cptr); cptr++) {
3169 }
3170
3171 // Skip Blank Lines and Comment Lines
3172 if ((strlen(cptr) != 0) && (*cptr != ';')) {
3173 break;
3174 }
3175 }
3176
3177 // Look for
3178 // dd 000000001h ; comment
3179 // dd XXXXXXXX
3180 // DD XXXXXXXXX
3181 // DD XXXXXXXXX
3182 //
3183 if ((tolower((int)cptr[0]) == 'd') && (tolower((int)cptr[1]) == 'd') && isspace ((int)cptr[2])) {
3184 //
3185 // Skip blanks and look for a hex digit
3186 //
3187 cptr += 3;
3188 for (; *cptr && isspace((int)*cptr); cptr++) {
3189 }
3190 if (isxdigit ((int)*cptr)) {
3191 if (sscanf (cptr, "%X", &ScannedData) != 1) {
3192 return STATUS_ERROR;
3193 }
3194 }
3195 *Data = (UINT32) ScannedData;
3196 return STATUS_SUCCESS;
3197 }
3198
3199 return STATUS_ERROR;
3200 }