summaryrefslogtreecommitdiffstats
path: root/BaseTools/Source/Python/Workspace/DscBuildData.py
blob: e481ea4f64781a1c0b33c1fedb94da3e431fb279 (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
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
## @file
# This file is used to create a database used by build tool
#
# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP<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.
#

## Platform build information from DSC file
#
#  This class is used to retrieve information stored in database and convert them
# into PlatformBuildClassObject form for easier use for AutoGen.
#
from __future__ import print_function
from __future__ import absolute_import
from Common.StringUtils import *
from Common.DataType import *
from Common.Misc import *
from types import *
from Common.Expression import *
from CommonDataClass.CommonClass import SkuInfoClass
from Common.TargetTxtClassObject import *
from Common.ToolDefClassObject import *
from .MetaDataTable import *
from .MetaFileTable import *
from .MetaFileParser import *

from .WorkspaceCommon import GetDeclaredPcd
from Common.Misc import AnalyzeDscPcd
from Common.Misc import ProcessDuplicatedInf
import re
from Common.Parsing import IsValidWord
from Common.VariableAttributes import VariableAttributes
import Common.GlobalData as GlobalData
import subprocess
from Common.Misc import SaveFileOnChange
from Workspace.BuildClassObject import PlatformBuildClassObject, StructurePcd, PcdClassObject, ModuleBuildClassObject
from collections import OrderedDict, defaultdict

PcdValueInitName = 'PcdValueInit'

PcdMainCHeader = '''
/**
  DO NOT EDIT
  FILE auto-generated
**/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <PcdValueCommon.h>
'''

PcdMainCEntry = '''
int
main (
  int   argc,
  char  *argv[]
  )
{
  return PcdValueMain (argc, argv);
}
'''

PcdMakefileHeader = '''
#
# DO NOT EDIT
# This file is auto-generated by build utility
#

'''

WindowsCFLAGS = 'CFLAGS = $(CFLAGS) /wd4200 /wd4034 /wd4101 '
LinuxCFLAGS = 'BUILD_CFLAGS += -Wno-pointer-to-int-cast -Wno-unused-variable '
PcdMakefileEnd = '''
!INCLUDE $(BASE_TOOLS_PATH)\Source\C\Makefiles\ms.common

LIBS = $(LIB_PATH)\Common.lib

!INCLUDE $(BASE_TOOLS_PATH)\Source\C\Makefiles\ms.app
'''

PcdGccMakefile = '''
MAKEROOT ?= $(EDK_TOOLS_PATH)/Source/C
LIBS = -lCommon
'''

variablePattern = re.compile(r'[\t\s]*0[xX][a-fA-F0-9]+$')
SkuIdPattern = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
## regular expressions for finding decimal and hex numbers
Pattern = re.compile('^[1-9]\d*|0$')
HexPattern = re.compile(r'0[xX][0-9a-fA-F]+$')
## Regular expression for finding header file inclusions
from AutoGen.GenMake import gIncludePattern

## Find dependencies for one source file
#
#  By searching recursively "#include" directive in file, find out all the
#  files needed by given source file. The dependecies will be only searched
#  in given search path list.
#
#   @param      SearchPathList  The list of search path
#
#   @retval     list            The list of files the given source file depends on
#
def GetDependencyList(FileStack, SearchPathList):
    DepDb = dict()
    DependencySet = set(FileStack)
    while len(FileStack) > 0:
        F = FileStack.pop()
        FullPathDependList = []
        CurrentFileDependencyList = []
        if F in DepDb:
            CurrentFileDependencyList = DepDb[F]
        else:
            try:
                Fd = open(F, 'r')
                FileContent = Fd.read()
            except BaseException as X:
                EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=F + "\n\t" + str(X))
            finally:
                if "Fd" in dir(locals()):
                    Fd.close()

            if len(FileContent) == 0:
                continue

            if FileContent[0] == 0xff or FileContent[0] == 0xfe:
                FileContent = unicode(FileContent, "utf-16")
            IncludedFileList = gIncludePattern.findall(FileContent)

            for Inc in IncludedFileList:
                Inc = Inc.strip()
                Inc = os.path.normpath(Inc)
                CurrentFileDependencyList.append(Inc)
            DepDb[F] = CurrentFileDependencyList

        CurrentFilePath = os.path.dirname(F)
        PathList = [CurrentFilePath] + SearchPathList
        for Inc in CurrentFileDependencyList:
            for SearchPath in PathList:
                FilePath = os.path.join(SearchPath, Inc)
                if not os.path.exists(FilePath):
                    continue
                if FilePath not in DependencySet:
                    FileStack.append(FilePath)
                    FullPathDependList.append(FilePath)
                break
        DependencySet.update(FullPathDependList)
    DependencyList = list(DependencySet)  # remove duplicate ones

    return DependencyList

class DscBuildData(PlatformBuildClassObject):
    # dict used to convert PCD type in database to string used by build tool
    _PCD_TYPE_STRING_ = {
        MODEL_PCD_FIXED_AT_BUILD        :   TAB_PCDS_FIXED_AT_BUILD,
        MODEL_PCD_PATCHABLE_IN_MODULE   :   TAB_PCDS_PATCHABLE_IN_MODULE,
        MODEL_PCD_FEATURE_FLAG          :   TAB_PCDS_FEATURE_FLAG,
        MODEL_PCD_DYNAMIC               :   TAB_PCDS_DYNAMIC,
        MODEL_PCD_DYNAMIC_DEFAULT       :   TAB_PCDS_DYNAMIC,
        MODEL_PCD_DYNAMIC_HII           :   TAB_PCDS_DYNAMIC_HII,
        MODEL_PCD_DYNAMIC_VPD           :   TAB_PCDS_DYNAMIC_VPD,
        MODEL_PCD_DYNAMIC_EX            :   TAB_PCDS_DYNAMIC_EX,
        MODEL_PCD_DYNAMIC_EX_DEFAULT    :   TAB_PCDS_DYNAMIC_EX,
        MODEL_PCD_DYNAMIC_EX_HII        :   TAB_PCDS_DYNAMIC_EX_HII,
        MODEL_PCD_DYNAMIC_EX_VPD        :   TAB_PCDS_DYNAMIC_EX_VPD,
    }

    # dict used to convert part of [Defines] to members of DscBuildData directly
    _PROPERTY_ = {
        #
        # Required Fields
        #
        TAB_DSC_DEFINES_PLATFORM_NAME           :   "_PlatformName",
        TAB_DSC_DEFINES_PLATFORM_GUID           :   "_Guid",
        TAB_DSC_DEFINES_PLATFORM_VERSION        :   "_Version",
        TAB_DSC_DEFINES_DSC_SPECIFICATION       :   "_DscSpecification",
        # TAB_DSC_DEFINES_OUTPUT_DIRECTORY        :   "_OutputDirectory",
        # TAB_DSC_DEFINES_SUPPORTED_ARCHITECTURES :   "_SupArchList",
        # TAB_DSC_DEFINES_BUILD_TARGETS           :   "_BuildTargets",
        TAB_DSC_DEFINES_SKUID_IDENTIFIER        :   "_SkuName",
        # TAB_DSC_DEFINES_FLASH_DEFINITION        :   "_FlashDefinition",
        TAB_DSC_DEFINES_BUILD_NUMBER            :   "_BuildNumber",
        TAB_DSC_DEFINES_MAKEFILE_NAME           :   "_MakefileName",
        TAB_DSC_DEFINES_BS_BASE_ADDRESS         :   "_BsBaseAddress",
        TAB_DSC_DEFINES_RT_BASE_ADDRESS         :   "_RtBaseAddress",
        # TAB_DSC_DEFINES_RFC_LANGUAGES           :   "_RFCLanguages",
        # TAB_DSC_DEFINES_ISO_LANGUAGES           :   "_ISOLanguages",
    }

    # used to compose dummy library class name for those forced library instances
    _NullLibraryNumber = 0

    ## Constructor of DscBuildData
    #
    #  Initialize object of DscBuildData
    #
    #   @param      FilePath        The path of platform description file
    #   @param      RawData         The raw data of DSC file
    #   @param      BuildDataBase   Database used to retrieve module/package information
    #   @param      Arch            The target architecture
    #   @param      Platform        (not used for DscBuildData)
    #   @param      Macros          Macros used for replacement in DSC file
    #
    def __init__(self, FilePath, RawData, BuildDataBase, Arch=TAB_ARCH_COMMON, Target=None, Toolchain=None):
        self.MetaFile = FilePath
        self._RawData = RawData
        self._Bdb = BuildDataBase
        self._Arch = Arch
        self._Target = Target
        self._Toolchain = Toolchain
        self._ToolChainFamily = None
        self._Clear()
        self._HandleOverridePath()
        self.WorkspaceDir = os.getenv("WORKSPACE") if os.getenv("WORKSPACE") else ""
        self.DefaultStores = None
        self.SkuIdMgr = SkuClass(self.SkuName, self.SkuIds)

    @property
    def OutputPath(self):
        if os.getenv("WORKSPACE"):
            return os.path.join(os.getenv("WORKSPACE"), self.OutputDirectory, self._Target + "_" + self._Toolchain, PcdValueInitName)
        else:
            return os.path.dirname(self.DscFile)

    ## XXX[key] = value
    def __setitem__(self, key, value):
        self.__dict__[self._PROPERTY_[key]] = value

    ## value = XXX[key]
    def __getitem__(self, key):
        return self.__dict__[self._PROPERTY_[key]]

    ## "in" test support
    def __contains__(self, key):
        return key in self._PROPERTY_

    ## Set all internal used members of DscBuildData to None
    def _Clear(self):
        self._Header            = None
        self._PlatformName      = None
        self._Guid              = None
        self._Version           = None
        self._DscSpecification  = None
        self._OutputDirectory   = None
        self._SupArchList       = None
        self._BuildTargets      = None
        self._SkuName           = None
        self._PcdInfoFlag       = None
        self._VarCheckFlag      = None
        self._FlashDefinition   = None
        self._Prebuild          = None
        self._Postbuild         = None
        self._BuildNumber       = None
        self._MakefileName      = None
        self._BsBaseAddress     = None
        self._RtBaseAddress     = None
        self._SkuIds            = None
        self._Modules           = None
        self._LibraryInstances  = None
        self._LibraryClasses    = None
        self._Pcds              = None
        self._DecPcds           = None
        self._BuildOptions      = None
        self._ModuleTypeOptions = None
        self._LoadFixAddress    = None
        self._RFCLanguages      = None
        self._ISOLanguages      = None
        self._VpdToolGuid       = None
        self._MacroDict         = None
        self.DefaultStores      = None

    ## handle Override Path of Module
    def _HandleOverridePath(self):
        RecordList = self._RawData[MODEL_META_DATA_COMPONENT, self._Arch]
        for Record in RecordList:
            ModuleId = Record[6]
            LineNo = Record[7]
            ModuleFile = PathClass(NormPath(Record[0]), GlobalData.gWorkspace, Arch=self._Arch)
            RecordList = self._RawData[MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH, self._Arch, None, ModuleId]
            if RecordList != []:
                SourceOverridePath = mws.join(GlobalData.gWorkspace, NormPath(RecordList[0][0]))

                # Check if the source override path exists
                if not os.path.isdir(SourceOverridePath):
                    EdkLogger.error('build', FILE_NOT_FOUND, Message='Source override path does not exist:', File=self.MetaFile, ExtraData=SourceOverridePath, Line=LineNo)

                # Add to GlobalData Variables
                GlobalData.gOverrideDir[ModuleFile.Key] = SourceOverridePath

    ## Get current effective macros
    @property
    def _Macros(self):
        if self._MacroDict is None:
            self._MacroDict = {}
            self._MacroDict.update(GlobalData.gPlatformDefines)
            self._MacroDict.update(GlobalData.gGlobalDefines)
            self._MacroDict.update(GlobalData.gCommandLineDefines)
        return self._MacroDict

    ## Get architecture
    @property
    def Arch(self):
        return self._Arch

    ## Retrieve all information in [Defines] section
    #
    #   (Retriving all [Defines] information in one-shot is just to save time.)
    #
    def _GetHeaderInfo(self):
        RecordList = self._RawData[MODEL_META_DATA_HEADER, self._Arch]
        for Record in RecordList:
            Name = Record[1]
            # items defined _PROPERTY_ don't need additional processing

            # some special items in [Defines] section need special treatment
            if Name == TAB_DSC_DEFINES_OUTPUT_DIRECTORY:
                self._OutputDirectory = NormPath(Record[2], self._Macros)
                if ' ' in self._OutputDirectory:
                    EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in OUTPUT_DIRECTORY",
                                    File=self.MetaFile, Line=Record[-1],
                                    ExtraData=self._OutputDirectory)
            elif Name == TAB_DSC_DEFINES_FLASH_DEFINITION:
                self._FlashDefinition = PathClass(NormPath(Record[2], self._Macros), GlobalData.gWorkspace)
                ErrorCode, ErrorInfo = self._FlashDefinition.Validate('.fdf')
                if ErrorCode != 0:
                    EdkLogger.error('build', ErrorCode, File=self.MetaFile, Line=Record[-1],
                                    ExtraData=ErrorInfo)
            elif Name == TAB_DSC_PREBUILD:
                PrebuildValue = Record[2]
                if Record[2][0] == '"':
                    if Record[2][-1] != '"':
                        EdkLogger.error('build', FORMAT_INVALID, 'Missing double quotes in the end of %s statement.' % TAB_DSC_PREBUILD,
                                    File=self.MetaFile, Line=Record[-1])
                    PrebuildValue = Record[2][1:-1]
                self._Prebuild = PrebuildValue
            elif Name == TAB_DSC_POSTBUILD:
                PostbuildValue = Record[2]
                if Record[2][0] == '"':
                    if Record[2][-1] != '"':
                        EdkLogger.error('build', FORMAT_INVALID, 'Missing double quotes in the end of %s statement.' % TAB_DSC_POSTBUILD,
                                    File=self.MetaFile, Line=Record[-1])
                    PostbuildValue = Record[2][1:-1]
                self._Postbuild = PostbuildValue
            elif Name == TAB_DSC_DEFINES_SUPPORTED_ARCHITECTURES:
                self._SupArchList = GetSplitValueList(Record[2], TAB_VALUE_SPLIT)
            elif Name == TAB_DSC_DEFINES_BUILD_TARGETS:
                self._BuildTargets = GetSplitValueList(Record[2])
            elif Name == TAB_DSC_DEFINES_SKUID_IDENTIFIER:
                if self._SkuName is None:
                    self._SkuName = Record[2]
                if GlobalData.gSKUID_CMD:
                    self._SkuName = GlobalData.gSKUID_CMD
            elif Name == TAB_DSC_DEFINES_PCD_INFO_GENERATION:
                self._PcdInfoFlag = Record[2]
            elif Name == TAB_DSC_DEFINES_PCD_VAR_CHECK_GENERATION:
                self._VarCheckFlag = Record[2]
            elif Name == TAB_FIX_LOAD_TOP_MEMORY_ADDRESS:
                try:
                    self._LoadFixAddress = int (Record[2], 0)
                except:
                    EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS %s is not valid dec or hex string" % (Record[2]))
            elif Name == TAB_DSC_DEFINES_RFC_LANGUAGES:
                if not Record[2] or Record[2][0] != '"' or Record[2][-1] != '"' or len(Record[2]) == 1:
                    EdkLogger.error('build', FORMAT_NOT_SUPPORTED, 'language code for RFC_LANGUAGES must have double quotes around it, for example: RFC_LANGUAGES = "en-us;zh-hans"',
                                    File=self.MetaFile, Line=Record[-1])
                LanguageCodes = Record[2][1:-1]
                if not LanguageCodes:
                    EdkLogger.error('build', FORMAT_NOT_SUPPORTED, 'one or more RFC4646 format language code must be provided for RFC_LANGUAGES statement',
                                    File=self.MetaFile, Line=Record[-1])
                LanguageList = GetSplitValueList(LanguageCodes, TAB_SEMI_COLON_SPLIT)
                # check whether there is empty entries in the list
                if None in LanguageList:
                    EdkLogger.error('build', FORMAT_NOT_SUPPORTED, 'one or more empty language code is in RFC_LANGUAGES statement',
                                    File=self.MetaFile, Line=Record[-1])
                self._RFCLanguages = LanguageList
            elif Name == TAB_DSC_DEFINES_ISO_LANGUAGES:
                if not Record[2] or Record[2][0] != '"' or Record[2][-1] != '"' or len(Record[2]) == 1:
                    EdkLogger.error('build', FORMAT_NOT_SUPPORTED, 'language code for ISO_LANGUAGES must have double quotes around it, for example: ISO_LANGUAGES = "engchn"',
                                    File=self.MetaFile, Line=Record[-1])
                LanguageCodes = Record[2][1:-1]
                if not LanguageCodes:
                    EdkLogger.error('build', FORMAT_NOT_SUPPORTED, 'one or more ISO639-2 format language code must be provided for ISO_LANGUAGES statement',
                                    File=self.MetaFile, Line=Record[-1])
                if len(LanguageCodes) % 3:
                    EdkLogger.error('build', FORMAT_NOT_SUPPORTED, 'bad ISO639-2 format for ISO_LANGUAGES',
                                    File=self.MetaFile, Line=Record[-1])
                LanguageList = []
                for i in range(0, len(LanguageCodes), 3):
                    LanguageList.append(LanguageCodes[i:i + 3])
                self._ISOLanguages = LanguageList
            elif Name == TAB_DSC_DEFINES_VPD_TOOL_GUID:
                #
                # try to convert GUID to a real UUID value to see whether the GUID is format
                # for VPD_TOOL_GUID is correct.
                #
                try:
                    uuid.UUID(Record[2])
                except:
                    EdkLogger.error("build", FORMAT_INVALID, "Invalid GUID format for VPD_TOOL_GUID", File=self.MetaFile)
                self._VpdToolGuid = Record[2]
            elif Name in self:
                self[Name] = Record[2]
        # set _Header to non-None in order to avoid database re-querying
        self._Header = 'DUMMY'

    ## Retrieve platform name
    @property
    def PlatformName(self):
        if self._PlatformName is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._PlatformName is None:
                EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No PLATFORM_NAME", File=self.MetaFile)
        return self._PlatformName

    @property
    def Platform(self):
        return self.PlatformName

    ## Retrieve file guid
    @property
    def Guid(self):
        if self._Guid is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._Guid is None:
                EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No PLATFORM_GUID", File=self.MetaFile)
        return self._Guid

    ## Retrieve platform version
    @property
    def Version(self):
        if self._Version is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._Version is None:
                EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No PLATFORM_VERSION", File=self.MetaFile)
        return self._Version

    ## Retrieve platform description file version
    @property
    def DscSpecification(self):
        if self._DscSpecification is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._DscSpecification is None:
                EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No DSC_SPECIFICATION", File=self.MetaFile)
        return self._DscSpecification

    ## Retrieve OUTPUT_DIRECTORY
    @property
    def OutputDirectory(self):
        if self._OutputDirectory is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._OutputDirectory is None:
                self._OutputDirectory = os.path.join("Build", self._PlatformName)
        return self._OutputDirectory

    ## Retrieve SUPPORTED_ARCHITECTURES
    @property
    def SupArchList(self):
        if self._SupArchList is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._SupArchList is None:
                EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No SUPPORTED_ARCHITECTURES", File=self.MetaFile)
        return self._SupArchList

    ## Retrieve BUILD_TARGETS
    @property
    def BuildTargets(self):
        if self._BuildTargets is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._BuildTargets is None:
                EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No BUILD_TARGETS", File=self.MetaFile)
        return self._BuildTargets

    @property
    def PcdInfoFlag(self):
        if self._PcdInfoFlag is None or self._PcdInfoFlag.upper() == 'FALSE':
            return False
        elif self._PcdInfoFlag.upper() == 'TRUE':
            return True
        else:
            return False

    @property
    def VarCheckFlag(self):
        if self._VarCheckFlag is None or self._VarCheckFlag.upper() == 'FALSE':
            return False
        elif self._VarCheckFlag.upper() == 'TRUE':
            return True
        else:
            return False

    # # Retrieve SKUID_IDENTIFIER
    @property
    def SkuName(self):
        if self._SkuName is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._SkuName is None:
                self._SkuName = TAB_DEFAULT
        return self._SkuName

    ## Override SKUID_IDENTIFIER
    @SkuName.setter
    def SkuName(self, Value):
        self._SkuName = Value

    @property
    def FlashDefinition(self):
        if self._FlashDefinition is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._FlashDefinition is None:
                self._FlashDefinition = ''
        return self._FlashDefinition

    @property
    def Prebuild(self):
        if self._Prebuild is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._Prebuild is None:
                self._Prebuild = ''
        return self._Prebuild

    @property
    def Postbuild(self):
        if self._Postbuild is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._Postbuild is None:
                self._Postbuild = ''
        return self._Postbuild

    ## Retrieve FLASH_DEFINITION
    @property
    def BuildNumber(self):
        if self._BuildNumber is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._BuildNumber is None:
                self._BuildNumber = ''
        return self._BuildNumber

    ## Retrieve MAKEFILE_NAME
    @property
    def MakefileName(self):
        if self._MakefileName is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._MakefileName is None:
                self._MakefileName = ''
        return self._MakefileName

    ## Retrieve BsBaseAddress
    @property
    def BsBaseAddress(self):
        if self._BsBaseAddress is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._BsBaseAddress is None:
                self._BsBaseAddress = ''
        return self._BsBaseAddress

    ## Retrieve RtBaseAddress
    @property
    def RtBaseAddress(self):
        if self._RtBaseAddress is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._RtBaseAddress is None:
                self._RtBaseAddress = ''
        return self._RtBaseAddress

    ## Retrieve the top address for the load fix address
    @property
    def LoadFixAddress(self):
        if self._LoadFixAddress is None:
            if self._Header is None:
                self._GetHeaderInfo()

            if self._LoadFixAddress is None:
                self._LoadFixAddress = self._Macros.get(TAB_FIX_LOAD_TOP_MEMORY_ADDRESS, '0')

            try:
                self._LoadFixAddress = int (self._LoadFixAddress, 0)
            except:
                EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS %s is not valid dec or hex string" % (self._LoadFixAddress))

        #
        # If command line defined, should override the value in DSC file.
        #
        if 'FIX_LOAD_TOP_MEMORY_ADDRESS' in GlobalData.gCommandLineDefines:
            try:
                self._LoadFixAddress = int(GlobalData.gCommandLineDefines['FIX_LOAD_TOP_MEMORY_ADDRESS'], 0)
            except:
                EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS %s is not valid dec or hex string" % (GlobalData.gCommandLineDefines['FIX_LOAD_TOP_MEMORY_ADDRESS']))

        if self._LoadFixAddress < 0:
            EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS is set to the invalid negative value 0x%x" % (self._LoadFixAddress))
        if self._LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self._LoadFixAddress % 0x1000 != 0:
            EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS is set to the invalid unaligned 4K value 0x%x" % (self._LoadFixAddress))

        return self._LoadFixAddress

    ## Retrieve RFCLanguage filter
    @property
    def RFCLanguages(self):
        if self._RFCLanguages is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._RFCLanguages is None:
                self._RFCLanguages = []
        return self._RFCLanguages

    ## Retrieve ISOLanguage filter
    @property
    def ISOLanguages(self):
        if self._ISOLanguages is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._ISOLanguages is None:
                self._ISOLanguages = []
        return self._ISOLanguages

    ## Retrieve the GUID string for VPD tool
    @property
    def VpdToolGuid(self):
        if self._VpdToolGuid is None:
            if self._Header is None:
                self._GetHeaderInfo()
            if self._VpdToolGuid is None:
                self._VpdToolGuid = ''
        return self._VpdToolGuid

    ## Retrieve [SkuIds] section information
    @property
    def SkuIds(self):
        if self._SkuIds is None:
            self._SkuIds = OrderedDict()
            RecordList = self._RawData[MODEL_EFI_SKU_ID, self._Arch]
            for Record in RecordList:
                if not Record[0]:
                    EdkLogger.error('build', FORMAT_INVALID, 'No Sku ID number',
                                    File=self.MetaFile, Line=Record[-1])
                if not Record[1]:
                    EdkLogger.error('build', FORMAT_INVALID, 'No Sku ID name',
                                    File=self.MetaFile, Line=Record[-1])
                if not Pattern.match(Record[0]) and not HexPattern.match(Record[0]):
                    EdkLogger.error('build', FORMAT_INVALID, "The format of the Sku ID number is invalid. It only support Integer and HexNumber",
                                    File=self.MetaFile, Line=Record[-1])
                if not SkuIdPattern.match(Record[1]) or (Record[2] and not SkuIdPattern.match(Record[2])):
                    EdkLogger.error('build', FORMAT_INVALID, "The format of the Sku ID name is invalid. The correct format is '(a-zA-Z_)(a-zA-Z0-9_)*'",
                                    File=self.MetaFile, Line=Record[-1])
                self._SkuIds[Record[1].upper()] = (str(DscBuildData.ToInt(Record[0])), Record[1].upper(), Record[2].upper())
            if TAB_DEFAULT not in self._SkuIds:
                self._SkuIds[TAB_DEFAULT] = ("0", TAB_DEFAULT, TAB_DEFAULT)
            if TAB_COMMON not in self._SkuIds:
                self._SkuIds[TAB_COMMON] = ("0", TAB_DEFAULT, TAB_DEFAULT)
        return self._SkuIds

    @staticmethod
    def ToInt(intstr):
        return int(intstr, 16) if intstr.upper().startswith("0X") else int(intstr)

    def _GetDefaultStores(self):
        if self.DefaultStores is None:
            self.DefaultStores = OrderedDict()
            RecordList = self._RawData[MODEL_EFI_DEFAULT_STORES, self._Arch]
            for Record in RecordList:
                if not Record[0]:
                    EdkLogger.error('build', FORMAT_INVALID, 'No DefaultStores ID number',
                                    File=self.MetaFile, Line=Record[-1])
                if not Record[1]:
                    EdkLogger.error('build', FORMAT_INVALID, 'No DefaultStores ID name',
                                    File=self.MetaFile, Line=Record[-1])
                if not Pattern.match(Record[0]) and not HexPattern.match(Record[0]):
                    EdkLogger.error('build', FORMAT_INVALID, "The format of the DefaultStores ID number is invalid. It only support Integer and HexNumber",
                                    File=self.MetaFile, Line=Record[-1])
                if not IsValidWord(Record[1]):
                    EdkLogger.error('build', FORMAT_INVALID, "The format of the DefaultStores ID name is invalid. The correct format is '(a-zA-Z0-9_)(a-zA-Z0-9_-.)*'",
                                    File=self.MetaFile, Line=Record[-1])
                self.DefaultStores[Record[1].upper()] = (DscBuildData.ToInt(Record[0]), Record[1].upper())
            if TAB_DEFAULT_STORES_DEFAULT not in self.DefaultStores:
                self.DefaultStores[TAB_DEFAULT_STORES_DEFAULT] = (0, TAB_DEFAULT_STORES_DEFAULT)
            GlobalData.gDefaultStores = sorted(self.DefaultStores.keys())
        return self.DefaultStores

    ## Retrieve [Components] section information
    @property
    def Modules(self):
        if self._Modules is not None:
            return self._Modules

        self._Modules = OrderedDict()
        RecordList = self._RawData[MODEL_META_DATA_COMPONENT, self._Arch]
        Macros = self._Macros
        Macros["EDK_SOURCE"] = GlobalData.gEcpSource
        for Record in RecordList:
            DuplicatedFile = False

            ModuleFile = PathClass(NormPath(Record[0], Macros), GlobalData.gWorkspace, Arch=self._Arch)
            ModuleId = Record[6]
            LineNo = Record[7]

            # check the file validation
            ErrorCode, ErrorInfo = ModuleFile.Validate('.inf')
            if ErrorCode != 0:
                EdkLogger.error('build', ErrorCode, File=self.MetaFile, Line=LineNo,
                                ExtraData=ErrorInfo)
            # Check duplication
            # If arch is COMMON, no duplicate module is checked since all modules in all component sections are selected
            if self._Arch != TAB_ARCH_COMMON and ModuleFile in self._Modules:
                DuplicatedFile = True

            Module = ModuleBuildClassObject()
            Module.MetaFile = ModuleFile

            # get module private library instance
            RecordList = self._RawData[MODEL_EFI_LIBRARY_CLASS, self._Arch, None, ModuleId]
            for Record in RecordList:
                LibraryClass = Record[0]
                LibraryPath = PathClass(NormPath(Record[1], Macros), GlobalData.gWorkspace, Arch=self._Arch)
                LineNo = Record[-1]

                # check the file validation
                ErrorCode, ErrorInfo = LibraryPath.Validate('.inf')
                if ErrorCode != 0:
                    EdkLogger.error('build', ErrorCode, File=self.MetaFile, Line=LineNo,
                                    ExtraData=ErrorInfo)

                if LibraryClass == '' or LibraryClass == 'NULL':
                    self._NullLibraryNumber += 1
                    LibraryClass = 'NULL%d' % self._NullLibraryNumber
                    EdkLogger.verbose("Found forced library for %s\n\t%s [%s]" % (ModuleFile, LibraryPath, LibraryClass))
                Module.LibraryClasses[LibraryClass] = LibraryPath
                if LibraryPath not in self.LibraryInstances:
                    self.LibraryInstances.append(LibraryPath)

            # get module private PCD setting
            for Type in [MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE, \
                         MODEL_PCD_FEATURE_FLAG, MODEL_PCD_DYNAMIC, MODEL_PCD_DYNAMIC_EX]:
                RecordList = self._RawData[Type, self._Arch, None, ModuleId]
                for TokenSpaceGuid, PcdCName, Setting, Dummy1, Dummy2, Dummy3, Dummy4, Dummy5 in RecordList:
                    TokenList = GetSplitValueList(Setting)
                    DefaultValue = TokenList[0]
                    # the format is PcdName| Value | VOID* | MaxDatumSize
                    if len(TokenList) > 2:
                        MaxDatumSize = TokenList[2]
                    else:
                        MaxDatumSize = ''
                    TypeString = self._PCD_TYPE_STRING_[Type]
                    Pcd = PcdClassObject(
                            PcdCName,
                            TokenSpaceGuid,
                            TypeString,
                            '',
                            DefaultValue,
                            '',
                            MaxDatumSize,
                            {},
                            False,
                            None
                            )
                    Module.Pcds[PcdCName, TokenSpaceGuid] = Pcd

            # get module private build options
            RecordList = self._RawData[MODEL_META_DATA_BUILD_OPTION, self._Arch, None, ModuleId]
            for ToolChainFamily, ToolChain, Option, Dummy1, Dummy2, Dummy3, Dummy4, Dummy5 in RecordList:
                if (ToolChainFamily, ToolChain) not in Module.BuildOptions:
                    Module.BuildOptions[ToolChainFamily, ToolChain] = Option
                else:
                    OptionString = Module.BuildOptions[ToolChainFamily, ToolChain]
                    Module.BuildOptions[ToolChainFamily, ToolChain] = OptionString + " " + Option

            RecordList = self._RawData[MODEL_META_DATA_HEADER, self._Arch, None, ModuleId]
            if DuplicatedFile and not RecordList:
                EdkLogger.error('build', FILE_DUPLICATED, File=self.MetaFile, ExtraData=str(ModuleFile), Line=LineNo)
            if RecordList:
                if len(RecordList) != 1:
                    EdkLogger.error('build', OPTION_UNKNOWN, 'Only FILE_GUID can be listed in <Defines> section.',
                                    File=self.MetaFile, ExtraData=str(ModuleFile), Line=LineNo)
                ModuleFile = ProcessDuplicatedInf(ModuleFile, RecordList[0][2], GlobalData.gWorkspace)
                ModuleFile.Arch = self._Arch

            self._Modules[ModuleFile] = Module
        return self._Modules

    ## Retrieve all possible library instances used in this platform
    @property
    def LibraryInstances(self):
        if self._LibraryInstances is None:
            self.LibraryClasses
        return self._LibraryInstances

    ## Retrieve [LibraryClasses] information
    @property
    def LibraryClasses(self):
        if self._LibraryClasses is None:
            self._LibraryInstances = []
            #
            # tdict is a special dict kind of type, used for selecting correct
            # library instance for given library class and module type
            #
            LibraryClassDict = tdict(True, 3)
            # track all library class names
            LibraryClassSet = set()
            RecordList = self._RawData[MODEL_EFI_LIBRARY_CLASS, self._Arch, None, -1]
            Macros = self._Macros
            for Record in RecordList:
                LibraryClass, LibraryInstance, Dummy, Arch, ModuleType, Dummy, Dummy, LineNo = Record
                if LibraryClass == '' or LibraryClass == 'NULL':
                    self._NullLibraryNumber += 1
                    LibraryClass = 'NULL%d' % self._NullLibraryNumber
                    EdkLogger.verbose("Found forced library for arch=%s\n\t%s [%s]" % (Arch, LibraryInstance, LibraryClass))
                LibraryClassSet.add(LibraryClass)
                LibraryInstance = PathClass(NormPath(LibraryInstance, Macros), GlobalData.gWorkspace, Arch=self._Arch)
                # check the file validation
                ErrorCode, ErrorInfo = LibraryInstance.Validate('.inf')
                if ErrorCode != 0:
                    EdkLogger.error('build', ErrorCode, File=self.MetaFile, Line=LineNo,
                                    ExtraData=ErrorInfo)

                if ModuleType != TAB_COMMON and ModuleType not in SUP_MODULE_LIST:
                    EdkLogger.error('build', OPTION_UNKNOWN, "Unknown module type [%s]" % ModuleType,
                                    File=self.MetaFile, ExtraData=LibraryInstance, Line=LineNo)
                LibraryClassDict[Arch, ModuleType, LibraryClass] = LibraryInstance
                if LibraryInstance not in self._LibraryInstances:
                    self._LibraryInstances.append(LibraryInstance)

            # resolve the specific library instance for each class and each module type
            self._LibraryClasses = tdict(True)
            for LibraryClass in LibraryClassSet:
                # try all possible module types
                for ModuleType in SUP_MODULE_LIST:
                    LibraryInstance = LibraryClassDict[self._Arch, ModuleType, LibraryClass]
                    if LibraryInstance is None:
                        continue
                    self._LibraryClasses[LibraryClass, ModuleType] = LibraryInstance

            # for Edk style library instances, which are listed in different section
            Macros["EDK_SOURCE"] = GlobalData.gEcpSource
            RecordList = self._RawData[MODEL_EFI_LIBRARY_INSTANCE, self._Arch]
            for Record in RecordList:
                File = PathClass(NormPath(Record[0], Macros), GlobalData.gWorkspace, Arch=self._Arch)
                LineNo = Record[-1]
                # check the file validation
                ErrorCode, ErrorInfo = File.Validate('.inf')
                if ErrorCode != 0:
                    EdkLogger.error('build', ErrorCode, File=self.MetaFile, Line=LineNo,
                                    ExtraData=ErrorInfo)
                if File not in self._LibraryInstances:
                    self._LibraryInstances.append(File)
                #
                # we need the module name as the library class name, so we have
                # to parse it here. (self._Bdb[] will trigger a file parse if it
                # hasn't been parsed)
                #
                Library = self._Bdb[File, self._Arch, self._Target, self._Toolchain]
                self._LibraryClasses[Library.BaseName, ':dummy:'] = Library
        return self._LibraryClasses

    def _ValidatePcd(self, PcdCName, TokenSpaceGuid, Setting, PcdType, LineNo):
        if self._DecPcds is None:

            FdfInfList = []
            if GlobalData.gFdfParser:
                FdfInfList = GlobalData.gFdfParser.Profile.InfList

            PkgSet = set()
            for Inf in FdfInfList:
                ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch=self._Arch)
                if ModuleFile in self._Modules:
                    continue
                ModuleData = self._Bdb[ModuleFile, self._Arch, self._Target, self._Toolchain]
                PkgSet.update(ModuleData.Packages)

            self._DecPcds, self._GuidDict = GetDeclaredPcd(self, self._Bdb, self._Arch, self._Target, self._Toolchain, PkgSet)
            self._GuidDict.update(GlobalData.gPlatformPcds)

        if (PcdCName, TokenSpaceGuid) not in self._DecPcds:
            EdkLogger.error('build', PARSER_ERROR,
                            "Pcd (%s.%s) defined in DSC is not declared in DEC files referenced in INF files in FDF. Arch: ['%s']" % (TokenSpaceGuid, PcdCName, self._Arch),
                            File=self.MetaFile, Line=LineNo)
        ValueList, IsValid, Index = AnalyzeDscPcd(Setting, PcdType, self._DecPcds[PcdCName, TokenSpaceGuid].DatumType)
        if not IsValid:
            if PcdType not in [MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_AT_BUILD]:
                EdkLogger.error('build', FORMAT_INVALID, "Pcd format incorrect.", File=self.MetaFile, Line=LineNo,
                                ExtraData="%s.%s|%s" % (TokenSpaceGuid, PcdCName, Setting))
            else:
                if ValueList[2] == '-1':
                    EdkLogger.error('build', FORMAT_INVALID, "Pcd format incorrect.", File=self.MetaFile, Line=LineNo,
                                ExtraData="%s.%s|%s" % (TokenSpaceGuid, PcdCName, Setting))
        if ValueList[Index]:
            DatumType = self._DecPcds[PcdCName, TokenSpaceGuid].DatumType
            try:
                ValueList[Index] = ValueExpressionEx(ValueList[Index], DatumType, self._GuidDict)(True)
            except BadExpression as Value:
                EdkLogger.error('Parser', FORMAT_INVALID, Value, File=self.MetaFile, Line=LineNo,
                                ExtraData="PCD [%s.%s] Value \"%s\" " % (
                                TokenSpaceGuid, PcdCName, ValueList[Index]))
            except EvaluationException as Excpt:
                if hasattr(Excpt, 'Pcd'):
                    if Excpt.Pcd in GlobalData.gPlatformOtherPcds:
                        EdkLogger.error('Parser', FORMAT_INVALID, "Cannot use this PCD (%s) in an expression as"
                                        " it must be defined in a [PcdsFixedAtBuild] or [PcdsFeatureFlag] section"
                                        " of the DSC file" % Excpt.Pcd,
                                        File=self.MetaFile, Line=LineNo)
                    else:
                        EdkLogger.error('Parser', FORMAT_INVALID, "PCD (%s) is not defined in DSC file" % Excpt.Pcd,
                                        File=self.MetaFile, Line=LineNo)
                else:
                    EdkLogger.error('Parser', FORMAT_INVALID, "Invalid expression: %s" % str(Excpt),
                                    File=self.MetaFile, Line=LineNo)

        if ValueList[Index]:
            Valid, ErrStr = CheckPcdDatum(self._DecPcds[PcdCName, TokenSpaceGuid].DatumType, ValueList[Index])
            if not Valid:
                EdkLogger.error('build', FORMAT_INVALID, ErrStr, File=self.MetaFile, Line=LineNo,
                                ExtraData="%s.%s" % (TokenSpaceGuid, PcdCName))
            if PcdType in (MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE):
                if self._DecPcds[PcdCName, TokenSpaceGuid].DatumType.strip() != ValueList[1].strip():
                    EdkLogger.error('build', FORMAT_INVALID, "Pcd datumtype used in DSC file is not the same as its declaration in DEC file.", File=self.MetaFile, Line=LineNo,
                                ExtraData="%s.%s|%s" % (TokenSpaceGuid, PcdCName, Setting))
        if (TokenSpaceGuid + '.' + PcdCName) in GlobalData.gPlatformPcds:
            if GlobalData.gPlatformPcds[TokenSpaceGuid + '.' + PcdCName] != ValueList[Index]:
                GlobalData.gPlatformPcds[TokenSpaceGuid + '.' + PcdCName] = ValueList[Index]
        return ValueList

    def _FilterPcdBySkuUsage(self, Pcds):
        available_sku = self.SkuIdMgr.AvailableSkuIdSet
        sku_usage = self.SkuIdMgr.SkuUsageType
        if sku_usage == SkuClass.SINGLE:
            for pcdname in Pcds:
                pcd = Pcds[pcdname]
                Pcds[pcdname].SkuInfoList = {TAB_DEFAULT:pcd.SkuInfoList[skuid] for skuid in pcd.SkuInfoList if skuid in available_sku}
                if isinstance(pcd, StructurePcd) and pcd.SkuOverrideValues:
                    Pcds[pcdname].SkuOverrideValues = {TAB_DEFAULT:pcd.SkuOverrideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_sku}
        else:
            for pcdname in Pcds:
                pcd = Pcds[pcdname]
                Pcds[pcdname].SkuInfoList = {skuid:pcd.SkuInfoList[skuid] for skuid in pcd.SkuInfoList if skuid in available_sku}
                if isinstance(pcd, StructurePcd) and pcd.SkuOverrideValues:
                    Pcds[pcdname].SkuOverrideValues = {skuid:pcd.SkuOverrideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_sku}
        return Pcds

    def CompleteHiiPcdsDefaultStores(self, Pcds):
        HiiPcd = [Pcds[pcd] for pcd in Pcds if Pcds[pcd].Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]]
        DefaultStoreMgr = DefaultStore(self.DefaultStores)
        for pcd in HiiPcd:
            for skuid in pcd.SkuInfoList:
                skuobj = pcd.SkuInfoList.get(skuid)
                if TAB_DEFAULT_STORES_DEFAULT not in skuobj.DefaultStoreDict:
                    PcdDefaultStoreSet = set(defaultstorename  for defaultstorename in skuobj.DefaultStoreDict)
                    mindefaultstorename = DefaultStoreMgr.GetMin(PcdDefaultStoreSet)
                    skuobj.DefaultStoreDict[TAB_DEFAULT_STORES_DEFAULT] = copy.deepcopy(skuobj.DefaultStoreDict[mindefaultstorename])
        return Pcds

    def RecoverCommandLinePcd(self):
        def UpdateCommandLineValue(pcd):
            if pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]:
                pcd.PcdValueFromComm = pcd.DefaultValue
            elif pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                pcd.PcdValueFromComm = pcd.SkuInfoList.get(TAB_DEFAULT).HiiDefaultValue
            else:
                pcd.PcdValueFromComm = pcd.SkuInfoList.get(TAB_DEFAULT).DefaultValue
        for pcd in self._Pcds:
            if isinstance(self._Pcds[pcd], StructurePcd) and (self._Pcds[pcd].PcdValueFromComm or self._Pcds[pcd].PcdFieldValueFromComm):
                UpdateCommandLineValue(self._Pcds[pcd])

    def __ParsePcdFromCommandLine(self):
        if GlobalData.BuildOptionPcd:
            for i, pcd in enumerate(GlobalData.BuildOptionPcd):
                if isinstance(pcd, tuple):
                    continue
                (pcdname, pcdvalue) = pcd.split('=')
                if not pcdvalue:
                    EdkLogger.error('build', AUTOGEN_ERROR, "No Value specified for the PCD %s." % (pcdname))
                if '.' in pcdname:
                    (Name1, Name2) = pcdname.split('.', 1)
                    if "." in Name2:
                        (Name3, FieldName) = Name2.split(".", 1)
                        if ((Name3, Name1)) in self.DecPcds:
                            HasTokenSpace = True
                            TokenCName = Name3
                            TokenSpaceGuidCName = Name1
                        else:
                            FieldName = Name2
                            TokenCName = Name1
                            TokenSpaceGuidCName = ''
                            HasTokenSpace = False
                    else:
                        if ((Name2, Name1)) in self.DecPcds:
                            HasTokenSpace = True
                            TokenCName = Name2
                            TokenSpaceGuidCName = Name1
                            FieldName =""
                        else:
                            FieldName = Name2
                            TokenCName = Name1
                            TokenSpaceGuidCName = ''
                            HasTokenSpace = False
                else:
                    FieldName = ""
                    TokenCName = pcdname
                    TokenSpaceGuidCName = ''
                    HasTokenSpace = False
                TokenSpaceGuidCNameList = []
                FoundFlag = False
                PcdDatumType = ''
                DisplayName = TokenCName
                if FieldName:
                    DisplayName = TokenCName + '.' + FieldName
                if not HasTokenSpace:
                    for key in self.DecPcds:
                        PcdItem = self.DecPcds[key]
                        if TokenCName == PcdItem.TokenCName:
                            if not PcdItem.TokenSpaceGuidCName in TokenSpaceGuidCNameList:
                                if len (TokenSpaceGuidCNameList) < 1:
                                    TokenSpaceGuidCNameList.append(PcdItem.TokenSpaceGuidCName)
                                    TokenSpaceGuidCName = PcdItem.TokenSpaceGuidCName
                                    PcdDatumType = PcdItem.DatumType
                                    FoundFlag = True
                                else:
                                    EdkLogger.error(
                                            'build',
                                             AUTOGEN_ERROR,
                                            "The Pcd %s is found under multiple different TokenSpaceGuid: %s and %s." % (DisplayName, PcdItem.TokenSpaceGuidCName, TokenSpaceGuidCNameList[0])
                                            )
                else:
                    if (TokenCName, TokenSpaceGuidCName) in self.DecPcds:
                        PcdDatumType = self.DecPcds[(TokenCName, TokenSpaceGuidCName)].DatumType
                        FoundFlag = True
                if not FoundFlag:
                    if HasTokenSpace:
                        EdkLogger.error('build', AUTOGEN_ERROR, "The Pcd %s.%s is not found in the DEC file." % (TokenSpaceGuidCName, DisplayName))
                    else:
                        EdkLogger.error('build', AUTOGEN_ERROR, "The Pcd %s is not found in the DEC file." % (DisplayName))
                pcdvalue = pcdvalue.replace("\\\\\\'", '\\\\\\"').replace('\\\'', '\'').replace('\\\\\\"', "\\'")
                if FieldName:
                    pcdvalue = DscBuildData.HandleFlexiblePcd(TokenSpaceGuidCName, TokenCName, pcdvalue, PcdDatumType, self._GuidDict, FieldName)
                else:
                    pcdvalue = DscBuildData.HandleFlexiblePcd(TokenSpaceGuidCName, TokenCName, pcdvalue, PcdDatumType, self._GuidDict)
                    IsValid, Cause = CheckPcdDatum(PcdDatumType, pcdvalue)
                    if not IsValid:
                        EdkLogger.error("build", FORMAT_INVALID, Cause, ExtraData="%s.%s" % (TokenSpaceGuidCName, TokenCName))
                GlobalData.BuildOptionPcd[i] = (TokenSpaceGuidCName, TokenCName, FieldName, pcdvalue, ("build command options", 1))

                for BuildData in self._Bdb._CACHE_.values():
                    if BuildData.MetaFile.Ext == '.dec' or BuildData.MetaFile.Ext == '.dsc':
                        continue
                    for key in BuildData.Pcds:
                        PcdItem = BuildData.Pcds[key]
                        if (TokenSpaceGuidCName, TokenCName) == (PcdItem.TokenSpaceGuidCName, PcdItem.TokenCName) and FieldName =="":
                            PcdItem.DefaultValue = pcdvalue
        #In command line, the latter full assign value in commandLine should override the former field assign value.
        #For example, --pcd Token.pcd.field="" --pcd Token.pcd=H"{}"
        delete_assign = []
        field_assign = {}
        if GlobalData.BuildOptionPcd:
            for pcdTuple in GlobalData.BuildOptionPcd:
                TokenSpaceGuid, Token, Field = pcdTuple[0], pcdTuple[1], pcdTuple[2]
                if Field:
                    if (TokenSpaceGuid, Token) not in field_assign:
                        field_assign[TokenSpaceGuid, Token] = []
                    field_assign[TokenSpaceGuid, Token].append(pcdTuple)
                else:
                    if (TokenSpaceGuid, Token) in field_assign:
                        delete_assign.extend(field_assign[TokenSpaceGuid, Token])
                        field_assign[TokenSpaceGuid, Token] = []
            for item in delete_assign:
                GlobalData.BuildOptionPcd.remove(item)

    @staticmethod
    def HandleFlexiblePcd(TokenSpaceGuidCName, TokenCName, PcdValue, PcdDatumType, GuidDict, FieldName=''):
        if FieldName:
            IsArray = False
            TokenCName += '.' + FieldName
        if PcdValue.startswith('H'):
            if FieldName and IsFieldValueAnArray(PcdValue[1:]):
                PcdDatumType = TAB_VOID
                IsArray = True
            if FieldName and not IsArray:
                return PcdValue
            try:
                PcdValue = ValueExpressionEx(PcdValue[1:], PcdDatumType, GuidDict)(True)
            except BadExpression as Value:
                EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s",  %s' %
                                (TokenSpaceGuidCName, TokenCName, PcdValue, Value))
        elif PcdValue.startswith("L'") or PcdValue.startswith("'"):
            if FieldName and IsFieldValueAnArray(PcdValue):
                PcdDatumType = TAB_VOID
                IsArray = True
            if FieldName and not IsArray:
                return PcdValue
            try:
                PcdValue = ValueExpressionEx(PcdValue, PcdDatumType, GuidDict)(True)
            except BadExpression as Value:
                EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s",  %s' %
                                (TokenSpaceGuidCName, TokenCName, PcdValue, Value))
        elif PcdValue.startswith('L'):
            PcdValue = 'L"' + PcdValue[1:] + '"'
            if FieldName and IsFieldValueAnArray(PcdValue):
                PcdDatumType = TAB_VOID
                IsArray = True
            if FieldName and not IsArray:
                return PcdValue
            try:
                PcdValue = ValueExpressionEx(PcdValue, PcdDatumType, GuidDict)(True)
            except BadExpression as Value:
                EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s",  %s' %
                                (TokenSpaceGuidCName, TokenCName, PcdValue, Value))
        else:
            if PcdValue.upper() == 'FALSE':
                PcdValue = str(0)
            if PcdValue.upper() == 'TRUE':
                PcdValue = str(1)
            if not FieldName:
                if PcdDatumType not in TAB_PCD_NUMERIC_TYPES:
                    PcdValue = '"' + PcdValue + '"'
                elif not PcdValue.isdigit() and not PcdValue.upper().startswith('0X'):
                    PcdValue = '"' + PcdValue + '"'
            else:
                IsArray = False
                Base = 10
                if PcdValue.upper().startswith('0X'):
                    Base = 16
                try:
                    Num = int(PcdValue, Base)
                except:
                    PcdValue = '"' + PcdValue + '"'
                if IsFieldValueAnArray(PcdValue):
                    PcdDatumType = TAB_VOID
                    IsArray = True
                if not IsArray:
                    return PcdValue
            try:
                PcdValue = ValueExpressionEx(PcdValue, PcdDatumType, GuidDict)(True)
            except BadExpression as Value:
                EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s",  %s' %
                                (TokenSpaceGuidCName, TokenCName, PcdValue, Value))
        return PcdValue

    ## Retrieve all PCD settings in platform
    @property
    def Pcds(self):
        if self._Pcds is None:
            self._Pcds = OrderedDict()
            self.__ParsePcdFromCommandLine()
            self._Pcds.update(self._GetPcd(MODEL_PCD_FIXED_AT_BUILD))
            self._Pcds.update(self._GetPcd(MODEL_PCD_PATCHABLE_IN_MODULE))
            self._Pcds.update(self._GetPcd(MODEL_PCD_FEATURE_FLAG))
            self._Pcds.update(self._GetDynamicPcd(MODEL_PCD_DYNAMIC_DEFAULT))
            self._Pcds.update(self._GetDynamicHiiPcd(MODEL_PCD_DYNAMIC_HII))
            self._Pcds.update(self._GetDynamicVpdPcd(MODEL_PCD_DYNAMIC_VPD))
            self._Pcds.update(self._GetDynamicPcd(MODEL_PCD_DYNAMIC_EX_DEFAULT))
            self._Pcds.update(self._GetDynamicHiiPcd(MODEL_PCD_DYNAMIC_EX_HII))
            self._Pcds.update(self._GetDynamicVpdPcd(MODEL_PCD_DYNAMIC_EX_VPD))

            self._Pcds = self.CompletePcdValues(self._Pcds)
            self._Pcds = self.OverrideByFdfOverAll(self._Pcds)
            self._Pcds = self.OverrideByCommOverAll(self._Pcds)
            self._Pcds = self.UpdateStructuredPcds(MODEL_PCD_TYPE_LIST, self._Pcds)
            self._Pcds = self.CompleteHiiPcdsDefaultStores(self._Pcds)
            self._Pcds = self._FilterPcdBySkuUsage(self._Pcds)

            self.RecoverCommandLinePcd()
        return self._Pcds

    ## Retrieve [BuildOptions]
    @property
    def BuildOptions(self):
        if self._BuildOptions is None:
            self._BuildOptions = OrderedDict()
            #
            # Retrieve build option for EDKII and EDK style module
            #
            for CodeBase in (EDKII_NAME, EDK_NAME):
                RecordList = self._RawData[MODEL_META_DATA_BUILD_OPTION, self._Arch, CodeBase]
                for ToolChainFamily, ToolChain, Option, Dummy1, Dummy2, Dummy3, Dummy4, Dummy5 in RecordList:
                    if Dummy3.upper() != TAB_COMMON:
                        continue
                    CurKey = (ToolChainFamily, ToolChain, CodeBase)
                    #
                    # Only flags can be appended
                    #
                    if CurKey not in self._BuildOptions or not ToolChain.endswith('_FLAGS') or Option.startswith('='):
                        self._BuildOptions[CurKey] = Option
                    else:
                        if ' ' + Option not in self._BuildOptions[CurKey]:
                            self._BuildOptions[CurKey] += ' ' + Option
        return self._BuildOptions

    def GetBuildOptionsByModuleType(self, Edk, ModuleType):
        if self._ModuleTypeOptions is None:
            self._ModuleTypeOptions = OrderedDict()
        if (Edk, ModuleType) not in self._ModuleTypeOptions:
            options = OrderedDict()
            self._ModuleTypeOptions[Edk, ModuleType] = options
            DriverType = '%s.%s' % (Edk, ModuleType)
            CommonDriverType = '%s.%s' % (TAB_COMMON, ModuleType)
            RecordList = self._RawData[MODEL_META_DATA_BUILD_OPTION, self._Arch]
            for ToolChainFamily, ToolChain, Option, Dummy1, Dummy2, Dummy3, Dummy4, Dummy5 in RecordList:
                Type = Dummy2 + '.' + Dummy3
                if Type.upper() == DriverType.upper() or Type.upper() == CommonDriverType.upper():
                    Key = (ToolChainFamily, ToolChain, Edk)
                    if Key not in options or not ToolChain.endswith('_FLAGS') or Option.startswith('='):
                        options[Key] = Option
                    else:
                        if ' ' + Option not in options[Key]:
                            options[Key] += ' ' + Option
        return self._ModuleTypeOptions[Edk, ModuleType]

    @staticmethod
    def GetStructurePcdInfo(PcdSet):
        structure_pcd_data = defaultdict(list)
        for item in PcdSet:
            structure_pcd_data[(item[0], item[1])].append(item)

        return structure_pcd_data

    @staticmethod
    def OverrideByFdf(StruPcds,workspace):
        if GlobalData.gFdfParser is None:
            return StruPcds
        StructurePcdInFdf = OrderedDict()
        fdfpcd = GlobalData.gFdfParser.Profile.PcdDict
        fdfpcdlocation = GlobalData.gFdfParser.Profile.PcdLocalDict
        for item in fdfpcd :
            if len(item[2]) and (item[0],item[1]) in StruPcds:
                StructurePcdInFdf[(item[1],item[0],item[2] )] = fdfpcd[item]
        GlobalPcds = {(item[0],item[1]) for item in StructurePcdInFdf}
        for Pcd in StruPcds.values():
            if (Pcd.TokenSpaceGuidCName,Pcd.TokenCName) not in GlobalPcds:
                continue
            FieldValues = OrderedDict()
            for item in StructurePcdInFdf:
                if (Pcd.TokenSpaceGuidCName,Pcd.TokenCName) == (item[0],item[1]) and item[2]:
                    FieldValues[item[2]] = StructurePcdInFdf[item]
            for field in FieldValues:
                if field not in Pcd.PcdFieldValueFromFdf:
                    Pcd.PcdFieldValueFromFdf[field] = ["","",""]
                Pcd.PcdFieldValueFromFdf[field][0] = FieldValues[field]
                Pcd.PcdFieldValueFromFdf[field][1] = os.path.relpath(fdfpcdlocation[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName,field)][0],workspace)
                Pcd.PcdFieldValueFromFdf[field][2] = fdfpcdlocation[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName,field)][1]

        return StruPcds

    @staticmethod
    def OverrideByComm(StruPcds):
        StructurePcdInCom = OrderedDict()
        for item in GlobalData.BuildOptionPcd:
            if len(item) == 5 and (item[1], item[0]) in StruPcds:
                StructurePcdInCom[(item[0], item[1], item[2] )] = (item[3], item[4])
        GlobalPcds = {(item[0], item[1]) for item in StructurePcdInCom}
        for Pcd in StruPcds.values():
            if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) not in GlobalPcds:
                continue
            FieldValues = OrderedDict()
            for item in StructurePcdInCom:
                if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) == (item[0], item[1]) and item[2]:
                    FieldValues[item[2]] = StructurePcdInCom[item]
            for field in FieldValues:
                if field not in Pcd.PcdFieldValueFromComm:
                    Pcd.PcdFieldValueFromComm[field] = ["", "", ""]
                Pcd.PcdFieldValueFromComm[field][0] = FieldValues[field][0]
                Pcd.PcdFieldValueFromComm[field][1] = FieldValues[field][1][0]
                Pcd.PcdFieldValueFromComm[field][2] = FieldValues[field][1][1]
        return StruPcds

    def OverrideByCommOverAll(self,AllPcds):
        def CheckStructureInComm(commpcds):
            if not commpcds:
                return False
            if len(commpcds[0]) == 5:
                return True
            return False
        NoFiledValues = OrderedDict()
        if CheckStructureInComm(GlobalData.BuildOptionPcd):
            StructurePcdInCom = OrderedDict()
            for item in GlobalData.BuildOptionPcd:
                StructurePcdInCom[(item[0], item[1], item[2] )] = (item[3], item[4])
            for item in StructurePcdInCom:
                if not item[2]:
                    NoFiledValues[(item[0], item[1])] = StructurePcdInCom[item]
        else:
            for item in GlobalData.BuildOptionPcd:
                NoFiledValues[(item[0], item[1])] = [item[2]]
        for Guid, Name in NoFiledValues:
            if (Name, Guid) in AllPcds:
                Pcd = AllPcds.get((Name, Guid))
                if isinstance(self._DecPcds.get((Pcd.TokenCName, Pcd.TokenSpaceGuidCName), None), StructurePcd):
                    self._DecPcds.get((Pcd.TokenCName, Pcd.TokenSpaceGuidCName)).PcdValueFromComm = NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0]
                else:
                    if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:
                        Pcd.PcdValueFromComm = NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0]
                        Pcd.DefaultValue = NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0]
                    else:
                        Pcd.PcdValueFromComm = StringToArray(NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0])
                        Pcd.DefaultValue = StringToArray(NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0])
                    for sku in Pcd.SkuInfoList:
                        SkuInfo = Pcd.SkuInfoList[sku]
                        if SkuInfo.DefaultValue:
                            if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:
                                SkuInfo.DefaultValue = NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0]
                            else:
                                SkuInfo.DefaultValue = StringToArray(NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0])
                        else:
                            if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:
                                SkuInfo.HiiDefaultValue = NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0]
                            else:
                                SkuInfo.HiiDefaultValue = StringToArray(NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0])
                            for defaultstore in SkuInfo.DefaultStoreDict:
                                if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:
                                    SkuInfo.DefaultStoreDict[defaultstore] = NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0]
                                else:
                                    SkuInfo.DefaultStoreDict[defaultstore] = StringToArray(NoFiledValues[(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)][0])
                    if Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII]]:
                        if Pcd.DatumType == TAB_VOID:
                            if not Pcd.MaxDatumSize:
                                Pcd.MaxDatumSize = '0'
                            CurrentSize = int(Pcd.MaxDatumSize, 16) if Pcd.MaxDatumSize.upper().startswith("0X") else int(Pcd.MaxDatumSize)
                            OptionSize = len((StringToArray(Pcd.PcdValueFromComm)).split(","))
                            MaxSize = max(CurrentSize, OptionSize)
                            Pcd.MaxDatumSize = str(MaxSize)
            else:
                PcdInDec = self.DecPcds.get((Name, Guid))
                if PcdInDec:
                    if PcdInDec.DatumType in TAB_PCD_NUMERIC_TYPES:
                        PcdInDec.PcdValueFromComm = NoFiledValues[(Guid, Name)][0]
                    else:
                        PcdInDec.PcdValueFromComm = StringToArray(NoFiledValues[(Guid, Name)][0])
                    if PcdInDec.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_FEATURE_FLAG],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX]]:
                        self.Pcds[Name, Guid] = copy.deepcopy(PcdInDec)
                        if PcdInDec.DatumType in TAB_PCD_NUMERIC_TYPES:
                            self.Pcds[Name, Guid].DefaultValue = NoFiledValues[( Guid, Name)][0]
                        else:
                            self.Pcds[Name, Guid].DefaultValue = StringToArray(NoFiledValues[( Guid, Name)][0])
                    if PcdInDec.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX]]:
                        if PcdInDec.DatumType in TAB_PCD_NUMERIC_TYPES:
                            self.Pcds[Name, Guid].SkuInfoList = {TAB_DEFAULT:SkuInfoClass(TAB_DEFAULT, self.SkuIds[TAB_DEFAULT][0], '', '', '', '', '', NoFiledValues[( Guid, Name)][0])}
                        else:
                            self.Pcds[Name, Guid].SkuInfoList = {TAB_DEFAULT:SkuInfoClass(TAB_DEFAULT, self.SkuIds[TAB_DEFAULT][0], '', '', '', '', '',  StringToArray(NoFiledValues[( Guid, Name)][0]))}
        return AllPcds

    def OverrideByFdfOverAll(self,AllPcds):

        if GlobalData.gFdfParser is None:
            return AllPcds
        NoFiledValues = GlobalData.gFdfParser.Profile.PcdDict
        for Name,Guid,Field in NoFiledValues:
            if len(Field):
                continue
            Value = NoFiledValues[(Name,Guid,Field)]
            if (Name,Guid) in AllPcds:
                Pcd = AllPcds.get((Name,Guid))
                if isinstance(self._DecPcds.get((Pcd.TokenCName,Pcd.TokenSpaceGuidCName), None),StructurePcd):
                    self._DecPcds.get((Pcd.TokenCName,Pcd.TokenSpaceGuidCName)).PcdValueFromComm = Value
                else:
                    Pcd.PcdValueFromComm = Value
                    Pcd.DefaultValue = Value
                    for sku in Pcd.SkuInfoList:
                        SkuInfo = Pcd.SkuInfoList[sku]
                        if SkuInfo.DefaultValue:
                            SkuInfo.DefaultValue = Value
                        else:
                            SkuInfo.HiiDefaultValue = Value
                            for defaultstore in SkuInfo.DefaultStoreDict:
                                SkuInfo.DefaultStoreDict[defaultstore] = Value
                    if Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII]]:
                        if Pcd.DatumType == TAB_VOID:
                            if not Pcd.MaxDatumSize:
                                Pcd.MaxDatumSize = '0'
                            CurrentSize = int(Pcd.MaxDatumSize,16) if Pcd.MaxDatumSize.upper().startswith("0X") else int(Pcd.MaxDatumSize)
                            OptionSize = len((StringToArray(Pcd.PcdValueFromComm)).split(","))
                            MaxSize = max(CurrentSize, OptionSize)
                            Pcd.MaxDatumSize = str(MaxSize)
            else:
                PcdInDec = self.DecPcds.get((Name,Guid))
                if PcdInDec:
                    PcdInDec.PcdValueFromFdf = Value
                    if PcdInDec.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_FEATURE_FLAG]]:
                        self.Pcds[Name, Guid] = copy.deepcopy(PcdInDec)
                        self.Pcds[Name, Guid].DefaultValue = Value
        return AllPcds

    def UpdateStructuredPcds(self, TypeList, AllPcds):

        DynamicPcdType = [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_DEFAULT],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_VPD],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_DEFAULT],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_VPD]]

        Pcds = AllPcds
        DefaultStoreMgr = DefaultStore(self.DefaultStores)
        SkuIds = self.SkuIds
        self.SkuIdMgr.AvailableSkuIdSet.update({TAB_DEFAULT:0})
        DefaultStores = {storename for pcdobj in AllPcds.values() for skuobj in pcdobj.SkuInfoList.values() for storename in skuobj.DefaultStoreDict}

        S_PcdSet = []
        # Find out all possible PCD candidates for self._Arch
        RecordList = []

        for Type in TypeList:
            RecordList.extend(self._RawData[Type, self._Arch])

        for TokenSpaceGuid, PcdCName, Setting, Arch, SkuName, default_store, Dummy4, Dummy5 in RecordList:
            SkuName = SkuName.upper()
            default_store = default_store.upper()
            SkuName = TAB_DEFAULT if SkuName == TAB_COMMON else SkuName
            if SkuName not in SkuIds:
                continue

            if SkuName in SkuIds and "." in TokenSpaceGuid:
                S_PcdSet.append([ TokenSpaceGuid.split(".")[0], TokenSpaceGuid.split(".")[1], PcdCName, SkuName, default_store, Dummy5, AnalyzePcdExpression(Setting)[0]])

        # handle pcd value override
        StrPcdSet = DscBuildData.GetStructurePcdInfo(S_PcdSet)
        S_pcd_set = OrderedDict()
        for str_pcd in StrPcdSet:
            str_pcd_obj = Pcds.get((str_pcd[1], str_pcd[0]), None)
            str_pcd_dec = self._DecPcds.get((str_pcd[1], str_pcd[0]), None)
            if not isinstance (str_pcd_dec, StructurePcd):
                EdkLogger.error('build', PARSER_ERROR,
                            "Pcd (%s.%s) is not declared as Structure PCD in DEC files. Arch: ['%s']" % (str_pcd[0], str_pcd[1], self._Arch),
                            File=self.MetaFile, Line = StrPcdSet[str_pcd][0][5])
            if str_pcd_dec:
                str_pcd_obj_str = StructurePcd()
                str_pcd_obj_str.copy(str_pcd_dec)
                if str_pcd_obj:
                    str_pcd_obj_str.copy(str_pcd_obj)
                    if str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                        str_pcd_obj_str.DefaultFromDSC = {skuname:{defaultstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaultstore, str_pcd_obj.SkuInfoList[skuname].HiiDefaultValue) for defaultstore in DefaultStores} for skuname in str_pcd_obj.SkuInfoList}
                    else:
                        str_pcd_obj_str.DefaultFromDSC = {skuname:{defaultstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaultstore, str_pcd_obj.SkuInfoList[skuname].DefaultValue) for defaultstore in DefaultStores} for skuname in str_pcd_obj.SkuInfoList}
                for str_pcd_data in StrPcdSet[str_pcd]:
                    if str_pcd_data[3] in SkuIds:
                        str_pcd_obj_str.AddOverrideValue(str_pcd_data[2], str(str_pcd_data[6]), TAB_DEFAULT if str_pcd_data[3] == TAB_COMMON else str_pcd_data[3], TAB_DEFAULT_STORES_DEFAULT if str_pcd_data[4] == TAB_COMMON else str_pcd_data[4], self.MetaFile.File if self.WorkspaceDir not in self.MetaFile.File else self.MetaFile.File[len(self.WorkspaceDir) if self.WorkspaceDir.endswith(os.path.sep) else len(self.WorkspaceDir)+1:], LineNo=str_pcd_data[5])
                S_pcd_set[str_pcd[1], str_pcd[0]] = str_pcd_obj_str
            else:
                EdkLogger.error('build', PARSER_ERROR,
                            "Pcd (%s.%s) defined in DSC is not declared in DEC files. Arch: ['%s']" % (str_pcd[0], str_pcd[1], self._Arch),
                            File=self.MetaFile, Line = StrPcdSet[str_pcd][0][5])
        # Add the Structure PCD that only defined in DEC, don't have override in DSC file
        for Pcd in self.DecPcds:
            if isinstance(self._DecPcds[Pcd], StructurePcd):
                if Pcd not in S_pcd_set:
                    str_pcd_obj_str = StructurePcd()
                    str_pcd_obj_str.copy(self._DecPcds[Pcd])
                    str_pcd_obj = Pcds.get(Pcd, None)
                    if str_pcd_obj:
                        str_pcd_obj_str.copy(str_pcd_obj)
                        if str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                            str_pcd_obj_str.DefaultFromDSC = {skuname:{defaultstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaultstore, str_pcd_obj.SkuInfoList[skuname].HiiDefaultValue) for defaultstore in DefaultStores} for skuname in str_pcd_obj.SkuInfoList}
                        else:
                            str_pcd_obj_str.DefaultFromDSC = {skuname:{defaultstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaultstore, str_pcd_obj.SkuInfoList[skuname].DefaultValue) for defaultstore in DefaultStores} for skuname in str_pcd_obj.SkuInfoList}
                    S_pcd_set[Pcd] = str_pcd_obj_str
        if S_pcd_set:
            GlobalData.gStructurePcd[self.Arch] = S_pcd_set
        for stru_pcd in S_pcd_set.values():
            for skuid in SkuIds:
                if skuid in stru_pcd.SkuOverrideValues:
                    continue
                nextskuid = self.SkuIdMgr.GetNextSkuId(skuid)
                NoDefault = False
                if skuid not in stru_pcd.SkuOverrideValues:
                    while nextskuid not in stru_pcd.SkuOverrideValues:
                        if nextskuid == TAB_DEFAULT:
                            NoDefault = True
                            break
                        nextskuid = self.SkuIdMgr.GetNextSkuId(nextskuid)
                    stru_pcd.SkuOverrideValues[skuid] = copy.deepcopy(stru_pcd.SkuOverrideValues[nextskuid]) if not NoDefault else copy.deepcopy({defaultstorename: stru_pcd.DefaultValues for defaultstorename in DefaultStores} if DefaultStores else {}) #{TAB_DEFAULT_STORES_DEFAULT:stru_pcd.DefaultValues})
                    if not NoDefault:
                        stru_pcd.ValueChain.add((skuid, ''))
            if stru_pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                for skuid in SkuIds:
                    nextskuid = skuid
                    NoDefault = False
                    if skuid not in stru_pcd.SkuOverrideValues:
                        while nextskuid not in stru_pcd.SkuOverrideValues:
                            if nextskuid == TAB_DEFAULT:
                                NoDefault = True
                                break
                            nextskuid = self.SkuIdMgr.GetNextSkuId(nextskuid)
                    if NoDefault:
                        continue
                    PcdDefaultStoreSet = set(defaultstorename  for defaultstorename in stru_pcd.SkuOverrideValues[nextskuid])
                    mindefaultstorename = DefaultStoreMgr.GetMin(PcdDefaultStoreSet)

                    for defaultstoreid in DefaultStores:
                        if defaultstoreid not in stru_pcd.SkuOverrideValues[skuid]:
                            stru_pcd.SkuOverrideValues[skuid][defaultstoreid] = copy.deepcopy(stru_pcd.SkuOverrideValues[nextskuid][mindefaultstorename])
                            stru_pcd.ValueChain.add((skuid, defaultstoreid))
        S_pcd_set = DscBuildData.OverrideByFdf(S_pcd_set,self.WorkspaceDir)
        S_pcd_set = DscBuildData.OverrideByComm(S_pcd_set)
        Str_Pcd_Values = self.GenerateByteArrayValue(S_pcd_set)
        if Str_Pcd_Values:
            for (skuname, StoreName, PcdGuid, PcdName, PcdValue) in Str_Pcd_Values:
                str_pcd_obj = S_pcd_set.get((PcdName, PcdGuid))
                if str_pcd_obj is None:
                    print(PcdName, PcdGuid)
                    raise
                if str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                    if skuname not in str_pcd_obj.SkuInfoList:
                        str_pcd_obj.SkuInfoList[skuname] = SkuInfoClass(SkuIdName=skuname, SkuId=self.SkuIds[skuname][0], HiiDefaultValue=PcdValue, DefaultStore = {StoreName:PcdValue})
                    else:
                        str_pcd_obj.SkuInfoList[skuname].HiiDefaultValue = PcdValue
                        str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.update({StoreName:PcdValue})
                elif str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]:
                    if skuname in (self.SkuIdMgr.SystemSkuId, TAB_DEFAULT, TAB_COMMON):
                        str_pcd_obj.DefaultValue = PcdValue
                else:
                    if skuname not in str_pcd_obj.SkuInfoList:
                        nextskuid = self.SkuIdMgr.GetNextSkuId(skuname)
                        NoDefault = False
                        while nextskuid not in str_pcd_obj.SkuInfoList:
                            if nextskuid == TAB_DEFAULT:
                                NoDefault = True
                                break
                            nextskuid = self.SkuIdMgr.GetNextSkuId(nextskuid)
                        str_pcd_obj.SkuInfoList[skuname] = copy.deepcopy(str_pcd_obj.SkuInfoList[nextskuid]) if not NoDefault else SkuInfoClass(SkuIdName=skuname, SkuId=self.SkuIds[skuname][0], DefaultValue=PcdValue)
                        str_pcd_obj.SkuInfoList[skuname].SkuId = self.SkuIds[skuname][0]
                        str_pcd_obj.SkuInfoList[skuname].SkuIdName = skuname
                    else:
                        str_pcd_obj.SkuInfoList[skuname].DefaultValue = PcdValue
            for str_pcd_obj in S_pcd_set.values():
                if str_pcd_obj.Type not in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII],
                                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                    continue
                PcdDefaultStoreSet = set(defaultstorename for skuobj in str_pcd_obj.SkuInfoList.values() for defaultstorename in skuobj.DefaultStoreDict)
                DefaultStoreObj = DefaultStore(self._GetDefaultStores())
                mindefaultstorename = DefaultStoreObj.GetMin(PcdDefaultStoreSet)
                str_pcd_obj.SkuInfoList[self.SkuIdMgr.SystemSkuId].HiiDefaultValue = str_pcd_obj.SkuInfoList[self.SkuIdMgr.SystemSkuId].DefaultStoreDict[mindefaultstorename]

            for str_pcd_obj in S_pcd_set.values():

                str_pcd_obj.MaxDatumSize = self.GetStructurePcdMaxSize(str_pcd_obj)
                Pcds[str_pcd_obj.TokenCName, str_pcd_obj.TokenSpaceGuidCName] = str_pcd_obj
                Pcds[str_pcd_obj.TokenCName, str_pcd_obj.TokenSpaceGuidCName].CustomAttribute['IsStru']=True

            for pcdkey in Pcds:
                pcd = Pcds[pcdkey]
                if TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                    pcd.SkuInfoList[TAB_DEFAULT] = pcd.SkuInfoList[TAB_COMMON]
                    del pcd.SkuInfoList[TAB_COMMON]
                elif TAB_DEFAULT in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                    del pcd.SkuInfoList[TAB_COMMON]

        map(self.FilterSkuSettings, [Pcds[pcdkey] for pcdkey in Pcds if Pcds[pcdkey].Type in DynamicPcdType])
        return Pcds

    ## Retrieve non-dynamic PCD settings
    #
    #   @param  Type    PCD type
    #
    #   @retval a dict object contains settings of given PCD type
    #
    def _GetPcd(self, Type):
        Pcds = OrderedDict()
        #
        # tdict is a special dict kind of type, used for selecting correct
        # PCD settings for certain ARCH
        #
        AvailableSkuIdSet = copy.copy(self.SkuIds)

        PcdDict = tdict(True, 3)
        PcdSet = set()
        # Find out all possible PCD candidates for self._Arch
        RecordList = self._RawData[Type, self._Arch]
        PcdValueDict = OrderedDict()
        for TokenSpaceGuid, PcdCName, Setting, Arch, SkuName, Dummy3, Dummy4, Dummy5 in RecordList:
            SkuName = SkuName.upper()
            SkuName = TAB_DEFAULT if SkuName == TAB_COMMON else SkuName
            if SkuName not in AvailableSkuIdSet:
                EdkLogger.error('build ', PARAMETER_INVALID, 'Sku %s is not defined in [SkuIds] section' % SkuName,
                                            File=self.MetaFile, Line=Dummy5)
            if SkuName in (self.SkuIdMgr.SystemSkuId, TAB_DEFAULT, TAB_COMMON):
                if "." not in TokenSpaceGuid:
                    PcdSet.add((PcdCName, TokenSpaceGuid, SkuName, Dummy5))
                PcdDict[Arch, PcdCName, TokenSpaceGuid, SkuName] = Setting

        for PcdCName, TokenSpaceGuid, SkuName, Dummy4 in PcdSet:
            Setting = PcdDict[self._Arch, PcdCName, TokenSpaceGuid, SkuName]
            if Setting is None:
                continue
            PcdValue, DatumType, MaxDatumSize = self._ValidatePcd(PcdCName, TokenSpaceGuid, Setting, Type, Dummy4)
            if MaxDatumSize:
                if int(MaxDatumSize, 0) > 0xFFFF:
                    EdkLogger.error('build', FORMAT_INVALID, "The size value must not exceed the maximum value of 0xFFFF (UINT16) for %s." % ".".join((TokenSpaceGuid, PcdCName)),
                                    File=self.MetaFile, Line=Dummy4)
                if int(MaxDatumSize, 0) < 0:
                    EdkLogger.error('build', FORMAT_INVALID, "The size value can't be set to negative value for %s." % ".".join((TokenSpaceGuid, PcdCName)),
                                    File=self.MetaFile, Line=Dummy4)
            if (PcdCName, TokenSpaceGuid) in PcdValueDict:
                PcdValueDict[PcdCName, TokenSpaceGuid][SkuName] = (PcdValue, DatumType, MaxDatumSize)
            else:
                PcdValueDict[PcdCName, TokenSpaceGuid] = {SkuName:(PcdValue, DatumType, MaxDatumSize)}

        for ((PcdCName, TokenSpaceGuid), PcdSetting) in PcdValueDict.iteritems():
            if self.SkuIdMgr.SystemSkuId in PcdSetting:
                PcdValue, DatumType, MaxDatumSize = PcdSetting[self.SkuIdMgr.SystemSkuId]
            elif TAB_DEFAULT in PcdSetting:
                PcdValue, DatumType, MaxDatumSize = PcdSetting[TAB_DEFAULT]
            elif TAB_COMMON in PcdSetting:
                PcdValue, DatumType, MaxDatumSize = PcdSetting[TAB_COMMON]
            else:
                PcdValue = None
                DatumType = None
                MaxDatumSize = None

            Pcds[PcdCName, TokenSpaceGuid] = PcdClassObject(
                                                PcdCName,
                                                TokenSpaceGuid,
                                                self._PCD_TYPE_STRING_[Type],
                                                DatumType,
                                                PcdValue,
                                                '',
                                                MaxDatumSize,
                                                {},
                                                False,
                                                None,
                                                IsDsc=True)

            if self.SkuIdMgr.SystemSkuId not in Pcds[PcdCName, TokenSpaceGuid].DscRawValue:
                Pcds[PcdCName, TokenSpaceGuid].DscRawValue[self.SkuIdMgr.SystemSkuId] = {}
            Pcds[PcdCName, TokenSpaceGuid].DscRawValue[self.SkuIdMgr.SystemSkuId][TAB_DEFAULT_STORES_DEFAULT] = PcdValue
        return Pcds

    def GetStructurePcdMaxSize(self, str_pcd):
        pcd_default_value = str_pcd.DefaultValue
        sku_values = [skuobj.HiiDefaultValue if str_pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]] else skuobj.DefaultValue for skuobj in str_pcd.SkuInfoList.values()]
        sku_values.append(pcd_default_value)

        def get_length(value):
            Value = value.strip()
            if len(value) > 1:
                if Value.startswith(TAB_GUID) and Value.endswith(')'):
                    return 16
                if Value.startswith('L"') and Value.endswith('"'):
                    return len(Value[2:-1])
                if Value[0] == '"' and Value[-1] == '"':
                    return len(Value) - 2
                if Value[0] == '{' and Value[-1] == '}':
                    return len(Value.split(","))
                if Value.startswith("L'") and Value.endswith("'") and len(list(Value[2:-1])) > 1:
                    return  len(list(Value[2:-1]))
                if Value[0] == "'" and Value[-1] == "'" and len(list(Value[1:-1])) > 1:
                    return len(Value) - 2
            return len(Value)

        return str(max(get_length(item) for item in sku_values))

    @staticmethod
    def ExecuteCommand (Command):
        try:
            Process = subprocess.Popen(Command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        except:
            EdkLogger.error('Build', COMMAND_FAILURE, 'Can not execute command: %s' % Command)
        Result = Process.communicate()
        return Process.returncode, Result[0], Result[1]

    @staticmethod
    def IntToCString(Value, ValueSize):
        Result = '"'
        if not isinstance (Value, str):
            for Index in range(0, ValueSize):
                Result = Result + '\\x%02x' % (Value & 0xff)
                Value = Value >> 8
        Result = Result + '"'
        return Result

    def GenerateSizeFunction(self, Pcd):
        CApp = "// Default Value in Dec \n"
        CApp = CApp + "void Cal_%s_%s_Size(UINT32 *Size){\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
        for FieldList in [Pcd.DefaultValues]:
            if not FieldList:
                continue
            for FieldName in FieldList:
                FieldName = "." + FieldName
                IsArray = IsFieldValueAnArray(FieldList[FieldName.strip(".")][0])
                if IsArray and not (FieldList[FieldName.strip(".")][0].startswith('{GUID') and FieldList[FieldName.strip(".")][0].endswith('}')):
                    try:
                        Value = ValueExpressionEx(FieldList[FieldName.strip(".")][0], TAB_VOID, self._GuidDict)(True)
                    except BadExpression:
                        EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                        (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName.strip('.'))), FieldList[FieldName.strip(".")][1], FieldList[FieldName.strip(".")][2]))
                    Value, ValueSize = ParseFieldValue(Value)
                    CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d / __ARRAY_ELEMENT_SIZE(%s, %s) + ((%d %% __ARRAY_ELEMENT_SIZE(%s, %s)) ? 1 : 0));  // From %s Line %d Value %s \n' % (Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), FieldList[FieldName.strip(".")][1], FieldList[FieldName.strip(".")][2], FieldList[FieldName.strip(".")][0]);
                else:
                    NewFieldName = ''
                    FieldName_ori = FieldName.strip('.')
                    while '[' in  FieldName:
                        NewFieldName = NewFieldName + FieldName.split('[', 1)[0] + '[0]'
                        ArrayIndex = int(FieldName.split('[', 1)[1].split(']', 1)[0])
                        FieldName = FieldName.split(']', 1)[1]
                    FieldName = NewFieldName + FieldName
                    while '[' in FieldName:
                        FieldName = FieldName.rsplit('[', 1)[0]
                        CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d); // From %s Line %d Value %s\n' % (Pcd.DatumType, FieldName.strip("."), ArrayIndex + 1, FieldList[FieldName_ori][1], FieldList[FieldName_ori][2], FieldList[FieldName_ori][0])
        for skuname in Pcd.SkuOverrideValues:
            if skuname == TAB_COMMON:
                continue
            for defaultstorenameitem in Pcd.SkuOverrideValues[skuname]:
                CApp = CApp + "// SkuName: %s,  DefaultStoreName: %s \n" % (skuname, defaultstorenameitem)
                for FieldList in [Pcd.SkuOverrideValues[skuname].get(defaultstorenameitem)]:
                    if not FieldList:
                        continue
                    for FieldName in FieldList:
                        FieldName = "." + FieldName
                        IsArray = IsFieldValueAnArray(FieldList[FieldName.strip(".")][0])
                        if IsArray and not (FieldList[FieldName.strip(".")][0].startswith('{GUID') and FieldList[FieldName.strip(".")][0].endswith('}')):
                            try:
                                Value = ValueExpressionEx(FieldList[FieldName.strip(".")][0], TAB_VOID, self._GuidDict)(True)
                            except BadExpression:
                                EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                                (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName.strip('.'))), FieldList[FieldName.strip(".")][1], FieldList[FieldName.strip(".")][2]))
                            Value, ValueSize = ParseFieldValue(Value)
                            CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d / __ARRAY_ELEMENT_SIZE(%s, %s) + ((%d %% __ARRAY_ELEMENT_SIZE(%s, %s)) ? 1 : 0)); // From %s Line %d Value %s\n' % (Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), FieldList[FieldName.strip(".")][1], FieldList[FieldName.strip(".")][2], FieldList[FieldName.strip(".")][0]);
                        else:
                            NewFieldName = ''
                            FieldName_ori = FieldName.strip('.')
                            while '[' in  FieldName:
                                NewFieldName = NewFieldName + FieldName.split('[', 1)[0] + '[0]'
                                ArrayIndex = int(FieldName.split('[', 1)[1].split(']', 1)[0])
                                FieldName = FieldName.split(']', 1)[1]
                            FieldName = NewFieldName + FieldName
                            while '[' in FieldName:
                                FieldName = FieldName.rsplit('[', 1)[0]
                                CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d); // From %s Line %d Value %s \n' % (Pcd.DatumType, FieldName.strip("."), ArrayIndex + 1, FieldList[FieldName_ori][1], FieldList[FieldName_ori][2], FieldList[FieldName_ori][0])
        if Pcd.PcdFieldValueFromFdf:
            CApp = CApp + "// From fdf \n"
        for FieldName in Pcd.PcdFieldValueFromFdf:
            FieldName = "." + FieldName
            IsArray = IsFieldValueAnArray(Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][0])
            if IsArray and not (Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][0].startswith('{GUID') and Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][0].endswith('}')):
                try:
                    Value = ValueExpressionEx(Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][0], TAB_VOID, self._GuidDict)(True)
                except BadExpression:
                    EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                    (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName.strip('.'))), Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][1], Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][2]))
                Value, ValueSize = ParseFieldValue(Value)
                CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d / __ARRAY_ELEMENT_SIZE(%s, %s) + ((%d %% __ARRAY_ELEMENT_SIZE(%s, %s)) ? 1 : 0)); // From %s Line %d Value %s\n' % (Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][1], Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][2], Pcd.PcdFieldValueFromFdf[FieldName.strip(".")][0]);
            else:
                NewFieldName = ''
                FieldName_ori = FieldName.strip('.')
                while '[' in  FieldName:
                    NewFieldName = NewFieldName + FieldName.split('[', 1)[0] + '[0]'
                    ArrayIndex = int(FieldName.split('[', 1)[1].split(']', 1)[0])
                    FieldName = FieldName.split(']', 1)[1]
                FieldName = NewFieldName + FieldName
                while '[' in FieldName:
                    FieldName = FieldName.rsplit('[', 1)[0]
                    CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d); // From %s Line %s Value %s \n' % (Pcd.DatumType, FieldName.strip("."), ArrayIndex + 1, Pcd.PcdFieldValueFromFdf[FieldName_ori][1], Pcd.PcdFieldValueFromFdf[FieldName_ori][2], Pcd.PcdFieldValueFromFdf[FieldName_ori][0])
        if Pcd.PcdFieldValueFromComm:
            CApp = CApp + "// From Command Line \n"
        for FieldName in Pcd.PcdFieldValueFromComm:
            FieldName = "." + FieldName
            IsArray = IsFieldValueAnArray(Pcd.PcdFieldValueFromComm[FieldName.strip(".")][0])
            if IsArray and not (Pcd.PcdFieldValueFromComm[FieldName.strip(".")][0].startswith('{GUID') and Pcd.PcdFieldValueFromComm[FieldName.strip(".")][0].endswith('}')):
                try:
                    Value = ValueExpressionEx(Pcd.PcdFieldValueFromComm[FieldName.strip(".")][0], TAB_VOID, self._GuidDict)(True)
                except BadExpression:
                    EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                    (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName.strip('.'))), Pcd.PcdFieldValueFromComm[FieldName.strip(".")][1], Pcd.PcdFieldValueFromComm[FieldName.strip(".")][2]))
                Value, ValueSize = ParseFieldValue(Value)
                CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d / __ARRAY_ELEMENT_SIZE(%s, %s) + ((%d %% __ARRAY_ELEMENT_SIZE(%s, %s)) ? 1 : 0)); // From %s Line %d Value %s\n' % (Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), ValueSize, Pcd.DatumType, FieldName.strip("."), Pcd.PcdFieldValueFromComm[FieldName.strip(".")][1], Pcd.PcdFieldValueFromComm[FieldName.strip(".")][2], Pcd.PcdFieldValueFromComm[FieldName.strip(".")][0]);
            else:
                NewFieldName = ''
                FieldName_ori = FieldName.strip('.')
                while '[' in  FieldName:
                    NewFieldName = NewFieldName + FieldName.split('[', 1)[0] + '[0]'
                    ArrayIndex = int(FieldName.split('[', 1)[1].split(']', 1)[0])
                    FieldName = FieldName.split(']', 1)[1]
                FieldName = NewFieldName + FieldName
                while '[' in FieldName:
                    FieldName = FieldName.rsplit('[', 1)[0]
                    CApp = CApp + '  __FLEXIBLE_SIZE(*Size, %s, %s, %d); // From %s Line %d Value %s \n' % (Pcd.DatumType, FieldName.strip("."), ArrayIndex + 1, Pcd.PcdFieldValueFromComm[FieldName_ori][1], Pcd.PcdFieldValueFromComm[FieldName_ori][2], Pcd.PcdFieldValueFromComm[FieldName_ori][0])
        CApp = CApp + "  *Size = (%d > *Size ? %d : *Size); // The Pcd maxsize is %d \n" % (Pcd.GetPcdMaxSize(), Pcd.GetPcdMaxSize(), Pcd.GetPcdMaxSize())
        CApp = CApp + "}\n"
        return CApp

    @staticmethod
    def GenerateSizeStatments(Pcd):
        CApp = '  Size = sizeof(%s);\n' % (Pcd.DatumType)
        CApp = CApp + '  Cal_%s_%s_Size(&Size);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
        return CApp

    def GenerateDefaultValueAssignFunction(self, Pcd):
        CApp = "// Default value in Dec \n"
        CApp = CApp + "void Assign_%s_%s_Default_Value(%s *Pcd){\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Pcd.DatumType)
        CApp = CApp + '  UINT32  FieldSize;\n'
        CApp = CApp + '  CHAR8   *Value;\n'
        DefaultValueFromDec = Pcd.DefaultValueFromDec
        IsArray = IsFieldValueAnArray(Pcd.DefaultValueFromDec)
        if IsArray:
            try:
                DefaultValueFromDec = ValueExpressionEx(Pcd.DefaultValueFromDec, TAB_VOID)(True)
            except BadExpression:
                EdkLogger.error("Build", FORMAT_INVALID, "Invalid value format for %s.%s, from DEC: %s" %
                                (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, DefaultValueFromDec))
        DefaultValueFromDec = StringToArray(DefaultValueFromDec)
        Value, ValueSize = ParseFieldValue (DefaultValueFromDec)
        if isinstance(Value, str):
            CApp = CApp + '  Pcd = %s; // From DEC Default Value %s\n' % (Value, Pcd.DefaultValueFromDec)
        elif IsArray:
        #
        # Use memcpy() to copy value into field
        #
            CApp = CApp + '  Value     = %s; // From DEC Default Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), Pcd.DefaultValueFromDec)
            CApp = CApp + '  memcpy (Pcd, Value, %d);\n' % (ValueSize)
        for FieldList in [Pcd.DefaultValues]:
            if not FieldList:
                continue
            for FieldName in FieldList:
                IsArray = IsFieldValueAnArray(FieldList[FieldName][0])
                if IsArray:
                    try:
                        FieldList[FieldName][0] = ValueExpressionEx(FieldList[FieldName][0], TAB_VOID, self._GuidDict)(True)
                    except BadExpression:
                        EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                        (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))

                try:
                    Value, ValueSize = ParseFieldValue (FieldList[FieldName][0])
                except Exception:
                    EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " % (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))
                if isinstance(Value, str):
                    CApp = CApp + '  Pcd->%s = %s; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                elif IsArray:
                    #
                    # Use memcpy() to copy value into field
                    #
                    CApp = CApp + '  FieldSize = __FIELD_SIZE(%s, %s);\n' % (Pcd.DatumType, FieldName)
                    CApp = CApp + '  Value     = %s; // From %s Line %d Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    CApp = CApp + '  __STATIC_ASSERT((__FIELD_SIZE(%s, %s) >= %d) || (__FIELD_SIZE(%s, %s) == 0), "Input buffer exceeds the buffer array"); // From %s Line %d Value %s\n' % (Pcd.DatumType, FieldName, ValueSize, Pcd.DatumType, FieldName, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    CApp = CApp + '  memcpy (&Pcd->%s, Value, (FieldSize > 0 && FieldSize < %d) ? FieldSize : %d);\n' % (FieldName, ValueSize, ValueSize)
                else:
                    if '[' in FieldName and ']' in FieldName:
                        Index = int(FieldName.split('[')[1].split(']')[0])
                        CApp = CApp + '  __STATIC_ASSERT((%d < __ARRAY_SIZE(Pcd->%s)) || (__ARRAY_SIZE(Pcd->%s) == 0), "array index exceeds the array number"); // From %s Line %d Index of %s\n' % (Index, FieldName.split('[')[0], FieldName.split('[')[0], FieldList[FieldName][1], FieldList[FieldName][2], FieldName)
                    if ValueSize > 4:
                        CApp = CApp + '  Pcd->%s = %dULL; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    else:
                        CApp = CApp + '  Pcd->%s = %d; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
        CApp = CApp + "}\n"
        return CApp

    @staticmethod
    def GenerateDefaultValueAssignStatement(Pcd):
        CApp = '  Assign_%s_%s_Default_Value(Pcd);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
        return CApp

    def GenerateInitValueFunction(self, Pcd, SkuName, DefaultStoreName):
        CApp = "// Value in Dsc for Sku: %s, DefaultStore %s\n" % (SkuName, DefaultStoreName)
        CApp = CApp + "void Assign_%s_%s_%s_%s_Value(%s *Pcd){\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, SkuName, DefaultStoreName, Pcd.DatumType)
        CApp = CApp + '  UINT32  FieldSize;\n'
        CApp = CApp + '  CHAR8   *Value;\n'

        CApp = CApp + "// SkuName: %s,  DefaultStoreName: %s \n" % (TAB_DEFAULT, TAB_DEFAULT_STORES_DEFAULT)
        inherit_OverrideValues = Pcd.SkuOverrideValues[SkuName]
        if (SkuName, DefaultStoreName) == (TAB_DEFAULT, TAB_DEFAULT_STORES_DEFAULT):
            pcddefaultvalue = Pcd.DefaultFromDSC.get(TAB_DEFAULT, {}).get(TAB_DEFAULT_STORES_DEFAULT) if Pcd.DefaultFromDSC else None
        else:
            pcddefaultvalue = Pcd.DscRawValue.get(SkuName, {}).get(DefaultStoreName)
        for FieldList in [pcddefaultvalue, inherit_OverrideValues.get(DefaultStoreName)]:
            if not FieldList:
                continue
            if pcddefaultvalue and FieldList == pcddefaultvalue:
                IsArray = IsFieldValueAnArray(FieldList)
                if IsArray:
                    try:
                        FieldList = ValueExpressionEx(FieldList, TAB_VOID)(True)
                    except BadExpression:
                        EdkLogger.error("Build", FORMAT_INVALID, "Invalid value format for %s.%s, from DSC: %s" %
                                        (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldList))
                Value, ValueSize = ParseFieldValue (FieldList)

                if (SkuName, DefaultStoreName) == (TAB_DEFAULT, TAB_DEFAULT_STORES_DEFAULT):
                    if isinstance(Value, str):
                        CApp = CApp + '  Pcd = %s; // From DSC Default Value %s\n' % (Value, Pcd.DefaultFromDSC.get(TAB_DEFAULT, {}).get(TAB_DEFAULT_STORES_DEFAULT, Pcd.DefaultValue) if Pcd.DefaultFromDSC else Pcd.DefaultValue)
                    elif IsArray:
                    #
                    # Use memcpy() to copy value into field
                    #
                        CApp = CApp + '  Value     = %s; // From DSC Default Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), Pcd.DefaultFromDSC.get(TAB_DEFAULT, {}).get(TAB_DEFAULT_STORES_DEFAULT, Pcd.DefaultValue) if Pcd.DefaultFromDSC else Pcd.DefaultValue)
                        CApp = CApp + '  memcpy (Pcd, Value, %d);\n' % (ValueSize)
                else:
                    if isinstance(Value, str):
                        CApp = CApp + '  Pcd = %s; // From DSC Default Value %s\n' % (Value, Pcd.DscRawValue.get(SkuName, {}).get(DefaultStoreName))
                    elif IsArray:
                    #
                    # Use memcpy() to copy value into field
                    #
                        CApp = CApp + '  Value     = %s; // From DSC Default Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), Pcd.DscRawValue.get(SkuName, {}).get(DefaultStoreName))
                        CApp = CApp + '  memcpy (Pcd, Value, %d);\n' % (ValueSize)
                continue
            if (SkuName, DefaultStoreName) == (TAB_DEFAULT, TAB_DEFAULT_STORES_DEFAULT) or (( (SkuName, '') not in Pcd.ValueChain) and ( (SkuName, DefaultStoreName) not in Pcd.ValueChain )):
                for FieldName in FieldList:
                    IsArray = IsFieldValueAnArray(FieldList[FieldName][0])
                    if IsArray:
                        try:
                            FieldValue = ValueExpressionEx(FieldList[FieldName][0], TAB_VOID, self._GuidDict)(True)
                        except BadExpression:
                            EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                            (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))
                    try:
                        if IsArray:
                            Value, ValueSize = ParseFieldValue (FieldValue)
                        else:
                            Value, ValueSize = ParseFieldValue (FieldList[FieldName][0])
                    except Exception:
                        EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " % (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))
                    if isinstance(Value, str):
                        CApp = CApp + '  Pcd->%s = %s; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    elif IsArray:
                    #
                    # Use memcpy() to copy value into field
                    #
                        CApp = CApp + '  FieldSize = __FIELD_SIZE(%s, %s);\n' % (Pcd.DatumType, FieldName)
                        CApp = CApp + '  Value     = %s; // From %s Line %d Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                        CApp = CApp + '  __STATIC_ASSERT((__FIELD_SIZE(%s, %s) >= %d) || (__FIELD_SIZE(%s, %s) == 0), "Input buffer exceeds the buffer array"); // From %s Line %d Value %s\n' % (Pcd.DatumType, FieldName, ValueSize, Pcd.DatumType, FieldName, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                        CApp = CApp + '  memcpy (&Pcd->%s, Value, (FieldSize > 0 && FieldSize < %d) ? FieldSize : %d);\n' % (FieldName, ValueSize, ValueSize)
                    else:
                        if '[' in FieldName and ']' in FieldName:
                            Index = int(FieldName.split('[')[1].split(']')[0])
                            CApp = CApp + '  __STATIC_ASSERT((%d < __ARRAY_SIZE(Pcd->%s)) || (__ARRAY_SIZE(Pcd->%s) == 0), "array index exceeds the array number"); // From %s Line %d Index of %s\n' % (Index, FieldName.split('[')[0], FieldName.split('[')[0], FieldList[FieldName][1], FieldList[FieldName][2], FieldName)
                        if ValueSize > 4:
                            CApp = CApp + '  Pcd->%s = %dULL; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                        else:
                            CApp = CApp + '  Pcd->%s = %d; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
        CApp = CApp + "}\n"
        return CApp

    @staticmethod
    def GenerateInitValueStatement(Pcd, SkuName, DefaultStoreName):
        CApp = '  Assign_%s_%s_%s_%s_Value(Pcd);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, SkuName, DefaultStoreName)
        return CApp

    def GenerateCommandLineValue(self, Pcd):
        CApp = "// Value in CommandLine\n"
        CApp = CApp + "void Assign_%s_%s_CommandLine_Value(%s *Pcd){\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Pcd.DatumType)
        CApp = CApp + '  UINT32  FieldSize;\n'
        CApp = CApp + '  CHAR8   *Value;\n'

        pcddefaultvalue = Pcd.PcdValueFromComm
        for FieldList in [pcddefaultvalue, Pcd.PcdFieldValueFromComm]:
            if not FieldList:
                continue
            if pcddefaultvalue and FieldList == pcddefaultvalue:
                IsArray = IsFieldValueAnArray(FieldList)
                if IsArray:
                    try:
                        FieldList = ValueExpressionEx(FieldList, TAB_VOID)(True)
                    except BadExpression:
                        EdkLogger.error("Build", FORMAT_INVALID, "Invalid value format for %s.%s, from Command: %s" %
                                        (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldList))
                Value, ValueSize = ParseFieldValue (FieldList)

                if isinstance(Value, str):
                    CApp = CApp + '  Pcd = %s; // From Command Line \n' % (Value)
                elif IsArray:
                #
                # Use memcpy() to copy value into field
                #
                    CApp = CApp + '  Value     = %s; // From Command Line.\n' % (DscBuildData.IntToCString(Value, ValueSize))
                    CApp = CApp + '  memcpy (Pcd, Value, %d);\n' % (ValueSize)
                continue
            for FieldName in FieldList:
                IsArray = IsFieldValueAnArray(FieldList[FieldName][0])
                if IsArray:
                    try:
                        FieldList[FieldName][0] = ValueExpressionEx(FieldList[FieldName][0], TAB_VOID, self._GuidDict)(True)
                    except BadExpression:
                        EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                        (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))
                    except:
                        print("error")
                try:
                    Value, ValueSize = ParseFieldValue (FieldList[FieldName][0])
                except Exception:
                    EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " % (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))
                if isinstance(Value, str):
                    CApp = CApp + '  Pcd->%s = %s; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                elif IsArray:
                #
                # Use memcpy() to copy value into field
                #
                    CApp = CApp + '  FieldSize = __FIELD_SIZE(%s, %s);\n' % (Pcd.DatumType, FieldName)
                    CApp = CApp + '  Value     = %s; // From %s Line %d Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    CApp = CApp + '  memcpy (&Pcd->%s, Value, (FieldSize > 0 && FieldSize < %d) ? FieldSize : %d);\n' % (FieldName, ValueSize, ValueSize)
                else:
                    if ValueSize > 4:
                        CApp = CApp + '  Pcd->%s = %dULL; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    else:
                        CApp = CApp + '  Pcd->%s = %d; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
        CApp = CApp + "}\n"
        return CApp

    @staticmethod
    def GenerateCommandLineValueStatement(Pcd):
        CApp = '  Assign_%s_%s_CommandLine_Value(Pcd);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
        return CApp
    def GenerateFdfValue(self,Pcd):
        CApp = "// Value in Fdf\n"
        CApp = CApp + "void Assign_%s_%s_Fdf_Value(%s *Pcd){\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType)
        CApp = CApp + '  UINT32  FieldSize;\n'
        CApp = CApp + '  CHAR8   *Value;\n'

        pcddefaultvalue = Pcd.PcdValueFromFdf
        for FieldList in [pcddefaultvalue,Pcd.PcdFieldValueFromFdf]:
            if not FieldList:
                continue
            if pcddefaultvalue and FieldList == pcddefaultvalue:
                IsArray = IsFieldValueAnArray(FieldList)
                if IsArray:
                    try:
                        FieldList = ValueExpressionEx(FieldList, TAB_VOID)(True)
                    except BadExpression:
                        EdkLogger.error("Build", FORMAT_INVALID, "Invalid value format for %s.%s, from Fdf: %s" %
                                        (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldList))
                Value, ValueSize = ParseFieldValue (FieldList)

                if isinstance(Value, str):
                    CApp = CApp + '  Pcd = %s; // From Fdf \n' % (Value)
                elif IsArray:
                #
                # Use memcpy() to copy value into field
                #
                    CApp = CApp + '  Value     = %s; // From Fdf .\n' % (DscBuildData.IntToCString(Value, ValueSize))
                    CApp = CApp + '  memcpy (Pcd, Value, %d);\n' % (ValueSize)
                continue
            for FieldName in FieldList:
                IsArray = IsFieldValueAnArray(FieldList[FieldName][0])
                if IsArray:
                    try:
                        FieldList[FieldName][0] = ValueExpressionEx(FieldList[FieldName][0], TAB_VOID, self._GuidDict)(True)
                    except BadExpression:
                        EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " %
                                        (".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName, FieldName)), FieldList[FieldName][1], FieldList[FieldName][2]))
                    except:
                        print("error")
                try:
                    Value, ValueSize = ParseFieldValue (FieldList[FieldName][0])
                except Exception:
                    EdkLogger.error('Build', FORMAT_INVALID, "Invalid value format for %s. From %s Line %d " % (".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName,FieldName)),FieldList[FieldName][1], FieldList[FieldName][2]))
                if isinstance(Value, str):
                    CApp = CApp + '  Pcd->%s = %s; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                elif IsArray:
                #
                # Use memcpy() to copy value into field
                #
                    CApp = CApp + '  FieldSize = __FIELD_SIZE(%s, %s);\n' % (Pcd.DatumType, FieldName)
                    CApp = CApp + '  Value     = %s; // From %s Line %d Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    CApp = CApp + '  memcpy (&Pcd->%s, Value, (FieldSize > 0 && FieldSize < %d) ? FieldSize : %d);\n' % (FieldName, ValueSize, ValueSize)
                else:
                    if ValueSize > 4:
                        CApp = CApp + '  Pcd->%s = %dULL; // From %s Line %d Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
                    else:
                        CApp = CApp + '  Pcd->%s = %d; // From %s Line %s Value %s\n' % (FieldName, Value, FieldList[FieldName][1], FieldList[FieldName][2], FieldList[FieldName][0])
        CApp = CApp + "}\n"
        return CApp

    @staticmethod
    def GenerateFdfValueStatement(Pcd):
        CApp = '  Assign_%s_%s_Fdf_Value(Pcd);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
        return CApp

    def GenerateInitializeFunc(self, SkuName, DefaultStore, Pcd, InitByteValue, CApp):
        OverrideValues = {DefaultStore:""}
        if Pcd.SkuOverrideValues:
            OverrideValues = Pcd.SkuOverrideValues[SkuName]
        if not OverrideValues:
            OverrideValues = {TAB_DEFAULT_STORES_DEFAULT:Pcd.DefaultValues}
        for DefaultStoreName in OverrideValues:
            CApp = CApp + 'void\n'
            CApp = CApp + 'Initialize_%s_%s_%s_%s(\n' % (SkuName, DefaultStoreName, Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
            CApp = CApp + '  void\n'
            CApp = CApp + '  )\n'
            CApp = CApp + '{\n'
            CApp = CApp + '  UINT32  Size;\n'
            CApp = CApp + '  UINT32  FieldSize;\n'
            CApp = CApp + '  CHAR8   *Value;\n'
            CApp = CApp + '  UINT32  OriginalSize;\n'
            CApp = CApp + '  VOID    *OriginalPcd;\n'
            CApp = CApp + '  %s      *Pcd;  // From %s Line %d \n' % (Pcd.DatumType, Pcd.PkgPath, Pcd.PcdDefineLineNo)
            CApp = CApp + '\n'

            if SkuName in Pcd.SkuInfoList:
                DefaultValue = Pcd.SkuInfoList[SkuName].DefaultStoreDict.get(DefaultStoreName, Pcd.SkuInfoList[SkuName].HiiDefaultValue if Pcd.SkuInfoList[SkuName].HiiDefaultValue  else Pcd.SkuInfoList[SkuName].DefaultValue)
            else:
                DefaultValue = Pcd.DefaultValue
            PcdDefaultValue = StringToArray(DefaultValue.strip())

            InitByteValue += '%s.%s.%s.%s|%s|%s\n' % (SkuName, DefaultStoreName, Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Pcd.DatumType, PcdDefaultValue)

            #
            # Get current PCD value and size
            #
            CApp = CApp + '  OriginalPcd = PcdGetPtr (%s, %s, %s, %s, &OriginalSize);\n' % (SkuName, DefaultStoreName, Pcd.TokenSpaceGuidCName, Pcd.TokenCName)

            #
            # Determine the size of the PCD.  For simple structures, sizeof(TYPE) provides
            # the correct value.  For structures with a flexible array member, the flexible
            # array member is detected, and the size is based on the highest index used with
            # the flexible array member.  The flexible array member must be the last field
            # in a structure.  The size formula for this case is:
            # OFFSET_OF(FlexbleArrayField) + sizeof(FlexibleArray[0]) * (HighestIndex + 1)
            #
            CApp = CApp + DscBuildData.GenerateSizeStatments(Pcd)

            #
            # Allocate and zero buffer for the PCD
            # Must handle cases where current value is smaller, larger, or same size
            # Always keep that larger one as the current size
            #
            CApp = CApp + '  Size = (OriginalSize > Size ? OriginalSize : Size);\n'
            CApp = CApp + '  Pcd     = (%s *)malloc (Size);\n' % (Pcd.DatumType)
            CApp = CApp + '  memset (Pcd, 0, Size);\n'

            #
            # Copy current PCD value into allocated buffer.
            #
            CApp = CApp + '  memcpy (Pcd, OriginalPcd, OriginalSize);\n'

            #
            # Assign field values in PCD
            #
            CApp = CApp + DscBuildData.GenerateDefaultValueAssignStatement(Pcd)
            if Pcd.Type not in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]:
                for skuname in self.SkuIdMgr.GetSkuChain(SkuName):
                    storeset = [DefaultStoreName] if DefaultStoreName == TAB_DEFAULT_STORES_DEFAULT else [TAB_DEFAULT_STORES_DEFAULT, DefaultStoreName]
                    for defaultstorenameitem in storeset:
                        CApp = CApp + "// SkuName: %s,  DefaultStoreName: %s \n" % (skuname, defaultstorenameitem)
                        CApp = CApp + DscBuildData.GenerateInitValueStatement(Pcd, skuname, defaultstorenameitem)
                    if skuname == SkuName:
                        break
            else:
                CApp = CApp + "// SkuName: %s,  DefaultStoreName: STANDARD \n" % self.SkuIdMgr.SystemSkuId
                CApp = CApp + DscBuildData.GenerateInitValueStatement(Pcd, self.SkuIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT)
            CApp = CApp + DscBuildData.GenerateFdfValueStatement(Pcd)
            CApp = CApp + DscBuildData.GenerateCommandLineValueStatement(Pcd)
            #
            # Set new PCD value and size
            #
            CApp = CApp + '  PcdSetPtr (%s, %s, %s, %s, Size, (UINT8 *)Pcd);\n' % (SkuName, DefaultStoreName, Pcd.TokenSpaceGuidCName, Pcd.TokenCName)

            #
            # Free PCD
            #
            CApp = CApp + '  free (Pcd);\n'
            CApp = CApp + '}\n'
            CApp = CApp + '\n'
        return InitByteValue, CApp
    def SkuOverrideValuesEmpty(self,OverrideValues):
        if not OverrideValues:
            return True
        for key in OverrideValues:
            if OverrideValues[key]:
                return False
        return True

    def GenerateByteArrayValue (self, StructuredPcds):
        #
        # Generate/Compile/Run C application to determine if there are any flexible array members
        #
        if not StructuredPcds:
            return

        InitByteValue = ""
        CApp = PcdMainCHeader

        IncludeFiles = set()
        for PcdName in StructuredPcds:
            Pcd = StructuredPcds[PcdName]
            for IncludeFile in Pcd.StructuredPcdIncludeFile:
                if IncludeFile not in IncludeFiles:
                    IncludeFiles.add(IncludeFile)
                    CApp = CApp + '#include <%s>\n' % (IncludeFile)
        CApp = CApp + '\n'
        for PcdName in StructuredPcds:
            Pcd = StructuredPcds[PcdName]
            CApp = CApp + self.GenerateSizeFunction(Pcd)
            CApp = CApp + self.GenerateDefaultValueAssignFunction(Pcd)
            CApp = CApp + self.GenerateFdfValue(Pcd)
            CApp = CApp + self.GenerateCommandLineValue(Pcd)
            if self.SkuOverrideValuesEmpty(Pcd.SkuOverrideValues) or Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]:
                CApp = CApp + self.GenerateInitValueFunction(Pcd, self.SkuIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT)
            else:
                for SkuName in self.SkuIdMgr.SkuOverrideOrder():
                    if SkuName not in Pcd.SkuOverrideValues:
                        continue
                    for DefaultStoreName in Pcd.SkuOverrideValues[SkuName]:
                        CApp = CApp + self.GenerateInitValueFunction(Pcd, SkuName, DefaultStoreName)
            if self.SkuOverrideValuesEmpty(Pcd.SkuOverrideValues) or Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD],
                        self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]:
                InitByteValue, CApp = self.GenerateInitializeFunc(self.SkuIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT, Pcd, InitByteValue, CApp)
            else:
                for SkuName in self.SkuIdMgr.SkuOverrideOrder():
                    if SkuName not in Pcd.SkuOverrideValues:
                        continue
                    for DefaultStoreName in Pcd.DefaultStoreName:
                        Pcd = StructuredPcds[PcdName]
                        InitByteValue, CApp = self.GenerateInitializeFunc(SkuName, DefaultStoreName, Pcd, InitByteValue, CApp)

        CApp = CApp + 'VOID\n'
        CApp = CApp + 'PcdEntryPoint(\n'
        CApp = CApp + '  VOID\n'
        CApp = CApp + '  )\n'
        CApp = CApp + '{\n'
        for Pcd in StructuredPcds.values():
            if self.SkuOverrideValuesEmpty(Pcd.SkuOverrideValues) or Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD], self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]:
                CApp = CApp + '  Initialize_%s_%s_%s_%s();\n' % (self.SkuIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT, Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
            else:
                for SkuName in self.SkuIdMgr.SkuOverrideOrder():
                    if SkuName not in self.SkuIdMgr.AvailableSkuIdSet:
                        continue
                    for DefaultStoreName in Pcd.SkuOverrideValues[SkuName]:
                        CApp = CApp + '  Initialize_%s_%s_%s_%s();\n' % (SkuName, DefaultStoreName, Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
        CApp = CApp + '}\n'

        CApp = CApp + PcdMainCEntry + '\n'

        if not os.path.exists(self.OutputPath):
            os.makedirs(self.OutputPath)
        CAppBaseFileName = os.path.join(self.OutputPath, PcdValueInitName)
        SaveFileOnChange(CAppBaseFileName + '.c', CApp, False)

        MakeApp = PcdMakefileHeader
        if sys.platform == "win32":
            MakeApp = MakeApp + 'APPNAME = %s\n' % (PcdValueInitName) + 'OBJECTS = %s\%s.obj\n' % (self.OutputPath, PcdValueInitName) + 'INC = '
        else:
            MakeApp = MakeApp + PcdGccMakefile
            MakeApp = MakeApp + 'APPNAME = %s\n' % (PcdValueInitName) + 'OBJECTS = %s/%s.o\n' % (self.OutputPath, PcdValueInitName) + \
                      'include $(MAKEROOT)/Makefiles/app.makefile\n' + 'INCLUDE +='

        IncSearchList = []
        PlatformInc = OrderedDict()
        for Cache in self._Bdb._CACHE_.values():
            if Cache.MetaFile.Ext.lower() != '.dec':
                continue
            if Cache.Includes:
                if str(Cache.MetaFile.Path) not in PlatformInc:
                    PlatformInc[str(Cache.MetaFile.Path)] = []
                    PlatformInc[str(Cache.MetaFile.Path)].append (os.path.dirname(Cache.MetaFile.Path))
                    PlatformInc[str(Cache.MetaFile.Path)].extend (Cache.CommonIncludes)

        PcdDependDEC = []
        for Pcd in StructuredPcds.values():
            for PackageDec in Pcd.PackageDecs:
                Package = os.path.normpath(mws.join(GlobalData.gWorkspace, PackageDec))
                if not os.path.exists(Package):
                    EdkLogger.error('Build', RESOURCE_NOT_AVAILABLE, "The dependent Package %s of PCD %s.%s is not exist." % (PackageDec, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))
                if Package not in PcdDependDEC:
                    PcdDependDEC.append(Package)

        if PlatformInc and PcdDependDEC:
            for pkg in PcdDependDEC:
                if pkg in PlatformInc:
                    for inc in PlatformInc[pkg]:
                        MakeApp += '-I'  + str(inc) + ' '
                        IncSearchList.append(inc)
        MakeApp = MakeApp + '\n'

        CC_FLAGS = LinuxCFLAGS
        if sys.platform == "win32":
            CC_FLAGS = WindowsCFLAGS
        BuildOptions = OrderedDict()
        for Options in self.BuildOptions:
            if Options[2] != EDKII_NAME:
                continue
            Family = Options[0]
            if Family and Family != self.ToolChainFamily:
                continue
            Target, Tag, Arch, Tool, Attr = Options[1].split("_")
            if Tool != 'CC':
                continue

            if Target == "*" or Target == self._Target:
                if Tag == "*" or Tag == self._Toolchain:
                    if Arch == "*" or Arch == self.Arch:
                        if Tool not in BuildOptions:
                            BuildOptions[Tool] = OrderedDict()
                        if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or self.BuildOptions[Options].startswith('='):
                            BuildOptions[Tool][Attr] = self.BuildOptions[Options]
                        else:
                            # append options for the same tool except PATH
                            if Attr != 'PATH':
                                BuildOptions[Tool][Attr] += " " + self.BuildOptions[Options]
                            else:
                                BuildOptions[Tool][Attr] = self.BuildOptions[Options]
        if BuildOptions:
            for Tool in BuildOptions:
                for Attr in BuildOptions[Tool]:
                    if Attr == "FLAGS":
                        Value = BuildOptions[Tool][Attr]
                        ValueList = Value.split()
                        if ValueList:
                            for Id, Item in enumerate(ValueList):
                                if Item in ['-D', '/D', '-U', '/U']:
                                    CC_FLAGS += ' ' + Item
                                    if Id + 1 < len(ValueList):
                                        CC_FLAGS += ' ' + ValueList[Id + 1]
                                elif Item.startswith(('-D', '/D', '-U', '/U')):
                                    CC_FLAGS += ' ' + Item
        MakeApp += CC_FLAGS

        if sys.platform == "win32":
            MakeApp = MakeApp + PcdMakefileEnd
        MakeApp = MakeApp + '\n'
        IncludeFileFullPaths = []
        for includefile in IncludeFiles:
            for includepath in IncSearchList:
                includefullpath = os.path.join(str(includepath), includefile)
                if os.path.exists(includefullpath):
                    IncludeFileFullPaths.append(os.path.normpath(includefullpath))
                    break
        SearchPathList = []
        SearchPathList.append(os.path.normpath(mws.join(GlobalData.gWorkspace, "BaseTools/Source/C/Include")))
        SearchPathList.append(os.path.normpath(mws.join(GlobalData.gWorkspace, "BaseTools/Source/C/Common")))
        SearchPathList.extend(str(item) for item in IncSearchList)
        IncFileList = GetDependencyList(IncludeFileFullPaths, SearchPathList)
        for include_file in IncFileList:
            MakeApp += "$(OBJECTS) : %s\n" % include_file
        MakeFileName = os.path.join(self.OutputPath, 'Makefile')
        MakeApp += "$(OBJECTS) : %s\n" % MakeFileName
        SaveFileOnChange(MakeFileName, MakeApp, False)

        InputValueFile = os.path.join(self.OutputPath, 'Input.txt')
        OutputValueFile = os.path.join(self.OutputPath, 'Output.txt')
        SaveFileOnChange(InputValueFile, InitByteValue, False)

        PcdValueInitExe = PcdValueInitName
        if not sys.platform == "win32":
            PcdValueInitExe = os.path.join(os.getenv("EDK_TOOLS_PATH"), 'Source', 'C', 'bin', PcdValueInitName)
        else:
            PcdValueInitExe = os.path.join(os.getenv("EDK_TOOLS_PATH"), 'Bin', 'Win32', PcdValueInitName) +".exe"

        Messages = ''
        if sys.platform == "win32":
            MakeCommand = 'nmake -f %s' % (MakeFileName)
            returncode, StdOut, StdErr = DscBuildData.ExecuteCommand (MakeCommand)
            Messages = StdOut
        else:
            MakeCommand = 'make -f %s' % (MakeFileName)
            returncode, StdOut, StdErr = DscBuildData.ExecuteCommand (MakeCommand)
            Messages = StdErr
        Messages = Messages.split('\n')
        MessageGroup = []
        if returncode != 0:
            CAppBaseFileName = os.path.join(self.OutputPath, PcdValueInitName)
            File = open (CAppBaseFileName + '.c', 'r')
            FileData = File.readlines()
            File.close()
            for Message in Messages:
                if " error" in Message or "warning" in Message:
                    FileInfo = Message.strip().split('(')
                    if len (FileInfo) > 1:
                        FileName = FileInfo [0]
                        FileLine = FileInfo [1].split (')')[0]
                    else:
                        FileInfo = Message.strip().split(':')
                        FileName = FileInfo [0]
                        FileLine = FileInfo [1]
                    if FileLine.isdigit():
                        error_line = FileData[int (FileLine) - 1]
                        if r"//" in error_line:
                            c_line, dsc_line = error_line.split(r"//")
                        else:
                            dsc_line = error_line
                        message_itmes = Message.split(":")
                        Index = 0
                        if "PcdValueInit.c" not in Message:
                            if not MessageGroup:
                                MessageGroup.append(Message)
                            break
                        else:
                            for item in message_itmes:
                                if "PcdValueInit.c" in item:
                                    Index = message_itmes.index(item)
                                    message_itmes[Index] = dsc_line.strip()
                                    break
                            MessageGroup.append(":".join(message_itmes[Index:]).strip())
                            continue
                    else:
                        MessageGroup.append(Message)
            if MessageGroup:
                EdkLogger.error("build", PCD_STRUCTURE_PCD_ERROR, "\n".join(MessageGroup) )
            else:
                EdkLogger.error('Build', COMMAND_FAILURE, 'Can not execute command: %s' % MakeCommand)

        if DscBuildData.NeedUpdateOutput(OutputValueFile, PcdValueInitExe, InputValueFile):
            Command = PcdValueInitExe + ' -i %s -o %s' % (InputValueFile, OutputValueFile)
            returncode, StdOut, StdErr = DscBuildData.ExecuteCommand (Command)
            if returncode != 0:
                EdkLogger.warn('Build', COMMAND_FAILURE, 'Can not collect output from command: %s' % Command)

        File = open (OutputValueFile, 'r')
        FileBuffer = File.readlines()
        File.close()

        StructurePcdSet = []
        for Pcd in FileBuffer:
            PcdValue = Pcd.split ('|')
            PcdInfo = PcdValue[0].split ('.')
            StructurePcdSet.append((PcdInfo[0], PcdInfo[1], PcdInfo[2], PcdInfo[3], PcdValue[2].strip()))
        return StructurePcdSet

    @staticmethod
    def NeedUpdateOutput(OutputFile, ValueCFile, StructureInput):
        if not os.path.exists(OutputFile):
            return True
        if os.stat(OutputFile).st_mtime <= os.stat(ValueCFile).st_mtime:
            return True
        if os.stat(OutputFile).st_mtime <= os.stat(StructureInput).st_mtime:
            return True
        return False

    ## Retrieve dynamic PCD settings
    #
    #   @param  Type    PCD type
    #
    #   @retval a dict object contains settings of given PCD type
    #
    def _GetDynamicPcd(self, Type):


        Pcds = OrderedDict()
        #
        # tdict is a special dict kind of type, used for selecting correct
        # PCD settings for certain ARCH and SKU
        #
        PcdDict = tdict(True, 4)
        PcdList = []
        # Find out all possible PCD candidates for self._Arch
        RecordList = self._RawData[Type, self._Arch]
        AvailableSkuIdSet = copy.copy(self.SkuIds)


        for TokenSpaceGuid, PcdCName, Setting, Arch, SkuName, Dummy3, Dummy4, Dummy5 in RecordList:
            SkuName = SkuName.upper()
            SkuName = TAB_DEFAULT if SkuName == TAB_COMMON else SkuName
            if SkuName not in AvailableSkuIdSet:
                EdkLogger.error('build', PARAMETER_INVALID, 'Sku %s is not defined in [SkuIds] section' % SkuName,
                                            File=self.MetaFile, Line=Dummy5)
            if "." not in TokenSpaceGuid:
                PcdList.append((PcdCName, TokenSpaceGuid, SkuName, Dummy5))
            PcdDict[Arch, SkuName, PcdCName, TokenSpaceGuid] = Setting

        # Remove redundant PCD candidates, per the ARCH and SKU
        for PcdCName, TokenSpaceGuid, SkuName, Dummy4 in PcdList:

            Setting = PcdDict[self._Arch, SkuName, PcdCName, TokenSpaceGuid]
            if Setting is None:
                continue

            PcdValue, DatumType, MaxDatumSize = self._ValidatePcd(PcdCName, TokenSpaceGuid, Setting, Type, Dummy4)
            if MaxDatumSize:
                if int(MaxDatumSize, 0) > 0xFFFF:
                    EdkLogger.error('build', FORMAT_INVALID, "The size value must not exceed the maximum value of 0xFFFF (UINT16) for %s." % ".".join((TokenSpaceGuid, PcdCName)),
                                    File=self.MetaFile, Line=Dummy4)
                if int(MaxDatumSize, 0) < 0:
                    EdkLogger.error('build', FORMAT_INVALID, "The size value can't be set to negative value for %s." % ".".join((TokenSpaceGuid, PcdCName)),
                                    File=self.MetaFile, Line=Dummy4)
            SkuInfo = SkuInfoClass(SkuName, self.SkuIds[SkuName][0], '', '', '', '', '', PcdValue)
            if (PcdCName, TokenSpaceGuid) in Pcds:
                pcdObject = Pcds[PcdCName, TokenSpaceGuid]
                pcdObject.SkuInfoList[SkuName] = SkuInfo
                if MaxDatumSize.strip():
                    CurrentMaxSize = int(MaxDatumSize.strip(), 0)
                else:
                    CurrentMaxSize = 0
                if pcdObject.MaxDatumSize:
                    PcdMaxSize = int(pcdObject.MaxDatumSize, 0)
                else:
                    PcdMaxSize = 0
                if CurrentMaxSize > PcdMaxSize:
                    pcdObject.MaxDatumSize = str(CurrentMaxSize)
            else:
                Pcds[PcdCName, TokenSpaceGuid] = PcdClassObject(
                                                    PcdCName,
                                                    TokenSpaceGuid,
                                                    self._PCD_TYPE_STRING_[Type],
                                                    DatumType,
                                                    PcdValue,
                                                    '',
                                                    MaxDatumSize,
                                                    OrderedDict({SkuName : SkuInfo}),
                                                    False,
                                                    None,
                                                    IsDsc=True)

            if SkuName not in Pcds[PcdCName, TokenSpaceGuid].DscRawValue:
                Pcds[PcdCName, TokenSpaceGuid].DscRawValue[SkuName] = {}
            Pcds[PcdCName, TokenSpaceGuid].DscRawValue[SkuName][TAB_DEFAULT_STORES_DEFAULT] = PcdValue

        for pcd in Pcds.values():
            pcdDecObject = self._DecPcds[pcd.TokenCName, pcd.TokenSpaceGuidCName]
            # Only fix the value while no value provided in DSC file.
            for sku in pcd.SkuInfoList.values():
                if not sku.DefaultValue:
                    sku.DefaultValue = pcdDecObject.DefaultValue
            if TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON not in pcd.SkuInfoList:
                valuefromDec = pcdDecObject.DefaultValue
                SkuInfo = SkuInfoClass(TAB_DEFAULT, '0', '', '', '', '', '', valuefromDec)
                pcd.SkuInfoList[TAB_DEFAULT] = SkuInfo
            elif TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                pcd.SkuInfoList[TAB_DEFAULT] = pcd.SkuInfoList[TAB_COMMON]
                del pcd.SkuInfoList[TAB_COMMON]
            elif TAB_DEFAULT in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                del pcd.SkuInfoList[TAB_COMMON]

        map(self.FilterSkuSettings, Pcds.values())

        return Pcds

    def FilterSkuSettings(self, PcdObj):

        if self.SkuIdMgr.SkuUsageType == self.SkuIdMgr.SINGLE:
            if TAB_DEFAULT in PcdObj.SkuInfoList and self.SkuIdMgr.SystemSkuId not in PcdObj.SkuInfoList:
                PcdObj.SkuInfoList[self.SkuIdMgr.SystemSkuId] = PcdObj.SkuInfoList[TAB_DEFAULT]
            PcdObj.SkuInfoList = {TAB_DEFAULT:PcdObj.SkuInfoList[self.SkuIdMgr.SystemSkuId]}
            PcdObj.SkuInfoList[TAB_DEFAULT].SkuIdName = TAB_DEFAULT
            PcdObj.SkuInfoList[TAB_DEFAULT].SkuId = '0'

        elif self.SkuIdMgr.SkuUsageType == self.SkuIdMgr.DEFAULT:
            PcdObj.SkuInfoList = {TAB_DEFAULT:PcdObj.SkuInfoList[TAB_DEFAULT]}

        return PcdObj

    @staticmethod
    def CompareVarAttr(Attr1, Attr2):
        if not Attr1 or not Attr2:  # for empty string
            return True
        Attr1s = [attr.strip() for attr in Attr1.split(",")]
        Attr1Set = set(Attr1s)
        Attr2s = [attr.strip() for attr in Attr2.split(",")]
        Attr2Set = set(Attr2s)
        if Attr2Set == Attr1Set:
            return True
        else:
            return False

    def CompletePcdValues(self, PcdSet):
        Pcds = OrderedDict()
        DefaultStoreObj = DefaultStore(self._GetDefaultStores())
        SkuIds = {skuname:skuid for skuname, skuid in self.SkuIdMgr.AvailableSkuIdSet.items() if skuname != TAB_COMMON}
        DefaultStores = set(storename for pcdobj in PcdSet.values() for skuobj in pcdobj.SkuInfoList.values() for storename in skuobj.DefaultStoreDict)
        for PcdCName, TokenSpaceGuid in PcdSet:
            PcdObj = PcdSet[(PcdCName, TokenSpaceGuid)]

            if PcdObj.Type not in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_DEFAULT],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_VPD],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_DEFAULT],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII],
                        self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_VPD]]:
                Pcds[PcdCName, TokenSpaceGuid]= PcdObj
                continue
            PcdType = PcdObj.Type
            if PcdType in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                for skuid in PcdObj.SkuInfoList:
                    skuobj = PcdObj.SkuInfoList[skuid]
                    mindefaultstorename = DefaultStoreObj.GetMin(set(defaultstorename for defaultstorename in skuobj.DefaultStoreDict))
                    for defaultstorename in DefaultStores:
                        if defaultstorename not in skuobj.DefaultStoreDict:
                            skuobj.DefaultStoreDict[defaultstorename] = copy.deepcopy(skuobj.DefaultStoreDict[mindefaultstorename])
                    skuobj.HiiDefaultValue = skuobj.DefaultStoreDict[mindefaultstorename]
            for skuname, skuid in SkuIds.items():
                if skuname not in PcdObj.SkuInfoList:
                    nextskuid = self.SkuIdMgr.GetNextSkuId(skuname)
                    while nextskuid not in PcdObj.SkuInfoList:
                        nextskuid = self.SkuIdMgr.GetNextSkuId(nextskuid)
                    PcdObj.SkuInfoList[skuname] = copy.deepcopy(PcdObj.SkuInfoList[nextskuid])
                    PcdObj.SkuInfoList[skuname].SkuId = skuid
                    PcdObj.SkuInfoList[skuname].SkuIdName = skuname
            if PcdType in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]:
                PcdObj.DefaultValue = PcdObj.SkuInfoList.values()[0].HiiDefaultValue if self.SkuIdMgr.SkuUsageType == self.SkuIdMgr.SINGLE else PcdObj.SkuInfoList[TAB_DEFAULT].HiiDefaultValue
            Pcds[PcdCName, TokenSpaceGuid]= PcdObj
        return Pcds
    ## Retrieve dynamic HII PCD settings
    #
    #   @param  Type    PCD type
    #
    #   @retval a dict object contains settings of given PCD type
    #
    def _GetDynamicHiiPcd(self, Type):

        VariableAttrs = {}

        Pcds = OrderedDict()
        UserDefinedDefaultStores = []
        #
        # tdict is a special dict kind of type, used for selecting correct
        # PCD settings for certain ARCH and SKU
        #
        PcdDict = tdict(True, 5)
        PcdSet = set()
        RecordList = self._RawData[Type, self._Arch]
        # Find out all possible PCD candidates for self._Arch
        AvailableSkuIdSet = copy.copy(self.SkuIds)
        DefaultStoresDefine = self._GetDefaultStores()

        for TokenSpaceGuid, PcdCName, Setting, Arch, SkuName, DefaultStore, Dummy4, Dummy5 in RecordList:
            SkuName = SkuName.upper()
            SkuName = TAB_DEFAULT if SkuName == TAB_COMMON else SkuName
            DefaultStore = DefaultStore.upper()
            if DefaultStore == TAB_COMMON:
                DefaultStore = TAB_DEFAULT_STORES_DEFAULT
            else:
                #The end user define [DefaultStores] and [SKUID_IDENTIFIER.Menufacturing] in DSC
                UserDefinedDefaultStores.append((PcdCName, TokenSpaceGuid))
            if SkuName not in AvailableSkuIdSet:
                EdkLogger.error('build', PARAMETER_INVALID, 'Sku %s is not defined in [SkuIds] section' % SkuName,
                                            File=self.MetaFile, Line=Dummy5)
            if DefaultStore not in DefaultStoresDefine:
                EdkLogger.error('build', PARAMETER_INVALID, 'DefaultStores %s is not defined in [DefaultStores] section' % DefaultStore,
                                            File=self.MetaFile, Line=Dummy5)
            if "." not in TokenSpaceGuid:
                PcdSet.add((PcdCName, TokenSpaceGuid, SkuName, DefaultStore, Dummy5))
            PcdDict[Arch, SkuName, PcdCName, TokenSpaceGuid, DefaultStore] = Setting


        # Remove redundant PCD candidates, per the ARCH and SKU
        for PcdCName, TokenSpaceGuid, SkuName, DefaultStore, Dummy4 in PcdSet:

            Setting = PcdDict[self._Arch, SkuName, PcdCName, TokenSpaceGuid, DefaultStore]
            if Setting is None:
                continue
            VariableName, VariableGuid, VariableOffset, DefaultValue, VarAttribute = self._ValidatePcd(PcdCName, TokenSpaceGuid, Setting, Type, Dummy4)

            rt, Msg = VariableAttributes.ValidateVarAttributes(VarAttribute)
            if not rt:
                EdkLogger.error("build", PCD_VARIABLE_ATTRIBUTES_ERROR, "Variable attributes settings for %s is incorrect.\n %s" % (".".join((TokenSpaceGuid, PcdCName)), Msg),
                        ExtraData="[%s]" % VarAttribute)
            ExceedMax = False
            FormatCorrect = True
            if VariableOffset.isdigit():
                if int(VariableOffset, 10) > 0xFFFF:
                    ExceedMax = True
            elif variablePattern.match(VariableOffset):
                if int(VariableOffset, 16) > 0xFFFF:
                    ExceedMax = True
            # For Offset written in "A.B"
            elif VariableOffset.find('.') > -1:
                VariableOffsetList = VariableOffset.split(".")
                if not (len(VariableOffsetList) == 2
                        and IsValidWord(VariableOffsetList[0])
                        and IsValidWord(VariableOffsetList[1])):
                    FormatCorrect = False
            else:
                FormatCorrect = False
            if not FormatCorrect:
                EdkLogger.error('Build', FORMAT_INVALID, "Invalid syntax or format of the variable offset value is incorrect for %s." % ".".join((TokenSpaceGuid, PcdCName)))

            if ExceedMax:
                EdkLogger.error('Build', OPTION_VALUE_INVALID, "The variable offset value must not exceed the maximum value of 0xFFFF (UINT16) for %s." % ".".join((TokenSpaceGuid, PcdCName)))
            if (VariableName, VariableGuid) not in VariableAttrs:
                VariableAttrs[(VariableName, VariableGuid)] = VarAttribute
            else:
                if not DscBuildData.CompareVarAttr(VariableAttrs[(VariableName, VariableGuid)], VarAttribute):
                    EdkLogger.error('Build', PCD_VARIABLE_ATTRIBUTES_CONFLICT_ERROR, "The variable %s.%s for DynamicHii PCDs has conflicting attributes [%s] and [%s] " % (VariableGuid, VariableName, VarAttribute, VariableAttrs[(VariableName, VariableGuid)]))

            pcdDecObject = self._DecPcds[PcdCName, TokenSpaceGuid]
            if (PcdCName, TokenSpaceGuid) in Pcds:
                pcdObject = Pcds[PcdCName, TokenSpaceGuid]
                if SkuName in pcdObject.SkuInfoList:
                    Skuitem = pcdObject.SkuInfoList[SkuName]
                    Skuitem.DefaultStoreDict.update({DefaultStore:DefaultValue})
                else:
                    SkuInfo = SkuInfoClass(SkuName, self.SkuIds[SkuName][0], VariableName, VariableGuid, VariableOffset, DefaultValue, VariableAttribute=VarAttribute, DefaultStore={DefaultStore:DefaultValue})
                    pcdObject.SkuInfoList[SkuName] = SkuInfo
            else:
                SkuInfo = SkuInfoClass(SkuName, self.SkuIds[SkuName][0], VariableName, VariableGuid, VariableOffset, DefaultValue, VariableAttribute=VarAttribute, DefaultStore={DefaultStore:DefaultValue})
                PcdClassObj = PcdClassObject(
                                                PcdCName,
                                                TokenSpaceGuid,
                                                self._PCD_TYPE_STRING_[Type],
                                                '',
                                                DefaultValue,
                                                '',
                                                '',
                                                OrderedDict({SkuName : SkuInfo}),
                                                False,
                                                None,
                                                pcdDecObject.validateranges,
                                                pcdDecObject.validlists,
                                                pcdDecObject.expressions,
                                                IsDsc=True)
                if (PcdCName, TokenSpaceGuid) in UserDefinedDefaultStores:
                    PcdClassObj.UserDefinedDefaultStoresFlag = True
                Pcds[PcdCName, TokenSpaceGuid] = PcdClassObj

                Pcds[PcdCName, TokenSpaceGuid].CustomAttribute['DscPosition'] = int(Dummy4)
            if SkuName not in Pcds[PcdCName, TokenSpaceGuid].DscRawValue:
                Pcds[PcdCName, TokenSpaceGuid].DscRawValue[SkuName] = {}
            Pcds[PcdCName, TokenSpaceGuid].DscRawValue[SkuName][DefaultStore] = DefaultValue
        for pcd in Pcds.values():
            SkuInfoObj = pcd.SkuInfoList.values()[0]
            pcdDecObject = self._DecPcds[pcd.TokenCName, pcd.TokenSpaceGuidCName]
            pcd.DatumType = pcdDecObject.DatumType
            # Only fix the value while no value provided in DSC file.
            for sku in pcd.SkuInfoList.values():
                if (sku.HiiDefaultValue == "" or sku.HiiDefaultValue is None):
                    sku.HiiDefaultValue = pcdDecObject.DefaultValue
                    for default_store in sku.DefaultStoreDict:
                        sku.DefaultStoreDict[default_store]=pcdDecObject.DefaultValue
                    pcd.DefaultValue = pcdDecObject.DefaultValue
            if TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON not in pcd.SkuInfoList:
                valuefromDec = pcdDecObject.DefaultValue
                SkuInfo = SkuInfoClass(TAB_DEFAULT, '0', SkuInfoObj.VariableName, SkuInfoObj.VariableGuid, SkuInfoObj.VariableOffset, valuefromDec, VariableAttribute=SkuInfoObj.VariableAttribute, DefaultStore={DefaultStore:valuefromDec})
                pcd.SkuInfoList[TAB_DEFAULT] = SkuInfo
            elif TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                pcd.SkuInfoList[TAB_DEFAULT] = pcd.SkuInfoList[TAB_COMMON]
                del pcd.SkuInfoList[TAB_COMMON]
            elif TAB_DEFAULT in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                del pcd.SkuInfoList[TAB_COMMON]

            if pcd.MaxDatumSize.strip():
                MaxSize = int(pcd.MaxDatumSize, 0)
            else:
                MaxSize = 0
            if pcd.DatumType not in TAB_PCD_NUMERIC_TYPES:
                for (_, skuobj) in pcd.SkuInfoList.items():
                    datalen = 0
                    skuobj.HiiDefaultValue = StringToArray(skuobj.HiiDefaultValue)
                    datalen = len(skuobj.HiiDefaultValue.split(","))
                    if datalen > MaxSize:
                        MaxSize = datalen
                    for defaultst in skuobj.DefaultStoreDict:
                        skuobj.DefaultStoreDict[defaultst] = StringToArray(skuobj.DefaultStoreDict[defaultst])
                pcd.DefaultValue = StringToArray(pcd.DefaultValue)
                pcd.MaxDatumSize = str(MaxSize)
        rt, invalidhii = DscBuildData.CheckVariableNameAssignment(Pcds)
        if not rt:
            invalidpcd = ",".join(invalidhii)
            EdkLogger.error('build', PCD_VARIABLE_INFO_ERROR, Message='The same HII PCD must map to the same EFI variable for all SKUs', File=self.MetaFile, ExtraData=invalidpcd)

        map(self.FilterSkuSettings, Pcds.values())

        return Pcds

    @staticmethod
    def CheckVariableNameAssignment(Pcds):
        invalidhii = []
        for pcdname in Pcds:
            pcd = Pcds[pcdname]
            varnameset = set(sku.VariableName for (skuid, sku) in pcd.SkuInfoList.items())
            if len(varnameset) > 1:
                invalidhii.append(".".join((pcdname[1], pcdname[0])))
        if len(invalidhii):
            return False, invalidhii
        else:
            return True, []
    ## Retrieve dynamic VPD PCD settings
    #
    #   @param  Type    PCD type
    #
    #   @retval a dict object contains settings of given PCD type
    #
    def _GetDynamicVpdPcd(self, Type):


        Pcds = OrderedDict()
        #
        # tdict is a special dict kind of type, used for selecting correct
        # PCD settings for certain ARCH and SKU
        #
        PcdDict = tdict(True, 4)
        PcdList = []

        # Find out all possible PCD candidates for self._Arch
        RecordList = self._RawData[Type, self._Arch]
        AvailableSkuIdSet = copy.copy(self.SkuIds)

        for TokenSpaceGuid, PcdCName, Setting, Arch, SkuName, Dummy3, Dummy4, Dummy5 in RecordList:
            SkuName = SkuName.upper()
            SkuName = TAB_DEFAULT if SkuName == TAB_COMMON else SkuName
            if SkuName not in AvailableSkuIdSet:
                EdkLogger.error('build', PARAMETER_INVALID, 'Sku %s is not defined in [SkuIds] section' % SkuName,
                                            File=self.MetaFile, Line=Dummy5)
            if "." not in TokenSpaceGuid:
                PcdList.append((PcdCName, TokenSpaceGuid, SkuName, Dummy5))
            PcdDict[Arch, SkuName, PcdCName, TokenSpaceGuid] = Setting

        # Remove redundant PCD candidates, per the ARCH and SKU
        for PcdCName, TokenSpaceGuid, SkuName, Dummy4 in PcdList:
            Setting = PcdDict[self._Arch, SkuName, PcdCName, TokenSpaceGuid]
            if Setting is None:
                continue
            #
            # For the VOID* type, it can have optional data of MaxDatumSize and InitialValue
            # For the Integer & Boolean type, the optional data can only be InitialValue.
            # At this point, we put all the data into the PcdClssObject for we don't know the PCD's datumtype
            # until the DEC parser has been called.
            #
            VpdOffset, MaxDatumSize, InitialValue = self._ValidatePcd(PcdCName, TokenSpaceGuid, Setting, Type, Dummy4)
            if MaxDatumSize:
                if int(MaxDatumSize, 0) > 0xFFFF:
                    EdkLogger.error('build', FORMAT_INVALID, "The size value must not exceed the maximum value of 0xFFFF (UINT16) for %s." % ".".join((TokenSpaceGuid, PcdCName)),
                                    File=self.MetaFile, Line=Dummy4)
                if int(MaxDatumSize, 0) < 0:
                    EdkLogger.error('build', FORMAT_INVALID, "The size value can't be set to negative value for %s." % ".".join((TokenSpaceGuid, PcdCName)),
                                    File=self.MetaFile, Line=Dummy4)
            SkuInfo = SkuInfoClass(SkuName, self.SkuIds[SkuName][0], '', '', '', '', VpdOffset, InitialValue)
            if (PcdCName, TokenSpaceGuid) in Pcds:
                pcdObject = Pcds[PcdCName, TokenSpaceGuid]
                pcdObject.SkuInfoList[SkuName] = SkuInfo
                if MaxDatumSize.strip():
                    CurrentMaxSize = int(MaxDatumSize.strip(), 0)
                else:
                    CurrentMaxSize = 0
                if pcdObject.MaxDatumSize:
                    PcdMaxSize = int(pcdObject.MaxDatumSize, 0)
                else:
                    PcdMaxSize = 0
                if CurrentMaxSize > PcdMaxSize:
                    pcdObject.MaxDatumSize = str(CurrentMaxSize)
            else:
                Pcds[PcdCName, TokenSpaceGuid] = PcdClassObject(
                                                PcdCName,
                                                TokenSpaceGuid,
                                                self._PCD_TYPE_STRING_[Type],
                                                '',
                                                InitialValue,
                                                '',
                                                MaxDatumSize,
                                                OrderedDict({SkuName : SkuInfo}),
                                                False,
                                                None,
                                                IsDsc=True)

            if SkuName not in Pcds[PcdCName, TokenSpaceGuid].DscRawValue:
                Pcds[PcdCName, TokenSpaceGuid].DscRawValue[SkuName] = {}
            Pcds[PcdCName, TokenSpaceGuid].DscRawValue[SkuName][TAB_DEFAULT_STORES_DEFAULT] = InitialValue
        for pcd in Pcds.values():
            SkuInfoObj = pcd.SkuInfoList.values()[0]
            pcdDecObject = self._DecPcds[pcd.TokenCName, pcd.TokenSpaceGuidCName]
            pcd.DatumType = pcdDecObject.DatumType
            # Only fix the value while no value provided in DSC file.
            for sku in pcd.SkuInfoList.values():
                if not sku.DefaultValue:
                    sku.DefaultValue = pcdDecObject.DefaultValue
            if TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON not in pcd.SkuInfoList:
                valuefromDec = pcdDecObject.DefaultValue
                SkuInfo = SkuInfoClass(TAB_DEFAULT, '0', '', '', '', '', SkuInfoObj.VpdOffset, valuefromDec)
                pcd.SkuInfoList[TAB_DEFAULT] = SkuInfo
            elif TAB_DEFAULT not in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                pcd.SkuInfoList[TAB_DEFAULT] = pcd.SkuInfoList[TAB_COMMON]
                del pcd.SkuInfoList[TAB_COMMON]
            elif TAB_DEFAULT in pcd.SkuInfoList and TAB_COMMON in pcd.SkuInfoList:
                del pcd.SkuInfoList[TAB_COMMON]


        map(self.FilterSkuSettings, Pcds.values())
        return Pcds

    ## Add external modules
    #
    #   The external modules are mostly those listed in FDF file, which don't
    # need "build".
    #
    #   @param  FilePath    The path of module description file
    #
    def AddModule(self, FilePath):
        FilePath = NormPath(FilePath)
        if FilePath not in self.Modules:
            Module = ModuleBuildClassObject()
            Module.MetaFile = FilePath
            self.Modules.append(Module)

    @property
    def ToolChainFamily(self):
        self._ToolChainFamily = TAB_COMPILER_MSFT
        BuildConfigurationFile = os.path.normpath(os.path.join(GlobalData.gConfDirectory, "target.txt"))
        if os.path.isfile(BuildConfigurationFile) == True:
            TargetTxt      = TargetTxtClassObject()
            TargetTxt.LoadTargetTxtFile(BuildConfigurationFile)
            ToolDefinitionFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF]
            if ToolDefinitionFile == '':
                ToolDefinitionFile = "tools_def.txt"
                ToolDefinitionFile = os.path.normpath(mws.join(self.WorkspaceDir, 'Conf', ToolDefinitionFile))
            if os.path.isfile(ToolDefinitionFile) == True:
                ToolDef        = ToolDefClassObject()
                ToolDef.LoadToolDefFile(ToolDefinitionFile)
                ToolDefinition = ToolDef.ToolsDefTxtDatabase
                if TAB_TOD_DEFINES_FAMILY not in ToolDefinition \
                   or self._Toolchain not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \
                   or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][self._Toolchain]:
                    self._ToolChainFamily = TAB_COMPILER_MSFT
                else:
                    self._ToolChainFamily = ToolDefinition[TAB_TOD_DEFINES_FAMILY][self._Toolchain]
        return self._ToolChainFamily

    ## Add external PCDs
    #
    #   The external PCDs are mostly those listed in FDF file to specify address
    # or offset information.
    #
    #   @param  Name    Name of the PCD
    #   @param  Guid    Token space guid of the PCD
    #   @param  Value   Value of the PCD
    #
    def AddPcd(self, Name, Guid, Value):
        if (Name, Guid) not in self.Pcds:
            self.Pcds[Name, Guid] = PcdClassObject(Name, Guid, '', '', '', '', '', {}, False, None)
        self.Pcds[Name, Guid].DefaultValue = Value

    @property
    def DecPcds(self):
        if self._DecPcds is None:
            FdfInfList = []
            if GlobalData.gFdfParser:
                FdfInfList = GlobalData.gFdfParser.Profile.InfList
            PkgSet = set()
            for Inf in FdfInfList:
                ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch=self._Arch)
                if ModuleFile in self._Modules:
                    continue
                ModuleData = self._Bdb[ModuleFile, self._Arch, self._Target, self._Toolchain]
                PkgSet.update(ModuleData.Packages)
            self._DecPcds, self._GuidDict = GetDeclaredPcd(self, self._Bdb, self._Arch, self._Target, self._Toolchain, PkgSet)
            self._GuidDict.update(GlobalData.gPlatformPcds)
        return self._DecPcds