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