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