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