summaryrefslogtreecommitdiffstats
path: root/SignedCapsulePkg/Library/IniParsingLib/IniParsingLib.c
blob: 5763e0494e1c4dc9a92f301920337a9db41ab821 (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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
/** @file
  This library parses the INI configuration file.

  The INI file format is:
    ================
    [SectionName]
    EntryName=EntryValue
    ================

    Where:
      1) SectionName is an ASCII string. The valid format is [A-Za-z0-9_]+
      2) EntryName is an ASCII string. The valid format is [A-Za-z0-9_]+
      3) EntryValue can be:
         3.1) an ASCII String. The valid format is [A-Za-z0-9_]+
         3.2) a GUID. The valid format is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is [A-Fa-f0-9]
         3.3) a decimal value. The valid format is [0-9]+
         3.4) a heximal value. The valid format is 0x[A-Fa-f0-9]+
      4) '#' or ';' can be used as comment at anywhere.
      5) TAB(0x20) or SPACE(0x9) can be used as separator.
      6) LF(\n, 0xA) or CR(\r, 0xD) can be used as line break.

  Caution: This module requires additional review when modified.
  This driver will have external input - INI data file.

  OpenIniFile(), PreProcessDataFile(), ProfileGetSection(), ProfileGetEntry()
  will receive untrusted input and do basic validation.

  Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>

  This program and the accompanying materials
  are licensed and made available under the terms and conditions
  of the BSD License which accompanies this distribution.  The
  full text of the license may be found at
  http://opensource.org/licenses/bsd-license.php

  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

#include <Uefi.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>

#define IS_HYPHEN(a)               ((a) == '-')
#define IS_NULL(a)                 ((a) == '\0')

// This is default allocation. Reallocation will happen if it is not enough.
#define MAX_LINE_LENGTH           512

typedef struct _INI_SECTION_ITEM SECTION_ITEM;
struct _INI_SECTION_ITEM {
  CHAR8                           *PtrSection;
  UINTN                           SecNameLen;
  CHAR8                           *PtrEntry;
  CHAR8                           *PtrValue;
  SECTION_ITEM                    *PtrNext;
};

typedef struct _INI_COMMENT_LINE COMMENT_LINE;
struct _INI_COMMENT_LINE {
  CHAR8                           *PtrComment;
  COMMENT_LINE                    *PtrNext;
};

typedef struct {
  SECTION_ITEM                  *SectionHead;
  COMMENT_LINE                  *CommentHead;
} INI_PARSING_LIB_CONTEXT;

/**
  Return if the digital char is valid.

  @param[in] DigitalChar    The digital char to be checked.
  @param[in] IncludeHex     If it include HEX char.

  @retval TRUE   The digital char is valid.
  @retval FALSE  The digital char is invalid.
**/
BOOLEAN
IsValidDigitalChar (
  IN CHAR8    DigitalChar,
  IN BOOLEAN  IncludeHex
  )
{
  if (DigitalChar >= '0' && DigitalChar <= '9') {
    return TRUE;
  }
  if (IncludeHex) {
    if (DigitalChar >= 'a' && DigitalChar <= 'f') {
      return TRUE;
    }
    if (DigitalChar >= 'A' && DigitalChar <= 'F') {
      return TRUE;
    }
  }
  return FALSE;
}

/**
  Return if the name char is valid.

  @param[in] NameChar    The name char to be checked.

  @retval TRUE   The name char is valid.
  @retval FALSE  The name char is invalid.
**/
BOOLEAN
IsValidNameChar (
  IN CHAR8  NameChar
  )
{
  if (NameChar >= 'a' && NameChar <= 'z') {
    return TRUE;
  }
  if (NameChar >= 'A' && NameChar <= 'Z') {
    return TRUE;
  }
  if (NameChar >= '0' && NameChar <= '9') {
    return TRUE;
  }
  if (NameChar == '_') {
    return TRUE;
  }
  return FALSE;
}

/**
  Return if the digital string is valid.

  @param[in] Digital        The digital to be checked.
  @param[in] Length         The length of digital string in bytes.
  @param[in] IncludeHex     If it include HEX char.

  @retval TRUE   The digital string is valid.
  @retval FALSE  The digital string is invalid.
**/
BOOLEAN
IsValidDigital (
  IN CHAR8    *Digital,
  IN UINTN    Length,
  IN BOOLEAN  IncludeHex
  )
{
  UINTN  Index;
  for (Index = 0; Index < Length; Index++) {
    if (!IsValidDigitalChar(Digital[Index], IncludeHex)) {
      return FALSE;
    }
  }
  return TRUE;
}

/**
  Return if the decimal string is valid.

  @param[in] Decimal The decimal string to be checked.
  @param[in] Length  The length of decimal string in bytes.

  @retval TRUE   The decimal string is valid.
  @retval FALSE  The decimal string is invalid.
**/
BOOLEAN
IsValidDecimalString (
  IN CHAR8  *Decimal,
  IN UINTN  Length
  )
{
  return IsValidDigital(Decimal, Length, FALSE);
}

/**
  Return if the heximal string is valid.

  @param[in] Hex     The heximal string to be checked.
  @param[in] Length  The length of heximal string in bytes.

  @retval TRUE   The heximal string is valid.
  @retval FALSE  The heximal string is invalid.
**/
BOOLEAN
IsValidHexString (
  IN CHAR8  *Hex,
  IN UINTN  Length
  )
{
  if (Length <= 2) {
    return FALSE;
  }
  if (Hex[0] != '0') {
    return FALSE;
  }
  if (Hex[1] != 'x' && Hex[1] != 'X') {
    return FALSE;
  }
  return IsValidDigital(&Hex[2], Length - 2, TRUE);
}

/**
  Return if the name string is valid.

  @param[in] Name    The name to be checked.
  @param[in] Length  The length of name string in bytes.

  @retval TRUE   The name string is valid.
  @retval FALSE  The name string is invalid.
**/
BOOLEAN
IsValidName (
  IN CHAR8  *Name,
  IN UINTN  Length
  )
{
  UINTN  Index;
  for (Index = 0; Index < Length; Index++) {
    if (!IsValidNameChar(Name[Index])) {
      return FALSE;
    }
  }
  return TRUE;
}

/**
  Return if the value string is valid GUID.

  @param[in] Value   The value to be checked.
  @param[in] Length  The length of value string in bytes.

  @retval TRUE   The value string is valid GUID.
  @retval FALSE  The value string is invalid GUID.
**/
BOOLEAN
IsValidGuid (
  IN CHAR8  *Value,
  IN UINTN  Length
  )
{
  if (Length != sizeof("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") - 1) {
    return FALSE;
  }
  if (!IS_HYPHEN(Value[8])) {
    return FALSE;
  }
  if (!IS_HYPHEN(Value[13])) {
    return FALSE;
  }
  if (!IS_HYPHEN(Value[18])) {
    return FALSE;
  }
  if (!IS_HYPHEN(Value[23])) {
    return FALSE;
  }
  if (!IsValidDigital(&Value[0], 8, TRUE)) {
    return FALSE;
  }
  if (!IsValidDigital(&Value[9], 4, TRUE)) {
    return FALSE;
  }
  if (!IsValidDigital(&Value[14], 4, TRUE)) {
    return FALSE;
  }
  if (!IsValidDigital(&Value[19], 4, TRUE)) {
    return FALSE;
  }
  if (!IsValidDigital(&Value[24], 12, TRUE)) {
    return FALSE;
  }
  return TRUE;
}

/**
  Return if the value string is valid.

  @param[in] Value    The value to be checked.
  @param[in] Length  The length of value string in bytes.

  @retval TRUE   The name string is valid.
  @retval FALSE  The name string is invalid.
**/
BOOLEAN
IsValidValue (
  IN CHAR8  *Value,
  IN UINTN  Length
  )
{
  if (IsValidName(Value, Length) || IsValidGuid(Value, Length)) {
    return TRUE;
  }
  return FALSE;
}

/**
  Dump an INI config file context.

  @param[in] Context         INI Config file context.
**/
VOID
DumpIniSection (
  IN VOID  *Context
  )
{
  INI_PARSING_LIB_CONTEXT               *IniContext;
  SECTION_ITEM                          *PtrSection;
  SECTION_ITEM                          *Section;

  if (Context == NULL) {
    return;
  }

  IniContext = Context;
  Section = IniContext->SectionHead;

  while (Section != NULL) {
    PtrSection = Section;
    Section = Section->PtrNext;
    if (PtrSection->PtrSection != NULL) {
      DEBUG((DEBUG_VERBOSE, "Section - %a\n", PtrSection->PtrSection));
    }
    if (PtrSection->PtrEntry != NULL) {
      DEBUG ((DEBUG_VERBOSE, "  Entry - %a\n", PtrSection->PtrEntry));
    }
    if (PtrSection->PtrValue != NULL) {
      DEBUG((DEBUG_VERBOSE, "  Value - %a\n", PtrSection->PtrValue));
    }
  }
}

/**
  Copy one line data from buffer data to the line buffer.

  @param[in]      Buffer          Buffer data.
  @param[in]      BufferSize      Buffer Size.
  @param[in, out] LineBuffer      Line buffer to store the found line data.
  @param[in, out] LineSize        On input, size of the input line buffer.
                                  On output, size of the actual line buffer.

  @retval EFI_BUFFER_TOO_SMALL  The size of input line buffer is not enough.
  @retval EFI_SUCCESS           Copy line data into the line buffer.

**/
EFI_STATUS
ProfileGetLine (
  IN      UINT8                         *Buffer,
  IN      UINTN                         BufferSize,
  IN OUT  UINT8                         *LineBuffer,
  IN OUT  UINTN                         *LineSize
  )
{
  UINTN                                 Length;
  UINT8                                 *PtrBuf;
  UINTN                                 PtrEnd;

  PtrBuf      = Buffer;
  PtrEnd      = (UINTN)Buffer + BufferSize;

  //
  // 0x0D indicates a line break. Otherwise there is no line break
  //
  while ((UINTN)PtrBuf < PtrEnd) {
    if (*PtrBuf == 0x0D || *PtrBuf == 0x0A) {
      break;
    }
    PtrBuf++;
  }

  if ((UINTN)PtrBuf >= (PtrEnd - 1)) {
    //
    // The buffer ends without any line break
    // or it is the last character of the buffer
    //
    Length    = BufferSize;
  } else if (*(PtrBuf + 1) == 0x0A) {
    //
    // Further check if a 0x0A follows. If yes, count 0xA
    //
    Length    = (UINTN) PtrBuf - (UINTN) Buffer + 2;
  } else {
    Length    = (UINTN) PtrBuf - (UINTN) Buffer + 1;
  }

  if (Length > (*LineSize)) {
    *LineSize = Length;
    return EFI_BUFFER_TOO_SMALL;
  }

  SetMem (LineBuffer, *LineSize, 0x0);
  *LineSize   = Length;
  CopyMem (LineBuffer, Buffer, Length);

  return EFI_SUCCESS;
}

/**
  Trim Buffer by removing all CR, LF, TAB, and SPACE chars in its head and tail.

  @param[in, out] Buffer          On input,  buffer data to be trimed.
                                  On output, the trimmed buffer.
  @param[in, out] BufferSize      On input,  size of original buffer data.
                                  On output, size of the trimmed buffer.

**/
VOID
ProfileTrim (
  IN OUT  UINT8                         *Buffer,
  IN OUT  UINTN                         *BufferSize
  )
{
  UINTN                                 Length;
  UINT8                                 *PtrBuf;
  UINT8                                 *PtrEnd;

  if (*BufferSize == 0) {
    return;
  }

  //
  // Trim the tail first, include CR, LF, TAB, and SPACE.
  //
  Length          = *BufferSize;
  PtrBuf          = (UINT8 *) ((UINTN) Buffer + Length - 1);
  while (PtrBuf >= Buffer) {
    if ((*PtrBuf != 0x0D) && (*PtrBuf != 0x0A )
      && (*PtrBuf != 0x20) && (*PtrBuf != 0x09)) {
      break;
    }
    PtrBuf --;
  }

  //
  // all spaces, a blank line, return directly;
  //
  if (PtrBuf < Buffer) {
    *BufferSize   = 0;
    return;
  }

  Length          = (UINTN)PtrBuf - (UINTN)Buffer + 1;
  PtrEnd          = PtrBuf;
  PtrBuf          = Buffer;

  //
  // Now skip the heading CR, LF, TAB and SPACE
  //
  while (PtrBuf <= PtrEnd) {
    if ((*PtrBuf != 0x0D) && (*PtrBuf != 0x0A )
      && (*PtrBuf != 0x20) && (*PtrBuf != 0x09)) {
      break;
    }
    PtrBuf++;
  }

  //
  // If no heading CR, LF, TAB or SPACE, directly return
  //
  if (PtrBuf == Buffer) {
    *BufferSize   = Length;
    return;
  }

  *BufferSize     = (UINTN)PtrEnd - (UINTN)PtrBuf + 1;

  //
  // The first Buffer..PtrBuf characters are CR, LF, TAB or SPACE.
  // Now move out all these characters.
  //
  while (PtrBuf <= PtrEnd) {
    *Buffer       = *PtrBuf;
    Buffer++;
    PtrBuf++;
  }

  return;
}

/**
  Insert new comment item into comment head.

  @param[in]      Buffer          Comment buffer to be added.
  @param[in]      BufferSize      Size of comment buffer.
  @param[in, out] CommentHead     Comment Item head entry.

  @retval EFI_OUT_OF_RESOURCES   No enough memory is allocated.
  @retval EFI_SUCCESS            New comment item is inserted.

**/
EFI_STATUS
ProfileGetComments (
  IN      UINT8                         *Buffer,
  IN      UINTN                         BufferSize,
  IN OUT  COMMENT_LINE                  **CommentHead
  )
{
  COMMENT_LINE                          *CommentItem;

  CommentItem = NULL;
  CommentItem = AllocatePool (sizeof (COMMENT_LINE));
  if (CommentItem == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  CommentItem->PtrNext  = *CommentHead;
  *CommentHead          = CommentItem;

  //
  // Add a trailing '\0'
  //
  CommentItem->PtrComment = AllocatePool (BufferSize + 1);
  if (CommentItem->PtrComment == NULL) {
    FreePool (CommentItem);
    return EFI_OUT_OF_RESOURCES;
  }
  CopyMem (CommentItem->PtrComment, Buffer, BufferSize);
  *(CommentItem->PtrComment + BufferSize) = '\0';

  return EFI_SUCCESS;
}

/**
  Add new section item into Section head.

  @param[in]      Buffer          Section item data buffer.
  @param[in]      BufferSize      Size of section item.
  @param[in, out] SectionHead     Section item head entry.

  @retval EFI_OUT_OF_RESOURCES   No enough memory is allocated.
  @retval EFI_SUCCESS            Section item is NULL or Section item is added.

**/
EFI_STATUS
ProfileGetSection (
  IN      UINT8                         *Buffer,
  IN      UINTN                         BufferSize,
  IN OUT  SECTION_ITEM                  **SectionHead
  )
{
  SECTION_ITEM                          *SectionItem;
  UINTN                                 Length;
  UINT8                                 *PtrBuf;
  UINT8                                 *PtrEnd;

  ASSERT(BufferSize >= 1);
  //
  // The first character of Buffer is '[', now we want for ']'
  //
  PtrEnd      = (UINT8 *)((UINTN)Buffer + BufferSize - 1);
  PtrBuf      = (UINT8 *)((UINTN)Buffer + 1);
  while (PtrBuf <= PtrEnd) {
    if (*PtrBuf == ']') {
      break;
    }
    PtrBuf ++;
  }
  if (PtrBuf > PtrEnd) {
    //
    // Not found. Invalid line
    //
    return EFI_NOT_FOUND;
  }
  if (PtrBuf <= Buffer + 1) {
    // Empty name
    return EFI_NOT_FOUND;
  }

  //
  // excluding the heading '[' and tailing ']'
  //
  Length      = PtrBuf - Buffer - 1;
  ProfileTrim (
    Buffer + 1,
    &Length
  );

  //
  // Invalid line if the section name is null
  //
  if (Length == 0) {
    return EFI_NOT_FOUND;
  }

  if (!IsValidName((CHAR8 *)Buffer + 1, Length)) {
    return EFI_INVALID_PARAMETER;
  }

  SectionItem = AllocatePool (sizeof (SECTION_ITEM));
  if (SectionItem == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  SectionItem->PtrSection = NULL;
  SectionItem->SecNameLen = Length;
  SectionItem->PtrEntry   = NULL;
  SectionItem->PtrValue   = NULL;
  SectionItem->PtrNext    = *SectionHead;
  *SectionHead            = SectionItem;

  //
  // Add a trailing '\0'
  //
  SectionItem->PtrSection = AllocatePool (Length + 1);
  if (SectionItem->PtrSection == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // excluding the heading '['
  //
  CopyMem (SectionItem->PtrSection, Buffer + 1, Length);
  *(SectionItem->PtrSection + Length) = '\0';

  return EFI_SUCCESS;
}

/**
  Add new section entry and entry value into Section head.

  @param[in]      Buffer          Section entry data buffer.
  @param[in]      BufferSize      Size of section entry.
  @param[in, out] SectionHead     Section item head entry.

  @retval EFI_OUT_OF_RESOURCES   No enough memory is allocated.
  @retval EFI_SUCCESS            Section entry is added.
  @retval EFI_NOT_FOUND          Section entry is not found.
  @retval EFI_INVALID_PARAMETER  Section entry is invalid.

**/
EFI_STATUS
ProfileGetEntry (
  IN      UINT8                         *Buffer,
  IN      UINTN                         BufferSize,
  IN OUT  SECTION_ITEM                  **SectionHead
  )
{
  EFI_STATUS                            Status;
  SECTION_ITEM                          *SectionItem;
  SECTION_ITEM                          *PtrSection;
  UINTN                                 Length;
  UINT8                                 *PtrBuf;
  UINT8                                 *PtrEnd;

  Status      = EFI_SUCCESS;
  PtrBuf      = Buffer;
  PtrEnd      = (UINT8 *) ((UINTN)Buffer + BufferSize - 1);

  //
  // First search for '='
  //
  while (PtrBuf <= PtrEnd) {
    if (*PtrBuf == '=') {
      break;
    }
    PtrBuf++;
  }
  if (PtrBuf > PtrEnd) {
    //
    // Not found. Invalid line
    //
    return EFI_NOT_FOUND;
  }
  if (PtrBuf <= Buffer) {
    // Empty name
    return EFI_NOT_FOUND;
  }

  //
  // excluding the tailing '='
  //
  Length      = PtrBuf - Buffer;
  ProfileTrim (
    Buffer,
    &Length
  );

  //
  // Invalid line if the entry name is null
  //
  if (Length == 0) {
    return EFI_NOT_FOUND;
  }

  if (!IsValidName((CHAR8 *)Buffer, Length)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Omit this line if no section header has been found before
  //
  if (*SectionHead == NULL) {
    return Status;
  }
  PtrSection  = *SectionHead;

  SectionItem = AllocatePool (sizeof (SECTION_ITEM));
  if (SectionItem == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  SectionItem->PtrSection = NULL;
  SectionItem->PtrEntry   = NULL;
  SectionItem->PtrValue   = NULL;
  SectionItem->SecNameLen = PtrSection->SecNameLen;
  SectionItem->PtrNext    = *SectionHead;
  *SectionHead            = SectionItem;

  //
  // SectionName, add a trailing '\0'
  //
  SectionItem->PtrSection = AllocatePool (PtrSection->SecNameLen + 1);
  if (SectionItem->PtrSection == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  CopyMem (SectionItem->PtrSection, PtrSection->PtrSection, PtrSection->SecNameLen + 1);

  //
  // EntryName, add a trailing '\0'
  //
  SectionItem->PtrEntry = AllocatePool (Length + 1);
  if (SectionItem->PtrEntry == NULL) {
    FreePool(SectionItem->PtrSection);
    return EFI_OUT_OF_RESOURCES;
  }
  CopyMem (SectionItem->PtrEntry, Buffer, Length);
  *(SectionItem->PtrEntry + Length) = '\0';

  //
  // Next search for '#' or ';'
  //
  PtrBuf      = PtrBuf + 1;
  Buffer      = PtrBuf;
  while (PtrBuf <= PtrEnd) {
    if (*PtrBuf == '#' || *PtrBuf == ';') {
      break;
    }
    PtrBuf++;
  }
  if (PtrBuf <= Buffer) {
    // Empty name
    FreePool(SectionItem->PtrEntry);
    FreePool(SectionItem->PtrSection);
    return EFI_NOT_FOUND;
  }
  Length      = PtrBuf - Buffer;
  ProfileTrim (
    Buffer,
    &Length
  );

  //
  // Invalid line if the entry value is null
  //
  if (Length == 0) {
    FreePool(SectionItem->PtrEntry);
    FreePool(SectionItem->PtrSection);
    return EFI_NOT_FOUND;
  }

  if (!IsValidValue((CHAR8 *)Buffer, Length)) {
    FreePool(SectionItem->PtrEntry);
    FreePool(SectionItem->PtrSection);
    return EFI_INVALID_PARAMETER;
  }

  //
  // EntryValue, add a trailing '\0'
  //
  SectionItem->PtrValue = AllocatePool (Length + 1);
  if (SectionItem->PtrValue == NULL) {
    FreePool(SectionItem->PtrEntry);
    FreePool(SectionItem->PtrSection);
    return EFI_OUT_OF_RESOURCES;
  }
  CopyMem (SectionItem->PtrValue, Buffer, Length);
  *(SectionItem->PtrValue + Length) = '\0';

  return EFI_SUCCESS;
}

/**
  Free all comment entry and section entry.

  @param[in] Section         Section entry list.
  @param[in] Comment         Comment entry list.

**/
VOID
FreeAllList (
  IN      SECTION_ITEM                  *Section,
  IN      COMMENT_LINE                  *Comment
  )
{
  SECTION_ITEM                          *PtrSection;
  COMMENT_LINE                          *PtrComment;

  while (Section != NULL) {
    PtrSection    = Section;
    Section       = Section->PtrNext;
    if (PtrSection->PtrEntry != NULL) {
      FreePool (PtrSection->PtrEntry);
    }
    if (PtrSection->PtrSection != NULL) {
      FreePool (PtrSection->PtrSection);
    }
    if (PtrSection->PtrValue != NULL) {
      FreePool (PtrSection->PtrValue);
    }
    FreePool (PtrSection);
  }

  while (Comment != NULL) {
    PtrComment    = Comment;
    Comment       = Comment->PtrNext;
    if (PtrComment->PtrComment != NULL) {
      FreePool (PtrComment->PtrComment);
    }
    FreePool (PtrComment);
  }

  return;
}

/**
  Get section entry value.

  @param[in]  Section         Section entry list.
  @param[in]  SectionName     Section name.
  @param[in]  EntryName       Section entry name.
  @param[out] EntryValue      Point to the got entry value.

  @retval EFI_NOT_FOUND  Section is not found.
  @retval EFI_SUCCESS    Section entry value is got.

**/
EFI_STATUS
UpdateGetProfileString (
  IN      SECTION_ITEM                  *Section,
  IN      CHAR8                         *SectionName,
  IN      CHAR8                         *EntryName,
  OUT     CHAR8                         **EntryValue
  )
{
  *EntryValue   = NULL;

  while (Section != NULL) {
    if (AsciiStrCmp ((CONST CHAR8 *) Section->PtrSection, (CONST CHAR8 *) SectionName) == 0) {
      if (Section->PtrEntry != NULL) {
        if (AsciiStrCmp ((CONST CHAR8 *) Section->PtrEntry, (CONST CHAR8 *) EntryName) == 0) {
          break;
        }
      }
    }
    Section     = Section->PtrNext;
  }

  if (Section == NULL) {
    return EFI_NOT_FOUND;
  }

  *EntryValue   = Section->PtrValue;

  return EFI_SUCCESS;
}

/**
  Pre process config data buffer into Section entry list and Comment entry list.

  @param[in]      DataBuffer      Config raw file buffer.
  @param[in]      BufferSize      Size of raw buffer.
  @param[in, out] SectionHead     Pointer to the section entry list.
  @param[in, out] CommentHead     Pointer to the comment entry list.

  @retval EFI_OUT_OF_RESOURCES  No enough memory is allocated.
  @retval EFI_SUCCESS           Config data buffer is preprocessed.
  @retval EFI_NOT_FOUND         Config data buffer is invalid, because Section or Entry is not found.
  @retval EFI_INVALID_PARAMETER Config data buffer is invalid, because Section or Entry is invalid.

**/
EFI_STATUS
PreProcessDataFile (
  IN      UINT8                         *DataBuffer,
  IN      UINTN                         BufferSize,
  IN OUT  SECTION_ITEM                  **SectionHead,
  IN OUT  COMMENT_LINE                  **CommentHead
  )
{
  EFI_STATUS                            Status;
  CHAR8                                 *Source;
  CHAR8                                 *CurrentPtr;
  CHAR8                                 *BufferEnd;
  CHAR8                                 *PtrLine;
  UINTN                                 LineLength;
  UINTN                                 SourceLength;
  UINTN                                 MaxLineLength;

  *SectionHead          = NULL;
  *CommentHead          = NULL;
  BufferEnd             = (CHAR8 *) ( (UINTN) DataBuffer + BufferSize);
  CurrentPtr            = (CHAR8 *) DataBuffer;
  MaxLineLength         = MAX_LINE_LENGTH;
  Status                = EFI_SUCCESS;

  PtrLine = AllocatePool (MaxLineLength);
  if (PtrLine == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  while (CurrentPtr < BufferEnd) {
    Source              = CurrentPtr;
    SourceLength        = (UINTN)BufferEnd - (UINTN)CurrentPtr;
    LineLength          = MaxLineLength;
    //
    // With the assumption that line length is less than 512
    // characters. Otherwise BUFFER_TOO_SMALL will be returned.
    //
    Status              = ProfileGetLine (
                            (UINT8 *) Source,
                            SourceLength,
                            (UINT8 *) PtrLine,
                            &LineLength
                            );
    if (EFI_ERROR (Status)) {
      if (Status == EFI_BUFFER_TOO_SMALL) {
        //
        // If buffer too small, re-allocate the buffer according
        // to the returned LineLength and try again.
        //
        FreePool (PtrLine);
        PtrLine         = NULL;
        PtrLine = AllocatePool (LineLength);
        if (PtrLine == NULL) {
          Status        = EFI_OUT_OF_RESOURCES;
          break;
        }
        SourceLength    = LineLength;
        Status          = ProfileGetLine (
                            (UINT8 *) Source,
                            SourceLength,
                            (UINT8 *) PtrLine,
                            &LineLength
                            );
        if (EFI_ERROR (Status)) {
          break;
        }
        MaxLineLength   = LineLength;
      } else {
        break;
      }
    }
    CurrentPtr          = (CHAR8 *) ( (UINTN) CurrentPtr + LineLength);

    //
    // Line got. Trim the line before processing it.
    //
    ProfileTrim (
      (UINT8 *) PtrLine,
      &LineLength
   );

    //
    // Blank line
    //
    if (LineLength == 0) {
      continue;
    }

    if (PtrLine[0] == '#' || PtrLine[0] == ';') {
      Status            = ProfileGetComments (
                            (UINT8 *) PtrLine,
                            LineLength,
                            CommentHead
                            );
    } else if (PtrLine[0] == '[') {
      Status            = ProfileGetSection (
                            (UINT8 *) PtrLine,
                            LineLength,
                            SectionHead
                            );
    } else {
      Status            = ProfileGetEntry (
                            (UINT8 *) PtrLine,
                            LineLength,
                            SectionHead
                            );
    }

    if (EFI_ERROR (Status)) {
      break;
    }
  }

  //
  // Free buffer
  //
  FreePool (PtrLine);

  return Status;
}

/**
  Open an INI config file and return a context.

  @param[in] DataBuffer      Config raw file buffer.
  @param[in] BufferSize      Size of raw buffer.

  @return       Config data buffer is opened and context is returned.
  @retval NULL  No enough memory is allocated.
  @retval NULL  Config data buffer is invalid.
**/
VOID *
EFIAPI
OpenIniFile (
  IN      UINT8                         *DataBuffer,
  IN      UINTN                         BufferSize
  )
{
  EFI_STATUS                            Status;
  INI_PARSING_LIB_CONTEXT               *IniContext;

  if (DataBuffer == NULL || BufferSize == 0) {
    return NULL;
  }

  IniContext = AllocateZeroPool(sizeof(INI_PARSING_LIB_CONTEXT));
  if (IniContext == NULL) {
    return NULL;
  }

  //
  // First process the data buffer and get all sections and entries
  //
  Status = PreProcessDataFile (
             DataBuffer,
             BufferSize,
             &IniContext->SectionHead,
             &IniContext->CommentHead
             );
  if (EFI_ERROR(Status)) {
    FreePool(IniContext);
    return NULL;
  }
  DEBUG_CODE_BEGIN ();
    DumpIniSection(IniContext);
  DEBUG_CODE_END ();
  return IniContext;
}

/**
  Get section entry string value.

  @param[in]  Context         INI Config file context.
  @param[in]  SectionName     Section name.
  @param[in]  EntryName       Section entry name.
  @param[out] EntryValue      Point to the got entry string value.

  @retval EFI_SUCCESS    Section entry string value is got.
  @retval EFI_NOT_FOUND  Section is not found.
**/
EFI_STATUS
EFIAPI
GetStringFromDataFile(
  IN      VOID                          *Context,
  IN      CHAR8                         *SectionName,
  IN      CHAR8                         *EntryName,
  OUT     CHAR8                         **EntryValue
  )
{
  INI_PARSING_LIB_CONTEXT               *IniContext;
  EFI_STATUS                            Status;

  if (Context == NULL || SectionName == NULL || EntryName == NULL || EntryValue == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  IniContext = Context;

  *EntryValue  = NULL;
  Status = UpdateGetProfileString (
             IniContext->SectionHead,
             SectionName,
             EntryName,
             EntryValue
             );
  return Status;
}

/**
  Get section entry GUID value.

  @param[in]  Context         INI Config file context.
  @param[in]  SectionName     Section name.
  @param[in]  EntryName       Section entry name.
  @param[out] Guid            Point to the got GUID value.

  @retval EFI_SUCCESS    Section entry GUID value is got.
  @retval EFI_NOT_FOUND  Section is not found.
**/
EFI_STATUS
EFIAPI
GetGuidFromDataFile (
  IN      VOID                          *Context,
  IN      CHAR8                         *SectionName,
  IN      CHAR8                         *EntryName,
  OUT     EFI_GUID                      *Guid
  )
{
  CHAR8                                 *Value;
  EFI_STATUS                            Status;
  RETURN_STATUS                         RStatus;

  if (Context == NULL || SectionName == NULL || EntryName == NULL || Guid == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = GetStringFromDataFile(
             Context,
             SectionName,
             EntryName,
             &Value
             );
  if (EFI_ERROR(Status)) {
    return EFI_NOT_FOUND;
  }
  ASSERT (Value != NULL);
  RStatus = AsciiStrToGuid (Value, Guid);
  if (RETURN_ERROR (RStatus) || (Value[GUID_STRING_LENGTH] != '\0')) {
    return EFI_NOT_FOUND;
  }
  return EFI_SUCCESS;
}

/**
  Get section entry decimal UINTN value.

  @param[in]  Context         INI Config file context.
  @param[in]  SectionName     Section name.
  @param[in]  EntryName       Section entry name.
  @param[out] Data            Point to the got decimal UINTN value.

  @retval EFI_SUCCESS    Section entry decimal UINTN value is got.
  @retval EFI_NOT_FOUND  Section is not found.
**/
EFI_STATUS
EFIAPI
GetDecimalUintnFromDataFile (
  IN      VOID                          *Context,
  IN      CHAR8                         *SectionName,
  IN      CHAR8                         *EntryName,
  OUT     UINTN                         *Data
  )
{
  CHAR8                                 *Value;
  EFI_STATUS                            Status;

  if (Context == NULL || SectionName == NULL || EntryName == NULL || Data == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = GetStringFromDataFile(
             Context,
             SectionName,
             EntryName,
             &Value
             );
  if (EFI_ERROR(Status)) {
    return EFI_NOT_FOUND;
  }
  ASSERT (Value != NULL);
  if (!IsValidDecimalString(Value, AsciiStrLen(Value))) {
    return EFI_NOT_FOUND;
  }
  *Data = AsciiStrDecimalToUintn(Value);
  return EFI_SUCCESS;
}

/**
  Get section entry heximal UINTN value.

  @param[in]  Context         INI Config file context.
  @param[in]  SectionName     Section name.
  @param[in]  EntryName       Section entry name.
  @param[out] Data            Point to the got heximal UINTN value.

  @retval EFI_SUCCESS    Section entry heximal UINTN value is got.
  @retval EFI_NOT_FOUND  Section is not found.
**/
EFI_STATUS
EFIAPI
GetHexUintnFromDataFile (
  IN      VOID                          *Context,
  IN      CHAR8                         *SectionName,
  IN      CHAR8                         *EntryName,
  OUT     UINTN                         *Data
  )
{
  CHAR8                                 *Value;
  EFI_STATUS                            Status;

  if (Context == NULL || SectionName == NULL || EntryName == NULL || Data == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = GetStringFromDataFile(
             Context,
             SectionName,
             EntryName,
             &Value
             );
  if (EFI_ERROR(Status)) {
    return EFI_NOT_FOUND;
  }
  ASSERT (Value != NULL);
  if (!IsValidHexString(Value, AsciiStrLen(Value))) {
    return EFI_NOT_FOUND;
  }
  *Data = AsciiStrHexToUintn(Value);
  return EFI_SUCCESS;
}

/**
  Get section entry heximal UINT64 value.

  @param[in]  Context         INI Config file context.
  @param[in]  SectionName     Section name.
  @param[in]  EntryName       Section entry name.
  @param[out] Data            Point to the got heximal UINT64 value.

  @retval EFI_SUCCESS    Section entry heximal UINT64 value is got.
  @retval EFI_NOT_FOUND  Section is not found.
**/
EFI_STATUS
EFIAPI
GetHexUint64FromDataFile (
  IN      VOID                          *Context,
  IN      CHAR8                         *SectionName,
  IN      CHAR8                         *EntryName,
  OUT     UINT64                        *Data
  )
{
  CHAR8                                 *Value;
  EFI_STATUS                            Status;

  if (Context == NULL || SectionName == NULL || EntryName == NULL || Data == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = GetStringFromDataFile(
             Context,
             SectionName,
             EntryName,
             &Value
             );
  if (EFI_ERROR(Status)) {
    return EFI_NOT_FOUND;
  }
  ASSERT (Value != NULL);
  if (!IsValidHexString(Value, AsciiStrLen(Value))) {
    return EFI_NOT_FOUND;
  }
  *Data = AsciiStrHexToUint64(Value);
  return EFI_SUCCESS;
}

/**
  Close an INI config file and free the context.

  @param[in] Context         INI Config file context.
**/
VOID
EFIAPI
CloseIniFile (
  IN      VOID                          *Context
  )
{
  INI_PARSING_LIB_CONTEXT               *IniContext;

  if (Context == NULL) {
    return ;
  }

  IniContext = Context;
  FreeAllList(IniContext->SectionHead, IniContext->CommentHead);

  return;
}