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