summaryrefslogtreecommitdiff
path: root/BaseTools/Source/Python/AutoGen/GenC.py
blob: fafcd70b86cb82f94eaa3a9fa7c65375b2fc0162 (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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
## @file
# Routines for generating AutoGen.h and AutoGen.c
#
# Copyright (c) 2007 - 2012, 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.
#

## Import Modules
#
import string

from Common import EdkLogger

from Common.BuildToolError import *
from Common.DataType import *
from Common.Misc import *
from Common.String import StringToArray
from StrGather import *

## PCD type string
gItemTypeStringDatabase  = {
    TAB_PCDS_FEATURE_FLAG       :   'FixedAtBuild',
    TAB_PCDS_FIXED_AT_BUILD     :   'FixedAtBuild',
    TAB_PCDS_PATCHABLE_IN_MODULE:   'BinaryPatch',
    TAB_PCDS_DYNAMIC            :   '',
    TAB_PCDS_DYNAMIC_DEFAULT    :   '',
    TAB_PCDS_DYNAMIC_VPD        :   '',
    TAB_PCDS_DYNAMIC_HII        :   '',
    TAB_PCDS_DYNAMIC_EX         :   '',
    TAB_PCDS_DYNAMIC_EX_DEFAULT :   '',
    TAB_PCDS_DYNAMIC_EX_VPD     :   '',
    TAB_PCDS_DYNAMIC_EX_HII     :   '',
}

## Dynamic PCD types
gDynamicPcd = [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC_DEFAULT, TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_HII]

## Dynamic-ex PCD types
gDynamicExPcd = [TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX_DEFAULT, TAB_PCDS_DYNAMIC_EX_VPD, TAB_PCDS_DYNAMIC_EX_HII]

## Datum size
gDatumSizeStringDatabase = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOLEAN','VOID*':'8'}
gDatumSizeStringDatabaseH = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOL','VOID*':'PTR'}
gDatumSizeStringDatabaseLib = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'Bool','VOID*':'Ptr'}

## Mapping between PCD driver type and EFI phase
gPcdPhaseMap = {
    "PEI_PCD_DRIVER"    :   "PEI",
    "DXE_PCD_DRIVER"    :   "DXE"
}

gPcdDatabaseCommonAutoGenH = """
//
// The following definition will be generated by build tool
//

//
// Common definitions
//
typedef UINT8 SKU_ID;

#define PCD_TYPE_SHIFT        28

#define PCD_TYPE_DATA         (0x0U << PCD_TYPE_SHIFT)
#define PCD_TYPE_HII          (0x8U << PCD_TYPE_SHIFT)
#define PCD_TYPE_VPD          (0x4U << PCD_TYPE_SHIFT)
#define PCD_TYPE_SKU_ENABLED  (0x2U << PCD_TYPE_SHIFT)
#define PCD_TYPE_STRING       (0x1U << PCD_TYPE_SHIFT)

#define PCD_TYPE_ALL_SET      (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_SKU_ENABLED | PCD_TYPE_STRING)

#define PCD_DATUM_TYPE_SHIFT  24

#define PCD_DATUM_TYPE_POINTER  (0x0U << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT8    (0x1U << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT16   (0x2U << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT32   (0x4U << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT64   (0x8U << PCD_DATUM_TYPE_SHIFT)

#define PCD_DATUM_TYPE_ALL_SET  (PCD_DATUM_TYPE_POINTER | \\
                                 PCD_DATUM_TYPE_UINT8   | \\
                                 PCD_DATUM_TYPE_UINT16  | \\
                                 PCD_DATUM_TYPE_UINT32  | \\
                                 PCD_DATUM_TYPE_UINT64)

#define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET))

typedef struct  {
  UINT32  ExTokenNumber;
  UINT16  LocalTokenNumber;   // PCD Number of this particular platform build
  UINT16  ExGuidIndex;        // Index of GuidTable
} DYNAMICEX_MAPPING;

typedef struct {
  UINT32  SkuDataStartOffset; //We have to use offsetof MACRO as we don't know padding done by compiler
  UINT32  SkuIdTableOffset;   //Offset from the PCD_DB
} SKU_HEAD;

typedef struct {
  UINT32  StringIndex;        // Offset in String Table in units of UINT32.
  UINT32  DefaultValueOffset; // Offset of the Default Value
  UINT16  GuidTableIndex;     // Offset in Guid Table in units of GUID.
  UINT16  Offset;             // Offset in Variable
} VARIABLE_HEAD;

typedef  struct {
  UINT32  Offset;
} VPD_HEAD;

typedef UINT32 STRING_HEAD;

typedef UINT16 SIZE_INFO;

#define offsetof(s,m)  (UINT32) (UINTN) &(((s *)0)->m)

"""

gPcdDatabaseEpilogueAutoGenH = """
typedef struct {
  PEI_PCD_DATABASE PeiDb;
  DXE_PCD_DATABASE DxeDb;
} PCD_DATABASE;

#define PCD_TOTAL_TOKEN_NUMBER (PEI_LOCAL_TOKEN_NUMBER + DXE_LOCAL_TOKEN_NUMBER)

"""

gPcdDatabaseAutoGenH = TemplateString("""
#define ${PHASE}_GUID_TABLE_SIZE                ${GUID_TABLE_SIZE}
#define ${PHASE}_STRING_TABLE_SIZE              ${STRING_TABLE_SIZE}
#define ${PHASE}_SKUID_TABLE_SIZE               ${SKUID_TABLE_SIZE}
#define ${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE  ${LOCAL_TOKEN_NUMBER_TABLE_SIZE}
#define ${PHASE}_LOCAL_TOKEN_NUMBER             ${LOCAL_TOKEN_NUMBER}
#define ${PHASE}_EXMAPPING_TABLE_SIZE           ${EXMAPPING_TABLE_SIZE}
#define ${PHASE}_EX_TOKEN_NUMBER                ${EX_TOKEN_NUMBER}
#define ${PHASE}_SIZE_TABLE_SIZE                ${SIZE_TABLE_SIZE}
#define ${PHASE}_GUID_TABLE_EMPTY               ${GUID_TABLE_EMPTY}
#define ${PHASE}_STRING_TABLE_EMPTY             ${STRING_TABLE_EMPTY}
#define ${PHASE}_SKUID_TABLE_EMPTY              ${SKUID_TABLE_EMPTY}
#define ${PHASE}_DATABASE_EMPTY                 ${DATABASE_EMPTY}
#define ${PHASE}_EXMAP_TABLE_EMPTY              ${EXMAP_TABLE_EMPTY}

typedef struct {
${BEGIN}  UINT64             ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}];
${END}
${BEGIN}  UINT64             ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64};
${END}
${BEGIN}  UINT32             ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}];
${END}
${BEGIN}  UINT32             ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32};
${END}
${BEGIN}  VPD_HEAD           ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}];
${END}
  DYNAMICEX_MAPPING  ExMapTable[${PHASE}_EXMAPPING_TABLE_SIZE];
  UINT32             LocalTokenNumberTable[${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE];
  GUID               GuidTable[${PHASE}_GUID_TABLE_SIZE];
${BEGIN}  STRING_HEAD        ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}];
${END}
${BEGIN}  VARIABLE_HEAD      ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}];
${END}
${BEGIN}  UINT8              StringTable${STRING_TABLE_INDEX}[${STRING_TABLE_LENGTH}]; /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
${END}
  SIZE_INFO          SizeTable[${PHASE}_SIZE_TABLE_SIZE];
${BEGIN}  UINT16             ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}];
${END}
${BEGIN}  UINT16             ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16};
${END}
${BEGIN}  UINT8              ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}];
${END}
${BEGIN}  UINT8              ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8};
${END}
${BEGIN}  BOOLEAN            ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}];
${END}
${BEGIN}  BOOLEAN            ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN};
${END}
  UINT8              SkuIdTable[${PHASE}_SKUID_TABLE_SIZE];
${SYSTEM_SKU_ID}
} ${PHASE}_PCD_DATABASE_INIT;

typedef struct {
${PCD_DATABASE_UNINIT_EMPTY}
${BEGIN}  UINT64   ${UNINIT_CNAME_DECL_UINT64}_${UNINIT_GUID_DECL_UINT64}[${UNINIT_NUMSKUS_DECL_UINT64}];
${END}
${BEGIN}  UINT32   ${UNINIT_CNAME_DECL_UINT32}_${UNINIT_GUID_DECL_UINT32}[${UNINIT_NUMSKUS_DECL_UINT32}];
${END}
${BEGIN}  UINT16   ${UNINIT_CNAME_DECL_UINT16}_${UNINIT_GUID_DECL_UINT16}[${UNINIT_NUMSKUS_DECL_UINT16}];
${END}
${BEGIN}  UINT8    ${UNINIT_CNAME_DECL_UINT8}_${UNINIT_GUID_DECL_UINT8}[${UNINIT_NUMSKUS_DECL_UINT8}];
${END}
${BEGIN}  BOOLEAN  ${UNINIT_CNAME_DECL_BOOLEAN}_${UNINIT_GUID_DECL_BOOLEAN}[${UNINIT_NUMSKUS_DECL_BOOLEAN}];
${END}
} ${PHASE}_PCD_DATABASE_UNINIT;

#define PCD_${PHASE}_SERVICE_DRIVER_VERSION         2

typedef struct {
  ${PHASE}_PCD_DATABASE_INIT    Init;
  ${PHASE}_PCD_DATABASE_UNINIT  Uninit;
} ${PHASE}_PCD_DATABASE;

#define ${PHASE}_NEX_TOKEN_NUMBER (${PHASE}_LOCAL_TOKEN_NUMBER - ${PHASE}_EX_TOKEN_NUMBER)
""")

gEmptyPcdDatabaseAutoGenC = TemplateString("""
${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
  /* ExMapTable */
  {
    {0, 0, 0}
  },
  /* LocalTokenNumberTable */
  {
    0
  },
  /* GuidTable */
  {
    {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}
  },
  /* StringTable */
  { 0 },
  /* SizeTable */
  {
    0, 0
  },
  /* SkuIdTable */
  { 0 },
  ${SYSTEM_SKU_ID_VALUE}
};
""")

gPcdDatabaseAutoGenC = TemplateString("""
${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
${BEGIN}  { ${INIT_VALUE_UINT64} }, /*  ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT64}, /* ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64} */
${END}
${BEGIN}  { ${INIT_VALUE_UINT32} }, /*  ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT32}, /* ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32} */
${END}
  /* VPD */
${BEGIN}  { ${VPD_HEAD_VALUE} }, /* ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}] */
${END}
  /* ExMapTable */
  {
${BEGIN}    { ${EXMAPPING_TABLE_EXTOKEN}, ${EXMAPPING_TABLE_LOCAL_TOKEN}, ${EXMAPPING_TABLE_GUID_INDEX} },
${END}
  },
  /* LocalTokenNumberTable */
  {
${BEGIN}    offsetof(${PHASE}_PCD_DATABASE, ${TOKEN_INIT}.${TOKEN_CNAME}_${TOKEN_GUID}${VARDEF_HEADER}) | ${TOKEN_TYPE},
${END}
  },
  /* GuidTable */
  {
${BEGIN}    ${GUID_STRUCTURE},
${END}
  },
${BEGIN}  { ${STRING_HEAD_VALUE} }, /* ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}] */
${END}
${BEGIN}  /* ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}] */
  {
    ${VARIABLE_HEAD_VALUE}
  },
${END}
 /* StringTable */
${BEGIN}  ${STRING_TABLE_VALUE}, /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
${END}
  /* SizeTable */
  {
${BEGIN}    ${SIZE_TABLE_MAXIMUM_LENGTH}, ${SIZE_TABLE_CURRENT_LENGTH}, /* ${SIZE_TABLE_CNAME}_${SIZE_TABLE_GUID} */
${END}
  },
${BEGIN}  { ${INIT_VALUE_UINT16} }, /*  ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT16}, /* ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16} */
${END}
${BEGIN}  { ${INIT_VALUE_UINT8} }, /*  ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT8}, /* ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8} */
${END}
${BEGIN}  { ${INIT_VALUE_BOOLEAN} }, /*  ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}] */
${END}
${BEGIN}  ${VARDEF_VALUE_BOOLEAN}, /* ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN} */
${END}
  /* SkuIdTable */
  { ${BEGIN}${SKUID_VALUE}, ${END} },
  ${SYSTEM_SKU_ID_VALUE}
};
""")


## AutoGen File Header Templates
gAutoGenHeaderString = TemplateString("""\
/**
  DO NOT EDIT
  FILE auto-generated
  Module name:
    ${FileName}
  Abstract:       Auto-generated ${FileName} for building module or library.
**/
""")

gAutoGenHPrologueString = TemplateString("""
#ifndef _${File}_${Guid}
#define _${File}_${Guid}

""")

gAutoGenHCppPrologueString = """\
#ifdef __cplusplus
extern "C" {
#endif

"""

gAutoGenHEpilogueString = """

#ifdef __cplusplus
}
#endif

#endif
"""

## PEI Core Entry Point Templates
gPeiCoreEntryPointPrototype = TemplateString("""
${BEGIN}
VOID
EFIAPI
${Function} (
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList,
  IN VOID                           *Context
  );
${END}
""")

gPeiCoreEntryPointString = TemplateString("""
${BEGIN}
VOID
EFIAPI
ProcessModuleEntryPointList (
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList,
  IN VOID                           *Context
  )

{
  ${Function} (SecCoreData, PpiList, Context);
}
${END}
""")


## DXE Core Entry Point Templates
gDxeCoreEntryPointPrototype = TemplateString("""
${BEGIN}
VOID
EFIAPI
${Function} (
  IN VOID  *HobStart
  );
${END}
""")

gDxeCoreEntryPointString = TemplateString("""
${BEGIN}
VOID
EFIAPI
ProcessModuleEntryPointList (
  IN VOID  *HobStart
  )

{
  ${Function} (HobStart);
}
${END}
""")

## PEIM Entry Point Templates
gPeimEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  );
${END}
""")

gPeimEntryPointString = [
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )

{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )

{
  return ${Function} (FileHandle, PeiServices);
}
${END}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )

{
  EFI_STATUS  Status;
  EFI_STATUS  CombinedStatus;

  CombinedStatus = EFI_LOAD_ERROR;
${BEGIN}
  Status = ${Function} (FileHandle, PeiServices);
  if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {
    CombinedStatus = Status;
  }
${END}
  return CombinedStatus;
}
""")
]

## SMM_CORE Entry Point Templates
gSmmCoreEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE   *SystemTable
  );
${END}
""")

gSmmCoreEntryPointString = TemplateString("""
${BEGIN}
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE   *SystemTable
  )
{
  return ${Function} (ImageHandle, SystemTable);
}
${END}
""")

## DXE SMM Entry Point Templates
gDxeSmmEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );
${END}
""")

gDxeSmmEntryPointString = [
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
static EFI_STATUS  mDriverEntryPointStatus;

VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
    mDriverEntryPointStatus = Status;
  }
  LongJump (&mJumpContext, (UINTN)-1);
  ASSERT (FALSE);
}

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  mDriverEntryPointStatus = EFI_LOAD_ERROR;

${BEGIN}
  if (SetJump (&mJumpContext) == 0) {
    ExitDriver (${Function} (ImageHandle, SystemTable));
    ASSERT (FALSE);
  }
${END}

  return mDriverEntryPointStatus;
}
""")
]

## UEFI Driver Entry Point Templates
gUefiDriverEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );
${END}
""")

gUefiDriverEntryPointString = [
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  return ${Function} (ImageHandle, SystemTable);
}
${END}
VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (EFI_ERROR (Status)) {
    ProcessLibraryDestructorList (gImageHandle, gST);
  }
  gBS->Exit (gImageHandle, Status, 0, NULL);
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
static EFI_STATUS  mDriverEntryPointStatus;

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  mDriverEntryPointStatus = EFI_LOAD_ERROR;
  ${BEGIN}
  if (SetJump (&mJumpContext) == 0) {
    ExitDriver (${Function} (ImageHandle, SystemTable));
    ASSERT (FALSE);
  }
  ${END}
  return mDriverEntryPointStatus;
}

VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
    mDriverEntryPointStatus = Status;
  }
  LongJump (&mJumpContext, (UINTN)-1);
  ASSERT (FALSE);
}
""")
]


## UEFI Application Entry Point Templates
gUefiApplicationEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );
${END}
""")

gUefiApplicationEntryPointString = [
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};

${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  return ${Function} (ImageHandle, SystemTable);
}
${END}
VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (EFI_ERROR (Status)) {
    ProcessLibraryDestructorList (gImageHandle, gST);
  }
  gBS->Exit (gImageHandle, Status, 0, NULL);
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  ${BEGIN}
  if (SetJump (&mJumpContext) == 0) {
    ExitDriver (${Function} (ImageHandle, SystemTable));
    ASSERT (FALSE);
  }
  ${END}
  return mDriverEntryPointStatus;
}

static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
static EFI_STATUS  mDriverEntryPointStatus = EFI_LOAD_ERROR;

VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
    mDriverEntryPointStatus = Status;
  }
  LongJump (&mJumpContext, (UINTN)-1);
  ASSERT (FALSE);
}
""")
]

## UEFI Unload Image Templates
gUefiUnloadImagePrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle
  );
${END}
""")

gUefiUnloadImageString = [
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};

EFI_STATUS
EFIAPI
ProcessModuleUnloadList (
  IN EFI_HANDLE        ImageHandle
  )
{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};

${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleUnloadList (
  IN EFI_HANDLE        ImageHandle
  )
{
  return ${Function} (ImageHandle);
}
${END}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};

EFI_STATUS
EFIAPI
ProcessModuleUnloadList (
  IN EFI_HANDLE        ImageHandle
  )
{
  EFI_STATUS  Status;

  Status = EFI_SUCCESS;
${BEGIN}
  if (EFI_ERROR (Status)) {
    ${Function} (ImageHandle);
  } else {
    Status = ${Function} (ImageHandle);
  }
${END}
  return Status;
}
""")
]

gLibraryStructorPrototype = {
'BASE'  : TemplateString("""${BEGIN}
RETURN_STATUS
EFIAPI
${Function} (
  VOID
  );${END}
"""),

'PEI'   : TemplateString("""${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN       EFI_PEI_FILE_HANDLE       FileHandle,
  IN CONST EFI_PEI_SERVICES          **PeiServices
  );${END}
"""),

'DXE'   : TemplateString("""${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );${END}
"""),
}

gLibraryStructorCall = {
'BASE'  : TemplateString("""${BEGIN}
  Status = ${Function} ();
  ASSERT_EFI_ERROR (Status);${END}
"""),

'PEI'   : TemplateString("""${BEGIN}
  Status = ${Function} (FileHandle, PeiServices);
  ASSERT_EFI_ERROR (Status);${END}
"""),

'DXE'   : TemplateString("""${BEGIN}
  Status = ${Function} (ImageHandle, SystemTable);
  ASSERT_EFI_ERROR (Status);${END}
"""),
}

## Library Constructor and Destructor Templates
gLibraryString = {
'BASE'  :   TemplateString("""
${BEGIN}${FunctionPrototype}${END}

VOID
EFIAPI
ProcessLibrary${Type}List (
  VOID
  )
{
${BEGIN}  EFI_STATUS  Status;
${FunctionCall}${END}
}
"""),

'PEI'   :   TemplateString("""
${BEGIN}${FunctionPrototype}${END}

VOID
EFIAPI
ProcessLibrary${Type}List (
  IN       EFI_PEI_FILE_HANDLE       FileHandle,
  IN CONST EFI_PEI_SERVICES          **PeiServices
  )
{
${BEGIN}  EFI_STATUS  Status;
${FunctionCall}${END}
}
"""),

'DXE'   :   TemplateString("""
${BEGIN}${FunctionPrototype}${END}

VOID
EFIAPI
ProcessLibrary${Type}List (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
${BEGIN}  EFI_STATUS  Status;
${FunctionCall}${END}
}
"""),
}

gBasicHeaderFile = "Base.h"

gModuleTypeHeaderFile = {
    "BASE"              :   [gBasicHeaderFile],
    "SEC"               :   ["PiPei.h", "Library/DebugLib.h"],
    "PEI_CORE"          :   ["PiPei.h", "Library/DebugLib.h", "Library/PeiCoreEntryPoint.h"],
    "PEIM"              :   ["PiPei.h", "Library/DebugLib.h", "Library/PeimEntryPoint.h"],
    "DXE_CORE"          :   ["PiDxe.h", "Library/DebugLib.h", "Library/DxeCoreEntryPoint.h"],
    "DXE_DRIVER"        :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "DXE_SMM_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "DXE_RUNTIME_DRIVER":   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "DXE_SAL_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "UEFI_DRIVER"       :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "UEFI_APPLICATION"  :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiApplicationEntryPoint.h"],
    "SMM_CORE"          :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiDriverEntryPoint.h"],
    "USER_DEFINED"      :   [gBasicHeaderFile]
}

## Create code for module PCDs
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      Pcd         The PCD object
#
def CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd):
    TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue   #Info.GuidList[Pcd.TokenSpaceGuidCName]
    PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
    #
    # Write PCDs
    #
    PcdTokenName = '_PCD_TOKEN_' + Pcd.TokenCName
    if Pcd.Type in gDynamicExPcd:
        TokenNumber = int(Pcd.TokenValue, 0)
    else:
        if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
            EdkLogger.error("build", AUTOGEN_ERROR,
                            "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                            ExtraData="[%s]" % str(Info))
        TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
    AutoGenH.Append('\n#define %s  %dU\n' % (PcdTokenName, TokenNumber))

    EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for " + Pcd.TokenCName + "." + Pcd.TokenSpaceGuidCName)
    if Pcd.Type not in gItemTypeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))
    if Pcd.DatumType not in gDatumSizeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))

    DatumSize = gDatumSizeStringDatabase[Pcd.DatumType]
    DatumSizeLib = gDatumSizeStringDatabaseLib[Pcd.DatumType]
    GetModeName = '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + Pcd.TokenCName
    SetModeName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + Pcd.TokenCName

    if Pcd.Type in gDynamicExPcd:
        AutoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
        if Pcd.DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
    elif Pcd.Type in gDynamicPcd:
        AutoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
        if Pcd.DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
    else:
        PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + Pcd.TokenCName
        Const = 'const'
        if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            Const = ''
        Type = ''
        Array = ''
        Value = Pcd.DefaultValue
        Unicode = False
        ValueNumber = 0

        if Pcd.DatumType == 'BOOLEAN':
            BoolValue = Value.upper()
            if BoolValue == 'TRUE' or BoolValue == '1':
                Value = '1U'
            elif BoolValue == 'FALSE' or BoolValue == '0':
                Value = '0U'

        if Pcd.DatumType in ['UINT64', 'UINT32', 'UINT16', 'UINT8']:
            try:
                if Value.upper().startswith('0X'):
                    ValueNumber = int (Value, 16)
                else:
                    ValueNumber = int (Value)
            except:
                EdkLogger.error("build", AUTOGEN_ERROR,
                                "PCD value is not valid dec or hex number for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                ExtraData="[%s]" % str(Info))
            if Pcd.DatumType == 'UINT64':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x10000000000000000:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                if not Value.endswith('ULL'):
                    Value += 'ULL'
            elif Pcd.DatumType == 'UINT32':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x100000000:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                if not Value.endswith('U'):
                    Value += 'U'
            elif Pcd.DatumType == 'UINT16':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x10000:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                if not Value.endswith('U'):
                    Value += 'U'                    
            elif Pcd.DatumType == 'UINT8':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x100:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                if not Value.endswith('U'):
                    Value += 'U'
        if Pcd.DatumType == 'VOID*':
            if Pcd.MaxDatumSize == None or Pcd.MaxDatumSize == '':
                EdkLogger.error("build", AUTOGEN_ERROR,
                                "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                ExtraData="[%s]" % str(Info))

            ArraySize = int(Pcd.MaxDatumSize, 0)
            if Value[0] == '{':
                Type = '(VOID *)'
            else:
                if Value[0] == 'L':
                    Unicode = True
                Value = Value.lstrip('L')   #.strip('"')
                Value = eval(Value)         # translate escape character
                NewValue = '{'
                for Index in range(0,len(Value)):
                    if Unicode:
                        NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ', '
                    else:
                        NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
                if Unicode:
                    ArraySize = ArraySize / 2;

                if ArraySize < (len(Value) + 1):
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                Value = NewValue + '0 }'
            Array = '[%d]' % ArraySize
        #
        # skip casting for fixed at build since it breaks ARM assembly.
        # Long term we need PCD macros that work in assembly
        #
        elif Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:
            Value = "((%s)%s)" % (Pcd.DatumType, Value)

        if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            PcdValueName = '_PCD_PATCHABLE_VALUE_' + Pcd.TokenCName
        else:
            PcdValueName = '_PCD_VALUE_' + Pcd.TokenCName
            
        if Pcd.DatumType == 'VOID*':
            #
            # For unicode, UINT16 array will be generated, so the alignment of unicode is guaranteed.
            #
            if Unicode:
                AutoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (Pcd.TokenCName, Pcd.MaxDatumSize))
                AutoGenH.Append('#define %s  %s%s\n' %(PcdValueName, Type, PcdVariableName))
                AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT16 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
                AutoGenH.Append('extern %s UINT16 %s%s;\n' %(Const, PcdVariableName, Array))
                AutoGenH.Append('#define %s  %s%s\n' %(GetModeName, Type, PcdVariableName))
            else:
                AutoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (Pcd.TokenCName, Pcd.MaxDatumSize))
                AutoGenH.Append('#define %s  %s%s\n' %(PcdValueName, Type, PcdVariableName))
                AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
                AutoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
                AutoGenH.Append('#define %s  %s%s\n' %(GetModeName, Type, PcdVariableName))
        elif Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            AutoGenH.Append('#define %s  %s\n' %(PcdValueName, Value))
            AutoGenC.Append('volatile %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
            AutoGenH.Append('extern volatile %s  %s  %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
            AutoGenH.Append('#define %s  %s%s\n' % (GetModeName, Type, PcdVariableName))
        else:
            AutoGenH.Append('#define %s  %s\n' %(PcdValueName, Value))
            AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
            AutoGenH.Append('extern %s  %s  %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
            AutoGenH.Append('#define %s  %s%s\n' % (GetModeName, Type, PcdVariableName))

        if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            if Pcd.DatumType == 'VOID*':
                AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPatchPcdSetPtr(_gPcd_BinaryPatch_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeName, Pcd.TokenCName, Pcd.TokenCName))
            else:
                AutoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (SetModeName, PcdVariableName))
        else:
            AutoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)

## Create code for library module PCDs
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      Pcd         The PCD object
#
def CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd):
    PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
    TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
    TokenCName  = Pcd.TokenCName
    TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue   #Info.GuidList[TokenSpaceGuidCName]
    if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))
    TokenNumber = PcdTokenNumber[TokenCName, TokenSpaceGuidCName]

    # If PCD is DynamicEx, then use TokenNumber declared in DEC file
    if Pcd.Type in gDynamicExPcd:
        TokenNumber = int(Pcd.TokenValue, 0)

    if Pcd.Type not in gItemTypeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))
    if Pcd.DatumType not in gDatumSizeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))

    DatumType   = Pcd.DatumType
    DatumSize   = gDatumSizeStringDatabaseH[DatumType]
    DatumSizeLib= gDatumSizeStringDatabaseLib[DatumType]
    GetModeName = '_PCD_GET_MODE_' + DatumSize + '_' + TokenCName
    SetModeName = '_PCD_SET_MODE_' + DatumSize + '_' + TokenCName

    Type = ''
    Array = ''
    if Pcd.DatumType == 'VOID*':
        Type = '(VOID *)'
        Array = '[]'

    AutoGenH.Append('#define _PCD_TOKEN_%s  %dU\n' % (TokenCName, TokenNumber))

    PcdItemType = Pcd.Type
    #if PcdItemType in gDynamicPcd:
    #    PcdItemType = TAB_PCDS_FIXED_AT_BUILD
    #    if (TokenCName, TokenSpaceGuidCName) in Info.PlatformInfo.Platform.Pcds:
    #        PcdItemType  = Info.PlatformInfo.Platform.Pcds[TokenCName, TokenSpaceGuidCName].Type
    if PcdItemType in gDynamicExPcd:
        PcdTokenName = '_PCD_TOKEN_' + TokenCName
        AutoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
        if DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName,DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
    if PcdItemType in gDynamicPcd:
        PcdTokenName = '_PCD_TOKEN_' + TokenCName
        AutoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
        if DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
    if PcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
        PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + TokenCName
        AutoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(DatumType, TokenCName, Array) )
        AutoGenH.Append('#define %s  %s_gPcd_BinaryPatch_%s\n' %(GetModeName, Type, TokenCName))
        AutoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (SetModeName, PcdVariableName))
    if PcdItemType == TAB_PCDS_FIXED_AT_BUILD or PcdItemType == TAB_PCDS_FEATURE_FLAG:
        AutoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(DatumType, TokenCName, Array))
        #AutoGenH.Append('#define _PCD_VALUE_%s  _gPcd_FixedAtBuild_%s\n' %(TokenCName, TokenCName))
        AutoGenH.Append('#define %s  %s_gPcd_FixedAtBuild_%s\n' %(GetModeName, Type, TokenCName))
        AutoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)

## Create code for PCD database in DXE or PEI phase
#
#   @param      Platform    The platform object
#   @retval     tuple       Two TemplateString objects for C code and header file,
#                           respectively
#
def CreatePcdDatabasePhaseSpecificAutoGen (Platform, Phase):
    AutoGenC = TemplateString()
    AutoGenH = TemplateString()

    Dict = {
        'PHASE'                         : Phase,
        'GUID_TABLE_SIZE'               : '1U',
        'STRING_TABLE_SIZE'             : '1U',
        'SKUID_TABLE_SIZE'              : '1U',
        'LOCAL_TOKEN_NUMBER_TABLE_SIZE' : '1U',
        'LOCAL_TOKEN_NUMBER'            : '0U',
        'EXMAPPING_TABLE_SIZE'          : '1U',
        'EX_TOKEN_NUMBER'               : '0U',
        'SIZE_TABLE_SIZE'               : '2U',
        'GUID_TABLE_EMPTY'              : 'TRUE',
        'STRING_TABLE_EMPTY'            : 'TRUE',
        'SKUID_TABLE_EMPTY'             : 'TRUE',
        'DATABASE_EMPTY'                : 'TRUE',
        'EXMAP_TABLE_EMPTY'             : 'TRUE',
        'PCD_DATABASE_UNINIT_EMPTY'     : '  UINT8  dummy; /* PCD_DATABASE_UNINIT is emptry */',
        'SYSTEM_SKU_ID'                 : '  SKU_ID             SystemSkuId;',
        'SYSTEM_SKU_ID_VALUE'           : '0U'
    }

    for DatumType in ['UINT64','UINT32','UINT16','UINT8','BOOLEAN', "VOID*"]:
        Dict['VARDEF_CNAME_' + DatumType] = []
        Dict['VARDEF_GUID_' + DatumType]  = []
        Dict['VARDEF_SKUID_' + DatumType] = []
        Dict['VARDEF_VALUE_' + DatumType] = []
        for Init in ['INIT','UNINIT']:
            Dict[Init+'_CNAME_DECL_' + DatumType]   = []
            Dict[Init+'_GUID_DECL_' + DatumType]    = []
            Dict[Init+'_NUMSKUS_DECL_' + DatumType] = []
            Dict[Init+'_VALUE_' + DatumType]        = []

    for Type in ['STRING_HEAD','VPD_HEAD','VARIABLE_HEAD']:
        Dict[Type + '_CNAME_DECL']   = []
        Dict[Type + '_GUID_DECL']    = []
        Dict[Type + '_NUMSKUS_DECL'] = []
        Dict[Type + '_VALUE'] = []

    Dict['STRING_TABLE_INDEX'] = []
    Dict['STRING_TABLE_LENGTH']  = []
    Dict['STRING_TABLE_CNAME'] = []
    Dict['STRING_TABLE_GUID']  = []
    Dict['STRING_TABLE_VALUE'] = []

    Dict['SIZE_TABLE_CNAME'] = []
    Dict['SIZE_TABLE_GUID']  = []
    Dict['SIZE_TABLE_CURRENT_LENGTH']  = []
    Dict['SIZE_TABLE_MAXIMUM_LENGTH']  = []

    Dict['EXMAPPING_TABLE_EXTOKEN'] = []
    Dict['EXMAPPING_TABLE_LOCAL_TOKEN'] = []
    Dict['EXMAPPING_TABLE_GUID_INDEX'] = []

    Dict['GUID_STRUCTURE'] = []

    Dict['SKUID_VALUE'] = []
    Dict['VARDEF_HEADER'] = []
    if Phase == 'DXE':
        Dict['SYSTEM_SKU_ID'] = ''
        Dict['SYSTEM_SKU_ID_VALUE'] = ''

    StringTableIndex = 0
    StringTableSize = 0
    NumberOfLocalTokens = 0
    NumberOfPeiLocalTokens = 0
    NumberOfDxeLocalTokens = 0
    NumberOfExTokens = 0
    NumberOfSizeItems = 0
    GuidList = []
    
    for Pcd in Platform.DynamicPcdList:
        CName = Pcd.TokenCName
        TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName

        EdkLogger.debug(EdkLogger.DEBUG_3, "PCD: %s %s (%s : %s)" % (CName, TokenSpaceGuidCName, Pcd.Phase, Phase))
        if Pcd.DatumType not in gDatumSizeStringDatabase:
            EdkLogger.error("build", AUTOGEN_ERROR,
                            "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                            ExtraData="[%s]" % str(Platform))

        if Pcd.Phase == 'PEI':
            NumberOfPeiLocalTokens += 1
        if Pcd.Phase == 'DXE':
            NumberOfDxeLocalTokens += 1
        if Pcd.Phase != Phase:
            continue

        #
        # TODO: need GetGuidValue() definition
        #
        TokenSpaceGuidStructure = Pcd.TokenSpaceGuidValue
        TokenSpaceGuid = GuidStructureStringToGuidValueName(TokenSpaceGuidStructure)
        if Pcd.Type in gDynamicExPcd:
            if TokenSpaceGuid not in GuidList:
                GuidList += [TokenSpaceGuid]
                Dict['GUID_STRUCTURE'].append(TokenSpaceGuidStructure)
            NumberOfExTokens += 1

        ValueList = []
        StringHeadOffsetList = []
        VpdHeadOffsetList = []
        VariableHeadValueList = []
        Pcd.InitString = 'UNINIT'

        if Pcd.DatumType == 'VOID*':
            if Pcd.Type not in ["DynamicVpd", "DynamicExVpd"]:
                Pcd.TokenTypeList = ['PCD_TYPE_STRING']
            else:
                Pcd.TokenTypeList = []
        elif Pcd.DatumType == 'BOOLEAN':
            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_UINT8']
        else:
            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_' + Pcd.DatumType]

        if len(Pcd.SkuInfoList) > 1:
            Pcd.TokenTypeList += ['PCD_TYPE_SKU_ENABLED']

        for SkuName in Pcd.SkuInfoList:
            Sku = Pcd.SkuInfoList[SkuName]
            SkuId = Sku.SkuId
            if SkuId == None or SkuId == '':
                continue

            if (SkuId + 'U') not in Dict['SKUID_VALUE']:
                Dict['SKUID_VALUE'].append(SkuId + 'U')

            SkuIdIndex =   Dict['SKUID_VALUE'].index(SkuId + 'U')
            if len(Sku.VariableName) > 0:
                Pcd.TokenTypeList += ['PCD_TYPE_HII']
                Pcd.InitString = 'INIT'
                VariableNameStructure = StringToArray(Sku.VariableName)
                if VariableNameStructure not in Dict['STRING_TABLE_VALUE']:
                    Dict['STRING_TABLE_CNAME'].append(CName)
                    Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
                    if StringTableIndex == 0:
                        Dict['STRING_TABLE_INDEX'].append('')
                    else:
                        Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)

                    Dict['STRING_TABLE_LENGTH'].append((len(Sku.VariableName) - 3 + 1) * 2)
                    Dict['STRING_TABLE_VALUE'].append(VariableNameStructure)
                    StringTableIndex += 1
                    StringTableSize += (len(Sku.VariableName) - 3 + 1) * 2

                VariableHeadStringIndex = 0
                for Index in range(Dict['STRING_TABLE_VALUE'].index(VariableNameStructure)):
                    VariableHeadStringIndex += Dict['STRING_TABLE_LENGTH'][Index]

                VariableGuidStructure = Sku.VariableGuidValue
                VariableGuid = GuidStructureStringToGuidValueName(VariableGuidStructure)
                if VariableGuid not in GuidList:
                    GuidList += [VariableGuid]
                    Dict['GUID_STRUCTURE'].append(VariableGuidStructure)
                VariableHeadGuidIndex = GuidList.index(VariableGuid)

                if "PCD_TYPE_STRING" in Pcd.TokenTypeList:
                    VariableHeadValueList.append('%dU, offsetof(%s_PCD_DATABASE, Init.%s_%s), %dU, %sU' %
                                                 (VariableHeadStringIndex, Phase, CName, TokenSpaceGuid, 
												 VariableHeadGuidIndex, Sku.VariableOffset))
                else:
                    VariableHeadValueList.append('%dU, offsetof(%s_PCD_DATABASE, Init.%s_%s_VariableDefault_%s), %dU, %sU' %
                                                 (VariableHeadStringIndex, Phase, CName, TokenSpaceGuid, SkuIdIndex, 
												 VariableHeadGuidIndex, Sku.VariableOffset))
                Dict['VARDEF_CNAME_'+Pcd.DatumType].append(CName)
                Dict['VARDEF_GUID_'+Pcd.DatumType].append(TokenSpaceGuid)
                Dict['VARDEF_SKUID_'+Pcd.DatumType].append(SkuIdIndex)
                if "PCD_TYPE_STRING" in  Pcd.TokenTypeList:
                    Dict['VARDEF_VALUE_' + Pcd.DatumType].append("%s_%s[%d]" % (Pcd.TokenCName, TokenSpaceGuid, SkuIdIndex))
                else:
                    #
                    # ULL (for UINT64) or U(other integer type) should be append to avoid
                    # warning under linux building environment.
                    #
                    if Pcd.DatumType == "UINT64":
                        Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue + "ULL")
                    elif Pcd.DatumType in ("UINT32", "UINT16", "UINT8"):
                        Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue + "U")
                    elif Pcd.DatumType == "BOOLEAN":
                        if Sku.HiiDefaultValue in ["1", "0"]:
                            Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue + "U")
                    else:
                        Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue)

            elif Sku.VpdOffset != '':
                Pcd.TokenTypeList += ['PCD_TYPE_VPD']
                Pcd.InitString = 'INIT'
                VpdHeadOffsetList.append(str(Sku.VpdOffset) + 'U')
                continue
          
            if Pcd.DatumType == 'VOID*':
                Pcd.TokenTypeList += ['PCD_TYPE_STRING']
                Pcd.InitString = 'INIT'
                if Sku.HiiDefaultValue != '' and Sku.DefaultValue == '':
                    Sku.DefaultValue = Sku.HiiDefaultValue
                if Sku.DefaultValue != '':
                    NumberOfSizeItems += 1
                    Dict['STRING_TABLE_CNAME'].append(CName)
                    Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)

                    if StringTableIndex == 0:
                        Dict['STRING_TABLE_INDEX'].append('')
                    else:
                        Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
                    if Sku.DefaultValue[0] == 'L':
                        Size = (len(Sku.DefaultValue) - 3 + 1) * 2
                        Dict['STRING_TABLE_VALUE'].append(StringToArray(Sku.DefaultValue))
                    elif Sku.DefaultValue[0] == '"':
                        Size = len(Sku.DefaultValue) - 2 + 1
                        Dict['STRING_TABLE_VALUE'].append(StringToArray(Sku.DefaultValue))
                    elif Sku.DefaultValue[0] == '{':
                        Size = len(Sku.DefaultValue.replace(',',' ').split())
                        Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)

                    StringHeadOffsetList.append(str(StringTableSize) + 'U')
                    Dict['SIZE_TABLE_CNAME'].append(CName)
                    Dict['SIZE_TABLE_GUID'].append(TokenSpaceGuid)
                    Dict['SIZE_TABLE_CURRENT_LENGTH'].append(str(Size) + 'U')
                    Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(str(Pcd.MaxDatumSize) + 'U')
                    if Pcd.MaxDatumSize != '':
                        MaxDatumSize = int(Pcd.MaxDatumSize, 0)
                        if MaxDatumSize < Size:
                            EdkLogger.error("build", AUTOGEN_ERROR,
                                            "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                            ExtraData="[%s]" % str(Platform))
                        Size = MaxDatumSize
                    Dict['STRING_TABLE_LENGTH'].append(Size)
                    StringTableIndex += 1
                    StringTableSize += (Size)
            else:
                if "PCD_TYPE_HII" not in Pcd.TokenTypeList:
                    Pcd.TokenTypeList += ['PCD_TYPE_DATA']
                    if Sku.DefaultValue == 'TRUE':
                        Pcd.InitString = 'INIT'
                    else:
                        try:
                            if int(Sku.DefaultValue, 0) != 0:
                                Pcd.InitString = 'INIT'
                        except:
                            pass
                
                #
                # For UNIT64 type PCD's value, ULL should be append to avoid
                # warning under linux building environment.
                #
                if Pcd.DatumType == "UINT64":
                    ValueList.append(Sku.DefaultValue + "ULL")
                elif Pcd.DatumType in ("UINT32", "UINT16", "UINT8"):
                    ValueList.append(Sku.DefaultValue + "U")
                elif Pcd.DatumType == "BOOLEAN":
                    if Sku.DefaultValue in ["1", "0"]:
                        ValueList.append(Sku.DefaultValue + "U")              
                else:
                    ValueList.append(Sku.DefaultValue)

        Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
        

        if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
            Dict['VARIABLE_HEAD_CNAME_DECL'].append(CName)
            Dict['VARIABLE_HEAD_GUID_DECL'].append(TokenSpaceGuid)
            Dict['VARIABLE_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
            Dict['VARIABLE_HEAD_VALUE'].append('{ %s }\n' % ' },\n    { '.join(VariableHeadValueList))
            Dict['VARDEF_HEADER'].append('_Variable_Header')
        else:
            Dict['VARDEF_HEADER'].append('')
        if 'PCD_TYPE_VPD' in Pcd.TokenTypeList:
            Dict['VPD_HEAD_CNAME_DECL'].append(CName)
            Dict['VPD_HEAD_GUID_DECL'].append(TokenSpaceGuid)
            Dict['VPD_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
            Dict['VPD_HEAD_VALUE'].append('{ %s }' % ' }, { '.join(VpdHeadOffsetList))
        if 'PCD_TYPE_STRING' in Pcd.TokenTypeList:
            Dict['STRING_HEAD_CNAME_DECL'].append(CName)
            Dict['STRING_HEAD_GUID_DECL'].append(TokenSpaceGuid)
            Dict['STRING_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
            Dict['STRING_HEAD_VALUE'].append(', '.join(StringHeadOffsetList))
        if 'PCD_TYPE_DATA' in Pcd.TokenTypeList:
            Dict[Pcd.InitString+'_CNAME_DECL_'+Pcd.DatumType].append(CName)
            Dict[Pcd.InitString+'_GUID_DECL_'+Pcd.DatumType].append(TokenSpaceGuid)
            Dict[Pcd.InitString+'_NUMSKUS_DECL_'+Pcd.DatumType].append(len(Pcd.SkuInfoList))
            if Pcd.InitString == 'UNINIT':
                Dict['PCD_DATABASE_UNINIT_EMPTY'] = ''
            else:
                Dict[Pcd.InitString+'_VALUE_'+Pcd.DatumType].append(', '.join(ValueList))

    if Phase == 'PEI':
        NumberOfLocalTokens = NumberOfPeiLocalTokens
    if Phase == 'DXE':
        NumberOfLocalTokens = NumberOfDxeLocalTokens

    Dict['TOKEN_INIT']       = ['' for x in range(NumberOfLocalTokens)]
    Dict['TOKEN_CNAME']      = ['' for x in range(NumberOfLocalTokens)]
    Dict['TOKEN_GUID']       = ['' for x in range(NumberOfLocalTokens)]
    Dict['TOKEN_TYPE']       = ['' for x in range(NumberOfLocalTokens)]
    
    for Pcd in Platform.DynamicPcdList:
        CName = Pcd.TokenCName
        TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
        if Pcd.Phase != Phase:
            continue

        TokenSpaceGuid = GuidStructureStringToGuidValueName(Pcd.TokenSpaceGuidValue) #(Platform.PackageList, TokenSpaceGuidCName))
        GeneratedTokenNumber = Platform.PcdTokenNumber[CName, TokenSpaceGuidCName] - 1
        if Phase == 'DXE':
            GeneratedTokenNumber -= NumberOfPeiLocalTokens

        EdkLogger.debug(EdkLogger.DEBUG_1, "PCD = %s.%s" % (CName, TokenSpaceGuidCName))
        EdkLogger.debug(EdkLogger.DEBUG_1, "phase = %s" % Phase)
        EdkLogger.debug(EdkLogger.DEBUG_1, "GeneratedTokenNumber = %s" % str(GeneratedTokenNumber))

        Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Init'
        if Pcd.InitString == 'UNINIT':
            Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Uninit'
        Dict['TOKEN_CNAME'][GeneratedTokenNumber] = CName
        Dict['TOKEN_GUID'][GeneratedTokenNumber] = TokenSpaceGuid
        Dict['TOKEN_TYPE'][GeneratedTokenNumber] = ' | '.join(Pcd.TokenTypeList)
        
        Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
        #
        # Update VARDEF_HEADER
        #
        if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
            Dict['VARDEF_HEADER'][GeneratedTokenNumber] = '_Variable_Header'
        else:
            Dict['VARDEF_HEADER'][GeneratedTokenNumber] = ''
        
        
        if Pcd.Type in gDynamicExPcd:
            Dict['EXMAPPING_TABLE_EXTOKEN'].append(str(Pcd.TokenValue) + 'U')
            if Phase == 'DXE':
                GeneratedTokenNumber += NumberOfPeiLocalTokens
            #
            # Per, PCD architecture specification, PCD Token Number is 1 based and 0 is defined as invalid token number.
            # For each EX type PCD, a PCD Token Number is assigned. When the
            # PCD Driver/PEIM map EX_GUID and EX_TOKEN_NUMBER to the PCD Token Number,
            # the non-EX Protocol/PPI interface can be called to get/set the value. This assumption is made by
            # Pcd Driver/PEIM in MdeModulePkg.
            # Therefore, 1 is added to GeneratedTokenNumber to generate a PCD Token Number before being inserted
            # to the EXMAPPING_TABLE.
            #
            Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(str(GeneratedTokenNumber + 1) + 'U')
            Dict['EXMAPPING_TABLE_GUID_INDEX'].append(str(GuidList.index(TokenSpaceGuid)) + 'U')

    if GuidList != []:
        Dict['GUID_TABLE_EMPTY'] = 'FALSE'
        Dict['GUID_TABLE_SIZE'] = str(len(GuidList)) + 'U'
    else:
        Dict['GUID_STRUCTURE'] = [GuidStringToGuidStructureString('00000000-0000-0000-0000-000000000000')]

    if StringTableIndex == 0:
        Dict['STRING_TABLE_INDEX'].append('')
        Dict['STRING_TABLE_LENGTH'].append(1)
        Dict['STRING_TABLE_CNAME'].append('')
        Dict['STRING_TABLE_GUID'].append('')
        Dict['STRING_TABLE_VALUE'].append('{ 0 }')
    else:
        Dict['STRING_TABLE_EMPTY'] = 'FALSE'
        Dict['STRING_TABLE_SIZE'] = str(StringTableSize) + 'U'

    if Dict['SIZE_TABLE_CNAME'] == []:
        Dict['SIZE_TABLE_CNAME'].append('')
        Dict['SIZE_TABLE_GUID'].append('')
        Dict['SIZE_TABLE_CURRENT_LENGTH'].append('0U')
        Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append('0U')

    if NumberOfLocalTokens != 0:
        Dict['DATABASE_EMPTY']                = 'FALSE'
        Dict['LOCAL_TOKEN_NUMBER_TABLE_SIZE'] = NumberOfLocalTokens
        Dict['LOCAL_TOKEN_NUMBER']            = NumberOfLocalTokens

    if NumberOfExTokens != 0:
        Dict['EXMAP_TABLE_EMPTY']    = 'FALSE'
        Dict['EXMAPPING_TABLE_SIZE'] = str(NumberOfExTokens) + 'U'
        Dict['EX_TOKEN_NUMBER']      = str(NumberOfExTokens) + 'U'
    else:
        Dict['EXMAPPING_TABLE_EXTOKEN'].append('0U')
        Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append('0U')
        Dict['EXMAPPING_TABLE_GUID_INDEX'].append('0U')

    if NumberOfSizeItems != 0:
        Dict['SIZE_TABLE_SIZE'] = str(NumberOfSizeItems * 2) + 'U'

    AutoGenH.Append(gPcdDatabaseAutoGenH.Replace(Dict))
    if NumberOfLocalTokens == 0:
        AutoGenC.Append(gEmptyPcdDatabaseAutoGenC.Replace(Dict))
    else:
        #
        # Update Size Table to the right order, it should be same with LocalTokenNumberTable
        #
        SizeCNameTempList = []
        SizeGuidTempList = []
        SizeCurLenTempList = []
        SizeMaxLenTempList = []
        ReOrderFlag = True
  
        if len(Dict['SIZE_TABLE_CNAME']) == 1:
            if not (Dict['SIZE_TABLE_CNAME'][0] and Dict['SIZE_TABLE_GUID'][0]):
                ReOrderFlag = False
        
        if ReOrderFlag:
            for Count in range(len(Dict['TOKEN_CNAME'])):
                for Count1 in range(len(Dict['SIZE_TABLE_CNAME'])):
                    if Dict['TOKEN_CNAME'][Count] == Dict['SIZE_TABLE_CNAME'][Count1] and \
                        Dict['TOKEN_GUID'][Count] == Dict['SIZE_TABLE_GUID'][Count1]:
                        SizeCNameTempList.append(Dict['SIZE_TABLE_CNAME'][Count1])
                        SizeGuidTempList.append(Dict['SIZE_TABLE_GUID'][Count1])
                        SizeCurLenTempList.append(Dict['SIZE_TABLE_CURRENT_LENGTH'][Count1])
                        SizeMaxLenTempList.append(Dict['SIZE_TABLE_MAXIMUM_LENGTH'][Count1])
                        
            for Count in range(len(Dict['SIZE_TABLE_CNAME'])):
                Dict['SIZE_TABLE_CNAME'][Count] = SizeCNameTempList[Count]
                Dict['SIZE_TABLE_GUID'][Count] = SizeGuidTempList[Count]
                Dict['SIZE_TABLE_CURRENT_LENGTH'][Count] = SizeCurLenTempList[Count]
                Dict['SIZE_TABLE_MAXIMUM_LENGTH'][Count] = SizeMaxLenTempList[Count]
                
        AutoGenC.Append(gPcdDatabaseAutoGenC.Replace(Dict))

    return AutoGenH, AutoGenC

## Create code for PCD database
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreatePcdDatabaseCode (Info, AutoGenC, AutoGenH):
    if Info.PcdIsDriver == "":
        return
    if Info.PcdIsDriver not in gPcdPhaseMap:
        EdkLogger.error("build", AUTOGEN_ERROR, "Not supported PcdIsDriver type:%s" % Info.PcdIsDriver,
                        ExtraData="[%s]" % str(Info))

    AutoGenH.Append(gPcdDatabaseCommonAutoGenH)
    AdditionalAutoGenH, AdditionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (Info.PlatformInfo, 'PEI')
    AutoGenH.Append(AdditionalAutoGenH.String)

    Phase = gPcdPhaseMap[Info.PcdIsDriver]
    if Phase == 'PEI':
        AutoGenC.Append(AdditionalAutoGenC.String)

    if Phase == 'DXE':
        AdditionalAutoGenH, AdditionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (Info.PlatformInfo, Phase)
        AutoGenH.Append(AdditionalAutoGenH.String)
        AutoGenC.Append(AdditionalAutoGenC.String)
        AutoGenH.Append(gPcdDatabaseEpilogueAutoGenH)

## Create code for library constructor
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH):
    #
    # Library Constructors
    #
    ConstructorPrototypeString = TemplateString()
    ConstructorCallingString = TemplateString()
    if Info.IsLibrary:
        DependentLibraryList = [Info.Module]
    else:
        DependentLibraryList = Info.DependentLibraryList
    for Lib in DependentLibraryList:
        if len(Lib.ConstructorList) <= 0:
            continue
        Dict = {'Function':Lib.ConstructorList}
        if Lib.ModuleType in ['BASE', 'SEC']:
            ConstructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
            ConstructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
        elif Lib.ModuleType in ['PEI_CORE','PEIM']:
            ConstructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
            ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
        elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
            ConstructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
            ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))

    if str(ConstructorPrototypeString) == '':
        ConstructorPrototypeList = []
    else:
        ConstructorPrototypeList = [str(ConstructorPrototypeString)]
    if str(ConstructorCallingString) == '':
        ConstructorCallingList = []
    else:
        ConstructorCallingList = [str(ConstructorCallingString)]

    Dict = {
        'Type'              :   'Constructor',
        'FunctionPrototype' :   ConstructorPrototypeList,
        'FunctionCall'      :   ConstructorCallingList
    }
    if Info.IsLibrary:
        AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
    else:
        if Info.ModuleType in ['BASE', 'SEC']:
            AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
        elif Info.ModuleType in ['PEI_CORE','PEIM']:
            AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
        elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
            AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))

## Create code for library destructor
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH):
    #
    # Library Destructors
    #
    DestructorPrototypeString = TemplateString()
    DestructorCallingString = TemplateString()
    if Info.IsLibrary:
        DependentLibraryList = [Info.Module]
    else:
        DependentLibraryList = Info.DependentLibraryList
    for Index in range(len(DependentLibraryList)-1, -1, -1):
        Lib = DependentLibraryList[Index]
        if len(Lib.DestructorList) <= 0:
            continue
        Dict = {'Function':Lib.DestructorList}
        if Lib.ModuleType in ['BASE', 'SEC']:
            DestructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
            DestructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
        elif Lib.ModuleType in ['PEI_CORE','PEIM']:
            DestructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
            DestructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
        elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION', 'SMM_CORE']:
            DestructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
            DestructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))

    if str(DestructorPrototypeString) == '':
        DestructorPrototypeList = []
    else:
        DestructorPrototypeList = [str(DestructorPrototypeString)]
    if str(DestructorCallingString) == '':
        DestructorCallingList = []
    else:
        DestructorCallingList = [str(DestructorCallingString)]

    Dict = {
        'Type'              :   'Destructor',
        'FunctionPrototype' :   DestructorPrototypeList,
        'FunctionCall'      :   DestructorCallingList
    }
    if Info.IsLibrary:
        AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
    else:
        if Info.ModuleType in ['BASE', 'SEC']:
            AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
        elif Info.ModuleType in ['PEI_CORE','PEIM']:
            AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
        elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
            AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))


## Create code for ModuleEntryPoint
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
        return
    #
    # Module Entry Points
    #
    NumEntryPoints = len(Info.Module.ModuleEntryPointList)
    if 'PI_SPECIFICATION_VERSION' in Info.Module.Specification:
        PiSpecVersion = Info.Module.Specification['PI_SPECIFICATION_VERSION']
    else:
        PiSpecVersion = '0x00000000'
    if 'UEFI_SPECIFICATION_VERSION' in Info.Module.Specification:
        UefiSpecVersion = Info.Module.Specification['UEFI_SPECIFICATION_VERSION']
    else:
        UefiSpecVersion = '0x00000000'
    Dict = {
        'Function'       :   Info.Module.ModuleEntryPointList,
        'PiSpecVersion'  :   PiSpecVersion + 'U',
        'UefiSpecVersion':   UefiSpecVersion + 'U'
    }

    if Info.ModuleType in ['PEI_CORE', 'DXE_CORE', 'SMM_CORE']:
        if Info.SourceFileList <> None and Info.SourceFileList <> []:
          if NumEntryPoints != 1:
              EdkLogger.error(
                  "build",
                  AUTOGEN_ERROR,
                  '%s must have exactly one entry point' % Info.ModuleType,
                  File=str(Info),
                  ExtraData= ", ".join(Info.Module.ModuleEntryPointList)
                  )
    if Info.ModuleType == 'PEI_CORE':
        AutoGenC.Append(gPeiCoreEntryPointString.Replace(Dict))
        AutoGenH.Append(gPeiCoreEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'DXE_CORE':
        AutoGenC.Append(gDxeCoreEntryPointString.Replace(Dict))
        AutoGenH.Append(gDxeCoreEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'SMM_CORE':
        AutoGenC.Append(gSmmCoreEntryPointString.Replace(Dict))
        AutoGenH.Append(gSmmCoreEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'PEIM':
        if NumEntryPoints < 2:
            AutoGenC.Append(gPeimEntryPointString[NumEntryPoints].Replace(Dict))
        else:
            AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict))
        AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:
        if NumEntryPoints < 2:
            AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Replace(Dict))
        else:
            AutoGenC.Append(gUefiDriverEntryPointString[2].Replace(Dict))
        AutoGenH.Append(gUefiDriverEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'DXE_SMM_DRIVER':
        if NumEntryPoints == 0:
            AutoGenC.Append(gDxeSmmEntryPointString[0].Replace(Dict))
        else:
            AutoGenC.Append(gDxeSmmEntryPointString[1].Replace(Dict))
        AutoGenH.Append(gDxeSmmEntryPointPrototype.Replace(Dict))    
    elif Info.ModuleType == 'UEFI_APPLICATION':
        if NumEntryPoints < 2:
            AutoGenC.Append(gUefiApplicationEntryPointString[NumEntryPoints].Replace(Dict))
        else:
            AutoGenC.Append(gUefiApplicationEntryPointString[2].Replace(Dict))
        AutoGenH.Append(gUefiApplicationEntryPointPrototype.Replace(Dict))

## Create code for ModuleUnloadImage
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
        return
    #
    # Unload Image Handlers
    #
    NumUnloadImage = len(Info.Module.ModuleUnloadImageList)
    Dict = {'Count':str(NumUnloadImage) + 'U', 'Function':Info.Module.ModuleUnloadImageList}
    if NumUnloadImage < 2:
        AutoGenC.Append(gUefiUnloadImageString[NumUnloadImage].Replace(Dict))
    else:
        AutoGenC.Append(gUefiUnloadImageString[2].Replace(Dict))
    AutoGenH.Append(gUefiUnloadImagePrototype.Replace(Dict))

## Create code for GUID
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        return

    if Info.ModuleType in ["USER_DEFINED", "BASE"]:
        GuidType = "GUID"
    else:
        GuidType = "EFI_GUID"

    if Info.GuidList:
        AutoGenC.Append("\n// Guids\n")
    #
    # GUIDs
    #
    for Key in Info.GuidList:
        AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.GuidList[Key]))

## Create code for protocol
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        return

    if Info.ModuleType in ["USER_DEFINED", "BASE"]:
        GuidType = "GUID"
    else:
        GuidType = "EFI_GUID"

    if Info.ProtocolList:
        AutoGenC.Append("\n// Protocols\n")
    #
    # Protocol GUIDs
    #
    for Key in Info.ProtocolList:
        AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.ProtocolList[Key]))

## Create code for PPI
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        return

    if Info.ModuleType in ["USER_DEFINED", "BASE"]:
        GuidType = "GUID"
    else:
        GuidType = "EFI_GUID"

    if Info.PpiList:
        AutoGenC.Append("\n// PPIs\n")
    #
    # PPI GUIDs
    #
    for Key in Info.PpiList:
        AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.PpiList[Key]))

## Create code for PCD
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreatePcdCode(Info, AutoGenC, AutoGenH):

    # Collect Token Space GUIDs used by DynamicEc PCDs
    TokenSpaceList = []
    for Pcd in Info.ModulePcdList:
       if Pcd.Type in gDynamicExPcd and Pcd.TokenSpaceGuidCName not in TokenSpaceList:
            TokenSpaceList += [Pcd.TokenSpaceGuidCName]
            
    # Add extern declarations to AutoGen.h if one or more Token Space GUIDs were found
    if TokenSpaceList <> []:            
        AutoGenH.Append("\n// Definition of PCD Token Space GUIDs used in this module\n\n")
        if Info.ModuleType in ["USER_DEFINED", "BASE"]:
            GuidType = "GUID"
        else:
            GuidType = "EFI_GUID"              
        for Item in TokenSpaceList:
            AutoGenH.Append('extern %s %s;\n' % (GuidType, Item))

    if Info.IsLibrary:
        if Info.ModulePcdList:
            AutoGenH.Append("\n// PCD definitions\n")
        for Pcd in Info.ModulePcdList:
            CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd)
    else:
        if Info.ModulePcdList:
            AutoGenH.Append("\n// Definition of PCDs used in this module\n")
            AutoGenC.Append("\n// Definition of PCDs used in this module\n")
        for Pcd in Info.ModulePcdList:
            CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd)

        if Info.LibraryPcdList:
            AutoGenH.Append("\n// Definition of PCDs used in libraries is in AutoGen.c\n")
            AutoGenC.Append("\n// Definition of PCDs used in libraries\n")
        for Pcd in Info.LibraryPcdList:
            CreateModulePcdCode(Info, AutoGenC, AutoGenC, Pcd)
    CreatePcdDatabaseCode(Info, AutoGenC, AutoGenH)

## Create code for unicode string definition
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      UniGenCFlag     UniString is generated into AutoGen C file when it is set to True
#   @param      UniGenBinBuffer Buffer to store uni string package data
#
def CreateUnicodeStringCode(Info, AutoGenC, AutoGenH, UniGenCFlag, UniGenBinBuffer):
    WorkingDir = os.getcwd()
    os.chdir(Info.WorkspaceDir)

    IncList = [Info.MetaFile.Dir]
    # Get all files under [Sources] section in inf file for EDK-II module
    EDK2Module = True
    SrcList = [F for F in Info.SourceFileList]
    if Info.AutoGenVersion < 0x00010005:
        EDK2Module = False
        # Get all files under the module directory for EDK-I module
        Cwd = os.getcwd()
        os.chdir(Info.MetaFile.Dir)
        for Root, Dirs, Files in os.walk("."):
            if 'CVS' in Dirs:
                Dirs.remove('CVS')
            if '.svn' in Dirs:
                Dirs.remove('.svn')
            for File in Files:
                File = PathClass(os.path.join(Root, File), Info.MetaFile.Dir)
                if File in SrcList:
                    continue
                SrcList.append(File)
        os.chdir(Cwd)

    if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-c') > -1:
        CompatibleMode = True
    else:
        CompatibleMode = False

    #
    # -s is a temporary option dedicated for building .UNI files with ISO 639-2 language codes of EDK Shell in EDK2
    #
    if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-s') > -1:
        if CompatibleMode:
            EdkLogger.error("build", AUTOGEN_ERROR,
                            "-c and -s build options should be used exclusively",
                            ExtraData="[%s]" % str(Info))
        ShellMode = True
    else:
        ShellMode = False

    #RFC4646 is only for EDKII modules and ISO639-2 for EDK modules
    if EDK2Module:
        FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.RFCLanguages]
    else:
        FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.ISOLanguages]
    Header, Code = GetStringFiles(Info.UnicodeFileList, SrcList, IncList, Info.IncludePathList, ['.uni', '.inf'], Info.Name, CompatibleMode, ShellMode, UniGenCFlag, UniGenBinBuffer, FilterInfo)
    if CompatibleMode or UniGenCFlag:
        AutoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
        AutoGenC.Append(Code)
        AutoGenC.Append("\n")
    AutoGenH.Append("\n//\n//Unicode String ID\n//\n")
    AutoGenH.Append(Header)
    if CompatibleMode or UniGenCFlag:
        AutoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % Info.Name)
    os.chdir(WorkingDir)

## Create common code
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateHeaderCode(Info, AutoGenC, AutoGenH):
    # file header
    AutoGenH.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.h'}))
    # header file Prologue
    AutoGenH.Append(gAutoGenHPrologueString.Replace({'File':'AUTOGENH','Guid':Info.Guid.replace('-','_')}))
    AutoGenH.Append(gAutoGenHCppPrologueString)
    if Info.AutoGenVersion >= 0x00010005:
        # header files includes
        AutoGenH.Append("#include <%s>\n" % gBasicHeaderFile)
        if Info.ModuleType in gModuleTypeHeaderFile \
           and gModuleTypeHeaderFile[Info.ModuleType][0] != gBasicHeaderFile:
            AutoGenH.Append("#include <%s>\n" % gModuleTypeHeaderFile[Info.ModuleType][0])
        #
        # if either PcdLib in [LibraryClasses] sections or there exist Pcd section, add PcdLib.h 
        # As if modules only uses FixedPcd, then PcdLib is not needed in [LibraryClasses] section.
        #
        if 'PcdLib' in Info.Module.LibraryClasses or Info.Module.Pcds:
            AutoGenH.Append("#include <Library/PcdLib.h>\n")

        AutoGenH.Append('\nextern GUID  gEfiCallerIdGuid;\n\n')

        if Info.IsLibrary:
            return

        AutoGenH.Append("#define EFI_CALLER_ID_GUID \\\n  %s\n" % GuidStringToGuidStructureString(Info.Guid))

    if Info.IsLibrary:
        return
    # C file header
    AutoGenC.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.c'}))
    if Info.AutoGenVersion >= 0x00010005:
        # C file header files includes
        if Info.ModuleType in gModuleTypeHeaderFile:
            for Inc in gModuleTypeHeaderFile[Info.ModuleType]:
                AutoGenC.Append("#include <%s>\n" % Inc)
        else:
            AutoGenC.Append("#include <%s>\n" % gBasicHeaderFile)

        #
        # Publish the CallerId Guid
        #
        AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(Info.Guid))

## Create common code for header file
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateFooterCode(Info, AutoGenC, AutoGenH):
    AutoGenH.Append(gAutoGenHEpilogueString)

## Create code for a module
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      UniGenCFlag     UniString is generated into AutoGen C file when it is set to True
#   @param      UniGenBinBuffer Buffer to store uni string package data
#
def CreateCode(Info, AutoGenC, AutoGenH, StringH, UniGenCFlag, UniGenBinBuffer):
    CreateHeaderCode(Info, AutoGenC, AutoGenH)

    if Info.AutoGenVersion >= 0x00010005:
        CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH)
        CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH)
        CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH)
        CreatePcdCode(Info, AutoGenC, AutoGenH)
        CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH)
        CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH)
        CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH)
        CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH)

    if Info.UnicodeFileList:
        FileName = "%sStrDefs.h" % Info.Name
        StringH.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
        StringH.Append(gAutoGenHPrologueString.Replace({'File':'STRDEFS', 'Guid':Info.Guid.replace('-','_')}))
        CreateUnicodeStringCode(Info, AutoGenC, StringH, UniGenCFlag, UniGenBinBuffer)
        StringH.Append("\n#endif\n")
        AutoGenH.Append('#include "%s"\n' % FileName)

    CreateFooterCode(Info, AutoGenC, AutoGenH)

    # no generation of AutoGen.c for Edk modules without unicode file
    if Info.AutoGenVersion < 0x00010005 and len(Info.UnicodeFileList) == 0:
        AutoGenC.String = ''

## Create the code file
#
#   @param      FilePath     The path of code file
#   @param      Content      The content of code file
#   @param      IsBinaryFile The flag indicating if the file is binary file or not
#
#   @retval     True        If file content is changed or file doesn't exist
#   @retval     False       If the file exists and the content is not changed
#
def Generate(FilePath, Content, IsBinaryFile):
    return SaveFileOnChange(FilePath, Content, IsBinaryFile)