]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFv/GenFvInternalLib.c
7c839e277944db70007060c2c07315e2e6db53cd
[mirror_edk2.git] / BaseTools / Source / C / GenFv / GenFvInternalLib.c
1 /** @file
2 This file contains the internal functions required to generate a Firmware Volume.
3
4 Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
5 Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
6 Portions Copyright (c) 2016 HP Development Company, L.P.<BR>
7 This program and the accompanying materials
8 are licensed and made available under the terms and conditions of the BSD License
9 which accompanies this distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php
11
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14
15 **/
16
17 //
18 // Include files
19 //
20
21 #if defined(__FreeBSD__)
22 #include <uuid.h>
23 #elif defined(__GNUC__)
24 #include <uuid/uuid.h>
25 #endif
26 #ifdef __GNUC__
27 #include <sys/stat.h>
28 #endif
29 #include <string.h>
30 #ifndef __GNUC__
31 #include <io.h>
32 #endif
33 #include <assert.h>
34
35 #include <Guid/FfsSectionAlignmentPadding.h>
36
37 #include "GenFvInternalLib.h"
38 #include "FvLib.h"
39 #include "PeCoffLib.h"
40 #include "WinNtInclude.h"
41
42 #define ARMT_UNCONDITIONAL_JUMP_INSTRUCTION 0xEB000000
43 #define ARM64_UNCONDITIONAL_JUMP_INSTRUCTION 0x14000000
44
45 BOOLEAN mArm = FALSE;
46 STATIC UINT32 MaxFfsAlignment = 0;
47
48 EFI_GUID mEfiFirmwareVolumeTopFileGuid = EFI_FFS_VOLUME_TOP_FILE_GUID;
49 EFI_GUID mFileGuidArray [MAX_NUMBER_OF_FILES_IN_FV];
50 EFI_GUID mZeroGuid = {0x0, 0x0, 0x0, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
51 EFI_GUID mDefaultCapsuleGuid = {0x3B6686BD, 0x0D76, 0x4030, { 0xB7, 0x0E, 0xB5, 0x51, 0x9E, 0x2F, 0xC5, 0xA0 }};
52 EFI_GUID mEfiFfsSectionAlignmentPaddingGuid = EFI_FFS_SECTION_ALIGNMENT_PADDING_GUID;
53
54 CHAR8 *mFvbAttributeName[] = {
55 EFI_FVB2_READ_DISABLED_CAP_STRING,
56 EFI_FVB2_READ_ENABLED_CAP_STRING,
57 EFI_FVB2_READ_STATUS_STRING,
58 EFI_FVB2_WRITE_DISABLED_CAP_STRING,
59 EFI_FVB2_WRITE_ENABLED_CAP_STRING,
60 EFI_FVB2_WRITE_STATUS_STRING,
61 EFI_FVB2_LOCK_CAP_STRING,
62 EFI_FVB2_LOCK_STATUS_STRING,
63 NULL,
64 EFI_FVB2_STICKY_WRITE_STRING,
65 EFI_FVB2_MEMORY_MAPPED_STRING,
66 EFI_FVB2_ERASE_POLARITY_STRING,
67 EFI_FVB2_READ_LOCK_CAP_STRING,
68 EFI_FVB2_READ_LOCK_STATUS_STRING,
69 EFI_FVB2_WRITE_LOCK_CAP_STRING,
70 EFI_FVB2_WRITE_LOCK_STATUS_STRING
71 };
72
73 CHAR8 *mFvbAlignmentName[] = {
74 EFI_FVB2_ALIGNMENT_1_STRING,
75 EFI_FVB2_ALIGNMENT_2_STRING,
76 EFI_FVB2_ALIGNMENT_4_STRING,
77 EFI_FVB2_ALIGNMENT_8_STRING,
78 EFI_FVB2_ALIGNMENT_16_STRING,
79 EFI_FVB2_ALIGNMENT_32_STRING,
80 EFI_FVB2_ALIGNMENT_64_STRING,
81 EFI_FVB2_ALIGNMENT_128_STRING,
82 EFI_FVB2_ALIGNMENT_256_STRING,
83 EFI_FVB2_ALIGNMENT_512_STRING,
84 EFI_FVB2_ALIGNMENT_1K_STRING,
85 EFI_FVB2_ALIGNMENT_2K_STRING,
86 EFI_FVB2_ALIGNMENT_4K_STRING,
87 EFI_FVB2_ALIGNMENT_8K_STRING,
88 EFI_FVB2_ALIGNMENT_16K_STRING,
89 EFI_FVB2_ALIGNMENT_32K_STRING,
90 EFI_FVB2_ALIGNMENT_64K_STRING,
91 EFI_FVB2_ALIGNMENT_128K_STRING,
92 EFI_FVB2_ALIGNMENT_256K_STRING,
93 EFI_FVB2_ALIGNMENT_512K_STRING,
94 EFI_FVB2_ALIGNMENT_1M_STRING,
95 EFI_FVB2_ALIGNMENT_2M_STRING,
96 EFI_FVB2_ALIGNMENT_4M_STRING,
97 EFI_FVB2_ALIGNMENT_8M_STRING,
98 EFI_FVB2_ALIGNMENT_16M_STRING,
99 EFI_FVB2_ALIGNMENT_32M_STRING,
100 EFI_FVB2_ALIGNMENT_64M_STRING,
101 EFI_FVB2_ALIGNMENT_128M_STRING,
102 EFI_FVB2_ALIGNMENT_256M_STRING,
103 EFI_FVB2_ALIGNMENT_512M_STRING,
104 EFI_FVB2_ALIGNMENT_1G_STRING,
105 EFI_FVB2_ALIGNMENT_2G_STRING
106 };
107
108 //
109 // This data array will be located at the base of the Firmware Volume Header (FVH)
110 // in the boot block. It must not exceed 14 bytes of code. The last 2 bytes
111 // will be used to keep the FVH checksum consistent.
112 // This code will be run in response to a starutp IPI for HT-enabled systems.
113 //
114 #define SIZEOF_STARTUP_DATA_ARRAY 0x10
115
116 UINT8 m128kRecoveryStartupApDataArray[SIZEOF_STARTUP_DATA_ARRAY] = {
117 //
118 // EA D0 FF 00 F0 ; far jmp F000:FFD0
119 // 0, 0, 0, 0, 0, 0, 0, 0, 0, ; Reserved bytes
120 // 0, 0 ; Checksum Padding
121 //
122 0xEA,
123 0xD0,
124 0xFF,
125 0x0,
126 0xF0,
127 0x00,
128 0x00,
129 0x00,
130 0x00,
131 0x00,
132 0x00,
133 0x00,
134 0x00,
135 0x00,
136 0x00,
137 0x00
138 };
139
140 UINT8 m64kRecoveryStartupApDataArray[SIZEOF_STARTUP_DATA_ARRAY] = {
141 //
142 // EB CE ; jmp short ($-0x30)
143 // ; (from offset 0x0 to offset 0xFFD0)
144 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ; Reserved bytes
145 // 0, 0 ; Checksum Padding
146 //
147 0xEB,
148 0xCE,
149 0x00,
150 0x00,
151 0x00,
152 0x00,
153 0x00,
154 0x00,
155 0x00,
156 0x00,
157 0x00,
158 0x00,
159 0x00,
160 0x00,
161 0x00,
162 0x00
163 };
164
165 FV_INFO mFvDataInfo;
166 CAP_INFO mCapDataInfo;
167 BOOLEAN mIsLargeFfs = FALSE;
168
169 EFI_PHYSICAL_ADDRESS mFvBaseAddress[0x10];
170 UINT32 mFvBaseAddressNumber = 0;
171
172 EFI_STATUS
173 ParseFvInf (
174 IN MEMORY_FILE *InfFile,
175 OUT FV_INFO *FvInfo
176 )
177 /*++
178
179 Routine Description:
180
181 This function parses a FV.INF file and copies info into a FV_INFO structure.
182
183 Arguments:
184
185 InfFile Memory file image.
186 FvInfo Information read from INF file.
187
188 Returns:
189
190 EFI_SUCCESS INF file information successfully retrieved.
191 EFI_ABORTED INF file has an invalid format.
192 EFI_NOT_FOUND A required string was not found in the INF file.
193 --*/
194 {
195 CHAR8 Value[MAX_LONG_FILE_PATH];
196 UINT64 Value64;
197 UINTN Index;
198 UINTN Number;
199 EFI_STATUS Status;
200 EFI_GUID GuidValue;
201
202 //
203 // Read the FV base address
204 //
205 if (!mFvDataInfo.BaseAddressSet) {
206 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_FV_BASE_ADDRESS_STRING, 0, Value);
207 if (Status == EFI_SUCCESS) {
208 //
209 // Get the base address
210 //
211 Status = AsciiStringToUint64 (Value, FALSE, &Value64);
212 if (EFI_ERROR (Status)) {
213 Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_FV_BASE_ADDRESS_STRING, Value);
214 return EFI_ABORTED;
215 }
216 DebugMsg (NULL, 0, 9, "rebase address", "%s = %s", EFI_FV_BASE_ADDRESS_STRING, Value);
217
218 FvInfo->BaseAddress = Value64;
219 FvInfo->BaseAddressSet = TRUE;
220 }
221 }
222
223 //
224 // Read the FV File System Guid
225 //
226 if (!FvInfo->FvFileSystemGuidSet) {
227 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_FV_FILESYSTEMGUID_STRING, 0, Value);
228 if (Status == EFI_SUCCESS) {
229 //
230 // Get the guid value
231 //
232 Status = StringToGuid (Value, &GuidValue);
233 if (EFI_ERROR (Status)) {
234 Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_FV_FILESYSTEMGUID_STRING, Value);
235 return EFI_ABORTED;
236 }
237 memcpy (&FvInfo->FvFileSystemGuid, &GuidValue, sizeof (EFI_GUID));
238 FvInfo->FvFileSystemGuidSet = TRUE;
239 }
240 }
241
242 //
243 // Read the FV Extension Header File Name
244 //
245 Status = FindToken (InfFile, ATTRIBUTES_SECTION_STRING, EFI_FV_EXT_HEADER_FILE_NAME, 0, Value);
246 if (Status == EFI_SUCCESS) {
247 strcpy (FvInfo->FvExtHeaderFile, Value);
248 }
249
250 //
251 // Read the FV file name
252 //
253 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_FV_FILE_NAME_STRING, 0, Value);
254 if (Status == EFI_SUCCESS) {
255 //
256 // copy the file name
257 //
258 strcpy (FvInfo->FvName, Value);
259 }
260
261 //
262 // Read Fv Attribute
263 //
264 for (Index = 0; Index < sizeof (mFvbAttributeName)/sizeof (CHAR8 *); Index ++) {
265 if ((mFvbAttributeName [Index] != NULL) && \
266 (FindToken (InfFile, ATTRIBUTES_SECTION_STRING, mFvbAttributeName [Index], 0, Value) == EFI_SUCCESS)) {
267 if ((strcmp (Value, TRUE_STRING) == 0) || (strcmp (Value, ONE_STRING) == 0)) {
268 FvInfo->FvAttributes |= 1 << Index;
269 } else if ((strcmp (Value, FALSE_STRING) != 0) && (strcmp (Value, ZERO_STRING) != 0)) {
270 Error (NULL, 0, 2000, "Invalid parameter", "%s expected %s | %s", mFvbAttributeName [Index], TRUE_STRING, FALSE_STRING);
271 return EFI_ABORTED;
272 }
273 }
274 }
275
276 //
277 // Read Fv Alignment
278 //
279 for (Index = 0; Index < sizeof (mFvbAlignmentName)/sizeof (CHAR8 *); Index ++) {
280 if (FindToken (InfFile, ATTRIBUTES_SECTION_STRING, mFvbAlignmentName [Index], 0, Value) == EFI_SUCCESS) {
281 if (strcmp (Value, TRUE_STRING) == 0) {
282 FvInfo->FvAttributes |= Index << 16;
283 DebugMsg (NULL, 0, 9, "FV file alignment", "Align = %s", mFvbAlignmentName [Index]);
284 break;
285 }
286 }
287 }
288
289 //
290 // Read weak alignment flag
291 //
292 Status = FindToken (InfFile, ATTRIBUTES_SECTION_STRING, EFI_FV_WEAK_ALIGNMENT_STRING, 0, Value);
293 if (Status == EFI_SUCCESS) {
294 if ((strcmp (Value, TRUE_STRING) == 0) || (strcmp (Value, ONE_STRING) == 0)) {
295 FvInfo->FvAttributes |= EFI_FVB2_WEAK_ALIGNMENT;
296 } else if ((strcmp (Value, FALSE_STRING) != 0) && (strcmp (Value, ZERO_STRING) != 0)) {
297 Error (NULL, 0, 2000, "Invalid parameter", "Weak alignment value expected one of TRUE, FALSE, 1 or 0.");
298 return EFI_ABORTED;
299 }
300 }
301
302 //
303 // Read block maps
304 //
305 for (Index = 0; Index < MAX_NUMBER_OF_FV_BLOCKS; Index++) {
306 if (FvInfo->FvBlocks[Index].Length == 0) {
307 //
308 // Read block size
309 //
310 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_BLOCK_SIZE_STRING, Index, Value);
311
312 if (Status == EFI_SUCCESS) {
313 //
314 // Update the size of block
315 //
316 Status = AsciiStringToUint64 (Value, FALSE, &Value64);
317 if (EFI_ERROR (Status)) {
318 Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_BLOCK_SIZE_STRING, Value);
319 return EFI_ABORTED;
320 }
321
322 FvInfo->FvBlocks[Index].Length = (UINT32) Value64;
323 DebugMsg (NULL, 0, 9, "FV Block Size", "%s = %s", EFI_BLOCK_SIZE_STRING, Value);
324 } else {
325 //
326 // If there is no blocks size, but there is the number of block, then we have a mismatched pair
327 // and should return an error.
328 //
329 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_NUM_BLOCKS_STRING, Index, Value);
330 if (!EFI_ERROR (Status)) {
331 Error (NULL, 0, 2000, "Invalid parameter", "both %s and %s must be specified.", EFI_NUM_BLOCKS_STRING, EFI_BLOCK_SIZE_STRING);
332 return EFI_ABORTED;
333 } else {
334 //
335 // We are done
336 //
337 break;
338 }
339 }
340
341 //
342 // Read blocks number
343 //
344 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_NUM_BLOCKS_STRING, Index, Value);
345
346 if (Status == EFI_SUCCESS) {
347 //
348 // Update the number of blocks
349 //
350 Status = AsciiStringToUint64 (Value, FALSE, &Value64);
351 if (EFI_ERROR (Status)) {
352 Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_NUM_BLOCKS_STRING, Value);
353 return EFI_ABORTED;
354 }
355
356 FvInfo->FvBlocks[Index].NumBlocks = (UINT32) Value64;
357 DebugMsg (NULL, 0, 9, "FV Block Number", "%s = %s", EFI_NUM_BLOCKS_STRING, Value);
358 }
359 }
360 }
361
362 if (Index == 0) {
363 Error (NULL, 0, 2001, "Missing required argument", "block size.");
364 return EFI_ABORTED;
365 }
366
367 //
368 // Read files
369 //
370 Number = 0;
371 for (Number = 0; Number < MAX_NUMBER_OF_FILES_IN_FV; Number ++) {
372 if (FvInfo->FvFiles[Number][0] == '\0') {
373 break;
374 }
375 }
376
377 for (Index = 0; Index < MAX_NUMBER_OF_FILES_IN_FV; Index++) {
378 //
379 // Read the FFS file list
380 //
381 Status = FindToken (InfFile, FILES_SECTION_STRING, EFI_FILE_NAME_STRING, Index, Value);
382
383 if (Status == EFI_SUCCESS) {
384 //
385 // Add the file
386 //
387 strcpy (FvInfo->FvFiles[Number + Index], Value);
388 DebugMsg (NULL, 0, 9, "FV component file", "the %uth name is %s", (unsigned) Index, Value);
389 } else {
390 break;
391 }
392 }
393
394 if ((Index + Number) == 0) {
395 Warning (NULL, 0, 0, "FV components are not specified.", NULL);
396 }
397
398 return EFI_SUCCESS;
399 }
400
401 VOID
402 UpdateFfsFileState (
403 IN EFI_FFS_FILE_HEADER *FfsFile,
404 IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader
405 )
406 /*++
407
408 Routine Description:
409
410 This function changes the FFS file attributes based on the erase polarity
411 of the FV. Update the reserved bits of State to EFI_FVB2_ERASE_POLARITY.
412
413 Arguments:
414
415 FfsFile File header.
416 FvHeader FV header.
417
418 Returns:
419
420 None
421
422 --*/
423 {
424 if (FvHeader->Attributes & EFI_FVB2_ERASE_POLARITY) {
425 FfsFile->State = (UINT8)~(FfsFile->State);
426 // FfsFile->State |= ~(UINT8) EFI_FILE_ALL_STATE_BITS;
427 }
428 }
429
430 EFI_STATUS
431 ReadFfsAlignment (
432 IN EFI_FFS_FILE_HEADER *FfsFile,
433 IN OUT UINT32 *Alignment
434 )
435 /*++
436
437 Routine Description:
438
439 This function determines the alignment of the FFS input file from the file
440 attributes.
441
442 Arguments:
443
444 FfsFile FFS file to parse
445 Alignment The minimum required alignment offset of the FFS file
446
447 Returns:
448
449 EFI_SUCCESS The function completed successfully.
450 EFI_INVALID_PARAMETER One of the input parameters was invalid.
451 EFI_ABORTED An error occurred.
452
453 --*/
454 {
455 //
456 // Verify input parameters.
457 //
458 if (FfsFile == NULL || Alignment == NULL) {
459 return EFI_INVALID_PARAMETER;
460 }
461
462 switch ((FfsFile->Attributes >> 3) & 0x07) {
463
464 case 0:
465 //
466 // 1 byte alignment
467 //
468 *Alignment = 0;
469 break;
470
471 case 1:
472 //
473 // 16 byte alignment
474 //
475 *Alignment = 4;
476 break;
477
478 case 2:
479 //
480 // 128 byte alignment
481 //
482 *Alignment = 7;
483 break;
484
485 case 3:
486 //
487 // 512 byte alignment
488 //
489 *Alignment = 9;
490 break;
491
492 case 4:
493 //
494 // 1K byte alignment
495 //
496 *Alignment = 10;
497 break;
498
499 case 5:
500 //
501 // 4K byte alignment
502 //
503 *Alignment = 12;
504 break;
505
506 case 6:
507 //
508 // 32K byte alignment
509 //
510 *Alignment = 15;
511 break;
512
513 case 7:
514 //
515 // 64K byte alignment
516 //
517 *Alignment = 16;
518 break;
519
520 default:
521 break;
522 }
523
524 return EFI_SUCCESS;
525 }
526
527 EFI_STATUS
528 AddPadFile (
529 IN OUT MEMORY_FILE *FvImage,
530 IN UINT32 DataAlignment,
531 IN VOID *FvEnd,
532 IN EFI_FIRMWARE_VOLUME_EXT_HEADER *ExtHeader,
533 IN UINT32 NextFfsSize
534 )
535 /*++
536
537 Routine Description:
538
539 This function adds a pad file to the FV image if it required to align the
540 data of the next file.
541
542 Arguments:
543
544 FvImage The memory image of the FV to add it to.
545 The current offset must be valid.
546 DataAlignment The data alignment of the next FFS file.
547 FvEnd End of the empty data in FvImage.
548 ExtHeader PI FvExtHeader Optional
549
550 Returns:
551
552 EFI_SUCCESS The function completed successfully.
553 EFI_INVALID_PARAMETER One of the input parameters was invalid.
554 EFI_OUT_OF_RESOURCES Insufficient resources exist in the FV to complete
555 the pad file add.
556
557 --*/
558 {
559 EFI_FFS_FILE_HEADER *PadFile;
560 UINTN PadFileSize;
561 UINT32 NextFfsHeaderSize;
562 UINT32 CurFfsHeaderSize;
563
564 CurFfsHeaderSize = sizeof (EFI_FFS_FILE_HEADER);
565 //
566 // Verify input parameters.
567 //
568 if (FvImage == NULL) {
569 return EFI_INVALID_PARAMETER;
570 }
571
572 //
573 // Calculate the pad file size
574 //
575
576 //
577 // Append extension header size
578 //
579 if (ExtHeader != NULL) {
580 PadFileSize = ExtHeader->ExtHeaderSize;
581 if (PadFileSize + sizeof (EFI_FFS_FILE_HEADER) >= MAX_FFS_SIZE) {
582 CurFfsHeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
583 }
584 PadFileSize += CurFfsHeaderSize;
585 } else {
586 NextFfsHeaderSize = sizeof (EFI_FFS_FILE_HEADER);
587 if (NextFfsSize >= MAX_FFS_SIZE) {
588 NextFfsHeaderSize = sizeof (EFI_FFS_FILE_HEADER2);
589 }
590 //
591 // Check if a pad file is necessary
592 //
593 if (((UINTN) FvImage->CurrentFilePointer - (UINTN) FvImage->FileImage + NextFfsHeaderSize) % DataAlignment == 0) {
594 return EFI_SUCCESS;
595 }
596 PadFileSize = (UINTN) FvImage->CurrentFilePointer - (UINTN) FvImage->FileImage + sizeof (EFI_FFS_FILE_HEADER) + NextFfsHeaderSize;
597 //
598 // Add whatever it takes to get to the next aligned address
599 //
600 while ((PadFileSize % DataAlignment) != 0) {
601 PadFileSize++;
602 }
603 //
604 // Subtract the next file header size
605 //
606 PadFileSize -= NextFfsHeaderSize;
607 //
608 // Subtract the starting offset to get size
609 //
610 PadFileSize -= (UINTN) FvImage->CurrentFilePointer - (UINTN) FvImage->FileImage;
611 }
612
613 //
614 // Verify that we have enough space for the file header
615 //
616 if (((UINTN) FvImage->CurrentFilePointer + PadFileSize) > (UINTN) FvEnd) {
617 return EFI_OUT_OF_RESOURCES;
618 }
619
620 //
621 // Write pad file header
622 //
623 PadFile = (EFI_FFS_FILE_HEADER *) FvImage->CurrentFilePointer;
624
625 //
626 // Write PadFile FFS header with PadType, don't need to set PAD file guid in its header.
627 //
628 PadFile->Type = EFI_FV_FILETYPE_FFS_PAD;
629 PadFile->Attributes = 0;
630
631 //
632 // Write pad file size (calculated size minus next file header size)
633 //
634 if (PadFileSize >= MAX_FFS_SIZE) {
635 memset(PadFile->Size, 0, sizeof(UINT8) * 3);
636 ((EFI_FFS_FILE_HEADER2 *)PadFile)->ExtendedSize = PadFileSize;
637 PadFile->Attributes |= FFS_ATTRIB_LARGE_FILE;
638 } else {
639 PadFile->Size[0] = (UINT8) (PadFileSize & 0xFF);
640 PadFile->Size[1] = (UINT8) ((PadFileSize >> 8) & 0xFF);
641 PadFile->Size[2] = (UINT8) ((PadFileSize >> 16) & 0xFF);
642 }
643
644 //
645 // Fill in checksums and state, they must be 0 for checksumming.
646 //
647 PadFile->IntegrityCheck.Checksum.Header = 0;
648 PadFile->IntegrityCheck.Checksum.File = 0;
649 PadFile->State = 0;
650 PadFile->IntegrityCheck.Checksum.Header = CalculateChecksum8 ((UINT8 *) PadFile, CurFfsHeaderSize);
651 PadFile->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
652
653 PadFile->State = EFI_FILE_HEADER_CONSTRUCTION | EFI_FILE_HEADER_VALID | EFI_FILE_DATA_VALID;
654 UpdateFfsFileState (
655 (EFI_FFS_FILE_HEADER *) PadFile,
656 (EFI_FIRMWARE_VOLUME_HEADER *) FvImage->FileImage
657 );
658
659 //
660 // Update the current FV pointer
661 //
662 FvImage->CurrentFilePointer += PadFileSize;
663
664 if (ExtHeader != NULL) {
665 //
666 // Copy Fv Extension Header and Set Fv Extension header offset
667 //
668 memcpy ((UINT8 *)PadFile + CurFfsHeaderSize, ExtHeader, ExtHeader->ExtHeaderSize);
669 ((EFI_FIRMWARE_VOLUME_HEADER *) FvImage->FileImage)->ExtHeaderOffset = (UINT16) ((UINTN) ((UINT8 *)PadFile + CurFfsHeaderSize) - (UINTN) FvImage->FileImage);
670 //
671 // Make next file start at QWord Boundry
672 //
673 while (((UINTN) FvImage->CurrentFilePointer & (EFI_FFS_FILE_HEADER_ALIGNMENT - 1)) != 0) {
674 FvImage->CurrentFilePointer++;
675 }
676 }
677
678 return EFI_SUCCESS;
679 }
680
681 BOOLEAN
682 IsVtfFile (
683 IN EFI_FFS_FILE_HEADER *FileBuffer
684 )
685 /*++
686
687 Routine Description:
688
689 This function checks the header to validate if it is a VTF file
690
691 Arguments:
692
693 FileBuffer Buffer in which content of a file has been read.
694
695 Returns:
696
697 TRUE If this is a VTF file
698 FALSE If this is not a VTF file
699
700 --*/
701 {
702 if (!memcmp (&FileBuffer->Name, &mEfiFirmwareVolumeTopFileGuid, sizeof (EFI_GUID))) {
703 return TRUE;
704 } else {
705 return FALSE;
706 }
707 }
708
709 EFI_STATUS
710 WriteMapFile (
711 IN OUT FILE *FvMapFile,
712 IN CHAR8 *FileName,
713 IN EFI_FFS_FILE_HEADER *FfsFile,
714 IN EFI_PHYSICAL_ADDRESS ImageBaseAddress,
715 IN PE_COFF_LOADER_IMAGE_CONTEXT *pImageContext
716 )
717 /*++
718
719 Routine Description:
720
721 This function gets the basic debug information (entrypoint, baseaddress, .text, .data section base address)
722 from PE/COFF image and abstracts Pe Map file information and add them into FvMap file for Debug.
723
724 Arguments:
725
726 FvMapFile A pointer to FvMap File
727 FileName Ffs File PathName
728 FfsFile A pointer to Ffs file image.
729 ImageBaseAddress PeImage Base Address.
730 pImageContext Image Context Information.
731
732 Returns:
733
734 EFI_SUCCESS Added required map information.
735
736 --*/
737 {
738 CHAR8 PeMapFileName [MAX_LONG_FILE_PATH];
739 CHAR8 *Cptr, *Cptr2;
740 CHAR8 FileGuidName [MAX_LINE_LEN];
741 FILE *PeMapFile;
742 CHAR8 Line [MAX_LINE_LEN];
743 CHAR8 KeyWord [MAX_LINE_LEN];
744 CHAR8 FunctionName [MAX_LINE_LEN];
745 EFI_PHYSICAL_ADDRESS FunctionAddress;
746 UINT32 FunctionType;
747 CHAR8 FunctionTypeName [MAX_LINE_LEN];
748 UINT32 Index;
749 UINT32 AddressOfEntryPoint;
750 UINT32 Offset;
751 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
752 EFI_TE_IMAGE_HEADER *TEImageHeader;
753 EFI_IMAGE_SECTION_HEADER *SectionHeader;
754 unsigned long long TempLongAddress;
755 UINT32 TextVirtualAddress;
756 UINT32 DataVirtualAddress;
757 EFI_PHYSICAL_ADDRESS LinkTimeBaseAddress;
758
759 //
760 // Init local variable
761 //
762 FunctionType = 0;
763 //
764 // Print FileGuid to string buffer.
765 //
766 PrintGuidToBuffer (&FfsFile->Name, (UINT8 *)FileGuidName, MAX_LINE_LEN, TRUE);
767
768 //
769 // Construct Map file Name
770 //
771 strcpy (PeMapFileName, FileName);
772
773 //
774 // Change '\\' to '/', unified path format.
775 //
776 Cptr = PeMapFileName;
777 while (*Cptr != '\0') {
778 if (*Cptr == '\\') {
779 *Cptr = FILE_SEP_CHAR;
780 }
781 Cptr ++;
782 }
783
784 //
785 // Get Map file
786 //
787 Cptr = PeMapFileName + strlen (PeMapFileName);
788 while ((*Cptr != '.') && (Cptr >= PeMapFileName)) {
789 Cptr --;
790 }
791 if (Cptr < PeMapFileName) {
792 return EFI_NOT_FOUND;
793 } else {
794 *(Cptr + 1) = 'm';
795 *(Cptr + 2) = 'a';
796 *(Cptr + 3) = 'p';
797 *(Cptr + 4) = '\0';
798 }
799
800 //
801 // Get module Name
802 //
803 Cptr2 = Cptr;
804 while ((*Cptr != FILE_SEP_CHAR) && (Cptr >= PeMapFileName)) {
805 Cptr --;
806 }
807 *Cptr2 = '\0';
808 strcpy (KeyWord, Cptr + 1);
809 *Cptr2 = '.';
810
811 //
812 // AddressOfEntryPoint and Offset in Image
813 //
814 if (!pImageContext->IsTeImage) {
815 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *) ((UINT8 *) pImageContext->Handle + pImageContext->PeCoffHeaderOffset);
816 AddressOfEntryPoint = ImgHdr->Pe32.OptionalHeader.AddressOfEntryPoint;
817 Offset = 0;
818 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (
819 (UINT8 *) ImgHdr +
820 sizeof (UINT32) +
821 sizeof (EFI_IMAGE_FILE_HEADER) +
822 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader
823 );
824 Index = ImgHdr->Pe32.FileHeader.NumberOfSections;
825 } else {
826 TEImageHeader = (EFI_TE_IMAGE_HEADER *) pImageContext->Handle;
827 AddressOfEntryPoint = TEImageHeader->AddressOfEntryPoint;
828 Offset = TEImageHeader->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);
829 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (TEImageHeader + 1);
830 Index = TEImageHeader->NumberOfSections;
831 }
832
833 //
834 // module information output
835 //
836 if (ImageBaseAddress == 0) {
837 fprintf (FvMapFile, "%s (dummy) (", KeyWord);
838 fprintf (FvMapFile, "BaseAddress=%010llx, ", (unsigned long long) ImageBaseAddress);
839 } else {
840 fprintf (FvMapFile, "%s (Fixed Flash Address, ", KeyWord);
841 fprintf (FvMapFile, "BaseAddress=0x%010llx, ", (unsigned long long) (ImageBaseAddress + Offset));
842 }
843
844 if (FfsFile->Type != EFI_FV_FILETYPE_SECURITY_CORE && pImageContext->Machine == EFI_IMAGE_MACHINE_IA64) {
845 //
846 // Process IPF PLABEL to get the real address after the image has been rebased.
847 // PLABEL structure is got by AddressOfEntryPoint offset to ImageBuffer stored in pImageContext->Handle.
848 //
849 fprintf (FvMapFile, "EntryPoint=0x%010llx", (unsigned long long) (*(UINT64 *)((UINTN) pImageContext->Handle + (UINTN) AddressOfEntryPoint)));
850 } else {
851 fprintf (FvMapFile, "EntryPoint=0x%010llx", (unsigned long long) (ImageBaseAddress + AddressOfEntryPoint));
852 }
853 fprintf (FvMapFile, ")\n");
854
855 fprintf (FvMapFile, "(GUID=%s", FileGuidName);
856 TextVirtualAddress = 0;
857 DataVirtualAddress = 0;
858 for (; Index > 0; Index --, SectionHeader ++) {
859 if (stricmp ((CHAR8 *)SectionHeader->Name, ".text") == 0) {
860 TextVirtualAddress = SectionHeader->VirtualAddress;
861 } else if (stricmp ((CHAR8 *)SectionHeader->Name, ".data") == 0) {
862 DataVirtualAddress = SectionHeader->VirtualAddress;
863 } else if (stricmp ((CHAR8 *)SectionHeader->Name, ".sdata") == 0) {
864 DataVirtualAddress = SectionHeader->VirtualAddress;
865 }
866 }
867 fprintf (FvMapFile, " .textbaseaddress=0x%010llx", (unsigned long long) (ImageBaseAddress + TextVirtualAddress));
868 fprintf (FvMapFile, " .databaseaddress=0x%010llx", (unsigned long long) (ImageBaseAddress + DataVirtualAddress));
869 fprintf (FvMapFile, ")\n\n");
870
871 //
872 // Open PeMapFile
873 //
874 PeMapFile = fopen (LongFilePath (PeMapFileName), "r");
875 if (PeMapFile == NULL) {
876 // fprintf (stdout, "can't open %s file to reading\n", PeMapFileName);
877 return EFI_ABORTED;
878 }
879 VerboseMsg ("The map file is %s", PeMapFileName);
880
881 //
882 // Output Functions information into Fv Map file
883 //
884 LinkTimeBaseAddress = 0;
885 while (fgets (Line, MAX_LINE_LEN, PeMapFile) != NULL) {
886 //
887 // Skip blank line
888 //
889 if (Line[0] == 0x0a) {
890 FunctionType = 0;
891 continue;
892 }
893 //
894 // By Address and Static keyword
895 //
896 if (FunctionType == 0) {
897 sscanf (Line, "%s", KeyWord);
898 if (stricmp (KeyWord, "Address") == 0) {
899 //
900 // function list
901 //
902 FunctionType = 1;
903 fgets (Line, MAX_LINE_LEN, PeMapFile);
904 } else if (stricmp (KeyWord, "Static") == 0) {
905 //
906 // static function list
907 //
908 FunctionType = 2;
909 fgets (Line, MAX_LINE_LEN, PeMapFile);
910 } else if (stricmp (KeyWord, "Preferred") ==0) {
911 sscanf (Line + strlen (" Preferred load address is"), "%llx", &TempLongAddress);
912 LinkTimeBaseAddress = (UINT64) TempLongAddress;
913 }
914 continue;
915 }
916 //
917 // Printf Function Information
918 //
919 if (FunctionType == 1) {
920 sscanf (Line, "%s %s %llx %s", KeyWord, FunctionName, &TempLongAddress, FunctionTypeName);
921 FunctionAddress = (UINT64) TempLongAddress;
922 if (FunctionTypeName [1] == '\0' && (FunctionTypeName [0] == 'f' || FunctionTypeName [0] == 'F')) {
923 fprintf (FvMapFile, " 0x%010llx ", (unsigned long long) (ImageBaseAddress + FunctionAddress - LinkTimeBaseAddress));
924 fprintf (FvMapFile, "%s\n", FunctionName);
925 }
926 } else if (FunctionType == 2) {
927 sscanf (Line, "%s %s %llx %s", KeyWord, FunctionName, &TempLongAddress, FunctionTypeName);
928 FunctionAddress = (UINT64) TempLongAddress;
929 if (FunctionTypeName [1] == '\0' && (FunctionTypeName [0] == 'f' || FunctionTypeName [0] == 'F')) {
930 fprintf (FvMapFile, " 0x%010llx ", (unsigned long long) (ImageBaseAddress + FunctionAddress - LinkTimeBaseAddress));
931 fprintf (FvMapFile, "%s\n", FunctionName);
932 }
933 }
934 }
935 //
936 // Close PeMap file
937 //
938 fprintf (FvMapFile, "\n\n");
939 fclose (PeMapFile);
940
941 return EFI_SUCCESS;
942 }
943
944 STATIC
945 BOOLEAN
946 AdjustInternalFfsPadding (
947 IN OUT EFI_FFS_FILE_HEADER *FfsFile,
948 IN OUT MEMORY_FILE *FvImage,
949 IN UINTN Alignment,
950 IN OUT UINTN *FileSize
951 )
952 /*++
953
954 Routine Description:
955
956 This function looks for a dedicated alignment padding section in the FFS, and
957 shrinks it to the size required to line up subsequent sections correctly.
958
959 Arguments:
960
961 FfsFile A pointer to Ffs file image.
962 FvImage The memory image of the FV to adjust it to.
963 Alignment Current file alignment
964 FileSize Reference to a variable holding the size of the FFS file
965
966 Returns:
967
968 TRUE Padding section was found and updated successfully
969 FALSE Otherwise
970
971 --*/
972 {
973 EFI_FILE_SECTION_POINTER PadSection;
974 UINT8 *Remainder;
975 EFI_STATUS Status;
976 UINT32 FfsHeaderLength;
977 UINT32 FfsFileLength;
978 UINT32 PadSize;
979 UINTN Misalignment;
980 EFI_FFS_INTEGRITY_CHECK *IntegrityCheck;
981
982 //
983 // Figure out the misalignment: all FFS sections are aligned relative to the
984 // start of the FFS payload, so use that as the base of the misalignment
985 // computation.
986 //
987 FfsHeaderLength = GetFfsHeaderLength(FfsFile);
988 Misalignment = (UINTN) FvImage->CurrentFilePointer -
989 (UINTN) FvImage->FileImage + FfsHeaderLength;
990 Misalignment &= Alignment - 1;
991 if (Misalignment == 0) {
992 // Nothing to do, return success
993 return TRUE;
994 }
995
996 //
997 // We only apply this optimization to FFS files with the FIXED attribute set,
998 // since the FFS will not be loadable at arbitrary offsets anymore after
999 // we adjust the size of the padding section.
1000 //
1001 if ((FfsFile->Attributes & FFS_ATTRIB_FIXED) == 0) {
1002 return FALSE;
1003 }
1004
1005 //
1006 // Look for a dedicated padding section that we can adjust to compensate
1007 // for the misalignment. If such a padding section exists, it precedes all
1008 // sections with alignment requirements, and so the adjustment will correct
1009 // all of them.
1010 //
1011 Status = GetSectionByType (FfsFile, EFI_SECTION_FREEFORM_SUBTYPE_GUID, 1,
1012 &PadSection);
1013 if (EFI_ERROR (Status) ||
1014 CompareGuid (&PadSection.FreeformSubtypeSection->SubTypeGuid,
1015 &mEfiFfsSectionAlignmentPaddingGuid) != 0) {
1016 return FALSE;
1017 }
1018
1019 //
1020 // Find out if the size of the padding section is sufficient to compensate
1021 // for the misalignment.
1022 //
1023 PadSize = GetSectionFileLength (PadSection.CommonHeader);
1024 if (Misalignment > PadSize - sizeof (EFI_FREEFORM_SUBTYPE_GUID_SECTION)) {
1025 return FALSE;
1026 }
1027
1028 //
1029 // Move the remainder of the FFS file towards the front, and adjust the
1030 // file size output parameter.
1031 //
1032 Remainder = (UINT8 *) PadSection.CommonHeader + PadSize;
1033 memmove (Remainder - Misalignment, Remainder,
1034 *FileSize - (UINTN) (Remainder - (UINTN) FfsFile));
1035 *FileSize -= Misalignment;
1036
1037 //
1038 // Update the padding section's length with the new values. Note that the
1039 // padding is always < 64 KB, so we can ignore EFI_COMMON_SECTION_HEADER2
1040 // ExtendedSize.
1041 //
1042 PadSize -= Misalignment;
1043 PadSection.CommonHeader->Size[0] = (UINT8) (PadSize & 0xff);
1044 PadSection.CommonHeader->Size[1] = (UINT8) ((PadSize & 0xff00) >> 8);
1045 PadSection.CommonHeader->Size[2] = (UINT8) ((PadSize & 0xff0000) >> 16);
1046
1047 //
1048 // Update the FFS header with the new overall length
1049 //
1050 FfsFileLength = GetFfsFileLength (FfsFile) - Misalignment;
1051 if (FfsHeaderLength > sizeof(EFI_FFS_FILE_HEADER)) {
1052 ((EFI_FFS_FILE_HEADER2 *)FfsFile)->ExtendedSize = FfsFileLength;
1053 } else {
1054 FfsFile->Size[0] = (UINT8) (FfsFileLength & 0x000000FF);
1055 FfsFile->Size[1] = (UINT8) ((FfsFileLength & 0x0000FF00) >> 8);
1056 FfsFile->Size[2] = (UINT8) ((FfsFileLength & 0x00FF0000) >> 16);
1057 }
1058
1059 //
1060 // Clear the alignment bits: these have become meaningless now that we have
1061 // adjusted the padding section.
1062 //
1063 FfsFile->Attributes &= ~FFS_ATTRIB_DATA_ALIGNMENT;
1064
1065 //
1066 // Recalculate the FFS header checksum. Instead of setting Header and State
1067 // both to zero, set Header to (UINT8)(-State) so State preserves its original
1068 // value
1069 //
1070 IntegrityCheck = &FfsFile->IntegrityCheck;
1071 IntegrityCheck->Checksum.Header = (UINT8) (0x100 - FfsFile->State);
1072 IntegrityCheck->Checksum.File = 0;
1073
1074 IntegrityCheck->Checksum.Header = CalculateChecksum8 (
1075 (UINT8 *) FfsFile, FfsHeaderLength);
1076
1077 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
1078 //
1079 // Ffs header checksum = zero, so only need to calculate ffs body.
1080 //
1081 IntegrityCheck->Checksum.File = CalculateChecksum8 (
1082 (UINT8 *) FfsFile + FfsHeaderLength,
1083 FfsFileLength - FfsHeaderLength);
1084 } else {
1085 IntegrityCheck->Checksum.File = FFS_FIXED_CHECKSUM;
1086 }
1087
1088 return TRUE;
1089 }
1090
1091 EFI_STATUS
1092 AddFile (
1093 IN OUT MEMORY_FILE *FvImage,
1094 IN FV_INFO *FvInfo,
1095 IN UINTN Index,
1096 IN OUT EFI_FFS_FILE_HEADER **VtfFileImage,
1097 IN FILE *FvMapFile,
1098 IN FILE *FvReportFile
1099 )
1100 /*++
1101
1102 Routine Description:
1103
1104 This function adds a file to the FV image. The file will pad to the
1105 appropriate alignment if required.
1106
1107 Arguments:
1108
1109 FvImage The memory image of the FV to add it to. The current offset
1110 must be valid.
1111 FvInfo Pointer to information about the FV.
1112 Index The file in the FvInfo file list to add.
1113 VtfFileImage A pointer to the VTF file within the FvImage. If this is equal
1114 to the end of the FvImage then no VTF previously found.
1115 FvMapFile Pointer to FvMap File
1116 FvReportFile Pointer to FvReport File
1117
1118 Returns:
1119
1120 EFI_SUCCESS The function completed successfully.
1121 EFI_INVALID_PARAMETER One of the input parameters was invalid.
1122 EFI_ABORTED An error occurred.
1123 EFI_OUT_OF_RESOURCES Insufficient resources exist to complete the add.
1124
1125 --*/
1126 {
1127 FILE *NewFile;
1128 UINTN FileSize;
1129 UINT8 *FileBuffer;
1130 UINTN NumBytesRead;
1131 UINT32 CurrentFileAlignment;
1132 EFI_STATUS Status;
1133 UINTN Index1;
1134 UINT8 FileGuidString[PRINTED_GUID_BUFFER_SIZE];
1135
1136 Index1 = 0;
1137 //
1138 // Verify input parameters.
1139 //
1140 if (FvImage == NULL || FvInfo == NULL || FvInfo->FvFiles[Index][0] == 0 || VtfFileImage == NULL) {
1141 return EFI_INVALID_PARAMETER;
1142 }
1143
1144 //
1145 // Read the file to add
1146 //
1147 NewFile = fopen (LongFilePath (FvInfo->FvFiles[Index]), "rb");
1148
1149 if (NewFile == NULL) {
1150 Error (NULL, 0, 0001, "Error opening file", FvInfo->FvFiles[Index]);
1151 return EFI_ABORTED;
1152 }
1153
1154 //
1155 // Get the file size
1156 //
1157 FileSize = _filelength (fileno (NewFile));
1158
1159 //
1160 // Read the file into a buffer
1161 //
1162 FileBuffer = malloc (FileSize);
1163 if (FileBuffer == NULL) {
1164 Error (NULL, 0, 4001, "Resouce", "memory cannot be allocated!");
1165 return EFI_OUT_OF_RESOURCES;
1166 }
1167
1168 NumBytesRead = fread (FileBuffer, sizeof (UINT8), FileSize, NewFile);
1169
1170 //
1171 // Done with the file, from this point on we will just use the buffer read.
1172 //
1173 fclose (NewFile);
1174
1175 //
1176 // Verify read successful
1177 //
1178 if (NumBytesRead != sizeof (UINT8) * FileSize) {
1179 free (FileBuffer);
1180 Error (NULL, 0, 0004, "Error reading file", FvInfo->FvFiles[Index]);
1181 return EFI_ABORTED;
1182 }
1183
1184 //
1185 // For None PI Ffs file, directly add them into FvImage.
1186 //
1187 if (!FvInfo->IsPiFvImage) {
1188 memcpy (FvImage->CurrentFilePointer, FileBuffer, FileSize);
1189 if (FvInfo->SizeofFvFiles[Index] > FileSize) {
1190 FvImage->CurrentFilePointer += FvInfo->SizeofFvFiles[Index];
1191 } else {
1192 FvImage->CurrentFilePointer += FileSize;
1193 }
1194 goto Done;
1195 }
1196
1197 //
1198 // Verify Ffs file
1199 //
1200 Status = VerifyFfsFile ((EFI_FFS_FILE_HEADER *)FileBuffer);
1201 if (EFI_ERROR (Status)) {
1202 free (FileBuffer);
1203 Error (NULL, 0, 3000, "Invalid", "%s is not a valid FFS file.", FvInfo->FvFiles[Index]);
1204 return EFI_INVALID_PARAMETER;
1205 }
1206
1207 //
1208 // Verify space exists to add the file
1209 //
1210 if (FileSize > (UINTN) ((UINTN) *VtfFileImage - (UINTN) FvImage->CurrentFilePointer)) {
1211 free (FileBuffer);
1212 Error (NULL, 0, 4002, "Resource", "FV space is full, not enough room to add file %s.", FvInfo->FvFiles[Index]);
1213 return EFI_OUT_OF_RESOURCES;
1214 }
1215
1216 //
1217 // Verify the input file is the duplicated file in this Fv image
1218 //
1219 for (Index1 = 0; Index1 < Index; Index1 ++) {
1220 if (CompareGuid ((EFI_GUID *) FileBuffer, &mFileGuidArray [Index1]) == 0) {
1221 Error (NULL, 0, 2000, "Invalid parameter", "the %dth file and %uth file have the same file GUID.", (unsigned) Index1 + 1, (unsigned) Index + 1);
1222 PrintGuid ((EFI_GUID *) FileBuffer);
1223 return EFI_INVALID_PARAMETER;
1224 }
1225 }
1226 CopyMem (&mFileGuidArray [Index], FileBuffer, sizeof (EFI_GUID));
1227
1228 //
1229 // Update the file state based on polarity of the FV.
1230 //
1231 UpdateFfsFileState (
1232 (EFI_FFS_FILE_HEADER *) FileBuffer,
1233 (EFI_FIRMWARE_VOLUME_HEADER *) FvImage->FileImage
1234 );
1235
1236 //
1237 // Check if alignment is required
1238 //
1239 ReadFfsAlignment ((EFI_FFS_FILE_HEADER *) FileBuffer, &CurrentFileAlignment);
1240
1241 //
1242 // Find the largest alignment of all the FFS files in the FV
1243 //
1244 if (CurrentFileAlignment > MaxFfsAlignment) {
1245 MaxFfsAlignment = CurrentFileAlignment;
1246 }
1247 //
1248 // If we have a VTF file, add it at the top.
1249 //
1250 if (IsVtfFile ((EFI_FFS_FILE_HEADER *) FileBuffer)) {
1251 if ((UINTN) *VtfFileImage == (UINTN) FvImage->Eof) {
1252 //
1253 // No previous VTF, add this one.
1254 //
1255 *VtfFileImage = (EFI_FFS_FILE_HEADER *) (UINTN) ((UINTN) FvImage->FileImage + FvInfo->Size - FileSize);
1256 //
1257 // Sanity check. The file MUST align appropriately
1258 //
1259 if (((UINTN) *VtfFileImage + GetFfsHeaderLength((EFI_FFS_FILE_HEADER *)FileBuffer) - (UINTN) FvImage->FileImage) % (1 << CurrentFileAlignment)) {
1260 Error (NULL, 0, 3000, "Invalid", "VTF file cannot be aligned on a %u-byte boundary.", (unsigned) (1 << CurrentFileAlignment));
1261 free (FileBuffer);
1262 return EFI_ABORTED;
1263 }
1264 //
1265 // Rebase the PE or TE image in FileBuffer of FFS file for XIP
1266 // Rebase for the debug genfvmap tool
1267 //
1268 Status = FfsRebase (FvInfo, FvInfo->FvFiles[Index], (EFI_FFS_FILE_HEADER *) FileBuffer, (UINTN) *VtfFileImage - (UINTN) FvImage->FileImage, FvMapFile);
1269 if (EFI_ERROR (Status)) {
1270 Error (NULL, 0, 3000, "Invalid", "Could not rebase %s.", FvInfo->FvFiles[Index]);
1271 return Status;
1272 }
1273 //
1274 // copy VTF File
1275 //
1276 memcpy (*VtfFileImage, FileBuffer, FileSize);
1277
1278 PrintGuidToBuffer ((EFI_GUID *) FileBuffer, FileGuidString, sizeof (FileGuidString), TRUE);
1279 fprintf (FvReportFile, "0x%08X %s\n", (unsigned)(UINTN) (((UINT8 *)*VtfFileImage) - (UINTN)FvImage->FileImage), FileGuidString);
1280
1281 free (FileBuffer);
1282 DebugMsg (NULL, 0, 9, "Add VTF FFS file in FV image", NULL);
1283 return EFI_SUCCESS;
1284 } else {
1285 //
1286 // Already found a VTF file.
1287 //
1288 Error (NULL, 0, 3000, "Invalid", "multiple VTF files are not permitted within a single FV.");
1289 free (FileBuffer);
1290 return EFI_ABORTED;
1291 }
1292 }
1293
1294 //
1295 // Add pad file if necessary
1296 //
1297 if (!AdjustInternalFfsPadding ((EFI_FFS_FILE_HEADER *) FileBuffer, FvImage,
1298 1 << CurrentFileAlignment, &FileSize)) {
1299 Status = AddPadFile (FvImage, 1 << CurrentFileAlignment, *VtfFileImage, NULL, FileSize);
1300 if (EFI_ERROR (Status)) {
1301 Error (NULL, 0, 4002, "Resource", "FV space is full, could not add pad file for data alignment property.");
1302 free (FileBuffer);
1303 return EFI_ABORTED;
1304 }
1305 }
1306 //
1307 // Add file
1308 //
1309 if ((UINTN) (FvImage->CurrentFilePointer + FileSize) <= (UINTN) (*VtfFileImage)) {
1310 //
1311 // Rebase the PE or TE image in FileBuffer of FFS file for XIP.
1312 // Rebase Bs and Rt drivers for the debug genfvmap tool.
1313 //
1314 Status = FfsRebase (FvInfo, FvInfo->FvFiles[Index], (EFI_FFS_FILE_HEADER *) FileBuffer, (UINTN) FvImage->CurrentFilePointer - (UINTN) FvImage->FileImage, FvMapFile);
1315 if (EFI_ERROR (Status)) {
1316 Error (NULL, 0, 3000, "Invalid", "Could not rebase %s.", FvInfo->FvFiles[Index]);
1317 return Status;
1318 }
1319 //
1320 // Copy the file
1321 //
1322 memcpy (FvImage->CurrentFilePointer, FileBuffer, FileSize);
1323 PrintGuidToBuffer ((EFI_GUID *) FileBuffer, FileGuidString, sizeof (FileGuidString), TRUE);
1324 fprintf (FvReportFile, "0x%08X %s\n", (unsigned) (FvImage->CurrentFilePointer - FvImage->FileImage), FileGuidString);
1325 FvImage->CurrentFilePointer += FileSize;
1326 } else {
1327 Error (NULL, 0, 4002, "Resource", "FV space is full, cannot add file %s.", FvInfo->FvFiles[Index]);
1328 free (FileBuffer);
1329 return EFI_ABORTED;
1330 }
1331 //
1332 // Make next file start at QWord Boundry
1333 //
1334 while (((UINTN) FvImage->CurrentFilePointer & (EFI_FFS_FILE_HEADER_ALIGNMENT - 1)) != 0) {
1335 FvImage->CurrentFilePointer++;
1336 }
1337
1338 Done:
1339 //
1340 // Free allocated memory.
1341 //
1342 free (FileBuffer);
1343
1344 return EFI_SUCCESS;
1345 }
1346
1347 EFI_STATUS
1348 PadFvImage (
1349 IN MEMORY_FILE *FvImage,
1350 IN EFI_FFS_FILE_HEADER *VtfFileImage
1351 )
1352 /*++
1353
1354 Routine Description:
1355
1356 This function places a pad file between the last file in the FV and the VTF
1357 file if the VTF file exists.
1358
1359 Arguments:
1360
1361 FvImage Memory file for the FV memory image
1362 VtfFileImage The address of the VTF file. If this is the end of the FV
1363 image, no VTF exists and no pad file is needed.
1364
1365 Returns:
1366
1367 EFI_SUCCESS Completed successfully.
1368 EFI_INVALID_PARAMETER One of the input parameters was NULL.
1369
1370 --*/
1371 {
1372 EFI_FFS_FILE_HEADER *PadFile;
1373 UINTN FileSize;
1374 UINT32 FfsHeaderSize;
1375
1376 //
1377 // If there is no VTF or the VTF naturally follows the previous file without a
1378 // pad file, then there's nothing to do
1379 //
1380 if ((UINTN) VtfFileImage == (UINTN) FvImage->Eof || \
1381 ((UINTN) VtfFileImage == (UINTN) FvImage->CurrentFilePointer)) {
1382 return EFI_SUCCESS;
1383 }
1384
1385 if ((UINTN) VtfFileImage < (UINTN) FvImage->CurrentFilePointer) {
1386 return EFI_INVALID_PARAMETER;
1387 }
1388
1389 //
1390 // Pad file starts at beginning of free space
1391 //
1392 PadFile = (EFI_FFS_FILE_HEADER *) FvImage->CurrentFilePointer;
1393
1394 //
1395 // write PadFile FFS header with PadType, don't need to set PAD file guid in its header.
1396 //
1397 PadFile->Type = EFI_FV_FILETYPE_FFS_PAD;
1398 PadFile->Attributes = 0;
1399
1400 //
1401 // FileSize includes the EFI_FFS_FILE_HEADER
1402 //
1403 FileSize = (UINTN) VtfFileImage - (UINTN) FvImage->CurrentFilePointer;
1404 if (FileSize >= MAX_FFS_SIZE) {
1405 PadFile->Attributes |= FFS_ATTRIB_LARGE_FILE;
1406 memset(PadFile->Size, 0, sizeof(UINT8) * 3);
1407 ((EFI_FFS_FILE_HEADER2 *)PadFile)->ExtendedSize = FileSize;
1408 FfsHeaderSize = sizeof(EFI_FFS_FILE_HEADER2);
1409 mIsLargeFfs = TRUE;
1410 } else {
1411 PadFile->Size[0] = (UINT8) (FileSize & 0x000000FF);
1412 PadFile->Size[1] = (UINT8) ((FileSize & 0x0000FF00) >> 8);
1413 PadFile->Size[2] = (UINT8) ((FileSize & 0x00FF0000) >> 16);
1414 FfsHeaderSize = sizeof(EFI_FFS_FILE_HEADER);
1415 }
1416
1417 //
1418 // Fill in checksums and state, must be zero during checksum calculation.
1419 //
1420 PadFile->IntegrityCheck.Checksum.Header = 0;
1421 PadFile->IntegrityCheck.Checksum.File = 0;
1422 PadFile->State = 0;
1423 PadFile->IntegrityCheck.Checksum.Header = CalculateChecksum8 ((UINT8 *) PadFile, FfsHeaderSize);
1424 PadFile->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
1425
1426 PadFile->State = EFI_FILE_HEADER_CONSTRUCTION | EFI_FILE_HEADER_VALID | EFI_FILE_DATA_VALID;
1427
1428 UpdateFfsFileState (
1429 (EFI_FFS_FILE_HEADER *) PadFile,
1430 (EFI_FIRMWARE_VOLUME_HEADER *) FvImage->FileImage
1431 );
1432 //
1433 // Update the current FV pointer
1434 //
1435 FvImage->CurrentFilePointer = FvImage->Eof;
1436
1437 return EFI_SUCCESS;
1438 }
1439
1440 EFI_STATUS
1441 UpdateResetVector (
1442 IN MEMORY_FILE *FvImage,
1443 IN FV_INFO *FvInfo,
1444 IN EFI_FFS_FILE_HEADER *VtfFile
1445 )
1446 /*++
1447
1448 Routine Description:
1449
1450 This parses the FV looking for the PEI core and then plugs the address into
1451 the SALE_ENTRY point of the BSF/VTF for IPF and does BUGBUG TBD action to
1452 complete an IA32 Bootstrap FV.
1453
1454 Arguments:
1455
1456 FvImage Memory file for the FV memory image
1457 FvInfo Information read from INF file.
1458 VtfFile Pointer to the VTF file in the FV image.
1459
1460 Returns:
1461
1462 EFI_SUCCESS Function Completed successfully.
1463 EFI_ABORTED Error encountered.
1464 EFI_INVALID_PARAMETER A required parameter was NULL.
1465 EFI_NOT_FOUND PEI Core file not found.
1466
1467 --*/
1468 {
1469 EFI_FFS_FILE_HEADER *PeiCoreFile;
1470 EFI_FFS_FILE_HEADER *SecCoreFile;
1471 EFI_STATUS Status;
1472 EFI_FILE_SECTION_POINTER Pe32Section;
1473 UINT32 EntryPoint;
1474 UINT32 BaseOfCode;
1475 UINT16 MachineType;
1476 EFI_PHYSICAL_ADDRESS PeiCorePhysicalAddress;
1477 EFI_PHYSICAL_ADDRESS SecCorePhysicalAddress;
1478 EFI_PHYSICAL_ADDRESS *SecCoreEntryAddressPtr;
1479 INT32 Ia32SecEntryOffset;
1480 UINT32 *Ia32ResetAddressPtr;
1481 UINT8 *BytePointer;
1482 UINT8 *BytePointer2;
1483 UINT16 *WordPointer;
1484 UINT16 CheckSum;
1485 UINT32 IpiVector;
1486 UINTN Index;
1487 EFI_FFS_FILE_STATE SavedState;
1488 UINT64 FitAddress;
1489 FIT_TABLE *FitTablePtr;
1490 BOOLEAN Vtf0Detected;
1491 UINT32 FfsHeaderSize;
1492 UINT32 SecHeaderSize;
1493
1494 //
1495 // Verify input parameters
1496 //
1497 if (FvImage == NULL || FvInfo == NULL || VtfFile == NULL) {
1498 return EFI_INVALID_PARAMETER;
1499 }
1500 //
1501 // Initialize FV library
1502 //
1503 InitializeFvLib (FvImage->FileImage, FvInfo->Size);
1504
1505 //
1506 // Verify VTF file
1507 //
1508 Status = VerifyFfsFile (VtfFile);
1509 if (EFI_ERROR (Status)) {
1510 return EFI_INVALID_PARAMETER;
1511 }
1512
1513 if (
1514 (((UINTN)FvImage->Eof - (UINTN)FvImage->FileImage) >=
1515 IA32_X64_VTF_SIGNATURE_OFFSET) &&
1516 (*(UINT32 *)(VOID*)((UINTN) FvImage->Eof -
1517 IA32_X64_VTF_SIGNATURE_OFFSET) ==
1518 IA32_X64_VTF0_SIGNATURE)
1519 ) {
1520 Vtf0Detected = TRUE;
1521 } else {
1522 Vtf0Detected = FALSE;
1523 }
1524
1525 //
1526 // Find the Sec Core
1527 //
1528 Status = GetFileByType (EFI_FV_FILETYPE_SECURITY_CORE, 1, &SecCoreFile);
1529 if (EFI_ERROR (Status) || SecCoreFile == NULL) {
1530 if (Vtf0Detected) {
1531 //
1532 // If the SEC core file is not found, but the VTF-0 signature
1533 // is found, we'll treat it as a VTF-0 'Volume Top File'.
1534 // This means no modifications are required to the VTF.
1535 //
1536 return EFI_SUCCESS;
1537 }
1538
1539 Error (NULL, 0, 3000, "Invalid", "could not find the SEC core file in the FV.");
1540 return EFI_ABORTED;
1541 }
1542 //
1543 // Sec Core found, now find PE32 section
1544 //
1545 Status = GetSectionByType (SecCoreFile, EFI_SECTION_PE32, 1, &Pe32Section);
1546 if (Status == EFI_NOT_FOUND) {
1547 Status = GetSectionByType (SecCoreFile, EFI_SECTION_TE, 1, &Pe32Section);
1548 }
1549
1550 if (EFI_ERROR (Status)) {
1551 Error (NULL, 0, 3000, "Invalid", "could not find a PE32 section in the SEC core file.");
1552 return EFI_ABORTED;
1553 }
1554
1555 SecHeaderSize = GetSectionHeaderLength(Pe32Section.CommonHeader);
1556 Status = GetPe32Info (
1557 (VOID *) ((UINTN) Pe32Section.Pe32Section + SecHeaderSize),
1558 &EntryPoint,
1559 &BaseOfCode,
1560 &MachineType
1561 );
1562
1563 if (EFI_ERROR (Status)) {
1564 Error (NULL, 0, 3000, "Invalid", "could not get the PE32 entry point for the SEC core.");
1565 return EFI_ABORTED;
1566 }
1567
1568 if (
1569 Vtf0Detected &&
1570 (MachineType == EFI_IMAGE_MACHINE_IA32 ||
1571 MachineType == EFI_IMAGE_MACHINE_X64)
1572 ) {
1573 //
1574 // If the SEC core code is IA32 or X64 and the VTF-0 signature
1575 // is found, we'll treat it as a VTF-0 'Volume Top File'.
1576 // This means no modifications are required to the VTF.
1577 //
1578 return EFI_SUCCESS;
1579 }
1580
1581 //
1582 // Physical address is FV base + offset of PE32 + offset of the entry point
1583 //
1584 SecCorePhysicalAddress = FvInfo->BaseAddress;
1585 SecCorePhysicalAddress += (UINTN) Pe32Section.Pe32Section + SecHeaderSize - (UINTN) FvImage->FileImage;
1586 SecCorePhysicalAddress += EntryPoint;
1587 DebugMsg (NULL, 0, 9, "SecCore physical entry point address", "Address = 0x%llX", (unsigned long long) SecCorePhysicalAddress);
1588
1589 //
1590 // Find the PEI Core
1591 //
1592 Status = GetFileByType (EFI_FV_FILETYPE_PEI_CORE, 1, &PeiCoreFile);
1593 if (EFI_ERROR (Status) || PeiCoreFile == NULL) {
1594 Error (NULL, 0, 3000, "Invalid", "could not find the PEI core in the FV.");
1595 return EFI_ABORTED;
1596 }
1597 //
1598 // PEI Core found, now find PE32 or TE section
1599 //
1600 Status = GetSectionByType (PeiCoreFile, EFI_SECTION_PE32, 1, &Pe32Section);
1601 if (Status == EFI_NOT_FOUND) {
1602 Status = GetSectionByType (PeiCoreFile, EFI_SECTION_TE, 1, &Pe32Section);
1603 }
1604
1605 if (EFI_ERROR (Status)) {
1606 Error (NULL, 0, 3000, "Invalid", "could not find either a PE32 or a TE section in PEI core file.");
1607 return EFI_ABORTED;
1608 }
1609
1610 SecHeaderSize = GetSectionHeaderLength(Pe32Section.CommonHeader);
1611 Status = GetPe32Info (
1612 (VOID *) ((UINTN) Pe32Section.Pe32Section + SecHeaderSize),
1613 &EntryPoint,
1614 &BaseOfCode,
1615 &MachineType
1616 );
1617
1618 if (EFI_ERROR (Status)) {
1619 Error (NULL, 0, 3000, "Invalid", "could not get the PE32 entry point for the PEI core.");
1620 return EFI_ABORTED;
1621 }
1622 //
1623 // Physical address is FV base + offset of PE32 + offset of the entry point
1624 //
1625 PeiCorePhysicalAddress = FvInfo->BaseAddress;
1626 PeiCorePhysicalAddress += (UINTN) Pe32Section.Pe32Section + SecHeaderSize - (UINTN) FvImage->FileImage;
1627 PeiCorePhysicalAddress += EntryPoint;
1628 DebugMsg (NULL, 0, 9, "PeiCore physical entry point address", "Address = 0x%llX", (unsigned long long) PeiCorePhysicalAddress);
1629
1630 if (MachineType == EFI_IMAGE_MACHINE_IA64) {
1631 //
1632 // Update PEI_CORE address
1633 //
1634 //
1635 // Set the uncached attribute bit in the physical address
1636 //
1637 PeiCorePhysicalAddress |= 0x8000000000000000ULL;
1638
1639 //
1640 // Check if address is aligned on a 16 byte boundary
1641 //
1642 if (PeiCorePhysicalAddress & 0xF) {
1643 Error (NULL, 0, 3000, "Invalid",
1644 "PEI_CORE entry point is not aligned on a 16 byte boundary, address specified is %llXh.",
1645 (unsigned long long) PeiCorePhysicalAddress
1646 );
1647 return EFI_ABORTED;
1648 }
1649 //
1650 // First Get the FIT table address
1651 //
1652 FitAddress = (*(UINT64 *) (FvImage->Eof - IPF_FIT_ADDRESS_OFFSET)) & 0xFFFFFFFF;
1653
1654 FitTablePtr = (FIT_TABLE *) (FvImage->FileImage + (FitAddress - FvInfo->BaseAddress));
1655
1656 Status = UpdatePeiCoreEntryInFit (FitTablePtr, PeiCorePhysicalAddress);
1657
1658 if (!EFI_ERROR (Status)) {
1659 UpdateFitCheckSum (FitTablePtr);
1660 }
1661
1662 //
1663 // Update SEC_CORE address
1664 //
1665 //
1666 // Set the uncached attribute bit in the physical address
1667 //
1668 SecCorePhysicalAddress |= 0x8000000000000000ULL;
1669 //
1670 // Check if address is aligned on a 16 byte boundary
1671 //
1672 if (SecCorePhysicalAddress & 0xF) {
1673 Error (NULL, 0, 3000, "Invalid",
1674 "SALE_ENTRY entry point is not aligned on a 16 byte boundary, address specified is %llXh.",
1675 (unsigned long long) SecCorePhysicalAddress
1676 );
1677 return EFI_ABORTED;
1678 }
1679 //
1680 // Update the address
1681 //
1682 SecCoreEntryAddressPtr = (EFI_PHYSICAL_ADDRESS *) ((UINTN) FvImage->Eof - IPF_SALE_ENTRY_ADDRESS_OFFSET);
1683 *SecCoreEntryAddressPtr = SecCorePhysicalAddress;
1684
1685 } else if (MachineType == EFI_IMAGE_MACHINE_IA32 || MachineType == EFI_IMAGE_MACHINE_X64) {
1686 //
1687 // Get the location to update
1688 //
1689 Ia32ResetAddressPtr = (UINT32 *) ((UINTN) FvImage->Eof - IA32_PEI_CORE_ENTRY_OFFSET);
1690
1691 //
1692 // Write lower 32 bits of physical address for Pei Core entry
1693 //
1694 *Ia32ResetAddressPtr = (UINT32) PeiCorePhysicalAddress;
1695
1696 //
1697 // Write SecCore Entry point relative address into the jmp instruction in reset vector.
1698 //
1699 Ia32ResetAddressPtr = (UINT32 *) ((UINTN) FvImage->Eof - IA32_SEC_CORE_ENTRY_OFFSET);
1700
1701 Ia32SecEntryOffset = (INT32) (SecCorePhysicalAddress - (FV_IMAGES_TOP_ADDRESS - IA32_SEC_CORE_ENTRY_OFFSET + 2));
1702 if (Ia32SecEntryOffset <= -65536) {
1703 Error (NULL, 0, 3000, "Invalid", "The SEC EXE file size is too large, it must be less than 64K.");
1704 return STATUS_ERROR;
1705 }
1706
1707 *(UINT16 *) Ia32ResetAddressPtr = (UINT16) Ia32SecEntryOffset;
1708
1709 //
1710 // Update the BFV base address
1711 //
1712 Ia32ResetAddressPtr = (UINT32 *) ((UINTN) FvImage->Eof - 4);
1713 *Ia32ResetAddressPtr = (UINT32) (FvInfo->BaseAddress);
1714 DebugMsg (NULL, 0, 9, "update BFV base address in the top FV image", "BFV base address = 0x%llX.", (unsigned long long) FvInfo->BaseAddress);
1715
1716 //
1717 // Update the Startup AP in the FVH header block ZeroVector region.
1718 //
1719 BytePointer = (UINT8 *) ((UINTN) FvImage->FileImage);
1720 if (FvInfo->Size <= 0x10000) {
1721 BytePointer2 = m64kRecoveryStartupApDataArray;
1722 } else if (FvInfo->Size <= 0x20000) {
1723 BytePointer2 = m128kRecoveryStartupApDataArray;
1724 } else {
1725 BytePointer2 = m128kRecoveryStartupApDataArray;
1726 //
1727 // Find the position to place Ap reset vector, the offset
1728 // between the position and the end of Fvrecovery.fv file
1729 // should not exceed 128kB to prevent Ap reset vector from
1730 // outside legacy E and F segment
1731 //
1732 Status = FindApResetVectorPosition (FvImage, &BytePointer);
1733 if (EFI_ERROR (Status)) {
1734 Error (NULL, 0, 3000, "Invalid", "FV image does not have enough space to place AP reset vector. The FV image needs to reserve at least 4KB of unused space.");
1735 return EFI_ABORTED;
1736 }
1737 }
1738
1739 for (Index = 0; Index < SIZEOF_STARTUP_DATA_ARRAY; Index++) {
1740 BytePointer[Index] = BytePointer2[Index];
1741 }
1742 //
1743 // Calculate the checksum
1744 //
1745 CheckSum = 0x0000;
1746 WordPointer = (UINT16 *) (BytePointer);
1747 for (Index = 0; Index < SIZEOF_STARTUP_DATA_ARRAY / 2; Index++) {
1748 CheckSum = (UINT16) (CheckSum + ((UINT16) *WordPointer));
1749 WordPointer++;
1750 }
1751 //
1752 // Update the checksum field
1753 //
1754 WordPointer = (UINT16 *) (BytePointer + SIZEOF_STARTUP_DATA_ARRAY - 2);
1755 *WordPointer = (UINT16) (0x10000 - (UINT32) CheckSum);
1756
1757 //
1758 // IpiVector at the 4k aligned address in the top 2 blocks in the PEI FV.
1759 //
1760 IpiVector = (UINT32) (FV_IMAGES_TOP_ADDRESS - ((UINTN) FvImage->Eof - (UINTN) BytePointer));
1761 DebugMsg (NULL, 0, 9, "Startup AP Vector address", "IpiVector at 0x%X", (unsigned) IpiVector);
1762 if ((IpiVector & 0xFFF) != 0) {
1763 Error (NULL, 0, 3000, "Invalid", "Startup AP Vector address are not 4K aligned, because the FV size is not 4K aligned");
1764 return EFI_ABORTED;
1765 }
1766 IpiVector = IpiVector >> 12;
1767 IpiVector = IpiVector & 0xFF;
1768
1769 //
1770 // Write IPI Vector at Offset FvrecoveryFileSize - 8
1771 //
1772 Ia32ResetAddressPtr = (UINT32 *) ((UINTN) FvImage->Eof - 8);
1773 *Ia32ResetAddressPtr = IpiVector;
1774 } else if (MachineType == EFI_IMAGE_MACHINE_ARMT) {
1775 //
1776 // Since the ARM reset vector is in the FV Header you really don't need a
1777 // Volume Top File, but if you have one for some reason don't crash...
1778 //
1779 } else if (MachineType == EFI_IMAGE_MACHINE_AARCH64) {
1780 //
1781 // Since the AArch64 reset vector is in the FV Header you really don't need a
1782 // Volume Top File, but if you have one for some reason don't crash...
1783 //
1784 } else {
1785 Error (NULL, 0, 3000, "Invalid", "machine type=0x%X in PEI core.", MachineType);
1786 return EFI_ABORTED;
1787 }
1788
1789 //
1790 // Now update file checksum
1791 //
1792 SavedState = VtfFile->State;
1793 VtfFile->IntegrityCheck.Checksum.File = 0;
1794 VtfFile->State = 0;
1795 if (VtfFile->Attributes & FFS_ATTRIB_CHECKSUM) {
1796 FfsHeaderSize = GetFfsHeaderLength(VtfFile);
1797 VtfFile->IntegrityCheck.Checksum.File = CalculateChecksum8 (
1798 (UINT8 *) ((UINT8 *)VtfFile + FfsHeaderSize),
1799 GetFfsFileLength (VtfFile) - FfsHeaderSize
1800 );
1801 } else {
1802 VtfFile->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
1803 }
1804
1805 VtfFile->State = SavedState;
1806
1807 return EFI_SUCCESS;
1808 }
1809
1810 EFI_STATUS
1811 FindCorePeSection(
1812 IN VOID *FvImageBuffer,
1813 IN UINT64 FvSize,
1814 IN EFI_FV_FILETYPE FileType,
1815 OUT EFI_FILE_SECTION_POINTER *Pe32Section
1816 )
1817 /*++
1818
1819 Routine Description:
1820
1821 Recursively searches the FV for the FFS file of specified type (typically
1822 SEC or PEI core) and extracts the PE32 section for further processing.
1823
1824 Arguments:
1825
1826 FvImageBuffer Buffer containing FV data
1827 FvSize Size of the FV
1828 FileType Type of FFS file to search for
1829 Pe32Section PE32 section pointer when FFS file is found.
1830
1831 Returns:
1832
1833 EFI_SUCCESS Function Completed successfully.
1834 EFI_ABORTED Error encountered.
1835 EFI_INVALID_PARAMETER A required parameter was NULL.
1836 EFI_NOT_FOUND Core file not found.
1837
1838 --*/
1839 {
1840 EFI_STATUS Status;
1841 EFI_FIRMWARE_VOLUME_HEADER *OrigFvHeader;
1842 UINT32 OrigFvLength;
1843 EFI_FFS_FILE_HEADER *CoreFfsFile;
1844 UINTN FvImageFileCount;
1845 EFI_FFS_FILE_HEADER *FvImageFile;
1846 UINTN EncapFvSectionCount;
1847 EFI_FILE_SECTION_POINTER EncapFvSection;
1848 EFI_FIRMWARE_VOLUME_HEADER *EncapsulatedFvHeader;
1849
1850 if (Pe32Section == NULL) {
1851 return EFI_INVALID_PARAMETER;
1852 }
1853
1854 //
1855 // Initialize FV library, saving previous values
1856 //
1857 OrigFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)NULL;
1858 GetFvHeader (&OrigFvHeader, &OrigFvLength);
1859 InitializeFvLib(FvImageBuffer, (UINT32)FvSize);
1860
1861 //
1862 // First see if we can obtain the file directly in outer FV
1863 //
1864 Status = GetFileByType(FileType, 1, &CoreFfsFile);
1865 if (!EFI_ERROR(Status) && (CoreFfsFile != NULL) ) {
1866
1867 //
1868 // Core found, now find PE32 or TE section
1869 //
1870 Status = GetSectionByType(CoreFfsFile, EFI_SECTION_PE32, 1, Pe32Section);
1871 if (EFI_ERROR(Status)) {
1872 Status = GetSectionByType(CoreFfsFile, EFI_SECTION_TE, 1, Pe32Section);
1873 }
1874
1875 if (EFI_ERROR(Status)) {
1876 Error(NULL, 0, 3000, "Invalid", "could not find a PE32 section in the core file.");
1877 return EFI_ABORTED;
1878 }
1879
1880 //
1881 // Core PE/TE section, found, return
1882 //
1883 Status = EFI_SUCCESS;
1884 goto EarlyExit;
1885 }
1886
1887 //
1888 // File was not found, look for FV Image file
1889 //
1890
1891 // iterate through all FV image files in outer FV
1892 for (FvImageFileCount = 1;; FvImageFileCount++) {
1893
1894 Status = GetFileByType(EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, FvImageFileCount, &FvImageFile);
1895
1896 if (EFI_ERROR(Status) || (FvImageFile == NULL) ) {
1897 // exit FV image file loop, no more found
1898 break;
1899 }
1900
1901 // Found an fv image file, look for an FV image section. The PI spec does not
1902 // preclude multiple FV image sections so we loop accordingly.
1903 for (EncapFvSectionCount = 1;; EncapFvSectionCount++) {
1904
1905 // Look for the next FV image section. The section search code will
1906 // iterate into encapsulation sections. For example, it will iterate
1907 // into an EFI_SECTION_GUID_DEFINED encapsulation section to find the
1908 // EFI_SECTION_FIRMWARE_VOLUME_IMAGE sections contained therein.
1909 Status = GetSectionByType(FvImageFile, EFI_SECTION_FIRMWARE_VOLUME_IMAGE, EncapFvSectionCount, &EncapFvSection);
1910
1911 if (EFI_ERROR(Status)) {
1912 // exit section inner loop, no more found
1913 break;
1914 }
1915
1916 EncapsulatedFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)((UINT8 *)EncapFvSection.FVImageSection + GetSectionHeaderLength(EncapFvSection.FVImageSection));
1917
1918 // recurse to search the encapsulated FV for this core file type
1919 Status = FindCorePeSection(EncapsulatedFvHeader, EncapsulatedFvHeader->FvLength, FileType, Pe32Section);
1920
1921 if (!EFI_ERROR(Status)) {
1922 // we found the core in the capsulated image, success
1923 goto EarlyExit;
1924 }
1925
1926 } // end encapsulated fv image section loop
1927 } // end fv image file loop
1928
1929 // core was not found
1930 Status = EFI_NOT_FOUND;
1931
1932 EarlyExit:
1933
1934 // restore FV lib values
1935 if(OrigFvHeader != NULL) {
1936 InitializeFvLib(OrigFvHeader, OrigFvLength);
1937 }
1938
1939 return Status;
1940 }
1941
1942 EFI_STATUS
1943 GetCoreMachineType(
1944 IN EFI_FILE_SECTION_POINTER Pe32Section,
1945 OUT UINT16 *CoreMachineType
1946 )
1947 /*++
1948
1949 Routine Description:
1950
1951 Returns the machine type of a P32 image, typically SEC or PEI core.
1952
1953 Arguments:
1954
1955 Pe32Section PE32 section data
1956 CoreMachineType The extracted machine type
1957
1958 Returns:
1959
1960 EFI_SUCCESS Function Completed successfully.
1961 EFI_ABORTED Error encountered.
1962 EFI_INVALID_PARAMETER A required parameter was NULL.
1963
1964 --*/
1965 {
1966 EFI_STATUS Status;
1967 UINT32 EntryPoint;
1968 UINT32 BaseOfCode;
1969
1970 if (CoreMachineType == NULL) {
1971 return EFI_INVALID_PARAMETER;
1972 }
1973
1974 Status = GetPe32Info(
1975 (VOID *)((UINTN)Pe32Section.Pe32Section + GetSectionHeaderLength(Pe32Section.CommonHeader)),
1976 &EntryPoint,
1977 &BaseOfCode,
1978 CoreMachineType
1979 );
1980 if (EFI_ERROR(Status)) {
1981 Error(NULL, 0, 3000, "Invalid", "could not get the PE32 machine type for the core.");
1982 return EFI_ABORTED;
1983 }
1984
1985 return EFI_SUCCESS;
1986 }
1987
1988 EFI_STATUS
1989 GetCoreEntryPointAddress(
1990 IN VOID *FvImageBuffer,
1991 IN FV_INFO *FvInfo,
1992 IN EFI_FILE_SECTION_POINTER Pe32Section,
1993 OUT EFI_PHYSICAL_ADDRESS *CoreEntryAddress
1994 )
1995 /*++
1996
1997 Routine Description:
1998
1999 Returns the physical address of the core (SEC or PEI) entry point.
2000
2001 Arguments:
2002
2003 FvImageBuffer Pointer to buffer containing FV data
2004 FvInfo Info for the parent FV
2005 Pe32Section PE32 section data
2006 CoreEntryAddress The extracted core entry physical address
2007
2008 Returns:
2009
2010 EFI_SUCCESS Function Completed successfully.
2011 EFI_ABORTED Error encountered.
2012 EFI_INVALID_PARAMETER A required parameter was NULL.
2013
2014 --*/
2015 {
2016 EFI_STATUS Status;
2017 UINT32 EntryPoint;
2018 UINT32 BaseOfCode;
2019 UINT16 MachineType;
2020 EFI_PHYSICAL_ADDRESS EntryPhysicalAddress;
2021
2022 if (CoreEntryAddress == NULL) {
2023 return EFI_INVALID_PARAMETER;
2024 }
2025
2026 Status = GetPe32Info(
2027 (VOID *)((UINTN)Pe32Section.Pe32Section + GetSectionHeaderLength(Pe32Section.CommonHeader)),
2028 &EntryPoint,
2029 &BaseOfCode,
2030 &MachineType
2031 );
2032 if (EFI_ERROR(Status)) {
2033 Error(NULL, 0, 3000, "Invalid", "could not get the PE32 entry point for the core.");
2034 return EFI_ABORTED;
2035 }
2036
2037 //
2038 // Physical address is FV base + offset of PE32 + offset of the entry point
2039 //
2040 EntryPhysicalAddress = FvInfo->BaseAddress;
2041 EntryPhysicalAddress += (UINTN)Pe32Section.Pe32Section + GetSectionHeaderLength(Pe32Section.CommonHeader) - (UINTN)FvImageBuffer;
2042 EntryPhysicalAddress += EntryPoint;
2043
2044 *CoreEntryAddress = EntryPhysicalAddress;
2045
2046 return EFI_SUCCESS;
2047 }
2048
2049 EFI_STATUS
2050 UpdateArmResetVectorIfNeeded (
2051 IN MEMORY_FILE *FvImage,
2052 IN FV_INFO *FvInfo
2053 )
2054 /*++
2055
2056 Routine Description:
2057 This parses the FV looking for SEC and patches that address into the
2058 beginning of the FV header.
2059
2060 For ARM32 the reset vector is at 0x00000000 or 0xFFFF0000.
2061 For AArch64 the reset vector is at 0x00000000.
2062
2063 This would commonly map to the first entry in the ROM.
2064 ARM32 Exceptions:
2065 Reset +0
2066 Undefined +4
2067 SWI +8
2068 Prefetch Abort +12
2069 Data Abort +16
2070 IRQ +20
2071 FIQ +24
2072
2073 We support two schemes on ARM.
2074 1) Beginning of the FV is the reset vector
2075 2) Reset vector is data bytes FDF file and that code branches to reset vector
2076 in the beginning of the FV (fixed size offset).
2077
2078 Need to have the jump for the reset vector at location zero.
2079 We also need to store the address or PEI (if it exists).
2080 We stub out a return from interrupt in case the debugger
2081 is using SWI (not done for AArch64, not enough space in struct).
2082 The optional entry to the common exception handler is
2083 to support full featured exception handling from ROM and is currently
2084 not support by this tool.
2085
2086 Arguments:
2087 FvImage Memory file for the FV memory image
2088 FvInfo Information read from INF file.
2089
2090 Returns:
2091
2092 EFI_SUCCESS Function Completed successfully.
2093 EFI_ABORTED Error encountered.
2094 EFI_INVALID_PARAMETER A required parameter was NULL.
2095 EFI_NOT_FOUND PEI Core file not found.
2096
2097 --*/
2098 {
2099 EFI_STATUS Status;
2100 EFI_FILE_SECTION_POINTER SecPe32;
2101 EFI_FILE_SECTION_POINTER PeiPe32;
2102 BOOLEAN UpdateVectorSec = FALSE;
2103 BOOLEAN UpdateVectorPei = FALSE;
2104 UINT16 MachineType = 0;
2105 EFI_PHYSICAL_ADDRESS SecCoreEntryAddress = 0;
2106 UINT16 PeiMachineType = 0;
2107 EFI_PHYSICAL_ADDRESS PeiCoreEntryAddress = 0;
2108
2109 //
2110 // Verify input parameters
2111 //
2112 if (FvImage == NULL || FvInfo == NULL) {
2113 return EFI_INVALID_PARAMETER;
2114 }
2115
2116 //
2117 // Locate an SEC Core instance and if found extract the machine type and entry point address
2118 //
2119 Status = FindCorePeSection(FvImage->FileImage, FvInfo->Size, EFI_FV_FILETYPE_SECURITY_CORE, &SecPe32);
2120 if (!EFI_ERROR(Status)) {
2121
2122 Status = GetCoreMachineType(SecPe32, &MachineType);
2123 if (EFI_ERROR(Status)) {
2124 Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 machine type for SEC Core.");
2125 return EFI_ABORTED;
2126 }
2127
2128 Status = GetCoreEntryPointAddress(FvImage->FileImage, FvInfo, SecPe32, &SecCoreEntryAddress);
2129 if (EFI_ERROR(Status)) {
2130 Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 entry point address for SEC Core.");
2131 return EFI_ABORTED;
2132 }
2133
2134 VerboseMsg("UpdateArmResetVectorIfNeeded found SEC core entry at 0x%llx", (unsigned long long)SecCoreEntryAddress);
2135 UpdateVectorSec = TRUE;
2136 }
2137
2138 //
2139 // Locate a PEI Core instance and if found extract the machine type and entry point address
2140 //
2141 Status = FindCorePeSection(FvImage->FileImage, FvInfo->Size, EFI_FV_FILETYPE_PEI_CORE, &PeiPe32);
2142 if (!EFI_ERROR(Status)) {
2143
2144 Status = GetCoreMachineType(PeiPe32, &PeiMachineType);
2145 if (EFI_ERROR(Status)) {
2146 Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 machine type for PEI Core.");
2147 return EFI_ABORTED;
2148 }
2149
2150 Status = GetCoreEntryPointAddress(FvImage->FileImage, FvInfo, PeiPe32, &PeiCoreEntryAddress);
2151 if (EFI_ERROR(Status)) {
2152 Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 entry point address for PEI Core.");
2153 return EFI_ABORTED;
2154 }
2155
2156 VerboseMsg("UpdateArmResetVectorIfNeeded found PEI core entry at 0x%llx", (unsigned long long)PeiCoreEntryAddress);
2157
2158 // if we previously found an SEC Core make sure machine types match
2159 if (UpdateVectorSec && (MachineType != PeiMachineType)) {
2160 Error(NULL, 0, 3000, "Invalid", "SEC and PEI machine types do not match, can't update reset vector");
2161 return EFI_ABORTED;
2162 }
2163 else {
2164 MachineType = PeiMachineType;
2165 }
2166
2167 UpdateVectorPei = TRUE;
2168 }
2169
2170 if (!UpdateVectorSec && !UpdateVectorPei) {
2171 return EFI_SUCCESS;
2172 }
2173
2174 if (MachineType == EFI_IMAGE_MACHINE_ARMT) {
2175 // ARM: Array of 4 UINT32s:
2176 // 0 - is branch relative to SEC entry point
2177 // 1 - PEI Entry Point
2178 // 2 - movs pc,lr for a SWI handler
2179 // 3 - Place holder for Common Exception Handler
2180 UINT32 ResetVector[4];
2181
2182 memset(ResetVector, 0, sizeof (ResetVector));
2183
2184 // if we found an SEC core entry point then generate a branch instruction
2185 // to it and populate a debugger SWI entry as well
2186 if (UpdateVectorSec) {
2187
2188 VerboseMsg("UpdateArmResetVectorIfNeeded updating ARM SEC vector");
2189
2190 // B SecEntryPoint - signed_immed_24 part +/-32MB offset
2191 // on ARM, the PC is always 8 ahead, so we're not really jumping from the base address, but from base address + 8
2192 ResetVector[0] = (INT32)(SecCoreEntryAddress - FvInfo->BaseAddress - 8) >> 2;
2193
2194 if (ResetVector[0] > 0x00FFFFFF) {
2195 Error(NULL, 0, 3000, "Invalid", "SEC Entry point must be within 32MB of the start of the FV");
2196 return EFI_ABORTED;
2197 }
2198
2199 // Add opcode for an uncondional branch with no link. i.e.: " B SecEntryPoint"
2200 ResetVector[0] |= ARMT_UNCONDITIONAL_JUMP_INSTRUCTION;
2201
2202 // SWI handler movs pc,lr. Just in case a debugger uses SWI
2203 ResetVector[2] = 0xE1B0F07E;
2204
2205 // Place holder to support a common interrupt handler from ROM.
2206 // Currently not suppprted. For this to be used the reset vector would not be in this FV
2207 // and the exception vectors would be hard coded in the ROM and just through this address
2208 // to find a common handler in the a module in the FV.
2209 ResetVector[3] = 0;
2210 }
2211
2212 // if a PEI core entry was found place its address in the vector area
2213 if (UpdateVectorPei) {
2214
2215 VerboseMsg("UpdateArmResetVectorIfNeeded updating ARM PEI address");
2216
2217 // Address of PEI Core, if we have one
2218 ResetVector[1] = (UINT32)PeiCoreEntryAddress;
2219 }
2220
2221 //
2222 // Copy to the beginning of the FV
2223 //
2224 memcpy(FvImage->FileImage, ResetVector, sizeof (ResetVector));
2225
2226 } else if (MachineType == EFI_IMAGE_MACHINE_AARCH64) {
2227 // AArch64: Used as UINT64 ResetVector[2]
2228 // 0 - is branch relative to SEC entry point
2229 // 1 - PEI Entry Point
2230 UINT64 ResetVector[2];
2231
2232 memset(ResetVector, 0, sizeof (ResetVector));
2233
2234 /* NOTE:
2235 ARMT above has an entry in ResetVector[2] for SWI. The way we are using the ResetVector
2236 array at the moment, for AArch64, does not allow us space for this as the header only
2237 allows for a fixed amount of bytes at the start. If we are sure that UEFI will live
2238 within the first 4GB of addressable RAM we could potensioally adopt the same ResetVector
2239 layout as above. But for the moment we replace the four 32bit vectors with two 64bit
2240 vectors in the same area of the Image heasder. This allows UEFI to start from a 64bit
2241 base.
2242 */
2243
2244 // if we found an SEC core entry point then generate a branch instruction to it
2245 if (UpdateVectorSec) {
2246
2247 VerboseMsg("UpdateArmResetVectorIfNeeded updating AArch64 SEC vector");
2248
2249 ResetVector[0] = (UINT64)(SecCoreEntryAddress - FvInfo->BaseAddress) >> 2;
2250
2251 // B SecEntryPoint - signed_immed_26 part +/-128MB offset
2252 if (ResetVector[0] > 0x03FFFFFF) {
2253 Error(NULL, 0, 3000, "Invalid", "SEC Entry point must be within 128MB of the start of the FV");
2254 return EFI_ABORTED;
2255 }
2256 // Add opcode for an uncondional branch with no link. i.e.: " B SecEntryPoint"
2257 ResetVector[0] |= ARM64_UNCONDITIONAL_JUMP_INSTRUCTION;
2258 }
2259
2260 // if a PEI core entry was found place its address in the vector area
2261 if (UpdateVectorPei) {
2262
2263 VerboseMsg("UpdateArmResetVectorIfNeeded updating AArch64 PEI address");
2264
2265 // Address of PEI Core, if we have one
2266 ResetVector[1] = (UINT64)PeiCoreEntryAddress;
2267 }
2268
2269 //
2270 // Copy to the beginning of the FV
2271 //
2272 memcpy(FvImage->FileImage, ResetVector, sizeof (ResetVector));
2273
2274 } else {
2275 Error(NULL, 0, 3000, "Invalid", "Unknown machine type");
2276 return EFI_ABORTED;
2277 }
2278
2279 return EFI_SUCCESS;
2280 }
2281
2282 EFI_STATUS
2283 GetPe32Info (
2284 IN UINT8 *Pe32,
2285 OUT UINT32 *EntryPoint,
2286 OUT UINT32 *BaseOfCode,
2287 OUT UINT16 *MachineType
2288 )
2289 /*++
2290
2291 Routine Description:
2292
2293 Retrieves the PE32 entry point offset and machine type from PE image or TeImage.
2294 See EfiImage.h for machine types. The entry point offset is from the beginning
2295 of the PE32 buffer passed in.
2296
2297 Arguments:
2298
2299 Pe32 Beginning of the PE32.
2300 EntryPoint Offset from the beginning of the PE32 to the image entry point.
2301 BaseOfCode Base address of code.
2302 MachineType Magic number for the machine type.
2303
2304 Returns:
2305
2306 EFI_SUCCESS Function completed successfully.
2307 EFI_ABORTED Error encountered.
2308 EFI_INVALID_PARAMETER A required parameter was NULL.
2309 EFI_UNSUPPORTED The operation is unsupported.
2310
2311 --*/
2312 {
2313 EFI_IMAGE_DOS_HEADER *DosHeader;
2314 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
2315 EFI_TE_IMAGE_HEADER *TeHeader;
2316
2317 //
2318 // Verify input parameters
2319 //
2320 if (Pe32 == NULL) {
2321 return EFI_INVALID_PARAMETER;
2322 }
2323
2324 //
2325 // First check whether it is one TE Image.
2326 //
2327 TeHeader = (EFI_TE_IMAGE_HEADER *) Pe32;
2328 if (TeHeader->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
2329 //
2330 // By TeImage Header to get output
2331 //
2332 *EntryPoint = TeHeader->AddressOfEntryPoint + sizeof (EFI_TE_IMAGE_HEADER) - TeHeader->StrippedSize;
2333 *BaseOfCode = TeHeader->BaseOfCode + sizeof (EFI_TE_IMAGE_HEADER) - TeHeader->StrippedSize;
2334 *MachineType = TeHeader->Machine;
2335 } else {
2336
2337 //
2338 // Then check whether
2339 // First is the DOS header
2340 //
2341 DosHeader = (EFI_IMAGE_DOS_HEADER *) Pe32;
2342
2343 //
2344 // Verify DOS header is expected
2345 //
2346 if (DosHeader->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
2347 Error (NULL, 0, 3000, "Invalid", "Unknown magic number in the DOS header, 0x%04X.", DosHeader->e_magic);
2348 return EFI_UNSUPPORTED;
2349 }
2350 //
2351 // Immediately following is the NT header.
2352 //
2353 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *) ((UINTN) Pe32 + DosHeader->e_lfanew);
2354
2355 //
2356 // Verify NT header is expected
2357 //
2358 if (ImgHdr->Pe32.Signature != EFI_IMAGE_NT_SIGNATURE) {
2359 Error (NULL, 0, 3000, "Invalid", "Unrecognized image signature 0x%08X.", (unsigned) ImgHdr->Pe32.Signature);
2360 return EFI_UNSUPPORTED;
2361 }
2362 //
2363 // Get output
2364 //
2365 *EntryPoint = ImgHdr->Pe32.OptionalHeader.AddressOfEntryPoint;
2366 *BaseOfCode = ImgHdr->Pe32.OptionalHeader.BaseOfCode;
2367 *MachineType = ImgHdr->Pe32.FileHeader.Machine;
2368 }
2369
2370 //
2371 // Verify machine type is supported
2372 //
2373 if ((*MachineType != EFI_IMAGE_MACHINE_IA32) && (*MachineType != EFI_IMAGE_MACHINE_IA64) && (*MachineType != EFI_IMAGE_MACHINE_X64) && (*MachineType != EFI_IMAGE_MACHINE_EBC) &&
2374 (*MachineType != EFI_IMAGE_MACHINE_ARMT) && (*MachineType != EFI_IMAGE_MACHINE_AARCH64)) {
2375 Error (NULL, 0, 3000, "Invalid", "Unrecognized machine type in the PE32 file.");
2376 return EFI_UNSUPPORTED;
2377 }
2378
2379 return EFI_SUCCESS;
2380 }
2381
2382 EFI_STATUS
2383 GenerateFvImage (
2384 IN CHAR8 *InfFileImage,
2385 IN UINTN InfFileSize,
2386 IN CHAR8 *FvFileName,
2387 IN CHAR8 *MapFileName
2388 )
2389 /*++
2390
2391 Routine Description:
2392
2393 This is the main function which will be called from application.
2394
2395 Arguments:
2396
2397 InfFileImage Buffer containing the INF file contents.
2398 InfFileSize Size of the contents of the InfFileImage buffer.
2399 FvFileName Requested name for the FV file.
2400 MapFileName Fv map file to log fv driver information.
2401
2402 Returns:
2403
2404 EFI_SUCCESS Function completed successfully.
2405 EFI_OUT_OF_RESOURCES Could not allocate required resources.
2406 EFI_ABORTED Error encountered.
2407 EFI_INVALID_PARAMETER A required parameter was NULL.
2408
2409 --*/
2410 {
2411 EFI_STATUS Status;
2412 MEMORY_FILE InfMemoryFile;
2413 MEMORY_FILE FvImageMemoryFile;
2414 UINTN Index;
2415 EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
2416 EFI_FFS_FILE_HEADER *VtfFileImage;
2417 UINT8 *FvBufferHeader; // to make sure fvimage header 8 type alignment.
2418 UINT8 *FvImage;
2419 UINTN FvImageSize;
2420 FILE *FvFile;
2421 CHAR8 FvMapName [MAX_LONG_FILE_PATH];
2422 FILE *FvMapFile;
2423 EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader;
2424 FILE *FvExtHeaderFile;
2425 UINTN FileSize;
2426 CHAR8 FvReportName[MAX_LONG_FILE_PATH];
2427 FILE *FvReportFile;
2428
2429 FvBufferHeader = NULL;
2430 FvFile = NULL;
2431 FvMapFile = NULL;
2432 FvReportFile = NULL;
2433
2434 if (InfFileImage != NULL) {
2435 //
2436 // Initialize file structures
2437 //
2438 InfMemoryFile.FileImage = InfFileImage;
2439 InfMemoryFile.CurrentFilePointer = InfFileImage;
2440 InfMemoryFile.Eof = InfFileImage + InfFileSize;
2441
2442 //
2443 // Parse the FV inf file for header information
2444 //
2445 Status = ParseFvInf (&InfMemoryFile, &mFvDataInfo);
2446 if (EFI_ERROR (Status)) {
2447 Error (NULL, 0, 0003, "Error parsing file", "the input FV INF file.");
2448 return Status;
2449 }
2450 }
2451
2452 //
2453 // Update the file name return values
2454 //
2455 if (FvFileName == NULL && mFvDataInfo.FvName[0] != '\0') {
2456 FvFileName = mFvDataInfo.FvName;
2457 }
2458
2459 if (FvFileName == NULL) {
2460 Error (NULL, 0, 1001, "Missing option", "Output file name");
2461 return EFI_ABORTED;
2462 }
2463
2464 if (mFvDataInfo.FvBlocks[0].Length == 0) {
2465 Error (NULL, 0, 1001, "Missing required argument", "Block Size");
2466 return EFI_ABORTED;
2467 }
2468
2469 //
2470 // Debug message Fv File System Guid
2471 //
2472 if (mFvDataInfo.FvFileSystemGuidSet) {
2473 DebugMsg (NULL, 0, 9, "FV File System Guid", "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
2474 (unsigned) mFvDataInfo.FvFileSystemGuid.Data1,
2475 mFvDataInfo.FvFileSystemGuid.Data2,
2476 mFvDataInfo.FvFileSystemGuid.Data3,
2477 mFvDataInfo.FvFileSystemGuid.Data4[0],
2478 mFvDataInfo.FvFileSystemGuid.Data4[1],
2479 mFvDataInfo.FvFileSystemGuid.Data4[2],
2480 mFvDataInfo.FvFileSystemGuid.Data4[3],
2481 mFvDataInfo.FvFileSystemGuid.Data4[4],
2482 mFvDataInfo.FvFileSystemGuid.Data4[5],
2483 mFvDataInfo.FvFileSystemGuid.Data4[6],
2484 mFvDataInfo.FvFileSystemGuid.Data4[7]);
2485 }
2486
2487 //
2488 // Add PI FV extension header
2489 //
2490 FvExtHeader = NULL;
2491 FvExtHeaderFile = NULL;
2492 if (mFvDataInfo.FvExtHeaderFile[0] != 0) {
2493 //
2494 // Open the FV Extension Header file
2495 //
2496 FvExtHeaderFile = fopen (LongFilePath (mFvDataInfo.FvExtHeaderFile), "rb");
2497
2498 //
2499 // Get the file size
2500 //
2501 FileSize = _filelength (fileno (FvExtHeaderFile));
2502
2503 //
2504 // Allocate a buffer for the FV Extension Header
2505 //
2506 FvExtHeader = malloc(FileSize);
2507 if (FvExtHeader == NULL) {
2508 fclose (FvExtHeaderFile);
2509 return EFI_OUT_OF_RESOURCES;
2510 }
2511
2512 //
2513 // Read the FV Extension Header
2514 //
2515 fread (FvExtHeader, sizeof (UINT8), FileSize, FvExtHeaderFile);
2516 fclose (FvExtHeaderFile);
2517
2518 //
2519 // See if there is an override for the FV Name GUID
2520 //
2521 if (mFvDataInfo.FvNameGuidSet) {
2522 memcpy (&FvExtHeader->FvName, &mFvDataInfo.FvNameGuid, sizeof (EFI_GUID));
2523 }
2524 memcpy (&mFvDataInfo.FvNameGuid, &FvExtHeader->FvName, sizeof (EFI_GUID));
2525 mFvDataInfo.FvNameGuidSet = TRUE;
2526 } else if (mFvDataInfo.FvNameGuidSet) {
2527 //
2528 // Allocate a buffer for the FV Extension Header
2529 //
2530 FvExtHeader = malloc(sizeof (EFI_FIRMWARE_VOLUME_EXT_HEADER));
2531 if (FvExtHeader == NULL) {
2532 return EFI_OUT_OF_RESOURCES;
2533 }
2534 memcpy (&FvExtHeader->FvName, &mFvDataInfo.FvNameGuid, sizeof (EFI_GUID));
2535 FvExtHeader->ExtHeaderSize = sizeof (EFI_FIRMWARE_VOLUME_EXT_HEADER);
2536 }
2537
2538 //
2539 // Debug message Fv Name Guid
2540 //
2541 if (mFvDataInfo.FvNameGuidSet) {
2542 DebugMsg (NULL, 0, 9, "FV Name Guid", "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
2543 (unsigned) mFvDataInfo.FvNameGuid.Data1,
2544 mFvDataInfo.FvNameGuid.Data2,
2545 mFvDataInfo.FvNameGuid.Data3,
2546 mFvDataInfo.FvNameGuid.Data4[0],
2547 mFvDataInfo.FvNameGuid.Data4[1],
2548 mFvDataInfo.FvNameGuid.Data4[2],
2549 mFvDataInfo.FvNameGuid.Data4[3],
2550 mFvDataInfo.FvNameGuid.Data4[4],
2551 mFvDataInfo.FvNameGuid.Data4[5],
2552 mFvDataInfo.FvNameGuid.Data4[6],
2553 mFvDataInfo.FvNameGuid.Data4[7]);
2554 }
2555
2556 if (CompareGuid (&mFvDataInfo.FvFileSystemGuid, &mEfiFirmwareFileSystem2Guid) == 0 ||
2557 CompareGuid (&mFvDataInfo.FvFileSystemGuid, &mEfiFirmwareFileSystem3Guid) == 0) {
2558 mFvDataInfo.IsPiFvImage = TRUE;
2559 }
2560
2561 //
2562 // FvMap file to log the function address of all modules in one Fvimage
2563 //
2564 if (MapFileName != NULL) {
2565 strcpy (FvMapName, MapFileName);
2566 } else {
2567 strcpy (FvMapName, FvFileName);
2568 strcat (FvMapName, ".map");
2569 }
2570 VerboseMsg ("FV Map file name is %s", FvMapName);
2571
2572 //
2573 // FvReport file to log the FV information in one Fvimage
2574 //
2575 strcpy (FvReportName, FvFileName);
2576 strcat (FvReportName, ".txt");
2577
2578 //
2579 // Calculate the FV size and Update Fv Size based on the actual FFS files.
2580 // And Update mFvDataInfo data.
2581 //
2582 Status = CalculateFvSize (&mFvDataInfo);
2583 if (EFI_ERROR (Status)) {
2584 return Status;
2585 }
2586 VerboseMsg ("the generated FV image size is %u bytes", (unsigned) mFvDataInfo.Size);
2587
2588 //
2589 // support fv image and empty fv image
2590 //
2591 FvImageSize = mFvDataInfo.Size;
2592
2593 //
2594 // Allocate the FV, assure FvImage Header 8 byte alignment
2595 //
2596 FvBufferHeader = malloc (FvImageSize + sizeof (UINT64));
2597 if (FvBufferHeader == NULL) {
2598 return EFI_OUT_OF_RESOURCES;
2599 }
2600 FvImage = (UINT8 *) (((UINTN) FvBufferHeader + 7) & ~7);
2601
2602 //
2603 // Initialize the FV to the erase polarity
2604 //
2605 if (mFvDataInfo.FvAttributes == 0) {
2606 //
2607 // Set Default Fv Attribute
2608 //
2609 mFvDataInfo.FvAttributes = FV_DEFAULT_ATTRIBUTE;
2610 }
2611 if (mFvDataInfo.FvAttributes & EFI_FVB2_ERASE_POLARITY) {
2612 memset (FvImage, -1, FvImageSize);
2613 } else {
2614 memset (FvImage, 0, FvImageSize);
2615 }
2616
2617 //
2618 // Initialize FV header
2619 //
2620 FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) FvImage;
2621
2622 //
2623 // Initialize the zero vector to all zeros.
2624 //
2625 memset (FvHeader->ZeroVector, 0, 16);
2626
2627 //
2628 // Copy the Fv file system GUID
2629 //
2630 memcpy (&FvHeader->FileSystemGuid, &mFvDataInfo.FvFileSystemGuid, sizeof (EFI_GUID));
2631
2632 FvHeader->FvLength = FvImageSize;
2633 FvHeader->Signature = EFI_FVH_SIGNATURE;
2634 FvHeader->Attributes = mFvDataInfo.FvAttributes;
2635 FvHeader->Revision = EFI_FVH_REVISION;
2636 FvHeader->ExtHeaderOffset = 0;
2637 FvHeader->Reserved[0] = 0;
2638
2639 //
2640 // Copy firmware block map
2641 //
2642 for (Index = 0; mFvDataInfo.FvBlocks[Index].Length != 0; Index++) {
2643 FvHeader->BlockMap[Index].NumBlocks = mFvDataInfo.FvBlocks[Index].NumBlocks;
2644 FvHeader->BlockMap[Index].Length = mFvDataInfo.FvBlocks[Index].Length;
2645 }
2646
2647 //
2648 // Add block map terminator
2649 //
2650 FvHeader->BlockMap[Index].NumBlocks = 0;
2651 FvHeader->BlockMap[Index].Length = 0;
2652
2653 //
2654 // Complete the header
2655 //
2656 FvHeader->HeaderLength = (UINT16) (((UINTN) &(FvHeader->BlockMap[Index + 1])) - (UINTN) FvImage);
2657 FvHeader->Checksum = 0;
2658 FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16));
2659
2660 //
2661 // If there is no FFS file, generate one empty FV
2662 //
2663 if (mFvDataInfo.FvFiles[0][0] == 0 && !mFvDataInfo.FvNameGuidSet) {
2664 goto WriteFile;
2665 }
2666
2667 //
2668 // Initialize our "file" view of the buffer
2669 //
2670 FvImageMemoryFile.FileImage = (CHAR8 *)FvImage;
2671 FvImageMemoryFile.CurrentFilePointer = (CHAR8 *)FvImage + FvHeader->HeaderLength;
2672 FvImageMemoryFile.Eof = (CHAR8 *)FvImage + FvImageSize;
2673
2674 //
2675 // Initialize the FV library.
2676 //
2677 InitializeFvLib (FvImageMemoryFile.FileImage, FvImageSize);
2678
2679 //
2680 // Initialize the VTF file address.
2681 //
2682 VtfFileImage = (EFI_FFS_FILE_HEADER *) FvImageMemoryFile.Eof;
2683
2684 //
2685 // Open FvMap file
2686 //
2687 FvMapFile = fopen (LongFilePath (FvMapName), "w");
2688 if (FvMapFile == NULL) {
2689 Error (NULL, 0, 0001, "Error opening file", FvMapName);
2690 return EFI_ABORTED;
2691 }
2692
2693 //
2694 // Open FvReport file
2695 //
2696 FvReportFile = fopen (LongFilePath (FvReportName), "w");
2697 if (FvReportFile == NULL) {
2698 Error (NULL, 0, 0001, "Error opening file", FvReportName);
2699 return EFI_ABORTED;
2700 }
2701 //
2702 // record FV size information into FvMap file.
2703 //
2704 if (mFvTotalSize != 0) {
2705 fprintf (FvMapFile, EFI_FV_TOTAL_SIZE_STRING);
2706 fprintf (FvMapFile, " = 0x%x\n", (unsigned) mFvTotalSize);
2707 }
2708 if (mFvTakenSize != 0) {
2709 fprintf (FvMapFile, EFI_FV_TAKEN_SIZE_STRING);
2710 fprintf (FvMapFile, " = 0x%x\n", (unsigned) mFvTakenSize);
2711 }
2712 if (mFvTotalSize != 0 && mFvTakenSize != 0) {
2713 fprintf (FvMapFile, EFI_FV_SPACE_SIZE_STRING);
2714 fprintf (FvMapFile, " = 0x%x\n\n", (unsigned) (mFvTotalSize - mFvTakenSize));
2715 }
2716
2717 //
2718 // record FV size information to FvReportFile.
2719 //
2720 fprintf (FvReportFile, "%s = 0x%x\n", EFI_FV_TOTAL_SIZE_STRING, (unsigned) mFvTotalSize);
2721 fprintf (FvReportFile, "%s = 0x%x\n", EFI_FV_TAKEN_SIZE_STRING, (unsigned) mFvTakenSize);
2722
2723 //
2724 // Add PI FV extension header
2725 //
2726 if (FvExtHeader != NULL) {
2727 //
2728 // Add FV Extended Header contents to the FV as a PAD file
2729 //
2730 AddPadFile (&FvImageMemoryFile, 4, VtfFileImage, FvExtHeader, 0);
2731
2732 //
2733 // Fv Extension header change update Fv Header Check sum
2734 //
2735 FvHeader->Checksum = 0;
2736 FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16));
2737 }
2738
2739 //
2740 // Add files to FV
2741 //
2742 for (Index = 0; mFvDataInfo.FvFiles[Index][0] != 0; Index++) {
2743 //
2744 // Add the file
2745 //
2746 Status = AddFile (&FvImageMemoryFile, &mFvDataInfo, Index, &VtfFileImage, FvMapFile, FvReportFile);
2747
2748 //
2749 // Exit if error detected while adding the file
2750 //
2751 if (EFI_ERROR (Status)) {
2752 goto Finish;
2753 }
2754 }
2755
2756 //
2757 // If there is a VTF file, some special actions need to occur.
2758 //
2759 if ((UINTN) VtfFileImage != (UINTN) FvImageMemoryFile.Eof) {
2760 //
2761 // Pad from the end of the last file to the beginning of the VTF file.
2762 // If the left space is less than sizeof (EFI_FFS_FILE_HEADER)?
2763 //
2764 Status = PadFvImage (&FvImageMemoryFile, VtfFileImage);
2765 if (EFI_ERROR (Status)) {
2766 Error (NULL, 0, 4002, "Resource", "FV space is full, cannot add pad file between the last file and the VTF file.");
2767 goto Finish;
2768 }
2769 if (!mArm) {
2770 //
2771 // Update reset vector (SALE_ENTRY for IPF)
2772 // Now for IA32 and IA64 platform, the fv which has bsf file must have the
2773 // EndAddress of 0xFFFFFFFF. Thus, only this type fv needs to update the
2774 // reset vector. If the PEI Core is found, the VTF file will probably get
2775 // corrupted by updating the entry point.
2776 //
2777 if ((mFvDataInfo.BaseAddress + mFvDataInfo.Size) == FV_IMAGES_TOP_ADDRESS) {
2778 Status = UpdateResetVector (&FvImageMemoryFile, &mFvDataInfo, VtfFileImage);
2779 if (EFI_ERROR(Status)) {
2780 Error (NULL, 0, 3000, "Invalid", "Could not update the reset vector.");
2781 goto Finish;
2782 }
2783 DebugMsg (NULL, 0, 9, "Update Reset vector in VTF file", NULL);
2784 }
2785 }
2786 }
2787
2788 if (mArm) {
2789 Status = UpdateArmResetVectorIfNeeded (&FvImageMemoryFile, &mFvDataInfo);
2790 if (EFI_ERROR (Status)) {
2791 Error (NULL, 0, 3000, "Invalid", "Could not update the reset vector.");
2792 goto Finish;
2793 }
2794
2795 //
2796 // Update Checksum for FvHeader
2797 //
2798 FvHeader->Checksum = 0;
2799 FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16));
2800 }
2801
2802 //
2803 // Update FV Alignment attribute to the largest alignment of all the FFS files in the FV
2804 //
2805 if (((FvHeader->Attributes & EFI_FVB2_WEAK_ALIGNMENT) != EFI_FVB2_WEAK_ALIGNMENT) &&
2806 (((FvHeader->Attributes & EFI_FVB2_ALIGNMENT) >> 16)) < MaxFfsAlignment) {
2807 FvHeader->Attributes = ((MaxFfsAlignment << 16) | (FvHeader->Attributes & 0xFFFF));
2808 //
2809 // Update Checksum for FvHeader
2810 //
2811 FvHeader->Checksum = 0;
2812 FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16));
2813 }
2814
2815 //
2816 // If there are large FFS in FV, the file system GUID should set to system 3 GUID.
2817 //
2818 if (mIsLargeFfs && CompareGuid (&FvHeader->FileSystemGuid, &mEfiFirmwareFileSystem2Guid) == 0) {
2819 memcpy (&FvHeader->FileSystemGuid, &mEfiFirmwareFileSystem3Guid, sizeof (EFI_GUID));
2820 FvHeader->Checksum = 0;
2821 FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16));
2822 }
2823
2824 WriteFile:
2825 //
2826 // Write fv file
2827 //
2828 FvFile = fopen (LongFilePath (FvFileName), "wb");
2829 if (FvFile == NULL) {
2830 Error (NULL, 0, 0001, "Error opening file", FvFileName);
2831 Status = EFI_ABORTED;
2832 goto Finish;
2833 }
2834
2835 if (fwrite (FvImage, 1, FvImageSize, FvFile) != FvImageSize) {
2836 Error (NULL, 0, 0002, "Error writing file", FvFileName);
2837 Status = EFI_ABORTED;
2838 goto Finish;
2839 }
2840
2841 Finish:
2842 if (FvBufferHeader != NULL) {
2843 free (FvBufferHeader);
2844 }
2845
2846 if (FvExtHeader != NULL) {
2847 free (FvExtHeader);
2848 }
2849
2850 if (FvFile != NULL) {
2851 fflush (FvFile);
2852 fclose (FvFile);
2853 }
2854
2855 if (FvMapFile != NULL) {
2856 fflush (FvMapFile);
2857 fclose (FvMapFile);
2858 }
2859
2860 if (FvReportFile != NULL) {
2861 fflush (FvReportFile);
2862 fclose (FvReportFile);
2863 }
2864 return Status;
2865 }
2866
2867 EFI_STATUS
2868 UpdatePeiCoreEntryInFit (
2869 IN FIT_TABLE *FitTablePtr,
2870 IN UINT64 PeiCorePhysicalAddress
2871 )
2872 /*++
2873
2874 Routine Description:
2875
2876 This function is used to update the Pei Core address in FIT, this can be used by Sec core to pass control from
2877 Sec to Pei Core
2878
2879 Arguments:
2880
2881 FitTablePtr - The pointer of FIT_TABLE.
2882 PeiCorePhysicalAddress - The address of Pei Core entry.
2883
2884 Returns:
2885
2886 EFI_SUCCESS - The PEI_CORE FIT entry was updated successfully.
2887 EFI_NOT_FOUND - Not found the PEI_CORE FIT entry.
2888
2889 --*/
2890 {
2891 FIT_TABLE *TmpFitPtr;
2892 UINTN Index;
2893 UINTN NumFitComponents;
2894
2895 TmpFitPtr = FitTablePtr;
2896 NumFitComponents = TmpFitPtr->CompSize;
2897
2898 for (Index = 0; Index < NumFitComponents; Index++) {
2899 if ((TmpFitPtr->CvAndType & FIT_TYPE_MASK) == COMP_TYPE_FIT_PEICORE) {
2900 TmpFitPtr->CompAddress = PeiCorePhysicalAddress;
2901 return EFI_SUCCESS;
2902 }
2903
2904 TmpFitPtr++;
2905 }
2906
2907 return EFI_NOT_FOUND;
2908 }
2909
2910 VOID
2911 UpdateFitCheckSum (
2912 IN FIT_TABLE *FitTablePtr
2913 )
2914 /*++
2915
2916 Routine Description:
2917
2918 This function is used to update the checksum for FIT.
2919
2920
2921 Arguments:
2922
2923 FitTablePtr - The pointer of FIT_TABLE.
2924
2925 Returns:
2926
2927 None.
2928
2929 --*/
2930 {
2931 if ((FitTablePtr->CvAndType & CHECKSUM_BIT_MASK) >> 7) {
2932 FitTablePtr->CheckSum = 0;
2933 FitTablePtr->CheckSum = CalculateChecksum8 ((UINT8 *) FitTablePtr, FitTablePtr->CompSize * 16);
2934 }
2935 }
2936
2937 EFI_STATUS
2938 CalculateFvSize (
2939 FV_INFO *FvInfoPtr
2940 )
2941 /*++
2942 Routine Description:
2943 Calculate the FV size and Update Fv Size based on the actual FFS files.
2944 And Update FvInfo data.
2945
2946 Arguments:
2947 FvInfoPtr - The pointer to FV_INFO structure.
2948
2949 Returns:
2950 EFI_ABORTED - Ffs Image Error
2951 EFI_SUCCESS - Successfully update FvSize
2952 --*/
2953 {
2954 UINTN CurrentOffset;
2955 UINTN Index;
2956 FILE *fpin;
2957 UINTN FfsFileSize;
2958 UINTN FvExtendHeaderSize;
2959 UINT32 FfsAlignment;
2960 UINT32 FfsHeaderSize;
2961 EFI_FFS_FILE_HEADER FfsHeader;
2962 BOOLEAN VtfFileFlag;
2963 UINTN VtfFileSize;
2964
2965 FvExtendHeaderSize = 0;
2966 VtfFileSize = 0;
2967 VtfFileFlag = FALSE;
2968 fpin = NULL;
2969 Index = 0;
2970
2971 //
2972 // Compute size for easy access later
2973 //
2974 FvInfoPtr->Size = 0;
2975 for (Index = 0; FvInfoPtr->FvBlocks[Index].NumBlocks > 0 && FvInfoPtr->FvBlocks[Index].Length > 0; Index++) {
2976 FvInfoPtr->Size += FvInfoPtr->FvBlocks[Index].NumBlocks * FvInfoPtr->FvBlocks[Index].Length;
2977 }
2978
2979 //
2980 // Calculate the required sizes for all FFS files.
2981 //
2982 CurrentOffset = sizeof (EFI_FIRMWARE_VOLUME_HEADER);
2983
2984 for (Index = 1;; Index ++) {
2985 CurrentOffset += sizeof (EFI_FV_BLOCK_MAP_ENTRY);
2986 if (FvInfoPtr->FvBlocks[Index].NumBlocks == 0 || FvInfoPtr->FvBlocks[Index].Length == 0) {
2987 break;
2988 }
2989 }
2990
2991 //
2992 // Calculate PI extension header
2993 //
2994 if (mFvDataInfo.FvExtHeaderFile[0] != '\0') {
2995 fpin = fopen (LongFilePath (mFvDataInfo.FvExtHeaderFile), "rb");
2996 if (fpin == NULL) {
2997 Error (NULL, 0, 0001, "Error opening file", mFvDataInfo.FvExtHeaderFile);
2998 return EFI_ABORTED;
2999 }
3000 FvExtendHeaderSize = _filelength (fileno (fpin));
3001 fclose (fpin);
3002 if (sizeof (EFI_FFS_FILE_HEADER) + FvExtendHeaderSize >= MAX_FFS_SIZE) {
3003 CurrentOffset += sizeof (EFI_FFS_FILE_HEADER2) + FvExtendHeaderSize;
3004 mIsLargeFfs = TRUE;
3005 } else {
3006 CurrentOffset += sizeof (EFI_FFS_FILE_HEADER) + FvExtendHeaderSize;
3007 }
3008 CurrentOffset = (CurrentOffset + 7) & (~7);
3009 } else if (mFvDataInfo.FvNameGuidSet) {
3010 CurrentOffset += sizeof (EFI_FFS_FILE_HEADER) + sizeof (EFI_FIRMWARE_VOLUME_EXT_HEADER);
3011 CurrentOffset = (CurrentOffset + 7) & (~7);
3012 }
3013
3014 //
3015 // Accumlate every FFS file size.
3016 //
3017 for (Index = 0; FvInfoPtr->FvFiles[Index][0] != 0; Index++) {
3018 //
3019 // Open FFS file
3020 //
3021 fpin = NULL;
3022 fpin = fopen (LongFilePath (FvInfoPtr->FvFiles[Index]), "rb");
3023 if (fpin == NULL) {
3024 Error (NULL, 0, 0001, "Error opening file", FvInfoPtr->FvFiles[Index]);
3025 return EFI_ABORTED;
3026 }
3027 //
3028 // Get the file size
3029 //
3030 FfsFileSize = _filelength (fileno (fpin));
3031 if (FfsFileSize >= MAX_FFS_SIZE) {
3032 FfsHeaderSize = sizeof(EFI_FFS_FILE_HEADER2);
3033 mIsLargeFfs = TRUE;
3034 } else {
3035 FfsHeaderSize = sizeof(EFI_FFS_FILE_HEADER);
3036 }
3037 //
3038 // Read Ffs File header
3039 //
3040 fread (&FfsHeader, sizeof (UINT8), sizeof (EFI_FFS_FILE_HEADER), fpin);
3041 //
3042 // close file
3043 //
3044 fclose (fpin);
3045
3046 if (FvInfoPtr->IsPiFvImage) {
3047 //
3048 // Check whether this ffs file is vtf file
3049 //
3050 if (IsVtfFile (&FfsHeader)) {
3051 if (VtfFileFlag) {
3052 //
3053 // One Fv image can't have two vtf files.
3054 //
3055 Error (NULL, 0, 3000,"Invalid", "One Fv image can't have two vtf files.");
3056 return EFI_ABORTED;
3057 }
3058 VtfFileFlag = TRUE;
3059 VtfFileSize = FfsFileSize;
3060 continue;
3061 }
3062
3063 //
3064 // Get the alignment of FFS file
3065 //
3066 ReadFfsAlignment (&FfsHeader, &FfsAlignment);
3067 FfsAlignment = 1 << FfsAlignment;
3068 //
3069 // Add Pad file
3070 //
3071 if (((CurrentOffset + FfsHeaderSize) % FfsAlignment) != 0) {
3072 //
3073 // Only EFI_FFS_FILE_HEADER is needed for a pad section.
3074 //
3075 CurrentOffset = (CurrentOffset + FfsHeaderSize + sizeof(EFI_FFS_FILE_HEADER) + FfsAlignment - 1) & ~(FfsAlignment - 1);
3076 CurrentOffset -= FfsHeaderSize;
3077 }
3078 }
3079
3080 //
3081 // Add ffs file size
3082 //
3083 if (FvInfoPtr->SizeofFvFiles[Index] > FfsFileSize) {
3084 CurrentOffset += FvInfoPtr->SizeofFvFiles[Index];
3085 } else {
3086 CurrentOffset += FfsFileSize;
3087 }
3088
3089 //
3090 // Make next ffs file start at QWord Boundry
3091 //
3092 if (FvInfoPtr->IsPiFvImage) {
3093 CurrentOffset = (CurrentOffset + EFI_FFS_FILE_HEADER_ALIGNMENT - 1) & ~(EFI_FFS_FILE_HEADER_ALIGNMENT - 1);
3094 }
3095 }
3096 CurrentOffset += VtfFileSize;
3097 DebugMsg (NULL, 0, 9, "FvImage size", "The calculated fv image size is 0x%x and the current set fv image size is 0x%x", (unsigned) CurrentOffset, (unsigned) FvInfoPtr->Size);
3098
3099 if (FvInfoPtr->Size == 0) {
3100 //
3101 // Update FvInfo data
3102 //
3103 FvInfoPtr->FvBlocks[0].NumBlocks = CurrentOffset / FvInfoPtr->FvBlocks[0].Length + ((CurrentOffset % FvInfoPtr->FvBlocks[0].Length)?1:0);
3104 FvInfoPtr->Size = FvInfoPtr->FvBlocks[0].NumBlocks * FvInfoPtr->FvBlocks[0].Length;
3105 FvInfoPtr->FvBlocks[1].NumBlocks = 0;
3106 FvInfoPtr->FvBlocks[1].Length = 0;
3107 } else if (FvInfoPtr->Size < CurrentOffset) {
3108 //
3109 // Not invalid
3110 //
3111 Error (NULL, 0, 3000, "Invalid", "the required fv image size 0x%x exceeds the set fv image size 0x%x", (unsigned) CurrentOffset, (unsigned) FvInfoPtr->Size);
3112 return EFI_INVALID_PARAMETER;
3113 }
3114
3115 //
3116 // Set Fv Size Information
3117 //
3118 mFvTotalSize = FvInfoPtr->Size;
3119 mFvTakenSize = CurrentOffset;
3120
3121 return EFI_SUCCESS;
3122 }
3123
3124 EFI_STATUS
3125 FfsRebaseImageRead (
3126 IN VOID *FileHandle,
3127 IN UINTN FileOffset,
3128 IN OUT UINT32 *ReadSize,
3129 OUT VOID *Buffer
3130 )
3131 /*++
3132
3133 Routine Description:
3134
3135 Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
3136
3137 Arguments:
3138
3139 FileHandle - The handle to the PE/COFF file
3140
3141 FileOffset - The offset, in bytes, into the file to read
3142
3143 ReadSize - The number of bytes to read from the file starting at FileOffset
3144
3145 Buffer - A pointer to the buffer to read the data into.
3146
3147 Returns:
3148
3149 EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
3150
3151 --*/
3152 {
3153 CHAR8 *Destination8;
3154 CHAR8 *Source8;
3155 UINT32 Length;
3156
3157 Destination8 = Buffer;
3158 Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
3159 Length = *ReadSize;
3160 while (Length--) {
3161 *(Destination8++) = *(Source8++);
3162 }
3163
3164 return EFI_SUCCESS;
3165 }
3166
3167 EFI_STATUS
3168 GetChildFvFromFfs (
3169 IN FV_INFO *FvInfo,
3170 IN EFI_FFS_FILE_HEADER *FfsFile,
3171 IN UINTN XipOffset
3172 )
3173 /*++
3174
3175 Routine Description:
3176
3177 This function gets all child FvImages in the input FfsFile, and records
3178 their base address to the parent image.
3179
3180 Arguments:
3181 FvInfo A pointer to FV_INFO struture.
3182 FfsFile A pointer to Ffs file image that may contain FvImage.
3183 XipOffset The offset address to the parent FvImage base.
3184
3185 Returns:
3186
3187 EFI_SUCCESS Base address of child Fv image is recorded.
3188 --*/
3189 {
3190 EFI_STATUS Status;
3191 UINTN Index;
3192 EFI_FILE_SECTION_POINTER SubFvSection;
3193 EFI_FIRMWARE_VOLUME_HEADER *SubFvImageHeader;
3194 EFI_PHYSICAL_ADDRESS SubFvBaseAddress;
3195 EFI_FILE_SECTION_POINTER CorePe32;
3196 UINT16 MachineType;
3197
3198 for (Index = 1;; Index++) {
3199 //
3200 // Find FV section
3201 //
3202 Status = GetSectionByType (FfsFile, EFI_SECTION_FIRMWARE_VOLUME_IMAGE, Index, &SubFvSection);
3203 if (EFI_ERROR (Status)) {
3204 break;
3205 }
3206 SubFvImageHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINT8 *) SubFvSection.FVImageSection + GetSectionHeaderLength(SubFvSection.FVImageSection));
3207
3208 //
3209 // See if there's an SEC core in the child FV
3210 Status = FindCorePeSection(SubFvImageHeader, SubFvImageHeader->FvLength, EFI_FV_FILETYPE_SECURITY_CORE, &CorePe32);
3211
3212 // if we couldn't find the SEC core, look for a PEI core
3213 if (EFI_ERROR(Status)) {
3214 Status = FindCorePeSection(SubFvImageHeader, SubFvImageHeader->FvLength, EFI_FV_FILETYPE_PEI_CORE, &CorePe32);
3215 }
3216
3217 if (!EFI_ERROR(Status)) {
3218 Status = GetCoreMachineType(CorePe32, &MachineType);
3219 if (EFI_ERROR(Status)) {
3220 Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 machine type for SEC/PEI Core.");
3221 return EFI_ABORTED;
3222 }
3223
3224 // machine type is ARM, set a flag so ARM reset vector procesing occurs
3225 if ((MachineType == EFI_IMAGE_MACHINE_ARMT) || (MachineType == EFI_IMAGE_MACHINE_AARCH64)) {
3226 VerboseMsg("Located ARM/AArch64 SEC/PEI core in child FV");
3227 mArm = TRUE;
3228 }
3229 }
3230
3231 //
3232 // Rebase on Flash
3233 //
3234 SubFvBaseAddress = FvInfo->BaseAddress + (UINTN) SubFvImageHeader - (UINTN) FfsFile + XipOffset;
3235 mFvBaseAddress[mFvBaseAddressNumber ++ ] = SubFvBaseAddress;
3236 }
3237
3238 return EFI_SUCCESS;
3239 }
3240
3241 EFI_STATUS
3242 FfsRebase (
3243 IN OUT FV_INFO *FvInfo,
3244 IN CHAR8 *FileName,
3245 IN OUT EFI_FFS_FILE_HEADER *FfsFile,
3246 IN UINTN XipOffset,
3247 IN FILE *FvMapFile
3248 )
3249 /*++
3250
3251 Routine Description:
3252
3253 This function determines if a file is XIP and should be rebased. It will
3254 rebase any PE32 sections found in the file using the base address.
3255
3256 Arguments:
3257
3258 FvInfo A pointer to FV_INFO struture.
3259 FileName Ffs File PathName
3260 FfsFile A pointer to Ffs file image.
3261 XipOffset The offset address to use for rebasing the XIP file image.
3262 FvMapFile FvMapFile to record the function address in one Fvimage
3263
3264 Returns:
3265
3266 EFI_SUCCESS The image was properly rebased.
3267 EFI_INVALID_PARAMETER An input parameter is invalid.
3268 EFI_ABORTED An error occurred while rebasing the input file image.
3269 EFI_OUT_OF_RESOURCES Could not allocate a required resource.
3270 EFI_NOT_FOUND No compressed sections could be found.
3271
3272 --*/
3273 {
3274 EFI_STATUS Status;
3275 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
3276 PE_COFF_LOADER_IMAGE_CONTEXT OrigImageContext;
3277 EFI_PHYSICAL_ADDRESS XipBase;
3278 EFI_PHYSICAL_ADDRESS NewPe32BaseAddress;
3279 UINTN Index;
3280 EFI_FILE_SECTION_POINTER CurrentPe32Section;
3281 EFI_FFS_FILE_STATE SavedState;
3282 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
3283 EFI_TE_IMAGE_HEADER *TEImageHeader;
3284 UINT8 *MemoryImagePointer;
3285 EFI_IMAGE_SECTION_HEADER *SectionHeader;
3286 CHAR8 PeFileName [MAX_LONG_FILE_PATH];
3287 CHAR8 *Cptr;
3288 FILE *PeFile;
3289 UINT8 *PeFileBuffer;
3290 UINT32 PeFileSize;
3291 CHAR8 *PdbPointer;
3292 UINT32 FfsHeaderSize;
3293 UINT32 CurSecHdrSize;
3294
3295 Index = 0;
3296 MemoryImagePointer = NULL;
3297 TEImageHeader = NULL;
3298 ImgHdr = NULL;
3299 SectionHeader = NULL;
3300 Cptr = NULL;
3301 PeFile = NULL;
3302 PeFileBuffer = NULL;
3303
3304 //
3305 // Don't need to relocate image when BaseAddress is zero and no ForceRebase Flag specified.
3306 //
3307 if ((FvInfo->BaseAddress == 0) && (FvInfo->ForceRebase == -1)) {
3308 return EFI_SUCCESS;
3309 }
3310
3311 //
3312 // If ForceRebase Flag specified to FALSE, will always not take rebase action.
3313 //
3314 if (FvInfo->ForceRebase == 0) {
3315 return EFI_SUCCESS;
3316 }
3317
3318
3319 XipBase = FvInfo->BaseAddress + XipOffset;
3320
3321 //
3322 // We only process files potentially containing PE32 sections.
3323 //
3324 switch (FfsFile->Type) {
3325 case EFI_FV_FILETYPE_SECURITY_CORE:
3326 case EFI_FV_FILETYPE_PEI_CORE:
3327 case EFI_FV_FILETYPE_PEIM:
3328 case EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER:
3329 case EFI_FV_FILETYPE_DRIVER:
3330 case EFI_FV_FILETYPE_DXE_CORE:
3331 break;
3332 case EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE:
3333 //
3334 // Rebase the inside FvImage.
3335 //
3336 GetChildFvFromFfs (FvInfo, FfsFile, XipOffset);
3337
3338 //
3339 // Search PE/TE section in FV sectin.
3340 //
3341 break;
3342 default:
3343 return EFI_SUCCESS;
3344 }
3345
3346 FfsHeaderSize = GetFfsHeaderLength(FfsFile);
3347 //
3348 // Rebase each PE32 section
3349 //
3350 Status = EFI_SUCCESS;
3351 for (Index = 1;; Index++) {
3352 //
3353 // Init Value
3354 //
3355 NewPe32BaseAddress = 0;
3356
3357 //
3358 // Find Pe Image
3359 //
3360 Status = GetSectionByType (FfsFile, EFI_SECTION_PE32, Index, &CurrentPe32Section);
3361 if (EFI_ERROR (Status)) {
3362 break;
3363 }
3364 CurSecHdrSize = GetSectionHeaderLength(CurrentPe32Section.CommonHeader);
3365
3366 //
3367 // Initialize context
3368 //
3369 memset (&ImageContext, 0, sizeof (ImageContext));
3370 ImageContext.Handle = (VOID *) ((UINTN) CurrentPe32Section.Pe32Section + CurSecHdrSize);
3371 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) FfsRebaseImageRead;
3372 Status = PeCoffLoaderGetImageInfo (&ImageContext);
3373 if (EFI_ERROR (Status)) {
3374 Error (NULL, 0, 3000, "Invalid PeImage", "The input file is %s and the return status is %x", FileName, (int) Status);
3375 return Status;
3376 }
3377
3378 if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_ARMT) ||
3379 (ImageContext.Machine == EFI_IMAGE_MACHINE_AARCH64) ) {
3380 mArm = TRUE;
3381 }
3382
3383 //
3384 // Keep Image Context for PE image in FV
3385 //
3386 memcpy (&OrigImageContext, &ImageContext, sizeof (ImageContext));
3387
3388 //
3389 // Get File PdbPointer
3390 //
3391 PdbPointer = PeCoffLoaderGetPdbPointer (ImageContext.Handle);
3392
3393 //
3394 // Get PeHeader pointer
3395 //
3396 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((UINTN) CurrentPe32Section.Pe32Section + CurSecHdrSize + ImageContext.PeCoffHeaderOffset);
3397
3398 //
3399 // Calculate the PE32 base address, based on file type
3400 //
3401 switch (FfsFile->Type) {
3402 case EFI_FV_FILETYPE_SECURITY_CORE:
3403 case EFI_FV_FILETYPE_PEI_CORE:
3404 case EFI_FV_FILETYPE_PEIM:
3405 case EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER:
3406 //
3407 // Check if section-alignment and file-alignment match or not
3408 //
3409 if ((ImgHdr->Pe32.OptionalHeader.SectionAlignment != ImgHdr->Pe32.OptionalHeader.FileAlignment)) {
3410 //
3411 // Xip module has the same section alignment and file alignment.
3412 //
3413 Error (NULL, 0, 3000, "Invalid", "Section-Alignment and File-Alignment do not match : %s.", FileName);
3414 return EFI_ABORTED;
3415 }
3416 //
3417 // PeImage has no reloc section. It will try to get reloc data from the original EFI image.
3418 //
3419 if (ImageContext.RelocationsStripped) {
3420 //
3421 // Construct the original efi file Name
3422 //
3423 strcpy (PeFileName, FileName);
3424 Cptr = PeFileName + strlen (PeFileName);
3425 while (*Cptr != '.') {
3426 Cptr --;
3427 }
3428 if (*Cptr != '.') {
3429 Error (NULL, 0, 3000, "Invalid", "The file %s has no .reloc section.", FileName);
3430 return EFI_ABORTED;
3431 } else {
3432 *(Cptr + 1) = 'e';
3433 *(Cptr + 2) = 'f';
3434 *(Cptr + 3) = 'i';
3435 *(Cptr + 4) = '\0';
3436 }
3437 PeFile = fopen (LongFilePath (PeFileName), "rb");
3438 if (PeFile == NULL) {
3439 Warning (NULL, 0, 0, "Invalid", "The file %s has no .reloc section.", FileName);
3440 //Error (NULL, 0, 3000, "Invalid", "The file %s has no .reloc section.", FileName);
3441 //return EFI_ABORTED;
3442 break;
3443 }
3444 //
3445 // Get the file size
3446 //
3447 PeFileSize = _filelength (fileno (PeFile));
3448 PeFileBuffer = (UINT8 *) malloc (PeFileSize);
3449 if (PeFileBuffer == NULL) {
3450 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated on rebase of %s", FileName);
3451 return EFI_OUT_OF_RESOURCES;
3452 }
3453 //
3454 // Read Pe File
3455 //
3456 fread (PeFileBuffer, sizeof (UINT8), PeFileSize, PeFile);
3457 //
3458 // close file
3459 //
3460 fclose (PeFile);
3461 //
3462 // Handle pointer to the original efi image.
3463 //
3464 ImageContext.Handle = PeFileBuffer;
3465 Status = PeCoffLoaderGetImageInfo (&ImageContext);
3466 if (EFI_ERROR (Status)) {
3467 Error (NULL, 0, 3000, "Invalid PeImage", "The input file is %s and the return status is %x", FileName, (int) Status);
3468 return Status;
3469 }
3470 ImageContext.RelocationsStripped = FALSE;
3471 }
3472
3473 NewPe32BaseAddress = XipBase + (UINTN) CurrentPe32Section.Pe32Section + CurSecHdrSize - (UINTN)FfsFile;
3474 break;
3475
3476 case EFI_FV_FILETYPE_DRIVER:
3477 case EFI_FV_FILETYPE_DXE_CORE:
3478 //
3479 // Check if section-alignment and file-alignment match or not
3480 //
3481 if ((ImgHdr->Pe32.OptionalHeader.SectionAlignment != ImgHdr->Pe32.OptionalHeader.FileAlignment)) {
3482 //
3483 // Xip module has the same section alignment and file alignment.
3484 //
3485 Error (NULL, 0, 3000, "Invalid", "Section-Alignment and File-Alignment do not match : %s.", FileName);
3486 return EFI_ABORTED;
3487 }
3488 NewPe32BaseAddress = XipBase + (UINTN) CurrentPe32Section.Pe32Section + CurSecHdrSize - (UINTN)FfsFile;
3489 break;
3490
3491 default:
3492 //
3493 // Not supported file type
3494 //
3495 return EFI_SUCCESS;
3496 }
3497
3498 //
3499 // Relocation doesn't exist
3500 //
3501 if (ImageContext.RelocationsStripped) {
3502 Warning (NULL, 0, 0, "Invalid", "The file %s has no .reloc section.", FileName);
3503 continue;
3504 }
3505
3506 //
3507 // Relocation exist and rebase
3508 //
3509 //
3510 // Load and Relocate Image Data
3511 //
3512 MemoryImagePointer = (UINT8 *) malloc ((UINTN) ImageContext.ImageSize + ImageContext.SectionAlignment);
3513 if (MemoryImagePointer == NULL) {
3514 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated on rebase of %s", FileName);
3515 return EFI_OUT_OF_RESOURCES;
3516 }
3517 memset ((VOID *) MemoryImagePointer, 0, (UINTN) ImageContext.ImageSize + ImageContext.SectionAlignment);
3518 ImageContext.ImageAddress = ((UINTN) MemoryImagePointer + ImageContext.SectionAlignment - 1) & (~((UINTN) ImageContext.SectionAlignment - 1));
3519
3520 Status = PeCoffLoaderLoadImage (&ImageContext);
3521 if (EFI_ERROR (Status)) {
3522 Error (NULL, 0, 3000, "Invalid", "LocateImage() call failed on rebase of %s", FileName);
3523 free ((VOID *) MemoryImagePointer);
3524 return Status;
3525 }
3526
3527 ImageContext.DestinationAddress = NewPe32BaseAddress;
3528 Status = PeCoffLoaderRelocateImage (&ImageContext);
3529 if (EFI_ERROR (Status)) {
3530 Error (NULL, 0, 3000, "Invalid", "RelocateImage() call failed on rebase of %s", FileName);
3531 free ((VOID *) MemoryImagePointer);
3532 return Status;
3533 }
3534
3535 //
3536 // Copy Relocated data to raw image file.
3537 //
3538 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (
3539 (UINTN) ImgHdr +
3540 sizeof (UINT32) +
3541 sizeof (EFI_IMAGE_FILE_HEADER) +
3542 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader
3543 );
3544
3545 for (Index = 0; Index < ImgHdr->Pe32.FileHeader.NumberOfSections; Index ++, SectionHeader ++) {
3546 CopyMem (
3547 (UINT8 *) CurrentPe32Section.Pe32Section + CurSecHdrSize + SectionHeader->PointerToRawData,
3548 (VOID*) (UINTN) (ImageContext.ImageAddress + SectionHeader->VirtualAddress),
3549 SectionHeader->SizeOfRawData
3550 );
3551 }
3552
3553 free ((VOID *) MemoryImagePointer);
3554 MemoryImagePointer = NULL;
3555 if (PeFileBuffer != NULL) {
3556 free (PeFileBuffer);
3557 PeFileBuffer = NULL;
3558 }
3559
3560 //
3561 // Update Image Base Address
3562 //
3563 if (ImgHdr->Pe32.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
3564 ImgHdr->Pe32.OptionalHeader.ImageBase = (UINT32) NewPe32BaseAddress;
3565 } else if (ImgHdr->Pe32Plus.OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
3566 ImgHdr->Pe32Plus.OptionalHeader.ImageBase = NewPe32BaseAddress;
3567 } else {
3568 Error (NULL, 0, 3000, "Invalid", "unknown PE magic signature %X in PE32 image %s",
3569 ImgHdr->Pe32.OptionalHeader.Magic,
3570 FileName
3571 );
3572 return EFI_ABORTED;
3573 }
3574
3575 //
3576 // Now update file checksum
3577 //
3578 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
3579 SavedState = FfsFile->State;
3580 FfsFile->IntegrityCheck.Checksum.File = 0;
3581 FfsFile->State = 0;
3582 FfsFile->IntegrityCheck.Checksum.File = CalculateChecksum8 (
3583 (UINT8 *) ((UINT8 *)FfsFile + FfsHeaderSize),
3584 GetFfsFileLength (FfsFile) - FfsHeaderSize
3585 );
3586 FfsFile->State = SavedState;
3587 }
3588
3589 //
3590 // Get this module function address from ModulePeMapFile and add them into FvMap file
3591 //
3592
3593 //
3594 // Default use FileName as map file path
3595 //
3596 if (PdbPointer == NULL) {
3597 PdbPointer = FileName;
3598 }
3599
3600 WriteMapFile (FvMapFile, PdbPointer, FfsFile, NewPe32BaseAddress, &OrigImageContext);
3601 }
3602
3603 if (FfsFile->Type != EFI_FV_FILETYPE_SECURITY_CORE &&
3604 FfsFile->Type != EFI_FV_FILETYPE_PEI_CORE &&
3605 FfsFile->Type != EFI_FV_FILETYPE_PEIM &&
3606 FfsFile->Type != EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER &&
3607 FfsFile->Type != EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE
3608 ) {
3609 //
3610 // Only Peim code may have a TE section
3611 //
3612 return EFI_SUCCESS;
3613 }
3614
3615 //
3616 // Now process TE sections
3617 //
3618 for (Index = 1;; Index++) {
3619 NewPe32BaseAddress = 0;
3620
3621 //
3622 // Find Te Image
3623 //
3624 Status = GetSectionByType (FfsFile, EFI_SECTION_TE, Index, &CurrentPe32Section);
3625 if (EFI_ERROR (Status)) {
3626 break;
3627 }
3628
3629 CurSecHdrSize = GetSectionHeaderLength(CurrentPe32Section.CommonHeader);
3630
3631 //
3632 // Calculate the TE base address, the FFS file base plus the offset of the TE section less the size stripped off
3633 // by GenTEImage
3634 //
3635 TEImageHeader = (EFI_TE_IMAGE_HEADER *) ((UINT8 *) CurrentPe32Section.Pe32Section + CurSecHdrSize);
3636
3637 //
3638 // Initialize context, load image info.
3639 //
3640 memset (&ImageContext, 0, sizeof (ImageContext));
3641 ImageContext.Handle = (VOID *) TEImageHeader;
3642 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) FfsRebaseImageRead;
3643 Status = PeCoffLoaderGetImageInfo (&ImageContext);
3644 if (EFI_ERROR (Status)) {
3645 Error (NULL, 0, 3000, "Invalid TeImage", "The input file is %s and the return status is %x", FileName, (int) Status);
3646 return Status;
3647 }
3648
3649 if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_ARMT) ||
3650 (ImageContext.Machine == EFI_IMAGE_MACHINE_AARCH64) ) {
3651 mArm = TRUE;
3652 }
3653
3654 //
3655 // Keep Image Context for TE image in FV
3656 //
3657 memcpy (&OrigImageContext, &ImageContext, sizeof (ImageContext));
3658
3659 //
3660 // Get File PdbPointer
3661 //
3662 PdbPointer = PeCoffLoaderGetPdbPointer (ImageContext.Handle);
3663
3664 //
3665 // Set new rebased address.
3666 //
3667 NewPe32BaseAddress = XipBase + (UINTN) TEImageHeader + sizeof (EFI_TE_IMAGE_HEADER) \
3668 - TEImageHeader->StrippedSize - (UINTN) FfsFile;
3669
3670 //
3671 // if reloc is stripped, try to get the original efi image to get reloc info.
3672 //
3673 if (ImageContext.RelocationsStripped) {
3674 //
3675 // Construct the original efi file name
3676 //
3677 strcpy (PeFileName, FileName);
3678 Cptr = PeFileName + strlen (PeFileName);
3679 while (*Cptr != '.') {
3680 Cptr --;
3681 }
3682
3683 if (*Cptr != '.') {
3684 Error (NULL, 0, 3000, "Invalid", "The file %s has no .reloc section.", FileName);
3685 return EFI_ABORTED;
3686 } else {
3687 *(Cptr + 1) = 'e';
3688 *(Cptr + 2) = 'f';
3689 *(Cptr + 3) = 'i';
3690 *(Cptr + 4) = '\0';
3691 }
3692
3693 PeFile = fopen (LongFilePath (PeFileName), "rb");
3694 if (PeFile == NULL) {
3695 Warning (NULL, 0, 0, "Invalid", "The file %s has no .reloc section.", FileName);
3696 //Error (NULL, 0, 3000, "Invalid", "The file %s has no .reloc section.", FileName);
3697 //return EFI_ABORTED;
3698 } else {
3699 //
3700 // Get the file size
3701 //
3702 PeFileSize = _filelength (fileno (PeFile));
3703 PeFileBuffer = (UINT8 *) malloc (PeFileSize);
3704 if (PeFileBuffer == NULL) {
3705 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated on rebase of %s", FileName);
3706 return EFI_OUT_OF_RESOURCES;
3707 }
3708 //
3709 // Read Pe File
3710 //
3711 fread (PeFileBuffer, sizeof (UINT8), PeFileSize, PeFile);
3712 //
3713 // close file
3714 //
3715 fclose (PeFile);
3716 //
3717 // Append reloc section into TeImage
3718 //
3719 ImageContext.Handle = PeFileBuffer;
3720 Status = PeCoffLoaderGetImageInfo (&ImageContext);
3721 if (EFI_ERROR (Status)) {
3722 Error (NULL, 0, 3000, "Invalid TeImage", "The input file is %s and the return status is %x", FileName, (int) Status);
3723 return Status;
3724 }
3725 ImageContext.RelocationsStripped = FALSE;
3726 }
3727 }
3728 //
3729 // Relocation doesn't exist
3730 //
3731 if (ImageContext.RelocationsStripped) {
3732 Warning (NULL, 0, 0, "Invalid", "The file %s has no .reloc section.", FileName);
3733 continue;
3734 }
3735
3736 //
3737 // Relocation exist and rebase
3738 //
3739 //
3740 // Load and Relocate Image Data
3741 //
3742 MemoryImagePointer = (UINT8 *) malloc ((UINTN) ImageContext.ImageSize + ImageContext.SectionAlignment);
3743 if (MemoryImagePointer == NULL) {
3744 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated on rebase of %s", FileName);
3745 return EFI_OUT_OF_RESOURCES;
3746 }
3747 memset ((VOID *) MemoryImagePointer, 0, (UINTN) ImageContext.ImageSize + ImageContext.SectionAlignment);
3748 ImageContext.ImageAddress = ((UINTN) MemoryImagePointer + ImageContext.SectionAlignment - 1) & (~((UINTN) ImageContext.SectionAlignment - 1));
3749
3750 Status = PeCoffLoaderLoadImage (&ImageContext);
3751 if (EFI_ERROR (Status)) {
3752 Error (NULL, 0, 3000, "Invalid", "LocateImage() call failed on rebase of %s", FileName);
3753 free ((VOID *) MemoryImagePointer);
3754 return Status;
3755 }
3756 //
3757 // Reloacate TeImage
3758 //
3759 ImageContext.DestinationAddress = NewPe32BaseAddress;
3760 Status = PeCoffLoaderRelocateImage (&ImageContext);
3761 if (EFI_ERROR (Status)) {
3762 Error (NULL, 0, 3000, "Invalid", "RelocateImage() call failed on rebase of TE image %s", FileName);
3763 free ((VOID *) MemoryImagePointer);
3764 return Status;
3765 }
3766
3767 //
3768 // Copy the relocated image into raw image file.
3769 //
3770 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) (TEImageHeader + 1);
3771 for (Index = 0; Index < TEImageHeader->NumberOfSections; Index ++, SectionHeader ++) {
3772 if (!ImageContext.IsTeImage) {
3773 CopyMem (
3774 (UINT8 *) TEImageHeader + sizeof (EFI_TE_IMAGE_HEADER) - TEImageHeader->StrippedSize + SectionHeader->PointerToRawData,
3775 (VOID*) (UINTN) (ImageContext.ImageAddress + SectionHeader->VirtualAddress),
3776 SectionHeader->SizeOfRawData
3777 );
3778 } else {
3779 CopyMem (
3780 (UINT8 *) TEImageHeader + sizeof (EFI_TE_IMAGE_HEADER) - TEImageHeader->StrippedSize + SectionHeader->PointerToRawData,
3781 (VOID*) (UINTN) (ImageContext.ImageAddress + sizeof (EFI_TE_IMAGE_HEADER) - TEImageHeader->StrippedSize + SectionHeader->VirtualAddress),
3782 SectionHeader->SizeOfRawData
3783 );
3784 }
3785 }
3786
3787 //
3788 // Free the allocated memory resource
3789 //
3790 free ((VOID *) MemoryImagePointer);
3791 MemoryImagePointer = NULL;
3792 if (PeFileBuffer != NULL) {
3793 free (PeFileBuffer);
3794 PeFileBuffer = NULL;
3795 }
3796
3797 //
3798 // Update Image Base Address
3799 //
3800 TEImageHeader->ImageBase = NewPe32BaseAddress;
3801
3802 //
3803 // Now update file checksum
3804 //
3805 if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) {
3806 SavedState = FfsFile->State;
3807 FfsFile->IntegrityCheck.Checksum.File = 0;
3808 FfsFile->State = 0;
3809 FfsFile->IntegrityCheck.Checksum.File = CalculateChecksum8 (
3810 (UINT8 *)((UINT8 *)FfsFile + FfsHeaderSize),
3811 GetFfsFileLength (FfsFile) - FfsHeaderSize
3812 );
3813 FfsFile->State = SavedState;
3814 }
3815 //
3816 // Get this module function address from ModulePeMapFile and add them into FvMap file
3817 //
3818
3819 //
3820 // Default use FileName as map file path
3821 //
3822 if (PdbPointer == NULL) {
3823 PdbPointer = FileName;
3824 }
3825
3826 WriteMapFile (
3827 FvMapFile,
3828 PdbPointer,
3829 FfsFile,
3830 NewPe32BaseAddress,
3831 &OrigImageContext
3832 );
3833 }
3834
3835 return EFI_SUCCESS;
3836 }
3837
3838 EFI_STATUS
3839 FindApResetVectorPosition (
3840 IN MEMORY_FILE *FvImage,
3841 OUT UINT8 **Pointer
3842 )
3843 /*++
3844
3845 Routine Description:
3846
3847 Find the position in this FvImage to place Ap reset vector.
3848
3849 Arguments:
3850
3851 FvImage Memory file for the FV memory image.
3852 Pointer Pointer to pointer to position.
3853
3854 Returns:
3855
3856 EFI_NOT_FOUND - No satisfied position is found.
3857 EFI_SUCCESS - The suitable position is return.
3858
3859 --*/
3860 {
3861 EFI_FFS_FILE_HEADER *PadFile;
3862 UINT32 Index;
3863 EFI_STATUS Status;
3864 UINT8 *FixPoint;
3865 UINT32 FileLength;
3866
3867 for (Index = 1; ;Index ++) {
3868 //
3869 // Find Pad File to add ApResetVector info
3870 //
3871 Status = GetFileByType (EFI_FV_FILETYPE_FFS_PAD, Index, &PadFile);
3872 if (EFI_ERROR (Status) || (PadFile == NULL)) {
3873 //
3874 // No Pad file to be found.
3875 //
3876 break;
3877 }
3878 //
3879 // Get Pad file size.
3880 //
3881 FileLength = GetFfsFileLength(PadFile);
3882 FileLength = (FileLength + EFI_FFS_FILE_HEADER_ALIGNMENT - 1) & ~(EFI_FFS_FILE_HEADER_ALIGNMENT - 1);
3883 //
3884 // FixPoint must be align on 0x1000 relative to FvImage Header
3885 //
3886 FixPoint = (UINT8*) PadFile + GetFfsHeaderLength(PadFile);
3887 FixPoint = FixPoint + 0x1000 - (((UINTN) FixPoint - (UINTN) FvImage->FileImage) & 0xFFF);
3888 //
3889 // FixPoint be larger at the last place of one fv image.
3890 //
3891 while (((UINTN) FixPoint + SIZEOF_STARTUP_DATA_ARRAY - (UINTN) PadFile) <= FileLength) {
3892 FixPoint += 0x1000;
3893 }
3894 FixPoint -= 0x1000;
3895
3896 if ((UINTN) FixPoint < ((UINTN) PadFile + GetFfsHeaderLength(PadFile))) {
3897 //
3898 // No alignment FixPoint in this Pad File.
3899 //
3900 continue;
3901 }
3902
3903 if ((UINTN) FvImage->Eof - (UINTN)FixPoint <= 0x20000) {
3904 //
3905 // Find the position to place ApResetVector
3906 //
3907 *Pointer = FixPoint;
3908 return EFI_SUCCESS;
3909 }
3910 }
3911
3912 return EFI_NOT_FOUND;
3913 }
3914
3915 EFI_STATUS
3916 ParseCapInf (
3917 IN MEMORY_FILE *InfFile,
3918 OUT CAP_INFO *CapInfo
3919 )
3920 /*++
3921
3922 Routine Description:
3923
3924 This function parses a Cap.INF file and copies info into a CAP_INFO structure.
3925
3926 Arguments:
3927
3928 InfFile Memory file image.
3929 CapInfo Information read from INF file.
3930
3931 Returns:
3932
3933 EFI_SUCCESS INF file information successfully retrieved.
3934 EFI_ABORTED INF file has an invalid format.
3935 EFI_NOT_FOUND A required string was not found in the INF file.
3936 --*/
3937 {
3938 CHAR8 Value[MAX_LONG_FILE_PATH];
3939 UINT64 Value64;
3940 UINTN Index, Number;
3941 EFI_STATUS Status;
3942
3943 //
3944 // Initialize Cap info
3945 //
3946 // memset (CapInfo, 0, sizeof (CAP_INFO));
3947 //
3948
3949 //
3950 // Read the Capsule Guid
3951 //
3952 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_CAPSULE_GUID_STRING, 0, Value);
3953 if (Status == EFI_SUCCESS) {
3954 //
3955 // Get the Capsule Guid
3956 //
3957 Status = StringToGuid (Value, &CapInfo->CapGuid);
3958 if (EFI_ERROR (Status)) {
3959 Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_CAPSULE_GUID_STRING, Value);
3960 return EFI_ABORTED;
3961 }
3962 DebugMsg (NULL, 0, 9, "Capsule Guid", "%s = %s", EFI_CAPSULE_GUID_STRING, Value);
3963 }
3964
3965 //
3966 // Read the Capsule Header Size
3967 //
3968 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_CAPSULE_HEADER_SIZE_STRING, 0, Value);
3969 if (Status == EFI_SUCCESS) {
3970 Status = AsciiStringToUint64 (Value, FALSE, &Value64);
3971 if (EFI_ERROR (Status)) {
3972 Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_CAPSULE_HEADER_SIZE_STRING, Value);
3973 return EFI_ABORTED;
3974 }
3975 CapInfo->HeaderSize = (UINT32) Value64;
3976 DebugMsg (NULL, 0, 9, "Capsule Header size", "%s = %s", EFI_CAPSULE_HEADER_SIZE_STRING, Value);
3977 }
3978
3979 //
3980 // Read the Capsule Flag
3981 //
3982 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_CAPSULE_FLAGS_STRING, 0, Value);
3983 if (Status == EFI_SUCCESS) {
3984 if (strstr (Value, "PopulateSystemTable") != NULL) {
3985 CapInfo->Flags |= CAPSULE_FLAGS_PERSIST_ACROSS_RESET | CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE;
3986 if (strstr (Value, "InitiateReset") != NULL) {
3987 CapInfo->Flags |= CAPSULE_FLAGS_INITIATE_RESET;
3988 }
3989 } else if (strstr (Value, "PersistAcrossReset") != NULL) {
3990 CapInfo->Flags |= CAPSULE_FLAGS_PERSIST_ACROSS_RESET;
3991 if (strstr (Value, "InitiateReset") != NULL) {
3992 CapInfo->Flags |= CAPSULE_FLAGS_INITIATE_RESET;
3993 }
3994 } else {
3995 Error (NULL, 0, 2000, "Invalid parameter", "invalid Flag setting for %s.", EFI_CAPSULE_FLAGS_STRING);
3996 return EFI_ABORTED;
3997 }
3998 DebugMsg (NULL, 0, 9, "Capsule Flag", Value);
3999 }
4000
4001 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_OEM_CAPSULE_FLAGS_STRING, 0, Value);
4002 if (Status == EFI_SUCCESS) {
4003 Status = AsciiStringToUint64 (Value, FALSE, &Value64);
4004 if (EFI_ERROR (Status) || Value64 > 0xffff) {
4005 Error (NULL, 0, 2000, "Invalid parameter",
4006 "invalid Flag setting for %s. Must be integer value between 0x0000 and 0xffff.",
4007 EFI_OEM_CAPSULE_FLAGS_STRING);
4008 return EFI_ABORTED;
4009 }
4010 CapInfo->Flags |= Value64;
4011 DebugMsg (NULL, 0, 9, "Capsule Extend Flag", Value);
4012 }
4013
4014 //
4015 // Read Capsule File name
4016 //
4017 Status = FindToken (InfFile, OPTIONS_SECTION_STRING, EFI_FILE_NAME_STRING, 0, Value);
4018 if (Status == EFI_SUCCESS) {
4019 //
4020 // Get output file name
4021 //
4022 strcpy (CapInfo->CapName, Value);
4023 }
4024
4025 //
4026 // Read the Capsule FileImage
4027 //
4028 Number = 0;
4029 for (Index = 0; Index < MAX_NUMBER_OF_FILES_IN_CAP; Index++) {
4030 if (CapInfo->CapFiles[Index][0] != '\0') {
4031 continue;
4032 }
4033 //
4034 // Read the capsule file name
4035 //
4036 Status = FindToken (InfFile, FILES_SECTION_STRING, EFI_FILE_NAME_STRING, Number++, Value);
4037
4038 if (Status == EFI_SUCCESS) {
4039 //
4040 // Add the file
4041 //
4042 strcpy (CapInfo->CapFiles[Index], Value);
4043 DebugMsg (NULL, 0, 9, "Capsule component file", "the %uth file name is %s", (unsigned) Index, CapInfo->CapFiles[Index]);
4044 } else {
4045 break;
4046 }
4047 }
4048
4049 if (Index == 0) {
4050 Warning (NULL, 0, 0, "Capsule components are not specified.", NULL);
4051 }
4052
4053 return EFI_SUCCESS;
4054 }
4055
4056 EFI_STATUS
4057 GenerateCapImage (
4058 IN CHAR8 *InfFileImage,
4059 IN UINTN InfFileSize,
4060 IN CHAR8 *CapFileName
4061 )
4062 /*++
4063
4064 Routine Description:
4065
4066 This is the main function which will be called from application to create UEFI Capsule image.
4067
4068 Arguments:
4069
4070 InfFileImage Buffer containing the INF file contents.
4071 InfFileSize Size of the contents of the InfFileImage buffer.
4072 CapFileName Requested name for the Cap file.
4073
4074 Returns:
4075
4076 EFI_SUCCESS Function completed successfully.
4077 EFI_OUT_OF_RESOURCES Could not allocate required resources.
4078 EFI_ABORTED Error encountered.
4079 EFI_INVALID_PARAMETER A required parameter was NULL.
4080
4081 --*/
4082 {
4083 UINT32 CapSize;
4084 UINT8 *CapBuffer;
4085 EFI_CAPSULE_HEADER *CapsuleHeader;
4086 MEMORY_FILE InfMemoryFile;
4087 UINT32 FileSize;
4088 UINT32 Index;
4089 FILE *fpin, *fpout;
4090 EFI_STATUS Status;
4091
4092 if (InfFileImage != NULL) {
4093 //
4094 // Initialize file structures
4095 //
4096 InfMemoryFile.FileImage = InfFileImage;
4097 InfMemoryFile.CurrentFilePointer = InfFileImage;
4098 InfMemoryFile.Eof = InfFileImage + InfFileSize;
4099
4100 //
4101 // Parse the Cap inf file for header information
4102 //
4103 Status = ParseCapInf (&InfMemoryFile, &mCapDataInfo);
4104 if (Status != EFI_SUCCESS) {
4105 return Status;
4106 }
4107 }
4108
4109 if (mCapDataInfo.HeaderSize == 0) {
4110 //
4111 // make header size align 16 bytes.
4112 //
4113 mCapDataInfo.HeaderSize = sizeof (EFI_CAPSULE_HEADER);
4114 mCapDataInfo.HeaderSize = (mCapDataInfo.HeaderSize + 0xF) & ~0xF;
4115 }
4116
4117 if (mCapDataInfo.HeaderSize < sizeof (EFI_CAPSULE_HEADER)) {
4118 Error (NULL, 0, 2000, "Invalid parameter", "The specified HeaderSize cannot be less than the size of EFI_CAPSULE_HEADER.");
4119 return EFI_INVALID_PARAMETER;
4120 }
4121
4122 if (CapFileName == NULL && mCapDataInfo.CapName[0] != '\0') {
4123 CapFileName = mCapDataInfo.CapName;
4124 }
4125
4126 if (CapFileName == NULL) {
4127 Error (NULL, 0, 2001, "Missing required argument", "Output Capsule file name");
4128 return EFI_INVALID_PARAMETER;
4129 }
4130
4131 //
4132 // Set Default Capsule Guid value
4133 //
4134 if (CompareGuid (&mCapDataInfo.CapGuid, &mZeroGuid) == 0) {
4135 memcpy (&mCapDataInfo.CapGuid, &mDefaultCapsuleGuid, sizeof (EFI_GUID));
4136 }
4137 //
4138 // Calculate the size of capsule image.
4139 //
4140 Index = 0;
4141 FileSize = 0;
4142 CapSize = mCapDataInfo.HeaderSize;
4143 while (mCapDataInfo.CapFiles [Index][0] != '\0') {
4144 fpin = fopen (LongFilePath (mCapDataInfo.CapFiles[Index]), "rb");
4145 if (fpin == NULL) {
4146 Error (NULL, 0, 0001, "Error opening file", mCapDataInfo.CapFiles[Index]);
4147 return EFI_ABORTED;
4148 }
4149 FileSize = _filelength (fileno (fpin));
4150 CapSize += FileSize;
4151 fclose (fpin);
4152 Index ++;
4153 }
4154
4155 //
4156 // Allocate buffer for capsule image.
4157 //
4158 CapBuffer = (UINT8 *) malloc (CapSize);
4159 if (CapBuffer == NULL) {
4160 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated for creating the capsule.");
4161 return EFI_OUT_OF_RESOURCES;
4162 }
4163
4164 //
4165 // Initialize the capsule header to zero
4166 //
4167 memset (CapBuffer, 0, mCapDataInfo.HeaderSize);
4168
4169 //
4170 // create capsule header and get capsule body
4171 //
4172 CapsuleHeader = (EFI_CAPSULE_HEADER *) CapBuffer;
4173 memcpy (&CapsuleHeader->CapsuleGuid, &mCapDataInfo.CapGuid, sizeof (EFI_GUID));
4174 CapsuleHeader->HeaderSize = mCapDataInfo.HeaderSize;
4175 CapsuleHeader->Flags = mCapDataInfo.Flags;
4176 CapsuleHeader->CapsuleImageSize = CapSize;
4177
4178 Index = 0;
4179 FileSize = 0;
4180 CapSize = CapsuleHeader->HeaderSize;
4181 while (mCapDataInfo.CapFiles [Index][0] != '\0') {
4182 fpin = fopen (LongFilePath (mCapDataInfo.CapFiles[Index]), "rb");
4183 if (fpin == NULL) {
4184 Error (NULL, 0, 0001, "Error opening file", mCapDataInfo.CapFiles[Index]);
4185 free (CapBuffer);
4186 return EFI_ABORTED;
4187 }
4188 FileSize = _filelength (fileno (fpin));
4189 fread (CapBuffer + CapSize, 1, FileSize, fpin);
4190 fclose (fpin);
4191 Index ++;
4192 CapSize += FileSize;
4193 }
4194
4195 //
4196 // write capsule data into the output file
4197 //
4198 fpout = fopen (LongFilePath (CapFileName), "wb");
4199 if (fpout == NULL) {
4200 Error (NULL, 0, 0001, "Error opening file", CapFileName);
4201 free (CapBuffer);
4202 return EFI_ABORTED;
4203 }
4204
4205 fwrite (CapBuffer, 1, CapSize, fpout);
4206 fclose (fpout);
4207
4208 VerboseMsg ("The size of the generated capsule image is %u bytes", (unsigned) CapSize);
4209
4210 return EFI_SUCCESS;
4211 }