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