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