summaryrefslogtreecommitdiffstats
path: root/BaseTools/Source/C/FCE/Variable.c
blob: 5c92060309ba0b731d6b0890783ff271c2d459ba (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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
/** @file

 Read and edit the EFI variable.

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

**/

#include "Fce.h"
#include "Variable.h"

extern LIST_ENTRY                  mAllVarListEntry;
extern MULTI_PLATFORM_PARAMETERS   mMultiPlatformParam;
extern G_EFI_FD_INFO               gEfiFdInfo;

EFI_GUID  gEfiVariableGuid     = EFI_VARIABLE_GUID;
/**

  Gets the pointer to the first variable header in given variable store area.

  @param VarStoreHeader  Pointer to the Variable Store Header.

  @return Pointer to the first variable header.

**/
static
VARIABLE_HEADER *
GetStartPointer (
  IN VARIABLE_STORE_HEADER       *VarStoreHeader
  )
{
  //
  // The end of variable store.
  //
  return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1);
}

/**

  Gets the pointer to the end of the variable storage area.

  This function gets pointer to the end of the variable storage
  area, according to the input variable store header.

  @param VarStoreHeader  Pointer to the Variable Store Header.

  @return Pointer to the end of the variable storage area.

**/
static
VARIABLE_HEADER *
GetEndPointer (
  IN VARIABLE_STORE_HEADER       *VarStoreHeader
  )
{
  //
  // The end of variable store
  //
  return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);
}


/**

  This code checks if variable header is valid or not.

  @param Variable        Pointer to the Variable Header.

  @retval TRUE           Variable header is valid.
  @retval FALSE          Variable header is not valid.

**/
static
BOOLEAN
IsValidVariableHeader (
  IN  VARIABLE_HEADER   *Variable
  )
{
  if ((Variable == NULL) || (Variable->StartId != VARIABLE_DATA)) {
    return FALSE;
  }

  return TRUE;
}

/**

  This code gets the size of name of variable.

  @param Variable        Pointer to the Variable Header.

  @return UINTN          Size of variable in bytes.

**/
static
UINTN
NameSizeOfVariable (
  IN  VARIABLE_HEADER   *Variable
  )
{
  if ((Variable->State    == (UINT8) (-1)) ||
      (Variable->DataSize == (UINT32) (-1)) ||
      (Variable->NameSize == (UINT32) (-1)) ||
      (Variable->Attributes == (UINT32) (-1))
      ) {
    return 0;
  }
  return (UINTN) Variable->NameSize;
}

/**

  This code gets the size of variable data.

  @param Variable        Pointer to the Variable Header.

  @return Size of variable in bytes.

**/
static
UINTN
DataSizeOfVariable (
  IN  VARIABLE_HEADER   *Variable
  )
{
  if ((Variable->State    == (UINT8)  (-1)) ||
      (Variable->DataSize == (UINT32) (-1)) ||
      (Variable->NameSize == (UINT32) (-1)) ||
      (Variable->Attributes == (UINT32) (-1))
      ) {
    return 0;
  }
  return (UINTN) Variable->DataSize;
}

/**

  This code gets the pointer to the variable name.

  @param Variable        Pointer to the Variable Header.

  @return Pointer to Variable Name which is Unicode encoding.

**/
static
CHAR16 *
GetVariableNamePtr (
  IN  VARIABLE_HEADER   *Variable
  )
{

  return (CHAR16 *) (Variable + 1);
}

/**

  This code gets the pointer to the variable data.

  @param Variable        Pointer to the Variable Header.

  @return Pointer to Variable Data.

**/
static
UINT8 *
GetVariableDataPtr (
  IN  VARIABLE_HEADER   *Variable
  )
{
  UINTN Value;

  //
  // Be careful about pad size for alignment.
  //
  Value =  (UINTN) GetVariableNamePtr (Variable);
  Value += NameSizeOfVariable (Variable);
  Value += GET_PAD_SIZE (NameSizeOfVariable (Variable));

  return (UINT8 *) Value;
}

/**

  This code gets the pointer to the next variable header.

  @param Variable        Pointer to the Variable Header.

  @return Pointer to next variable header.

**/
static
VARIABLE_HEADER *
GetNextVariablePtr (
  IN  VARIABLE_HEADER   *Variable
  )
{
  UINTN Value;

  if (!IsValidVariableHeader (Variable)) {
    return NULL;
  }

  Value =  (UINTN) GetVariableDataPtr (Variable);
  Value += DataSizeOfVariable (Variable);
  Value += GET_PAD_SIZE (DataSizeOfVariable (Variable));

  //
  // Be careful about pad size for alignment.
  //
  return (VARIABLE_HEADER *) HEADER_ALIGN (Value);
}

/**
  Search and get a free space in the EFI variable zone

  @param VariableStoreHeader       The start of a EFI variable zone.
  @param VarListSize               The size of a variables needs to be allocated.
  @param FreeBeginVar              The dual pointer to the free NV space.

  @retval EFI_SUCCESS              Return the beginning of a free variable space.
  @retval RETURN_BUFFER_TOO_SMALL  Failed.
**/
static
EFI_STATUS
GetVariableVar (
  IN      VARIABLE_STORE_HEADER  *VariableStoreHeader,
  IN      UINT32                 VarListSize,
  IN OUT  CHAR8                  **FreeBeginVar
)
{
  BOOLEAN          Flag;
  VARIABLE_HEADER  *Variable;
  VARIABLE_HEADER  *EndOfVariable;
  CHAR8            *BeginVar;

  BeginVar      = NULL;
  Flag          = FALSE;
  Variable      = NULL;
  EndOfVariable = NULL;
  *FreeBeginVar = NULL;

  if (VariableStoreHeader == NULL) {
    *FreeBeginVar = NULL;
    return RETURN_INVALID_PARAMETER;
  }
  Variable      = GetStartPointer (VariableStoreHeader);
  EndOfVariable = GetEndPointer(VariableStoreHeader);
  //
  //Search the beginning of free NV
  //
  while (Variable != EndOfVariable) {
    BeginVar = (CHAR8 *)Variable;
    Variable = GetNextVariablePtr (Variable);
    if (Variable == NULL) {
      Flag = TRUE;
      break;
    }
  }
  //
  // Check whether the free space is more than what we want
  //
  if ((CHAR8 *)BeginVar + VarListSize > (CHAR8 *)EndOfVariable) {
    return RETURN_BUFFER_TOO_SMALL;
  }
  //
  // If not find the available space, return NULL
  //
  if (!Flag) {
    return RETURN_BUFFER_TOO_SMALL;
  }
  *FreeBeginVar = BeginVar;

  return EFI_SUCCESS;
}

/**
  Search whether the variable in VarList has existed in current NV.

  Parse the FFS or Fd image, and find the valid variable pointer.

  @param VariableStoreHeader    The start of a EFI variable zone.
  @param VarList                The pointer to the VarList

  @retval address               If the variable existed in current NV, return address
  @return NULL                  Otherwise, return NULL
**/
static
VARIABLE_HEADER  *
FindVariableInNv (
  IN     VARIABLE_STORE_HEADER  *VariableStoreHeader,
  IN     FORMSET_STORAGE        *Storage
  )
{
  BOOLEAN          Flag;
  VARIABLE_HEADER  *Variable;
  VARIABLE_HEADER  *EndOfVariable;
  CHAR16           *VariableName;

  Flag            = FALSE;
  Variable        = NULL;
  EndOfVariable   = NULL;
  VariableName    = NULL;

  if ((VariableStoreHeader == NULL) || (Storage == NULL) || (Storage->Name == NULL)) {
    return NULL;
  }
  Variable      = GetStartPointer (VariableStoreHeader);
  EndOfVariable = GetEndPointer(VariableStoreHeader);
  //
  // Parse and compare the variable in the NV space one by one
  //
  while ((Variable != EndOfVariable) && (Variable != NULL)) {
    VariableName = (CHAR16 *)((CHAR8 *)Variable + sizeof (VARIABLE_HEADER));
    if (!CompareGuid (&Variable->VendorGuid, &Storage->Guid) \
      && !FceStrCmp (Storage->Name, VariableName) \
      && (Variable->State == VAR_ADDED)) {
      Flag = TRUE;
      break;
    }
    Variable = GetNextVariablePtr (Variable);
  }
  if (!Flag) {
    return NULL;
  }
  return Variable;
}
/**
  Exchange the data between Efi variable and the data of VarList when the
  variable use the authenticated variable header

  If VarToList is TRUE, copy the efi variable data to the VarList; Otherwise,
  update the data from varlist to efi variable.

  @param VarToList         The flag to control the direction of exchange.
  @param StorageListHead   Decide which variale list be updated

  @retval EFI_SUCCESS           Get the address successfully.
  @retval EFI_OUT_OF_RESOURCES  No available in the EFI variable zone.
**/

EFI_STATUS
SynEfiVariable (
  IN  BOOLEAN     VarToList,
  IN  LIST_ENTRY  *StorageListHead
  )
{
  EFI_FIRMWARE_VOLUME_HEADER    *VarAddr;
  LIST_ENTRY                    *StorageLink;
  FORMSET_STORAGE               *Storage;
  EFI_STATUS                    Status;
  CHAR8                         *NewAvailableAddr;
  CHAR8                         *DataBase;
  VARIABLE_HEADER               *VariableHeader;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;
  UINTN                         VarNameSize;

  Status              = EFI_SUCCESS;
  DataBase            = NULL;
  NewAvailableAddr    = NULL;
  VarNameSize         = 0;
  VariableHeader      = NULL;
  VarAddr             = (EFI_FIRMWARE_VOLUME_HEADER   *) gEfiFdInfo.EfiVariableAddr;
  VariableStoreHeader = (VARIABLE_STORE_HEADER *)((CHAR8 *)VarAddr + VarAddr->HeaderLength);
  //
  //Parse the variable range, and check whether there is some existed ones.
  //
  StorageLink = GetFirstNode (StorageListHead);
  while (!IsNull (StorageListHead, StorageLink)) {
    Storage = FORMSET_STORAGE_FROM_LINK (StorageLink);
     //
     // Ignore the invalid varlist node
     //
     if (Storage->Buffer == NULL) {
      StorageLink = GetNextNode (StorageListHead, StorageLink);
      continue;
     }
     //
     // Report error, if the variable name is invalid.
     //
     if ((Storage->Name == NULL) || (FceStrLen(Storage->Name) == 0)) {
       printf ("Error. One variable name is NULL. Its GUID is: ");
       PrintGuid(&(Storage->Guid));
       return EFI_INVALID_PARAMETER;
     }
     VariableHeader = FindVariableInNv (
                        VariableStoreHeader,
                        Storage
                        );

    if (VarToList) {
     //
     //Copy the data from NV to the VarList.
     //
     if (VariableHeader != NULL) {
       if (Storage->Buffer == NULL) {
         Storage->Buffer = calloc (Storage->Size, sizeof (CHAR8));
         ASSERT (Storage->Buffer != NULL);
       }
       DataBase    = (CHAR8*)GetVariableDataPtr (VariableHeader);
       memcpy (
         Storage->Buffer,
         (VOID *) DataBase,
         Storage->Size
        );
      }
    } else {
       //
       //If existed, copy the List data to the variable in NV directly. If not found, create a new one.
       //
       VarNameSize = 2 * (FceStrLen (Storage->Name) + 1);
       //
       //If this variable has existed in current FD, the data in VarList has
       // been updated, and this variable is not authenticated type, then
       // update it from VarList to the FD.
       //
       if ((VariableHeader != NULL)    \
         && (Storage->Buffer != NULL)
         ) {
           DataBase = (CHAR8*)GetVariableDataPtr (VariableHeader);
           memcpy (
             (VOID *) DataBase,
             Storage->Buffer,
             Storage->Size
           );
       } else if ((VariableHeader == NULL) && (Storage->Buffer != NULL)){
         //
         //If EfiVarstore is not EFI_VARIABLE_NON_VOLATILE, only skip it.
         //
         if (Storage->NewEfiVarstore
           && ((Storage->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0)
         ) {
          StorageLink = GetNextNode (StorageListHead, StorageLink);
          continue;
         }
         //
         // Try to get the available zone from the efi variables
         //
         Status = GetVariableVar (
                    VariableStoreHeader,
                    Storage->Size + sizeof (VARIABLE_HEADER),
                    &NewAvailableAddr
                    );

         if (!EFI_ERROR (Status)) {
           //
           // Create the variable header
           //
           VariableHeader             = (VARIABLE_HEADER *) NewAvailableAddr;
           VariableHeader->StartId    = VARIABLE_DATA;
           VariableHeader->State      = VAR_ADDED;
           VariableHeader->Reserved   = 0x0;
           if (Storage->NewEfiVarstore) {
             VariableHeader->Attributes = Storage->Attributes;
           } else {
             VariableHeader->Attributes = EFI_VARIABLE_NON_VOLATILE|EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
           }
           VariableHeader->NameSize   = VarNameSize;
           VariableHeader->DataSize   = Storage->Size;
           //
           //Copy the Guid, variable name, and data in sequence.
           //
           memcpy (
             (VOID *)&(VariableHeader->VendorGuid),
             &(Storage->Guid),
             sizeof (EFI_GUID)
             );
           NewAvailableAddr = NewAvailableAddr + sizeof (VARIABLE_HEADER);
           memcpy (
             (VOID *) NewAvailableAddr,
              Storage->Name,
              VarNameSize
              );

           NewAvailableAddr = NewAvailableAddr + VarNameSize + GET_PAD_SIZE (VarNameSize);
           memcpy (
             (VOID *) NewAvailableAddr,
             Storage->Buffer,
             Storage->Size * sizeof (CHAR8)
             );
         } else {
           printf ("Error. No available space in NV ram.\n");
           return EFI_OUT_OF_RESOURCES;
         }
       }
    }
    StorageLink = GetNextNode (StorageListHead, StorageLink);
  }
  return Status;
}

/**
  Remove the variable from Efi variable

  Found the variable with the same name in StorageListHead and remove it.

  @param StorageListHead   Decide which variale list be removed.

  @retval EFI_SUCCESS      Remove the variables successfully.
**/
EFI_STATUS
RemoveNormalEfiVariable (
  IN  LIST_ENTRY  *StorageListHead
  )
{
  EFI_FIRMWARE_VOLUME_HEADER    *VarAddr;
  LIST_ENTRY                    *StorageLink;
  FORMSET_STORAGE               *Storage;
  VARIABLE_HEADER               *VariableHeader;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;

  VariableHeader      = NULL;
  VarAddr             = (EFI_FIRMWARE_VOLUME_HEADER   *) gEfiFdInfo.EfiVariableAddr;
  VariableStoreHeader = (VARIABLE_STORE_HEADER *)((CHAR8 *)VarAddr + VarAddr->HeaderLength);
  //
  //Parse the variable range, and check whether there is some existed ones.
  //
  StorageLink = GetFirstNode (StorageListHead);
  while (!IsNull (StorageListHead, StorageLink)) {
    Storage = FORMSET_STORAGE_FROM_LINK (StorageLink);
    //
    // Ignore the invalid varlist node
    //
    if (Storage->Buffer == NULL) {
      StorageLink = GetNextNode (StorageListHead, StorageLink);
      continue;
    }
    //
    // Report error, if the variable name is invalid.
    //
    if ((Storage->Name == NULL) || (FceStrLen(Storage->Name) == 0)) {
      printf ("Error. One variable name is NULL. Its GUID is: ");
      PrintGuid(&(Storage->Guid));
      return EFI_INVALID_PARAMETER;
    }
    VariableHeader = FindVariableInNv (
                       VariableStoreHeader,
                       Storage
                       );
    if (VariableHeader != NULL) {
      VariableHeader->State = VAR_DELETED;
    }
    StorageLink = GetNextNode (StorageListHead, StorageLink);
  }
  return EFI_SUCCESS;
}

/**
  Check the store variable is no-authenticated or not

  @param VarToList     The pointer to the header of Variable Store.

  @retval TRUE         If no-authenticated, return TRUE.
  @retval FALSE        Otherwise, return FALSE.
**/

BOOLEAN
CheckNormalVarStoreOrNot (
  IN VOID  *VariableStoreHeader
  )
{
  if (!CompareGuid (
    &gEfiVariableGuid,
    &((VARIABLE_STORE_HEADER *)VariableStoreHeader)->Signature)
    ) {
    return TRUE;
  } else {
    return FALSE;
  }
}

/**
  Copy variable to binary in multi-platform mode

  @param  Storage           The pointer to a storage in storage list.
  @param  StorageBeginning  The pointer to the beginning of storage under specifed platformId and defaultId
  @param  Index             The number of the storage. If the Index is 0, record the variable header to
                            the binary. Or else, only record the storage.

  @return length          The length of storage
**/
UINT32
CopyVariableToBinary (
  IN      FORMSET_STORAGE   *Storage,
  IN OUT  UINT8             *StorageBeginning,
  IN      UINT32            Index
  )
{
  EFI_STATUS                    Status;
  CHAR8                         *NewAvailableAddr;
  VARIABLE_HEADER               *VariableHeader;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;
  UINTN                         VarNameSize;
  UINT32                        HeaderLength;

  Status              = EFI_SUCCESS;
  NewAvailableAddr    = NULL;
  VarNameSize         = 0;
  HeaderLength        = 0;
  VariableHeader      = NULL;
  VariableStoreHeader = NULL;

  if ((Storage->Name == NULL) || (FceStrLen(Storage->Name) == 0)) {
    printf ("Error. One variable name is NULL. Its GUID is: ");
    PrintGuid(&(Storage->Guid));
    return 0;
  }
  //
  // If the first storage under one specified platformId and defaultId, create the variable header
  //
  if (Index == 0) {
    HeaderLength = WriteDefaultAndPlatformId (StorageBeginning, Storage);
    VariableStoreHeader = (VARIABLE_STORE_HEADER *) (StorageBeginning + HeaderLength);
    //
    //Create the Variable Storage header
    //
    memcpy (&(VariableStoreHeader->Signature), &gEfiVariableGuid, sizeof (EFI_GUID));
    VariableStoreHeader->Format = 0x5A;
    VariableStoreHeader->State  = 0xFE;
    //
    //Assign a big size here. It will be fixed after the storage under a specifed platformId and defaultId are all written.
    //
    VariableStoreHeader->Size   = gEfiFdInfo.FdSize;
  }

  VariableStoreHeader = (VARIABLE_STORE_HEADER *) (StorageBeginning + *(UINT16 *)StorageBeginning);

  Status = GetVariableVar (
             VariableStoreHeader,
             Storage->Size + sizeof (VARIABLE_HEADER),
             &NewAvailableAddr
           );
  if (EFI_ERROR (Status)) {
    return FAIL;
  }
  //
  // Create the variable header
  //
  VarNameSize                = 2 * (FceStrLen (Storage->Name) + 1);
  VariableHeader             = (VARIABLE_HEADER *) NewAvailableAddr;
  VariableHeader->StartId    = VARIABLE_DATA;
  VariableHeader->State      = VAR_ADDED;
  VariableHeader->Reserved   = 0x0;
  if (Storage->NewEfiVarstore) {
    VariableHeader->Attributes = Storage->Attributes;
  } else {
    VariableHeader->Attributes = EFI_VARIABLE_NON_VOLATILE|EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
  }
  VariableHeader->NameSize   = VarNameSize;
  VariableHeader->DataSize   = Storage->Size;
  //
  //Copy the Guid, variable name, and data in sequence.
  //
  memcpy (
    (VOID *)&(VariableHeader->VendorGuid),
    &(Storage->Guid),
    sizeof (EFI_GUID)
  );
  NewAvailableAddr = NewAvailableAddr + sizeof (VARIABLE_HEADER);
  memcpy (
    (VOID *) NewAvailableAddr,
    Storage->Name,
    VarNameSize
  );

  NewAvailableAddr = NewAvailableAddr + VarNameSize + GET_PAD_SIZE (VarNameSize);
  memcpy (
    (VOID *) NewAvailableAddr,
    Storage->Buffer,
    Storage->Size * sizeof (CHAR8)
  );
  //
  // Return the length which is from the beginning of Binary
  //
  return ((UINT32) ((UINT8*)NewAvailableAddr - StorageBeginning) + Storage->Size);
}
/**
  Copy variable to binary in multi-platform mode

  @param  Storage           The pointer to a storage in storage list.
  @param  StorageBeginning  The pointer to the beginning of storage under specifed platformId and defaultId
  @param  Index             The number of the storage. If the Index is 0, record the variable header to
                            the binary. Or else, only record the storage.

  @return length          The length of storage
**/
UINT32
CopyVariableToNvStoreBinary (
  IN      FORMSET_STORAGE   *Storage,
  IN OUT  UINT8             *StorageBeginning,
  IN      UINT32            Index
  )
{
  EFI_STATUS                    Status;
  CHAR8                         *NewAvailableAddr;
  VARIABLE_HEADER               *VariableHeader;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;
  UINTN                         VarNameSize;
  UINT32                        HeaderLength;
  PCD_DEFAULT_DATA              *PcdDefaultDataHeader;

  Status              = EFI_SUCCESS;
  NewAvailableAddr    = NULL;
  VarNameSize         = 0;
  HeaderLength        = 0;
  VariableHeader      = NULL;
  VariableStoreHeader = NULL;

  if ((Storage->Name == NULL) || (FceStrLen(Storage->Name) == 0)) {
    printf ("Error. One variable name is NULL. Its GUID is: ");
    PrintGuid(&(Storage->Guid));
    return 0;
  }
  //
  // If the first storage under one specified platformId and defaultId, create the variable header
  //
  if (Index == 0) {
    HeaderLength = WriteNvStoreDefaultAndPlatformId (StorageBeginning, Storage);
    PcdDefaultDataHeader = (PCD_DEFAULT_DATA *)StorageBeginning;
    PcdDefaultDataHeader->HeaderSize = HeaderLength;
    VariableStoreHeader = (VARIABLE_STORE_HEADER *) (StorageBeginning + HeaderLength + 4);
    //
    //Create the Variable Storage header
    //
    memcpy (&(VariableStoreHeader->Signature), &gEfiVariableGuid, sizeof (EFI_GUID));
    VariableStoreHeader->Format = 0x5A;
    VariableStoreHeader->State  = 0xFE;
    //
    //Assign a big size here. It will be fixed after the storage under a specifed platformId and defaultId are all written.
    //
    VariableStoreHeader->Size   = gEfiFdInfo.FdSize;
  }
  PcdDefaultDataHeader = (PCD_DEFAULT_DATA *)StorageBeginning;
  VariableStoreHeader = (VARIABLE_STORE_HEADER *) (StorageBeginning + PcdDefaultDataHeader->HeaderSize + 4);
  Status = GetVariableVar (
             VariableStoreHeader,
             Storage->Size + sizeof (VARIABLE_HEADER),
             &NewAvailableAddr
           );
  if (EFI_ERROR (Status)) {
    return FAIL;
  }
  //
  // Create the variable header
  //
  VarNameSize                = 2 * (FceStrLen (Storage->Name) + 1);
  VariableHeader             = (VARIABLE_HEADER *) NewAvailableAddr;
  VariableHeader->StartId    = VARIABLE_DATA;
  VariableHeader->State      = VAR_ADDED;
  VariableHeader->Reserved   = 0x0;
  if (Storage->NewEfiVarstore) {
    VariableHeader->Attributes = Storage->Attributes;
  } else {
    VariableHeader->Attributes = EFI_VARIABLE_NON_VOLATILE|EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
  }
  VariableHeader->NameSize   = VarNameSize;
  VariableHeader->DataSize   = Storage->Size;
  //
  //Copy the Guid, variable name, and data in sequence.
  //
  memcpy (
    (VOID *)&(VariableHeader->VendorGuid),
    &(Storage->Guid),
    sizeof (EFI_GUID)
  );

  NewAvailableAddr = NewAvailableAddr + sizeof (VARIABLE_HEADER);
  memcpy (
    (VOID *) NewAvailableAddr,
    Storage->Name,
    VarNameSize
  );

  NewAvailableAddr = NewAvailableAddr + VarNameSize + GET_PAD_SIZE (VarNameSize);
  memcpy (
    (VOID *) NewAvailableAddr,
    Storage->Buffer,
    Storage->Size * sizeof (CHAR8)
  );
  //
  // Return the length which is from the beginning of Binary
  //
  return ((UINT32) ((UINT8*)NewAvailableAddr - StorageBeginning - PcdDefaultDataHeader->HeaderSize - 4) + Storage->Size);
}
/**
  Read variable to storage list in multi-platform mode

  @param  Binary            The pointer to the header of storage under specifed platformId and defaultId
  @param  StorageListEntry  The pointer to the storage list.

  @return length          The length of storage
**/
UINT32
ReadNvStoreVariableToList (
  IN      UINT8             *Binary,
  IN      LIST_ENTRY        *StorageListEntry
  )
{
  VARIABLE_HEADER               *EndOfVariable;
  VARIABLE_HEADER               *Variable;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;
  FORMSET_STORAGE               *Storage;
  UINT32                        Length;
  PCD_DEFAULT_DATA             *PcdDefaultData;
  UINT8                         *DataBase;
  static UINT16                 PreDefaultId;
  static UINT64                 PrePlatformId;

  VariableStoreHeader = NULL;
  Variable            = NULL;
  Length              = 0;
  DataBase            = Binary;

  PcdDefaultData      = (PCD_DEFAULT_DATA *)DataBase;
  PrePlatformId       = PcdDefaultData->DefaultInfo[0].SkuId;
  PreDefaultId        = PcdDefaultData->DefaultInfo[0].DefaultId;
  VariableStoreHeader = (VARIABLE_STORE_HEADER *) (DataBase + PcdDefaultData->HeaderSize + 4);
  EndOfVariable       = GetEndPointer(VariableStoreHeader);

  for (Variable = GetStartPointer (VariableStoreHeader);
    Length < VariableStoreHeader->Size;
    Length += sizeof (VARIABLE_HEADER) + Variable->NameSize + Variable->DataSize
  ) {
    //
    // Create the storage
    //
    Storage = NULL;
    Storage = calloc (sizeof (FORMSET_STORAGE), sizeof (CHAR8));
    if (Storage == NULL) {
      printf ("Allocate memory failed.\n");
      return FAIL;
    }
    //
    // Store the DefaultId and PlatformId collected from the header to Storage.
    //
    Storage->DefaultId[0] = PreDefaultId;
    Storage->PlatformId[0] = PrePlatformId;
    Storage->DefaultPlatformIdNum = 0;

    Storage->Attributes     = Variable->Attributes;
    Storage->Size           = (UINT16)Variable->DataSize;
    Storage->Name           = calloc (Variable->NameSize, sizeof (UINT8));
    ASSERT (Storage->Name != NULL);
    Storage->Buffer         = calloc (Variable->DataSize, sizeof (UINT8));
    ASSERT (Storage->Buffer != NULL);
    memcpy (
      &(Storage->Guid),
      &(Variable->VendorGuid),
      sizeof (EFI_GUID)
    );
    memcpy (
      Storage->Name,
      (UINT8 *)Variable + sizeof (VARIABLE_HEADER),
      Variable->NameSize
    );
    memcpy (
      Storage->Buffer,
      (UINT8 *)Variable + sizeof (VARIABLE_HEADER) + Variable->NameSize + GET_PAD_SIZE (Variable->NameSize),
      Storage->Size * sizeof (CHAR8)
    );
    //
    // Assigned the value for comparison in verify mode
    //
    Storage->Type           = EFI_IFR_VARSTORE_EFI_OP;
    Storage->NewEfiVarstore = TRUE;
    InitializeListHead (&Storage->NameValueListHead);

    InsertTailList(StorageListEntry, &Storage->Link);
    //
    // If the last variable, exit.
    //
    if (Variable == EndOfVariable) {
      break;
    }

    Variable = GetNextVariablePtr (Variable);
    assert (Variable != NULL);
    if (!IsValidVariableHeader(Variable)) {
      break;
    }
  }

  return Length;
}
/**
  Read variable to storage list in multi-platform mode

  @param  Binary            The pointer to the header of storage under specifed platformId and defaultId
  @param  StorageListEntry  The pointer to the storage list.

  @return length          The length of storage
**/
UINT32
ReadVariableToList (
  IN      UINT8             *Binary,
  IN      LIST_ENTRY        *StorageListEntry
  )
{
  VARIABLE_HEADER               *EndOfVariable;
  VARIABLE_HEADER               *Variable;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;
  FORMSET_STORAGE               *Storage;
  BOOLEAN                       ReadIdHeaderFlag;
  UINT32                        Length;
  EFI_COMMON_SECTION_HEADER     *SectionHeader;
  UINT8                         *DataBase;
  static UINT16                 PreDefaultId[MAX_PLATFORM_DEFAULT_ID_NUM];
  static UINT64                 PrePlatformId[MAX_PLATFORM_DEFAULT_ID_NUM];

  VariableStoreHeader = NULL;
  Variable            = NULL;
  ReadIdHeaderFlag    = TRUE;
  Length              = 0;
  SectionHeader       = (EFI_COMMON_SECTION_HEADER *)Binary;
  DataBase            = Binary + sizeof (EFI_COMMON_SECTION_HEADER);
  VariableStoreHeader = (VARIABLE_STORE_HEADER *) (DataBase + *(UINT16 *)DataBase);
  EndOfVariable       = GetEndPointer(VariableStoreHeader);

  for (Variable = GetStartPointer (VariableStoreHeader);
    Length < VariableStoreHeader->Size;
    Length += sizeof (VARIABLE_HEADER) + Variable->NameSize + Variable->DataSize
  ) {
    //
    // Create the storage
    //
    Storage = NULL;
    Storage = calloc (sizeof (FORMSET_STORAGE), sizeof (CHAR8));
    if (Storage == NULL) {
      printf ("Allocate memory failed.\n");
      return FAIL;
    }
    //
    // If access the first storage, read the platformId and defaultId
    //
    if (ReadIdHeaderFlag) {
      ReadDefaultAndPlatformIdFromBfv (DataBase, Storage);
      Length += sizeof (VARIABLE_HEADER) + Variable->NameSize + Variable->DataSize;
      ReadIdHeaderFlag = FALSE;
      memcpy (PreDefaultId, Storage->DefaultId, MAX_PLATFORM_DEFAULT_ID_NUM * sizeof (UINT16));
      memcpy (PrePlatformId, Storage->PlatformId, MAX_PLATFORM_DEFAULT_ID_NUM * sizeof (UINT64));
    } else {
      //
      // Store the DefaultId and PlatformId collected from the header to Storage.
      //
      memcpy (Storage->DefaultId, PreDefaultId, MAX_PLATFORM_DEFAULT_ID_NUM * sizeof (UINT16));
      memcpy (Storage->PlatformId, PrePlatformId, MAX_PLATFORM_DEFAULT_ID_NUM * sizeof (UINT64));
    }
    Storage->Attributes     = Variable->Attributes;
    Storage->Size           = (UINT16)Variable->DataSize;
    Storage->Name           = calloc (Variable->NameSize, sizeof (UINT8));
    ASSERT (Storage->Name != NULL);
    Storage->Buffer         = calloc (Variable->DataSize, sizeof (UINT8));
    ASSERT (Storage->Buffer != NULL);
    memcpy (
      &(Storage->Guid),
      &(Variable->VendorGuid),
      sizeof (EFI_GUID)
    );
    memcpy (
      Storage->Name,
      (UINT8 *)Variable + sizeof (VARIABLE_HEADER),
      Variable->NameSize
    );
    memcpy (
      Storage->Buffer,
      (UINT8 *)Variable + sizeof (VARIABLE_HEADER) + Variable->NameSize + GET_PAD_SIZE (Variable->NameSize),
      Storage->Size * sizeof (CHAR8)
    );
    //
    // Assigned the value for comparison in verify mode
    //
    Storage->Type           = EFI_IFR_VARSTORE_EFI_OP;
    Storage->NewEfiVarstore = TRUE;
    InitializeListHead (&Storage->NameValueListHead);

    InsertTailList(StorageListEntry, &Storage->Link);
    //
    // If the last variable, exit.
    //
    if (Variable == EndOfVariable) {
      break;
    }

    Variable = GetNextVariablePtr (Variable);
    assert (Variable != NULL);
  }
  //
  // Return the length which is from the beginning of Binary
  //
  Length = FvBufExpand3ByteSize (SectionHeader->Size);

  return Length;
}

/**
  Check whether exists the valid normal variables in NvStorage or not.

  @retval TRUE      If existed, return TRUE.
  @retval FALSE     Others
**/
BOOLEAN
ExistNormalEfiVarOrNot (
  IN  LIST_ENTRY  *StorageListHead
  )
{
  EFI_FIRMWARE_VOLUME_HEADER    *VarAddr;
  LIST_ENTRY                    *StorageLink;
  FORMSET_STORAGE               *Storage;
  VARIABLE_HEADER               *VariableHeader;
  VARIABLE_STORE_HEADER         *VariableStoreHeader;

  VariableHeader      = NULL;
  VarAddr             = (EFI_FIRMWARE_VOLUME_HEADER   *) gEfiFdInfo.EfiVariableAddr;
  VariableStoreHeader = (VARIABLE_STORE_HEADER *)((CHAR8 *)VarAddr + VarAddr->HeaderLength);
  //
  //Parse the variable range, and check whether there is some existed ones.
  //
  StorageLink = GetFirstNode (StorageListHead);
  while (!IsNull (StorageListHead, StorageLink)) {
    Storage = FORMSET_STORAGE_FROM_LINK (StorageLink);
    //
    // Ignore the invalid varlist node
    //
    if ((Storage->Buffer == NULL)
      || (Storage->Name == NULL)
      || (FceStrLen(Storage->Name) == 0)
      ) {
     StorageLink = GetNextNode (StorageListHead, StorageLink);
     continue;
    }
    //
    // Report error, if the variable name is invalid.
    //
    if ((Storage->Name == NULL) || (FceStrLen(Storage->Name) == 0)) {
      StorageLink = GetNextNode (StorageListHead, StorageLink);
     continue;
    }
    VariableHeader = FindVariableInNv (
                       VariableStoreHeader,
                       Storage
                     );

    if ((VariableHeader != NULL)) {
       return TRUE;
    }
    StorageLink = GetNextNode (StorageListHead, StorageLink);
  }
  return FALSE;
}

/**
  Fix the size of variable header.

  @param  Binary            The pointer to the header of storage under specifed platformId and defaultId
  @param  Length            The length of binary.

**/
VOID
FixVariableHeaderSize (
  IN  UINT8   *BinaryBeginning,
  IN  UINT32  Length
  )
{
  VARIABLE_STORE_HEADER         *VariableStoreHeader;

  VariableStoreHeader       = (VARIABLE_STORE_HEADER *) (BinaryBeginning + *(UINT16 *)BinaryBeginning);
  VariableStoreHeader->Size =  Length -  *(UINT16 *)BinaryBeginning;
}

/**
  Fix the size of variable header.

  @param  Binary            The pointer to the header of storage under specifed platformId and defaultId
  @param  Length            The length of binary.

**/
VOID
FixNvStoreVariableHeaderSize (
  IN  UINT8   *BinaryBeginning,
  IN  UINT32  Length
  )
{
  VARIABLE_STORE_HEADER         *VariableStoreHeader;
  PCD_DEFAULT_DATA              *PcdDefaultDataHeader;

  PcdDefaultDataHeader      = (PCD_DEFAULT_DATA *)(BinaryBeginning);
  VariableStoreHeader       = (VARIABLE_STORE_HEADER *) (BinaryBeginning + PcdDefaultDataHeader->HeaderSize + 4);
  VariableStoreHeader->Size = Length;
  PcdDefaultDataHeader->DataSize = VariableStoreHeader->Size + PcdDefaultDataHeader->HeaderSize + 4;
}