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