summaryrefslogtreecommitdiffstats
path: root/BaseTools/Source/C/BfmLib/BinFileManager.c
blob: 8c8b67bd375994e799ebc5a91461ec5d192fe578 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
/** @file

 The main entry of BFM tool.

 Copyright (c) 2011-2019, Intel Corporation. All rights reserved.<BR>
 SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include "BinFileManager.h"

BOOLEAN     mFvGuidIsSet = FALSE;
EFI_GUID    mFvNameGuid  = {0};
CHAR8*      mFvNameGuidString = NULL;
CHAR8*      mGuidToolDefinition     = "GuidToolDefinitionConf.ini";

//
// Store GUIDed Section guid->tool mapping
//
EFI_HANDLE mParsedGuidedSectionTools = NULL;


/**
  Search the config file from the path list.

  Split the path from env PATH, and then search the cofig
  file from these paths. The priority is from left to
  right of PATH string. When met the first Config file, it
  will break and return the pointer to the full file name.

  @param  PathList         the pointer to the path list.
  @param  FileName         the pointer to the file name.

  @retval The pointer to the file name.
  @return NULL       An error occurred.
**/
CHAR8 *
SearchConfigFromPathList (
  IN  CHAR8  *PathList,
  IN  CHAR8  *FileName
)
{
  CHAR8  *CurDir;
  CHAR8  *FileNamePath;

  CurDir       = NULL;
  FileNamePath = NULL;
#ifndef __GNUC__
  CurDir = strtok (PathList,";");
#else
  CurDir = strtok (PathList,":");
#endif
  while (CurDir != NULL) {
    FileNamePath  = (char *)calloc(
                     strlen (CurDir) + strlen (OS_SEP_STR) +strlen (FileName) + 1,
                     sizeof(char)
                     );
    if (FileNamePath == NULL) {
      return NULL;
    }
    sprintf(FileNamePath, "%s%c%s", CurDir, OS_SEP, FileName);
    if (access (FileNamePath, 0) != -1) {
      return FileNamePath;
    }
#ifndef __GNUC__
    CurDir = strtok(NULL, ";");
#else
    CurDir = strtok(NULL, ":");
#endif
    free (FileNamePath);
    FileNamePath = NULL;
  }
  return NULL;
}

/**

  Show the FD image layout information. Only display the modules with UI name.

  @param[in]   FdInName    Input FD binary/image file name;
  @param[in]   FvName      The FV ID in the FD file;
  @param[in]   ViewFlag    Is this call for view or other operate(add/del/replace)
  @param[in]   FdData      The Fd data structure store the FD information.

  @retval      EFI_SUCCESS
  @retval      EFI_INVALID_PARAMETER
  @retval      EFI_ABORTED

**/
EFI_STATUS
BfmImageView (
  IN     CHAR8*           FdInName,
  IN     CHAR8*           FvName,
  IN     BOOLEAN          ViewFlag,
  IN     FIRMWARE_DEVICE  **FdData
)
{
  EFI_STATUS                  Status;
  FIRMWARE_DEVICE             *LocalFdData;
  FV_INFORMATION              *CurrentFv;
  FILE                        *InputFile;
  UINT32                      FvSize;
  UINTN                       BytesRead;
  EFI_FIRMWARE_VOLUME_HEADER  *FvImage;
  UINT32                      FfsCount;
  UINT8                       FvCount;
  UINT8                       LastFvNumber;

  LocalFdData    = NULL;
  CurrentFv      = NULL;
  FvImage        = NULL;
  FvSize         = 0;
  BytesRead      = 0;
  FfsCount       = 0;
  FvCount        = 0;
  LastFvNumber   = 0;

  //
  // Check the FD file name/path.
  //
  if (FdInName == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Open the file containing the FV
  //
  InputFile = fopen (FdInName, "rb");
  if (InputFile == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = LibFindFvInFd (InputFile, &LocalFdData);

  if (EFI_ERROR(Status)) {
    fclose (InputFile);
    return EFI_ABORTED;
  }

  CurrentFv = LocalFdData->Fv;

  do {

    memset (CurrentFv->FvName, '\0', _MAX_PATH);

    if (LastFvNumber == 0) {
      sprintf (CurrentFv->FvName, "FV%d", LastFvNumber);
    } else {
      sprintf (CurrentFv->FvName, "FV%d", LastFvNumber);
    }

    //
    // Determine size of FV
    //
    if (fseek (InputFile, CurrentFv->ImageAddress, SEEK_SET) != 0) {
      fclose (InputFile);
      LibBfmFreeFd( LocalFdData);
      return EFI_ABORTED;
    }

    Status = LibGetFvSize(InputFile, &FvSize);
    if (EFI_ERROR (Status)) {
      fclose (InputFile);
      return EFI_ABORTED;
    }

    //
    // Seek to the start of the image, then read the entire FV to the buffer
    //
    fseek (InputFile, CurrentFv->ImageAddress, SEEK_SET);

    FvImage = (EFI_FIRMWARE_VOLUME_HEADER *) malloc (FvSize);

    if (FvImage == NULL) {
      fclose (InputFile);
      LibBfmFreeFd( LocalFdData);
      return EFI_ABORTED;
    }

    BytesRead = fread (FvImage, 1, FvSize, InputFile);
    if ((unsigned int) BytesRead != FvSize) {
      free (FvImage);
      fclose (InputFile);
      LibBfmFreeFd( LocalFdData);
      return EFI_ABORTED;
    }

    //
    // Collect FV information each by each.
    //
    Status = LibGetFvInfo (FvImage, CurrentFv, FvName, 0, &FfsCount, ViewFlag, FALSE);
    free (FvImage);
    FvImage = NULL;
    if (EFI_ERROR (Status)) {
      fclose (InputFile);
      LibBfmFreeFd( LocalFdData);
      return Status;
    }
    FvCount = CurrentFv->FvLevel;
    LastFvNumber = LastFvNumber+FvCount;

    FfsCount = 0;

    CurrentFv = CurrentFv->FvNext;

  } while (CurrentFv != NULL);

  if (!ViewFlag) {
    *FdData = LocalFdData;
  } else {
    LibBfmFreeFd( LocalFdData);
  }

  fclose (InputFile);

  return EFI_SUCCESS;
}

/**
  Add an FFS file into a specify FV.

  @param[in]   FdInName     Input FD binary/image file name;
  @param[in]   NewFile      The name of the file add in;
  @param[in]   FdOutName    Name of output fd file.

  @retval      EFI_SUCCESS
  @retval      EFI_INVALID_PARAMETER
  @retval      EFI_ABORTED

**/
EFI_STATUS
BfmImageAdd (
  IN     CHAR8*  FdInName,
  IN     CHAR8*  NewFile,
  IN     CHAR8*  FdOutName
)
{
  EFI_STATUS                  Status;
  FIRMWARE_DEVICE             *FdData;
  FV_INFORMATION              *FvInFd;
  ENCAP_INFO_DATA             *LocalEncapData;
  ENCAP_INFO_DATA             *LocalEncapDataTemp;
  FILE*                       NewFdFile;
  FILE*                       NewFvFile;
  UINT64                      NewFvLength;
  UINT64                      NewFfsLength;
  VOID*                       Buffer;
  CHAR8                       *TemDir;
  UINT8                       FvEncapLevel;
  UINT8                       NewAddedFfsLevel;
  BOOLEAN                     FfsLevelFoundFlag;
  CHAR8                       *OutputFileName;
  CHAR8                       *FvId;
  BOOLEAN                     FirstInFlag;
  BOOLEAN                     FvGuidExisted;

  NewFvLength                 = 0;
  FvEncapLevel                = 0;
  NewAddedFfsLevel            = 0;

  FfsLevelFoundFlag           = FALSE;
  FirstInFlag                 = TRUE;
  FdData                      = NULL;
  FvInFd                      = NULL;
  LocalEncapData              = NULL;
  NewFdFile                   = NULL;
  NewFvFile                   = NULL;
  Buffer                      = NULL;
  TemDir                      = NULL;
  LocalEncapDataTemp          = NULL;
  OutputFileName              = NULL;
  FvId                        = NULL;
  FvGuidExisted               = FALSE;

  //
  // Get the size of ffs file to be inserted.
  //
  NewFfsLength = GetFileSize(NewFile);

  Status = BfmImageView (FdInName, NULL, FALSE, &FdData);

  if (EFI_ERROR (Status)) {
    printf ("Error while parse %s FD image.\n", FdInName);
    return Status;
  }
  //
  // Check the FvGuid whether exists or not when the BIOS hasn't default setting.
  // If the FV image with -g GUID can't be found, the storage is still saved into the BFV and report warning message.
  //
  FvInFd = FdData->Fv;
  do {
    if (mFvGuidIsSet && FvInFd->IsInputFvFlag) {
      FvGuidExisted = TRUE;
    break;
    }
    FvInFd = FvInFd->FvNext;
  } while (FvInFd != NULL);

  if (mFvGuidIsSet && !FvGuidExisted) {
    printf ("Fv image with the specified FV Name Guid %s can't be found in current FD.\n", mFvNameGuidString);
    LibBfmFreeFd(FdData);
    return EFI_ABORTED;
  }
  //
  // Iterate to write FFS to each BFV.
  //
  FvInFd = FdData->Fv;
  do {
    if ((FvGuidExisted && mFvGuidIsSet && FvInFd->IsInputFvFlag) || ((!FvGuidExisted || (!mFvGuidIsSet)) && FvInFd->IsBfvFlag)) {

      Status = LibLocateBfv (FdData, &FvId, &FvInFd);

      if (EFI_ERROR (Status)) {
        printf("Error while locate BFV from FD.\n");
        LibBfmFreeFd(FdData);
        return Status;
      }

      //
      // Determine the new added ffs file level in the FV.
      //
      LocalEncapData = FvInFd->EncapData;

      while (LocalEncapData != NULL && !FfsLevelFoundFlag ) {
        if (LocalEncapData->Type == BFM_ENCAP_TREE_FV) {
          if (FvEncapLevel == ((UINT8) atoi (FvId + 2) - (UINT8) atoi (FvInFd->FvName + 2))) {
            //
            // Found the FFS level in this FV.
            //
            LocalEncapDataTemp = LocalEncapData;
            while (LocalEncapDataTemp != NULL) {
              if (LocalEncapDataTemp->Type == BFM_ENCAP_TREE_FFS) {
                NewAddedFfsLevel  = LocalEncapDataTemp->Level;
                FfsLevelFoundFlag = TRUE;
                break;
              }
              if (LocalEncapDataTemp->NextNode != NULL) {
                LocalEncapDataTemp = LocalEncapDataTemp->NextNode;
              } else {
                break;
              }
            }
          }
          FvEncapLevel ++;
        }

        if (LocalEncapData->NextNode == NULL) {
          break;
        } else {
          LocalEncapData = LocalEncapData->NextNode;
        }
      }

      //
      // Add the new file into FV.
      //
      FvInFd->FfsNumbers += 1;
      if (strlen (NewFile) > _MAX_PATH - 1) {
        printf ("The NewFile name is too long \n");
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }
      strncpy (FvInFd->FfsAttuibutes[FvInFd->FfsNumbers].FfsName, NewFile, _MAX_PATH - 1);
      FvInFd->FfsAttuibutes[FvInFd->FfsNumbers].FfsName[_MAX_PATH - 1] = 0;
      FvInFd->FfsAttuibutes[FvInFd->FfsNumbers].Level   = NewAddedFfsLevel;

      TemDir = getcwd (NULL, _MAX_PATH);
      if (strlen (TemDir) + strlen (OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MAX_PATH - 1) {
        printf ("The directory is too long \n");
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }
      strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen (TemDir) - 1);
      strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen (TemDir) - 1);
      mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO);
      Status = LibEncapNewFvFile (FvInFd, TemDir, &OutputFileName);

      if (EFI_ERROR (Status)) {
        printf("Error. The boot firmware volume (BFV) has only the spare space 0x%lx bytes. But the default setting data takes 0x%llx bytes, which can't be inserted into BFV. \n",(unsigned long) GetBfvPadSize (), (unsigned long long)NewFfsLength);
        LibBfmFreeFd(FdData);
        return Status;
      }

      if (FirstInFlag) {
        //
        // Write New Fv file into the NewFd file.
        //
        Status = LibCreateNewFdCopy (FdInName, FdOutName);
        if (EFI_ERROR (Status)) {
          printf("Error while copy from %s to %s file. \n", FdInName, FdOutName);
          LibBfmFreeFd(FdData);
          return Status;
        }
        FirstInFlag = FALSE;
      }

      NewFdFile = fopen (FdOutName, "rb+");
      if (NewFdFile == NULL) {
        printf("Error while create FD file %s. \n", FdOutName);
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }

      NewFvFile = fopen (OutputFileName, "rb+");

      if (NewFvFile == NULL) {
        printf("Error while create Fv file %s. \n", OutputFileName);
        fclose(NewFdFile);
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }

      fseek(NewFvFile,0,SEEK_SET);
      fseek(NewFvFile,0,SEEK_END);

      NewFvLength = ftell(NewFvFile);

      fseek(NewFvFile,0,SEEK_SET);

      Buffer = malloc ((size_t)NewFvLength);

      if (Buffer == NULL)  {
        printf ("Error while allocate resource! \n");
        fclose(NewFdFile);
        fclose(NewFvFile);
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }

      if (fread (Buffer, 1, (size_t) NewFvLength, NewFvFile) != (size_t) NewFvLength) {
        printf("Error while reading Fv file %s. \n", OutputFileName);
        free (Buffer);
        fclose(NewFdFile);
        fclose(NewFvFile);
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }

      fseek(NewFdFile, FvInFd->ImageAddress, SEEK_SET);
      fseek(NewFdFile, FvInFd->ImageAddress, SEEK_SET);

      if (NewFvLength <= FvInFd->FvHeader->FvLength) {
        if (fwrite (Buffer, 1, (size_t) NewFvLength, NewFdFile) != (size_t) NewFvLength) {
          printf("Error while writing FD file %s. \n", FdOutName);
          fclose(NewFdFile);
          fclose (NewFvFile);
          free (Buffer);
          LibBfmFreeFd(FdData);
          return EFI_ABORTED;
        }
      } else {
        printf("Error. The new size of BFV is 0x%llx bytes, which is larger than the previous size of BFV 0x%llx bytes. \n", (unsigned long long) NewFvLength, (unsigned long long) FvInFd->FvHeader->FvLength);
        free (Buffer);
        fclose(NewFdFile);
        fclose(NewFvFile);
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }

      fclose(NewFdFile);
      fclose(NewFvFile);
      free (Buffer);
      Buffer = NULL;

    }
    FvInFd = FvInFd->FvNext;
  } while (FvInFd != NULL);


  LibBfmFreeFd(FdData);

  if (TemDir == NULL) {
    if (mFvGuidIsSet) {
      printf ("Fv image with the specified FV Name Guid %s can't be found.\n", mFvNameGuidString);
    } else {
      printf ("BFV image can't be found.\n");
    }
    return EFI_NOT_FOUND;
  }

  Status = LibRmDir (TemDir);

  if (EFI_ERROR (Status)) {
    printf("Error while remove temporary directory. \n");
    return Status;
  }

  return EFI_SUCCESS;
}


/**
  Replace an FFS file into a specify FV.

  @param[in]   FdInName     Input FD binary/image file name;
  @param[in]   NewFile      The name of the file add in;
  @param[in]   FdOutName    Name of output fd file.

  @retval      EFI_SUCCESS
  @retval      EFI_INVALID_PARAMETER
  @retval      EFI_ABORTED

**/
EFI_STATUS
BfmImageReplace (
  IN     CHAR8*  FdInName,
  IN     CHAR8*  NewFile,
  IN     CHAR8*  FdOutName
)
{
  EFI_STATUS                  Status;
  FIRMWARE_DEVICE             *FdData;
  FV_INFORMATION              *FvInFd;
  FILE*                       NewFdFile;
  FILE*                       NewFvFile;
  UINT64                      NewFvLength;
  UINT64                      NewFfsLength;
  VOID*                       Buffer;
  CHAR8                       *TemDir;
  CHAR8                       *OutputFileName;
  CHAR8                       *FvId;
  BOOLEAN                     FirstInFlag;
  UINT32                      Index;
  BOOLEAN                     FvToBeUpdate;
  BOOLEAN                     FdIsUpdate;
  ENCAP_INFO_DATA             *LocalEncapData;
  ENCAP_INFO_DATA             *LocalEncapDataTemp;
  UINT8                       FvEncapLevel;
  UINT8                       NewAddedFfsLevel;
  BOOLEAN                     FfsLevelFoundFlag;
  EFI_GUID                    EfiNewAddToBfvGuid;
  FILE*                       FfsFile;
  UINTN                       BytesRead;
  BOOLEAN                     ReplaceSameFv;
  BOOLEAN                     FvGuidExisted;

  NewFvLength                 = 0;
  FdIsUpdate                  = FALSE;
  FirstInFlag                 = TRUE;
  FdData                      = NULL;
  FvInFd                      = NULL;
  NewFdFile                   = NULL;
  NewFvFile                   = NULL;
  Buffer                      = NULL;
  TemDir                      = NULL;
  OutputFileName              = NULL;
  FvId                        = NULL;
  FfsFile                     = NULL;
  BytesRead                   = 0;
  ReplaceSameFv               = FALSE;
  FvGuidExisted               = FALSE;

  //
  // Get the size of ffs file to be inserted.
  //
  NewFfsLength = GetFileSize(NewFile);
  //
  // Get FFS GUID
  //
  FfsFile = fopen (NewFile, "rb");
  if (FfsFile == NULL) {
    printf ("Error while read %s.\n", NewFile);
  return EFI_ABORTED;
  }
  fseek (FfsFile, 0, SEEK_SET);
  BytesRead = fread (&EfiNewAddToBfvGuid, 1, sizeof(EFI_GUID), FfsFile);
  fclose (FfsFile);
  if (BytesRead != sizeof(EFI_GUID)) {
    printf ("Error while read the GUID from %s.\n", NewFile);
  return EFI_ABORTED;
  }
  Status = BfmImageView (FdInName, NULL, FALSE, &FdData);

  if (EFI_ERROR (Status)) {
    printf ("Error while parse %s FD image.\n", FdInName);
    return Status;
  }

  //
  // Check the FvGuid whether exists or not when the BIOS has default setting.
  // 1.  No option means the storage is saved into the same FV image.
  // 2.  The FV image with -g GUID can't be found. The storage is still saved into the same FV image and report warning message.
  //
  if (!mFvGuidIsSet) {
    ReplaceSameFv = TRUE;
  }
  FvInFd = FdData->Fv;
  do {
    if (mFvGuidIsSet && FvInFd->IsInputFvFlag) {
      FvGuidExisted = TRUE;
    break;
    }
    FvInFd = FvInFd->FvNext;
  } while (FvInFd != NULL);

  if (mFvGuidIsSet && !FvGuidExisted) {
    printf ("Fv image with the specified FV Name Guid %s can't be found in current FD.\n", mFvNameGuidString);
    ReplaceSameFv = TRUE;
    LibBfmFreeFd(FdData);
    return EFI_ABORTED;
  }
  //
  // Interate to insert or replace default setting to Fv
  //
  FvInFd = FdData->Fv;
  do {
    FvToBeUpdate = FALSE;
    if (mFvGuidIsSet && FvInFd->IsInputFvFlag) {
      FvToBeUpdate = TRUE;
    }

    Status = LibLocateBfv (FdData, &FvId, &FvInFd);

    if (EFI_ERROR (Status)) {
      printf("Error while locate BFV from FD.\n");
      LibBfmFreeFd(FdData);
      return Status;
    }

    Index = 0;
    while (Index <= FvInFd->FfsNumbers) {
      //
      // Locate the multi-platform ffs in Fv and then replace or delete it.
      //
      if (!CompareGuid(&FvInFd->FfsHeader[Index].Name, &EfiNewAddToBfvGuid)) {
      if (ReplaceSameFv) {
      FvToBeUpdate = TRUE;
      }
        break;
      }
      Index ++;
    }

    if (FvToBeUpdate || (Index <= FvInFd->FfsNumbers)) {
      if (FvToBeUpdate) {
        FdIsUpdate = TRUE;
        if (Index <= FvInFd->FfsNumbers) {
          //
          // Override original default data by New File
          //
          if (strlen (NewFile) > _MAX_PATH - 1) {
            printf ("The NewFile name is too long \n");
            LibBfmFreeFd(FdData);
            return EFI_ABORTED;
          }
          strncpy (FvInFd->FfsAttuibutes[Index].FfsName, NewFile, _MAX_PATH - 1);
          FvInFd->FfsAttuibutes[Index].FfsName[_MAX_PATH - 1] = 0;
        } else {
          FfsLevelFoundFlag           = FALSE;
          FvEncapLevel                = 0;
          NewAddedFfsLevel            = 0;
          //
          // Determine the new added ffs file level in the FV.
          //
          LocalEncapData = FvInFd->EncapData;

          while (LocalEncapData != NULL && !FfsLevelFoundFlag ) {
            if (LocalEncapData->Type == BFM_ENCAP_TREE_FV) {
              if (FvEncapLevel == ((UINT8) atoi (FvId + 2) - (UINT8) atoi (FvInFd->FvName + 2))) {
                //
                // Found the FFS level in this FV.
                //
                LocalEncapDataTemp = LocalEncapData;
                while (LocalEncapDataTemp != NULL) {
                  if (LocalEncapDataTemp->Type == BFM_ENCAP_TREE_FFS) {
                    NewAddedFfsLevel  = LocalEncapDataTemp->Level;
                    FfsLevelFoundFlag = TRUE;
                    break;
                  }
                  if (LocalEncapDataTemp->NextNode != NULL) {
                    LocalEncapDataTemp = LocalEncapDataTemp->NextNode;
                  } else {
                    break;
                  }
                }
              }
              FvEncapLevel ++;
            }

            if (LocalEncapData->NextNode == NULL) {
              break;
            } else {
              LocalEncapData = LocalEncapData->NextNode;
            }
          }

          //
          // Add the new file into FV.
          //
          FvInFd->FfsNumbers += 1;
          memcpy (FvInFd->FfsAttuibutes[FvInFd->FfsNumbers].FfsName, NewFile, _MAX_PATH);
          FvInFd->FfsAttuibutes[FvInFd->FfsNumbers].Level   = NewAddedFfsLevel;
        }
      } else {
        //
        // Remove original default data from FV.
        //
        FvInFd->FfsAttuibutes[Index].FfsName[0] = '\0';
      }

      if (TemDir == NULL) {
        TemDir = getcwd (NULL, _MAX_PATH);
        if (strlen (TemDir) + strlen (OS_SEP_STR)+ strlen (TEMP_DIR_NAME) > _MAX_PATH - 1) {
          printf ("The directory is too long \n");
          LibBfmFreeFd(FdData);
          return EFI_ABORTED;
        }
        strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen (TemDir) - 1);
        strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen (TemDir) - 1);
        mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO);
      }

      Status = LibEncapNewFvFile (FvInFd, TemDir, &OutputFileName);

      if (EFI_ERROR (Status)) {
        printf("Error. The boot firmware volume (BFV) has only the spare space 0x%lx bytes. But the default setting data takes 0x%llx bytes, which can't be inserted into BFV. \n", (unsigned long) GetBfvPadSize (), (unsigned long long) NewFfsLength);
        LibBfmFreeFd(FdData);
        return Status;
      }

      if (FirstInFlag) {
        //
        // Write New Fv file into the NewFd file.
        //
        Status = LibCreateNewFdCopy (FdInName, FdOutName);
        if (EFI_ERROR (Status)) {
          printf("Error while copy from %s to %s file. \n", FdInName, FdOutName);
          LibBfmFreeFd(FdData);
          return Status;
        }
        FirstInFlag = FALSE;
      }

      NewFdFile = fopen (FdOutName, "rb+");
      if (NewFdFile == NULL) {
        printf("Error while create FD file %s. \n", FdOutName);
        LibBfmFreeFd(FdData);
        return EFI_ABORTED;
      }

      NewFvFile = fopen (OutputFileName, "rb+");

      if (NewFvFile == NULL) {
        printf("Error while create Fv file %s. \n", OutputFileName);
        LibBfmFreeFd(FdData);
        fclose (NewFdFile);
        return EFI_ABORTED;
      }

      fseek(NewFvFile,0,SEEK_SET);
      fseek(NewFvFile,0,SEEK_END);

      NewFvLength = ftell(NewFvFile);

      fseek(NewFvFile,0,SEEK_SET);

      Buffer = malloc ((size_t)NewFvLength);

      if (Buffer == NULL)  {
        LibBfmFreeFd(FdData);
        fclose (NewFdFile);
        fclose (NewFvFile);
        return EFI_ABORTED;
      }

      if (fread (Buffer, 1, (size_t) NewFvLength, NewFvFile) != (size_t) NewFvLength) {
        printf("Error while read Fv file %s. \n", OutputFileName);
        LibBfmFreeFd(FdData);
        free (Buffer);
        fclose (NewFdFile);
        fclose (NewFvFile);
        return EFI_ABORTED;
      }

      fseek(NewFdFile, FvInFd->ImageAddress, SEEK_SET);
      fseek(NewFdFile, FvInFd->ImageAddress, SEEK_SET);

      if (NewFvLength <= FvInFd->FvHeader->FvLength) {
        if (fwrite (Buffer, 1, (size_t) NewFvLength, NewFdFile) != (size_t) NewFvLength) {
          printf("Error while write FD file %s. \n", FdOutName);
          fclose(NewFdFile);
          fclose (NewFvFile);
          LibBfmFreeFd(FdData);
          free (Buffer);
          return EFI_ABORTED;
        }
      } else {
        printf("Error. The new size of BFV is 0x%llx bytes, which is larger than the previous size of BFV 0x%llx bytes. \n", (unsigned long long) NewFvLength, (unsigned long long) FvInFd->FvHeader->FvLength);
        free (Buffer);
        LibBfmFreeFd(FdData);
        fclose (NewFdFile);
        fclose (NewFvFile);
        return EFI_ABORTED;
      }

      fclose(NewFdFile);
      fclose(NewFvFile);
      free (Buffer);
      Buffer = NULL;

    }
    FvInFd = FvInFd->FvNext;
  } while (FvInFd != NULL);

  LibBfmFreeFd(FdData);

  if (TemDir == NULL || !FdIsUpdate) {
    if (mFvGuidIsSet) {
      printf ("Fv image with the specified FV Name Guid %s can't be found.\n", mFvNameGuidString);
    } else {
      printf ("BFV image can't be found.\n");
    }
    return EFI_NOT_FOUND;
  }

  Status = LibRmDir (TemDir);

  if (EFI_ERROR (Status)) {
    printf("Error while remove temporary directory. \n");
    return Status;
  }

  return EFI_SUCCESS;
}

/**

  The main entry of BFM tool.

**/
int main(
  int      Argc,
  char     *Argv[]
)
{
  EFI_STATUS                    Status;
  FIRMWARE_DEVICE               *FdData;
  CHAR8                         *InFilePath;
  CHAR8                         FullGuidToolDefinition[_MAX_PATH];
  CHAR8                         *FileName;
  UINTN                         FileNameIndex;
  CHAR8                         *PathList;
  UINTN                         EnvLen;
  CHAR8                         *NewPathList;

  FdData                      = NULL;
  PathList                    = NULL;
  NewPathList                 = NULL;
  EnvLen                      = 0;

  if (Argc <= 1) {
    return -1;
  }
  FileName = Argv[0];
  //
  // Save, skip filename arg
  //
  Argc--;
  Argv++;

  if ((stricmp(Argv[0], "-v") == 0)) {
    //
    // Check the revison of BfmLib
    // BfmLib -v
    //
    printf("%s\n", __BUILD_VERSION);
    return 1;

  }
  //
  // Workaroud: the first call to this function
  //            returns a file name ends with dot
  //
#ifndef __GNUC__
  tmpnam (NULL);
#else
  CHAR8 tmp[] = "/tmp/fileXXXXXX";
  UINTN Fdtmp;
  Fdtmp = mkstemp(tmp);
  close(Fdtmp);
#endif
  //
  // Get the same path with the application itself
  //
  if (strlen (FileName) > _MAX_PATH - 1) {
    Error (NULL, 0, 2000, "Parameter: Input file name is too long", NULL);
    return -1;
  }
  strncpy (FullGuidToolDefinition, FileName, _MAX_PATH - 1);
  FullGuidToolDefinition[_MAX_PATH - 1] = 0;
  FileNameIndex = strlen (FullGuidToolDefinition);
  while (FileNameIndex != 0) {
    FileNameIndex --;
    if (FullGuidToolDefinition[FileNameIndex] == OS_SEP) {
    FullGuidToolDefinition[FileNameIndex] = 0;
      break;
    }
  }
  //
  // Build the path list for Config file scan. The priority is below.
  // 1. Scan the current path
  // 2. Scan the same path with the application itself
  // 3. Scan the current %PATH% of OS environment
  // 4. Use the build-in default configuration
  //
  PathList = getenv("PATH");
  if (PathList == NULL) {
    Error (NULL, 0, 1001, "Option: Environment variable 'PATH' does not exist", NULL);
    return -1;
  }
  EnvLen = strlen(PathList);
  NewPathList  = (char *)calloc(
                     strlen (".")
                     + strlen (";")
                     + strlen (FullGuidToolDefinition)
                     + strlen (";")
                     + EnvLen
                     + 1,
                     sizeof(char)
                  );
  if (NewPathList == NULL) {
    Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL);
    PathList = NULL;
    free (PathList);
    return -1;
  }
#ifndef __GNUC__
  sprintf (NewPathList, "%s;%s;%s", ".", FullGuidToolDefinition, PathList);
#else
  sprintf (NewPathList, "%s:%s:%s", ".", FullGuidToolDefinition, PathList);
#endif

  PathList = NULL;
  free (PathList);
  //
  // Load Guid Tools definition
  //
  InFilePath = SearchConfigFromPathList(NewPathList, mGuidToolDefinition);
  free (NewPathList);
  if (InFilePath != NULL) {
    printf ("\nThe Guid Tool Definition of BfmLib comes from the '%s'. \n", InFilePath);
    mParsedGuidedSectionTools = ParseGuidedSectionToolsFile (InFilePath);
    free (InFilePath);
  } else {
    //
    // Use the pre-defined standard guided tools.
    //
  printf ("\nThe Guid Tool Definition of BfmLib comes from the build-in default configuration. \n");
    mParsedGuidedSectionTools = LibPreDefinedGuidedTools ();
  }

  //
  // BfmLib -e FdName.Fd
  //
  if ((stricmp(Argv[0], "-e") == 0)) {

    if (Argc != 2) {
      return -1;
    }
    //
    // Extract FFS files.
    //
    Status = BfmImageView (Argv[1], NULL, FALSE, &FdData);

    if (EFI_ERROR (Status)) {
      return -1;
    }

    if (FdData == NULL) {
      return -1;
    }

    LibBfmFreeFd(FdData);

  } else if ((stricmp(Argv[0], "-i") == 0)) {
    //
    // Insert FFS files to BFV
    // BfmLib -i InFdName.Fd FfsName.ffs OutFdName.Fd -g FvNameGuid
    //
    if (Argc == 6) {
      mFvGuidIsSet      = TRUE;
      mFvNameGuidString = Argv[5];
      StringToGuid (Argv[5], &mFvNameGuid);
      Argc -= 2;
    }
    if (Argc != 4) {
      return -1;
    }
    Status = BfmImageAdd(Argv[1], Argv[2], Argv[3]);

    if (EFI_ERROR (Status)) {
      return -1;
    }

  } else if ((stricmp(Argv[0], "-r") == 0)) {
    //
    // Replace FFS files in BFV
    // BfmLib -r InFdName.Fd FfsName.ffs OutFdName.Fd -g FvNameGuid
    //
    if (Argc == 6) {
      mFvGuidIsSet      = TRUE;
      mFvNameGuidString = Argv[5];
      StringToGuid (Argv[5], &mFvNameGuid);
      Argc -= 2;
    }
    if (Argc != 4) {
      return -1;
    }
    Status = BfmImageReplace (Argv[1], Argv[2], Argv[3]);

    if (EFI_ERROR (Status)) {
      return -1;
    }

  } else {
    //
    // Invalid parameter.
    //
    return -1;
  }

  return 1;
}