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