summaryrefslogtreecommitdiffstats
path: root/src/usr/targeting/common/xmltohb/xmltohb.pl
blob: 98392becc7cb486921a042a6101ffe071433cc45 (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
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# $Source: src/usr/targeting/common/xmltohb/xmltohb.pl $ 
#  
# IBM CONFIDENTIAL 
#  
# COPYRIGHT International Business Machines Corp. 2011,2012 
#  
# p1 
#  
# Object Code Only (OCO) source materials 
# Licensed Internal Code Source Materials 
# IBM HostBoot Licensed Internal Code 
#  
# The source code for this program is not published or otherwise 
# divested of its trade secrets, irrespective of what has been 
# deposited with the U.S. Copyright Office. 
#  
# Origin: 30 
#  
# IBM_PROLOG_END_TAG 

#
# Purpose:
# Author: Nick Bofferding
# Last Updated: 09/09/2011
#
# Version: 1.0
#
# Change Log **********************************************************
#
# End Change Log ******************************************************

use strict;

################################################################################
# Use of the following packages
################################################################################

use Getopt::Long;
use Pod::Usage;
use XML::Simple;
use Text::Wrap;
use Data::Dumper;
use POSIX;

################################################################################
# Set PREFERRED_PARSER to XML::Parser. Otherwise it uses XML::SAX which contains
# bugs that result in XML parse errors that can be fixed by adjusting white-
# space (i.e. parse errors that do not make sense).
################################################################################
$XML::Simple::PREFERRED_PARSER = 'XML::Parser';

################################################################################
# Process command line parameters, issue help text if needed
################################################################################

sub main{ }
my $cfgSrcOutputDir = ".";
my $cfgImgOutputDir = ".";
my $cfgHbXmlFile = "./hb.xml";
my $cfgVmmConstsFile = "../../../include/usr/vmmconst.h";
my $cfgFapiAttributesXmlFile = "";
my $cfgImgOutputFile = "./targeting.bin";
my $cfgHelp = 0;
my $cfgMan = 0;
my $cfgVerbose = 0;
my $cfgShortEnums = 0;
my $cfgBigEndian = 1;
my $cfgIncludeFspAttributes = 0;

GetOptions("hb-xml-file:s" => \$cfgHbXmlFile,
           "src-output-dir:s" =>  \$cfgSrcOutputDir,
           "img-output-dir:s" =>  \$cfgImgOutputDir,
           "fapi-attributes-xml-file:s" => \$cfgFapiAttributesXmlFile,
           "img-output-file:s" =>  \$cfgImgOutputFile,
           "vmm-consts-file:s" =>  \$cfgVmmConstsFile,
           "short-enums!" =>  \$cfgShortEnums,
           "big-endian!" =>  \$cfgBigEndian,
           "include-fsp-attributes!" =>  \$cfgIncludeFspAttributes,
           "help" => \$cfgHelp,
           "man" => \$cfgMan,
           "verbose" => \$cfgVerbose ) || pod2usage(-verbose => 0);

pod2usage(-verbose => 1) if $cfgHelp;
pod2usage(-verbose => 2) if $cfgMan;

# Remove extraneous '/' from end of path names; use temporary version of $/ for
# the chomp
{
    local $/ = '/';
    chomp($cfgSrcOutputDir);
    $cfgSrcOutputDir .= "/";

    chomp($cfgImgOutputDir);
    $cfgImgOutputDir .= "/";
}

if($cfgVerbose)
{
    print STDOUT "Host boot intemediate XML model = $cfgHbXmlFile\n";
    print STDOUT "Fapi attributes XML file = $cfgFapiAttributesXmlFile\n";
    print STDOUT "Source output dir = $cfgSrcOutputDir\n";
    print STDOUT "Image output dir = $cfgImgOutputDir\n";
    print STDOUT "VMM constants file = $cfgVmmConstsFile\n";
    print STDOUT "Short enums = $cfgShortEnums\n";
    print STDOUT "Big endian = $cfgBigEndian\n";
    print STDOUT "include-fsp-attributes = $cfgIncludeFspAttributes\n",
}

################################################################################
# Initialize some globals
################################################################################

my $xml = new XML::Simple (KeyAttr=>[]);

# Until full machine parseable workbook parsing splits out all the input files,
# use the intermediate representation containing the full host boot model.
# Aborts application if file name not found.
my $attributes = $xml->XMLin($cfgHbXmlFile,
    forcearray => ['enumerationType','attribute','hwpfToHbAttrMap']);
my $fapiAttributes = {};
if ($cfgFapiAttributesXmlFile ne "")
{
    $fapiAttributes = $xml->XMLin($cfgFapiAttributesXmlFile,
        forcearray => ['attribute']);
}
# save attributes defined as Target_t type
my %Target_t = ();

# Perform some sanity validation of the model (so we don't have to later)
validateAttributes($attributes);
validateTargetInstances($attributes);
validateTargetTypes($attributes);
validateTargetTypesExtension($attributes);
handleTgtPtrAttributes(\$attributes, \%Target_t);

# Open the output files and write them
if( !($cfgSrcOutputDir =~ "none") )
{
    open(TRAIT_FILE,">$cfgSrcOutputDir"."attributetraits.H")
      or fatal ("Trait file: \"$cfgSrcOutputDir"
        . "attributetraits.H\" could not be opened.");
    my $traitFile = *TRAIT_FILE;
    writeTraitFileHeader($traitFile);
    writeTraitFileTraits($attributes,$traitFile);
    writeTraitFileFooter($traitFile);
    close $traitFile;

    open(ATTR_FILE,">$cfgSrcOutputDir"."attributeenums.H")
      or fatal ("Attribute enum file: \"$cfgSrcOutputDir"
        . "attributeenums.H\" could not be opened.");
    my $enumFile = *ATTR_FILE;
    writeEnumFileHeader($enumFile);
    writeEnumFileAttrIdEnum($attributes,$enumFile);
    writeEnumFileAttrEnums($attributes,$enumFile);
    writeEnumFileFooter($enumFile);
    close $enumFile;

    open(STRING_HEADER_FILE,">$cfgSrcOutputDir"."attributestrings.H")
      or fatal ("Attribute string header file: \"$cfgSrcOutputDir"
        . "attributestrings.H\" could not be opened.");
    my $stringHeaderFile = *STRING_HEADER_FILE;
    writeStringHeaderFileHeader($stringHeaderFile);
    writeStringHeaderFileStrings($attributes,$stringHeaderFile);
    writeStringHeaderFileFooter($stringHeaderFile);
    close $stringHeaderFile;

    open(STRING_IMPLEMENTATION_FILE,">$cfgSrcOutputDir"."attributestrings.C")
      or fatal ("Attribute string source file: \"$cfgSrcOutputDir"
        . "attributestrings.C\" could not be opened.");
    my $stringImplementationFile = *STRING_IMPLEMENTATION_FILE;
    writeStringImplementationFileHeader($stringImplementationFile);
    writeStringImplementationFileStrings($attributes,$stringImplementationFile);
    writeStringImplementationFileFooter($stringImplementationFile);
    close $stringImplementationFile;

    open(STRUCTS_HEADER_FILE,">$cfgSrcOutputDir"."attributestructs.H")
      or fatal ("Attribute struct file: \"$cfgSrcOutputDir"
        . "attributestructs.H\" could not be opened.");
    my $structFile = *STRUCTS_HEADER_FILE;
    writeStructFileHeader($structFile);
    writeStructFileStructs($attributes,$structFile);
    writeStructFileFooter($structFile);
    close $structFile;

    open(PNOR_HEADER_DEF_FILE,">$cfgSrcOutputDir"."pnortargeting.H")
      or fatal ("Targeting header definition header file: \"$cfgSrcOutputDir"
        . "pnortargeting.H\" could not be opened.");
    my $pnorHeaderDefFile = *PNOR_HEADER_DEF_FILE;
    writeHeaderFormatHeaderFile($pnorHeaderDefFile);
    close $pnorHeaderDefFile;

    open(FAPI_PLAT_ATTR_MACROS_FILE,">$cfgSrcOutputDir"."fapiplatattrmacros.H")
      or fatal ("FAPI platform attribute macro header file: \"$cfgSrcOutputDir"
        . "fapiplatattrmacros.H\" could not be opened.");
    my $fapiPlatAttrMacrosHeaderFile = *FAPI_PLAT_ATTR_MACROS_FILE;
    writeFapiPlatAttrMacrosHeaderFileHeader ($fapiPlatAttrMacrosHeaderFile);
    writeFapiPlatAttrMacrosHeaderFileContent($attributes,$fapiAttributes,
        $fapiPlatAttrMacrosHeaderFile);
    writeFapiPlatAttrMacrosHeaderFileFooter ($fapiPlatAttrMacrosHeaderFile);
    close $fapiPlatAttrMacrosHeaderFile;

    #fixme-Remove when RTC:38197 is done
    open(ATTR_DUMP_FILE,">$cfgSrcOutputDir"."attributedump.C")
      or fatal ("Attribute dump file: \"$cfgSrcOutputDir"
		. "attributedump.C\" could not be opened.");
    my $dumpFile = *ATTR_DUMP_FILE;
    writeDumpFile($attributes,$dumpFile);
    close $dumpFile;

    open(ATTR_ATTRERRL_C_FILE,">$cfgSrcOutputDir"."errludattribute.C")
      or fatal ("Attribute errlog C file: \"$cfgSrcOutputDir"
		. "errludattribute.C\" could not be opened.");
    my $attrErrlCFile = *ATTR_ATTRERRL_C_FILE;
    writeAttrErrlCFile($attributes,$attrErrlCFile);
    close $attrErrlCFile;

    open(ATTR_ATTRERRL_H_FILE,">$cfgSrcOutputDir"."errludattribute.H")
      or fatal ("Attribute errlog H file: \"$cfgSrcOutputDir"
		. "errludattribute.H\" could not be opened.");
    my $attrErrlHFile = *ATTR_ATTRERRL_H_FILE;
    writeAttrErrlHFile($attributes,$attrErrlHFile);
    close $attrErrlHFile;

}

if( !($cfgImgOutputDir =~ "none") )
{
    my $Data = generateTargetingImage($cfgVmmConstsFile,$attributes,\%Target_t);

    open(PNOR_TARGETING_FILE,">$cfgImgOutputDir".$cfgImgOutputFile)
      or fatal ("Targeting image file: \"$cfgImgOutputDir"
        . "$cfgImgOutputFile\" could not be opened.");
    binmode(PNOR_TARGETING_FILE);
    print PNOR_TARGETING_FILE "$Data";
    close(PNOR_TARGETING_FILE);
}

exit(0);

################################################################################
# Report a fatal error and quit
################################################################################

sub DEBUG_FUNCTIONS { }
sub fatal {
    my($msg) = @_;

    print STDERR "[FATAL!] $msg\n";

    for(my $caller = 1; ; $caller++)
    {
        my ($package, $filename, $callerLine,
            $subr, $has_args, $wantarray )= caller($caller);
        my $line = (caller($caller-1))[2];
        if(!$line) { last; }

        print STDERR "     $caller: $subr" . "(". $line . ")\n";
    }

    exit(1);
}

sub VALIDATION_FUNCTIONS { }

################################################################################
# Validates sub-elements of an element against criteria
################################################################################

sub validateSubElements {
    my($name,$mustBeHash,$element,$criteria) = @_;

    if($mustBeHash && (ref($element) ne "HASH"))
    {
        print "name=$name, mustBeHash=$mustBeHash, element=$element, criteria=$criteria \n";
        fatal("$name must be in the form of a hash.");
    }

    # print keys %{$element} . "\n";

    for my $subElementName (sort(keys %{$element}))
    {
        if(!exists $criteria->{$subElementName})
        {
            fatal("$name element cannot have child element of type "
                  . "\"$subElementName\".");
        }
    }

    for my $subElementName (sort(keys %{$criteria}))
    {
        if(   ($criteria->{$subElementName}{required} == 1)
           && (!exists $element->{$subElementName}))
        {
            fatal("$name element missing required child element "
                  . "\"$subElementName\".");
        }

        if(exists $element->{$subElementName}
           && ($criteria->{$subElementName}{isscalar} == 1)
             && (ref ($element->{$subElementName}) eq "HASH"))
        {
            fatal("$name element child element \"$subElementName\" should be "
                  . "scalar, but is a hash.");
        }
    }
}


################################################################################
# Validates attribute element for correctness
################################################################################

sub validateAttributes {
    my($attributes) = @_;

    my %elements = ( );
    $elements{"id"}          = { required => 1, isscalar => 1};
    $elements{"description"} = { required => 1, isscalar => 1};
    $elements{"persistency"} = { required => 1, isscalar => 1};
    $elements{"fspOnly"}     = { required => 0, isscalar => 0};
    $elements{"hbOnly"}      = { required => 0, isscalar => 0};
    $elements{"readable"}    = { required => 0, isscalar => 0};
    $elements{"simpleType"}  = { required => 0, isscalar => 0};
    $elements{"complexType"} = { required => 0, isscalar => 0};
    $elements{"nativeType"}  = { required => 0, isscalar => 0};
    $elements{"writeable"}   = { required => 0, isscalar => 0};
    $elements{"hasStringConversion"}
                             = { required => 0, isscalar => 0};
    $elements{"hwpfToHbAttrMap"}
                             = { required => 0, isscalar => 0};

    foreach my $attribute (@{$attributes->{attribute}})
    {
        validateSubElements("attribute",1,$attribute,\%elements);
    }
}

################################################################################
# Validates field element for correctness
################################################################################

sub validateFieldElement {
    my($field) = @_;

    my %elements = ( );
    $elements{"type"}        = { required => 1, isscalar => 1};
    $elements{"name"}        = { required => 1, isscalar => 1};
    $elements{"description"} = { required => 1, isscalar => 1};
    $elements{"default"}     = { required => 1, isscalar => 1};
    $elements{"bits"}        = { required => 0, isscalar => 1};

    validateSubElements("field",1,$field,\%elements);
}

################################################################################
# Validates target type extension elements for correctness
################################################################################

sub validateTargetTypesExtension {
    my($attributes) = @_;

    my %elements = ( );
    $elements{"id"}          = { required => 1, isscalar => 1};
    $elements{"attribute"}   = { required => 1, isscalar => 1};

    foreach my $targetTypeExtension (@{$attributes->{targetTypeExtension}})
    {
        validateSubElements("targetTypeExtension",1,
                            $targetTypeExtension,\%elements);
    }
}

################################################################################
# Validates target type elements for correctness
################################################################################

sub validateTargetTypes {
    my($attributes) = @_;

    my %elements = ( );
    $elements{"id"}          = { required => 1, isscalar => 1};
    $elements{"parent"}      = { required => 0, isscalar => 1};
    $elements{"attribute"}   = { required => 0, isscalar => 0};
    $elements{"fspOnly"}     = { required => 0, isscalar => 0};

    foreach my $targetType (@{$attributes->{targetType}})
    {
        validateSubElements("targetType",1,$targetType,\%elements);
    }
}

################################################################################
# Validates target instance elements for correctness
################################################################################

sub validateTargetInstances{
    my($attributes) = @_;

    my %elements = ( );
    $elements{"id"}          = { required => 1, isscalar => 1};
    $elements{"type"}        = { required => 1, isscalar => 1};
    $elements{"attribute"}   = { required => 0, isscalar => 0};

    foreach my $targetInstance (@{$attributes->{targetInstance}})
    {
        validateSubElements("targetInstance",1,$targetInstance,\%elements);
    }
}

################################################################################
# Convert PHYS_PATH into index for Target_t attribute's value
################################################################################

sub handleTgtPtrAttributes{
    my($attributes, $Target_t) = @_;

    my $aId = 0;
    ${$Target_t}{'NULL'} = $aId;
    foreach my $attribute (@{${$attributes}->{attribute}})
    {
        $aId++;
        if(exists $attribute->{simpleType} &&
           exists $attribute->{simpleType}->{'Target_t'})
        {
            ${$Target_t}{"$attribute->{id}"} = $aId;
        }
    }

    my %TargetList = ();
    my $index = 1;
    # Mapping instance's PHYS_PATH to index (1-base)
    foreach my $targetInstance (@{${$attributes}->{targetInstance}})
    {
        foreach my $attr (@{$targetInstance->{attribute}})
        {
            if ($attr->{id} eq "PHYS_PATH")
            {
                $TargetList{$attr->{default}} = $index++;
                last;
            }
        }
    }
    # replace Target_t attribute's value with instance's index
    foreach my $targetInstance (@{${$attributes}->{targetInstance}})
    {
        foreach my $attr (@{$targetInstance->{attribute}})
        {
            # An instance has a Target_t attribute
            if(exists ${$Target_t}{$attr->{id}})
            {
                if (exists $TargetList{$attr->{default}})
                {
                    $attr->{default} = $TargetList{$attr->{default}};
                }
                else
                {
                    fatal("$attr->{id} attribute has an unknown value "
                          . "$attr->{default}\n"
                          . "It must be NULL or a valid PHYS_PATH\n");
                }
            }
        }
    }
}

sub SOURCE_FILE_GENERATION_FUNCTIONS { }

################################################################################
# Writes the plat attribute macros header file header
################################################################################

sub writeFapiPlatAttrMacrosHeaderFileHeader {
    my($outFile) = @_;

    print $outFile <<VERBATIM;

#ifndef FAPI_FAPIPLATATTRMACROS_H
#define FAPI_FAPIPLATATTRMACROS_H

/**
 *  \@file fapiplatattrmacros.H
 *
 *  \@brief FAPI -> HB attribute mappings.  This file is autogenerated and
 *      should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdint.h>

//******************************************************************************
// Macros
//******************************************************************************

namespace fapi
{

namespace platAttrSvc
{
VERBATIM
}

################################################################################
# Writes the plat attribute macros
################################################################################

sub writeFapiPlatAttrMacrosHeaderFileContent {
    my($attributes,$fapiAttributes,$outFile) = @_;

    my $macroSection = "";
    my $attrSection = "";

    foreach my $attribute (@{$attributes->{attribute}})
    {
        foreach my $hwpfToHbAttrMap (@{$attribute->{hwpfToHbAttrMap}})
        {
            if(   !exists $hwpfToHbAttrMap->{id}
               || !exists $hwpfToHbAttrMap->{macro})
            {
                fatal("id,macro fields required\n");
            }

            my $fapiReadable  = 0;
            my $fapiWriteable = 0;
            my $instantiated = 0;

            if ($cfgFapiAttributesXmlFile eq "")
            {
                #No FAPI attributes xml file specified
                if(exists $attribute->{readable})
                {
                    $macroSection .= '    #define ' .  $hwpfToHbAttrMap->{id} .
                        "_GETMACRO(ID,PTARGET,VAL) \\\n" .
                        "        FAPI_PLAT_ATTR_SVC_GETMACRO_" .
                        $hwpfToHbAttrMap->{macro} . "(ID,PTARGET,VAL)\n";
                    $instantiated = 1;
                }

                if(exists $attribute->{writeable})
                {
                    $macroSection .= '    #ifndef ' .  $hwpfToHbAttrMap->{id} .
                        "_SETMACRO\n";
                    $macroSection .= '    #define ' .  $hwpfToHbAttrMap->{id} .
                        "_SETMACRO(ID,PTARGET,VAL) \\\n" .
                        "        FAPI_PLAT_ATTR_SVC_SETMACRO_" .
                        $hwpfToHbAttrMap->{macro} . "(ID,PTARGET,VAL)\n";
                    $macroSection .= "    #endif\n";
                    $instantiated = 1;
                }
            }
            else
            {
                #FAPI attribute xml file specified - validate against FAPI attrs
                foreach my $fapiAttr (@{$fapiAttributes->{attribute}})
                {
                    if(   (exists $fapiAttr->{id})
                       && ($fapiAttr->{id} eq $hwpfToHbAttrMap->{id}) )
                    {
                        # Check that non-platInit attributes are in the
                        # volatile-zeroed section and have a direct mapping
                        if (! exists $fapiAttr->{platInit})
                        {
                            if ($hwpfToHbAttrMap->{macro} ne "DIRECT")
                            {
                                fatal("FAPI non-platInit attr " .
                                      "'$hwpfToHbAttrMap->{id}' is " .
                                      "'$hwpfToHbAttrMap->{macro}', " .
                                      "it must be DIRECT");
                            }

                            if ($attribute->{persistency} ne "volatile-zeroed")
                            {
                                fatal("FAPI non-platInit attr " .
                                      "'$hwpfToHbAttrMap->{id}' is " .
                                      "'$attribute->{persistency}', " .
                                      "it must be volatile-zeroed");
                            }

                        }

                        # All FAPI attributes are readable
                        $fapiReadable = 1;

                        if(exists $fapiAttr->{writeable})
                        {
                            $fapiWriteable = 1;
                        }

                        last;
                    }
                }

                if($fapiReadable)
                {
                    if(exists $attribute->{readable})
                    {
                        $macroSection .= '    #define ' .  $hwpfToHbAttrMap->{id} .
                            "_GETMACRO(ID,PTARGET,VAL) \\\n" .
                            "        FAPI_PLAT_ATTR_SVC_GETMACRO_" .
                            $hwpfToHbAttrMap->{macro} . "(ID,PTARGET,VAL)\n";
                        $instantiated = 1;
                    }
                    else
                    {
                        fatal("FAPI attribute $hwpfToHbAttrMap->{id} requires " .
                            "platform supply readable attribute.");
                    }
                }

                if($fapiWriteable)
                {
                    if(exists $attribute->{writeable})
                    {
                        $macroSection .= '    #define ' .  $hwpfToHbAttrMap->{id} .
                            "_SETMACRO(ID,PTARGET,VAL) \\\n" .
                            "        FAPI_PLAT_ATTR_SVC_SETMACRO_" .
                            $hwpfToHbAttrMap->{macro} . "(ID,PTARGET,VAL)\n";
                        $instantiated = 1;
                    }
                    else
                    {
                        fatal("FAPI attribute $hwpfToHbAttrMap->{id} requires "
                            . "platform supply writeable attribute.");
                    }
                }
            }

            if($instantiated)
            {
                $attrSection .= '    #define FAPI_PLAT_ATTR_SVC_MACRO_' .
                    $hwpfToHbAttrMap->{macro} . "_FAPI_" .
                    $hwpfToHbAttrMap->{id} . " \\\n" .
                    "        TARGETING::ATTR_" .
                    $attribute->{id} . "\n";
            }
        }
    }

    print $outFile $attrSection;
    print $outFile "\n";
    print $outFile $macroSection;
    print $outFile "\n";
}

################################################################################
# Writes the plat attribute macros header file footer
################################################################################

sub writeFapiPlatAttrMacrosHeaderFileFooter {
    my($outFile) = @_;

print $outFile <<VERBATIM;
} // End namespace platAttrSvc

} // End namespace fapi

#endif // FAPI_FAPIPLATATTRMACROS_H

VERBATIM

}

################################################################################
# Writes the pnor targeting header format file
################################################################################

sub writeHeaderFormatHeaderFile {
    my($outFile) = @_;

    print $outFile <<VERBATIM;

#ifndef TARG_PNORHEADER_H
#define TARG_PNORHEADER_H

/**
 *  \@file pnorheader.H
 *
 *  \@brief Definition for structure of targeting's PNOR image header.  This
 *      file is autogenerated and should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <builtins.h>
#include <stdint.h>
#include <targeting/adapters/types.H>
#include <targeting/common/pointer.H>

// Targeting component

//******************************************************************************
// Complex Types
//******************************************************************************

namespace TARGETING
{
    const uint32_t PNOR_TARG_EYE_CATCHER = 0x54415247;

    enum SECTION_TYPE
    {
        // Targeting read-only section backed to PNOR.  Always the 0th section.
        SECTION_TYPE_PNOR_RO        = 0x00,

        // Targeting read-write section backed to PNOR
        SECTION_TYPE_PNOR_RW        = 0x01,

        // Targeting heap section initialized out of PNOR
        SECTION_TYPE_HEAP_PNOR_INIT = 0x02,

        // Targeting heap section intialized to zero
        SECTION_TYPE_HEAP_ZERO_INIT = 0x03,

        // FSP section

        // Initialized to zero on Fsp Reset / Obliterate on Fsp Reset or R/R
        SECTION_TYPE_FSP_P0_ZERO_INIT = 0x4,
        
        // Initialized from Flash / Obliterate on Fsp Reset or R/R
        SECTION_TYPE_FSP_P0_FLASH_INIT = 0x5,
        
        // This section remains across fsp power cycle, fixed, never updates
        SECTION_TYPE_FSP_P3_RO = 0x6,

        // This section persist changes across Fsp Power cycle
        SECTION_TYPE_FSP_P3_RW = 0x7,
         
        // Initialized to zero on hard reset, else existing P1 memory
        // copied on R/R
        SECTION_TYPE_FSP_P1_ZERO_INIT = 0x8,

        // Intialized to default from P3 on hard reset, else existing P1
        // memory copied on R/R
        SECTION_TYPE_FSP_P1_FLASH_INIT = 0x9,

        // HOSTBOOT section

        // Targeting heap section intialized to zero
        SECTION_TYPE_HB_HEAP_ZERO_INIT = 0x0A,

    };

    struct TargetingSection
    {
        // Type of targeting section
        const SECTION_TYPE sectionType : 8;

        // Offset of the section within the PNOR targeting image from byte zero
        // of the targeting header
        const uint32_t     sectionOffset;

        // Size of the section within the PNOR targeting image
        const uint32_t     sectionSize;

    } PACKED;

    struct TargetingHeader
    {
        // Eyecatcher to quickly verify correct population of targeting PNOR
        // data
        const uint32_t         eyeCatcher;

        // Major version of the PNOR targeting image
        const uint16_t         majorVersion;

        // Minor version of the PNOR targeting image
        const uint16_t         minorVersion;

        // Total size of the targeting header (from beginning of header).  The
        // PNOR RO targeting data is located immediately following the header
        const uint32_t         headerSize;

        // Virtual memory offset from the virtual memory address of the previous
        // section where the attribute resource provider must load the next
        // section.  If there is no previous section, it will represent the
        // offset from the virtual memory base address (typically 0)
        const uint32_t         vmmSectionOffset;

        // Virtual memory base address where the attribute resource provider
        // must load the 0th (PNOR RO) section
        AbstractPointer<void>    vmmBaseAddress;

        // Size of each TargetingSection record
        const uint32_t         sizeOfSection;

        // Number of TargetingSection records
        const uint32_t         numSections;

        // Offset to the first TargetingSection record, from the end of this
        // field
        const uint32_t         offsetToSections;

        // Pad, in bytes, given by "offsetToSections"

        // const TargetingSection sections[numSections];

    } PACKED;

} // End namespace TARGETING

#endif // TARG_PNORHEADER_H

VERBATIM

}

################################################################################
# Writes the string implementation file header
################################################################################

sub writeStringImplementationFileHeader {
    my($outFile) = @_;

    print $outFile <<VERBATIM;

/**
 *  \@file attributestrings.C
 *
 *  \@brief Attribute string implementation.  This file is autogenerated and
 *      should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdint.h>
#include <stdlib.h>

// Targeting component
#include <targeting/common/attributes.H>

namespace TARGETING {

VERBATIM

}

################################################################################
# Writes string implementation
################################################################################

sub writeStringImplementationFileStrings {
    my($attributes,$outFile) = @_;

    foreach my $attribute (@{$attributes->{attribute}})
    {
        if(exists $attribute->{simpleType})
        {
            my $simpleType = $attribute->{simpleType};
            if(exists $simpleType->{enumeration})
            {
                my $enumeration = $simpleType->{enumeration};

                print $outFile "//*********************************************"
                    . "*********************************\n";
                print $outFile "// attrToString<ATTR_", $attribute->{id}, ">\n";
                print $outFile "//*********************************************"
                    . "*********************************\n\n";
                print $outFile "template<>\n";
                print $outFile "const char* attrToString<ATTR_",
                    $attribute->{id},"> (\n";
                print $outFile "    AttributeTraits<ATTR_",$attribute->{id},
                    ">::Type const& i_attrValue)\n";
                print $outFile "{\n";
                print $outFile "    switch(i_attrValue)\n";
                print $outFile "    {\n";
                my $enumerationType = getEnumerationType($attributes,
                    $enumeration->{id});

                foreach my $enumerator (@{$enumerationType->{enumerator}})
                {
                    print $outFile "        case ", $attribute->{id}, "_",
                        $enumerator->{name},":\n";
                    print $outFile "            return \"",
                        $enumerator->{name},"\";\n";
                }

                print $outFile "        default:\n";
                print $outFile "            return \"Cannot decode ",
                    $attribute->{id}, "\";\n";
                print $outFile "    }\n";
                print $outFile "}\n\n";
           }
        }
    }
}

################################################################################
# Locate generic attribute definition, given an enumeration ID
################################################################################

sub getEnumerationType {

    my($attributes,$id) = @_;
    my $matchingEnumeration;

    foreach my $enumerationType (@{$attributes->{enumerationType}})
    {
        if($id eq $enumerationType->{id})
        {
            $matchingEnumeration = $enumerationType;
            last;
        }
    }

    if(!exists $matchingEnumeration->{id})
    {
        fatal("Could not find enumeration with ID of " . $id . "\n");
    }

    return $matchingEnumeration;
}

################################################################################
# Writes the string implementation file footer
################################################################################

sub writeStringImplementationFileFooter {
    my($outFile) = @_;

print $outFile <<VERBATIM;
} // End namespace TARGETING

VERBATIM
}

################################################################################
# Writes the struct file header
################################################################################

sub writeStructFileHeader {
    my($outFile) = @_;

print $outFile <<VERBATIM;

#ifndef TARG_ATTRIBUTESTRUCTS_H
#define TARG_ATTRIBUTESTRUCTS_H

/**
 *  \@file attributestructs.H
 *
 *  \@brief Complex structures for host boot attributes.  This file is
 *      autogenerated and should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdint.h>
#include <stdlib.h>

// Targeting component
#include <builtins.h>
#include <targeting/common/attributes.H>
#include <targeting/common/entitypath.H>

//******************************************************************************
// Complex Types
//******************************************************************************

namespace TARGETING
{

VERBATIM

}

################################################################################
# Writes struct header file structs
################################################################################

sub writeStructFileStructs {
    my($attributes,$outFile) = @_;

    foreach my $attribute (@{$attributes->{attribute}})
    {
        if(exists $attribute->{complexType})
        {
            my $complexType = $attribute->{complexType};
            if(!exists $complexType->{description})
            {
                fatal("ERROR: Complex type requires a 'description'.");
            }

            print $outFile "/**\n";
            print $outFile wrapBrief($complexType->{description});
            print $outFile " */\n";

            print $outFile "struct ",
                calculateStructName($attribute->{id}), "\n";
            print $outFile "{\n";

            my $complex = $attribute->{complexType};
            foreach my $field (@{$complex->{field}})
            {
                validateFieldElement($field);

                my $bits = "";
                if($field->{bits})
                {
                    $bits = " : " . $field->{bits};
                }

                print $outFile wrapComment($field->{description});
                print $outFile "    ", $field->{type}, " ", $field->{name},
                    $bits, "; \n\n";
            }

            print $outFile "} PACKED;\n\n";
        }
    }
}

################################################################################
# Writes the struct file footer
################################################################################

sub writeStructFileFooter {
    my($outFile) = @_;

print $outFile <<VERBATIM;
} // End namespace TARGETING

#endif // TARG_ATTRIBUTESTRUCTS_H

VERBATIM

}

################################################################################
# Writes the string header file header
################################################################################

sub writeStringHeaderFileHeader {
    my($outFile) = @_;

print $outFile <<VERBATIM;

#ifndef TARG_ATTRIBUTESTRINGS_H
#define TARG_ATTRIBUTESTRINGS_H

/**
 *  \@file attributestrings.H
 *
 *  \@brief Attribute string conversion routines.  This file is autogenerated
 *      and should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdint.h>
#include <stdlib.h>

namespace TARGETING
{

/**
 *  \@brief Class used to clarify compiler error when caller attempts to
 *      stringify an unsupported attribute
 */
class InvalidAttributeForStringification;

/**
 *  \@brief Return attribute as a string
 *
 *  \@param[in] i_attrValue Value of the attribute
 *
 *  \@return String which decodes the attribute value
 */
template<const ATTRIBUTE_ID A>
const char* attrToString(
    typename AttributeTraits<A>::Type const& i_attrValue)
{
    // Default behavior is to fail the compile if caller attempt to print an
    // unsupported string
    return InvalidAttributeForStringification();
}

VERBATIM

}

################################################################################
# Writes string interfaces
################################################################################

sub writeStringHeaderFileStrings {
    my($attributes,$outFile) = @_;

    foreach my $attribute (@{$attributes->{attribute}})
    {
        if(exists $attribute->{simpleType})
        {
            my $simpleType = $attribute->{simpleType};
            if(exists $simpleType->{enumeration})
            {
                my $enumeration = $simpleType->{enumeration};
                print $outFile "/**\n";
                print $outFile " *  \@brief See "
                    . "attrToString<const ATTRIBUTE_ID A>\n";
                print $outFile " */\n";
                print $outFile "template<>\n";
                print $outFile "const char* attrToString<ATTR_",
                    $attribute->{id},">(\n";
                print $outFile "    AttributeTraits<ATTR_",$attribute->{id},
                    ">::Type const& i_attrValue);\n";
                print $outFile "\n";
            }
        }
    }
}

################################################################################
# Writes the string header file footer
################################################################################

sub writeStringHeaderFileFooter {
    my($outFile) = @_;

print $outFile <<VERBATIM;

} // End namespace TARGETING

#endif // TARG_ATTRIBUTESTRINGS_H

VERBATIM
}

################################################################################
# Writes the enum file header
################################################################################

sub writeEnumFileHeader {
    my($outFile) = @_;

print $outFile <<VERBATIM;

#ifndef TARG_ATTRIBUTEENUMS_H
#define TARG_ATTRIBUTEENUMS_H

/**
 *  \@file attributeenums.H
 *
 *  \@brief Defined enums for platform attributes
 *
 *  This header file contains enumerations for supported platform attributes
 *  (as opposed to HWPF attributes).  This file is automatically
 *  generated and should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

#include <stdint.h>
#include <stdlib.h>

//******************************************************************************
// Enumerations
//******************************************************************************

namespace TARGETING
{

VERBATIM

}

################################################################################
# Writes the enum file attribute enumeration
################################################################################

sub writeEnumFileAttrIdEnum {
    my($attributes,$outFile) = @_;

    print $outFile <<VERBATIM;
/**
 *  \@brief Platform attribute IDs
 *
 *  Enumeration defining every possible platform attribute that can be
 *  associated with a target. This file is autogenerated and should not be
 *  altered.
 */
enum ATTRIBUTE_ID
{
VERBATIM

    my $attrId;
    my $hexVal;

    # Format below intentionally > 80 chars for clarity

    format ATTRENUMFORMAT =
    ATTR_@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< = @<<<<<<<<<<
    $attrId,                                                         $hexVal .","
.
    select($outFile);
    $~ = 'ATTRENUMFORMAT';

    my $attributeIdEnumeration = getAttributeIdEnumeration($attributes);
    foreach my $enumerator (@{$attributeIdEnumeration->{enumerator}})
    {
        $hexVal = sprintf "0x%08X", $enumerator->{value};
        $attrId = $enumerator->{name};
        write;
    }

    print $outFile "};\n\n";
}

################################################################################
# Writes other enumerations to enumeration file
################################################################################

sub writeEnumFileAttrEnums {
    my($attributes,$outFile) = @_;

    my $enumName = "";
    my $enumHex = "";

    # Format below intentionally > 80 chars for clarity

    format ENUMFORMAT =
    @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< = @<<<<<<<<<<
    $enumName,                                                       $enumHex .","
.
    select($outFile);
    $~ = 'ENUMFORMAT';

    foreach my $enumerationType (@{$attributes->{enumerationType}})
    {
        print $outFile "/**\n";
        print $outFile wrapBrief( $enumerationType->{description} );
        print $outFile " */\n";
        print $outFile "enum ", $enumerationType->{id}, "\n";
        print $outFile "{\n";

        foreach my $enumerator (@{$enumerationType->{enumerator}})
        {
            $enumHex = sprintf "0x%08X",
                enumNameToValue($enumerationType,$enumerator->{name});
            $enumName = $enumerationType->{id} . "_" . $enumerator->{name};
            write;
        }

        print $outFile "};\n\n";
    }
}

################################################################################
# Writes the enum file footer
################################################################################

sub writeEnumFileFooter {
    my($outFile) = @_;

print $outFile <<VERBATIM;
} // End namespace TARGETING

#endif // TARG_ATTRIBUTEENUMS_H

VERBATIM
}

################################################################################
# Writes the trait file header
################################################################################

sub writeTraitFileHeader {
    my($outFile) = @_;

print $outFile <<VERBATIM;

#ifndef TARG_ATTRIBUTETRAITS_H
#define TARG_ATTRIBUTETRAITS_H

/**
 *  \@file attributetraits.H
 *
 *  \@brief Templates which map attributes to their type/properties
 *
 *  This header file contains templates which map attributes to their
 *  type/properties.  This file is autogenerated and should not be altered.
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdint.h>
#include <stdlib.h>
#include <targeting/common/entitypath.H>

namespace TARGETING
{

//******************************************************************************
// Attribute Property Mappings
//******************************************************************************

/**
 *  \@brief Template associating a specific attribute with a type and other
 *      properties, such as whether it is readable/writable
 *
 *      This is automatically generated
 *
 *      enum {
 *          disabled = Special value for the basic, unused wildcard attribute
 *          readable = Attribute is readable
 *          writable = Attribute is writable
 *          hasStringConversion = Attribute has debug string conversion
 *      }
 *
 *      typedef <type> TYPE // <type> is the Attribute's valid type
 */
template<const ATTRIBUTE_ID A>
class AttributeTraits
{
    private:
        enum { disabled };
        typedef void* Type;
};

VERBATIM

}

################################################################################
# Writes computed traits to trait file
################################################################################

sub writeTraitFileTraits {
    my($attributes,$outFile) = @_;

    my $typedefs = "";

    foreach my $attribute (@{$attributes->{attribute}})
    {
        # Build boolean traits

        my $traits = "";
        foreach my $trait ("writeable","readable","hasStringConversion")
        {
            if(exists $attribute->{$trait})
            {
                $traits .= " $trait,";
            }
        }

        # Mark the attribute as being a host boot mutex or non-host boot mutex
        if(   (exists $attribute->{simpleType})
           && (exists $attribute->{simpleType}->{hbmutex}) )
        {
            $traits .= " hbMutex,";
        }
        else
        {
            $traits .= " notHbMutex,";
        }

        chop($traits);

        # Build value type

        my $type = "";
        my $dimensions = "";
        if(exists $attribute->{simpleType})
        {
            my $simpleType = $attribute->{simpleType};
            my $simpleTypeProperties = simpleTypeProperties();
            for my $typeName (sort(keys %{$simpleType}))
            {
                if(exists $simpleTypeProperties->{$typeName})
                {
                    if(    $simpleTypeProperties->{$typeName}{typeName}
                       eq "XMLTOHB_USE_PARENT_ATTR_ID")
                    {
                        $type = $attribute->{id};
                    }
                    else
                    {
                        $type = $simpleTypeProperties->{$typeName}{typeName};
                    }

                    if(   (exists $simpleType->{array})
                       && ($simpleTypeProperties->{$typeName}{supportsArray}) )
                    {
                         my @bounds = split(/,/,$simpleType->{array});
                         foreach my $bound (@bounds)
                         {
                             $dimensions .= "[$bound]";
                         }
                    }
                    elsif(exists $simpleType->{string})
                    {
                        # Create the string dimension
                        if(exists $simpleType->{string}->{sizeInclNull})
                        {
                            $dimensions .=
                                "[$simpleType->{string}->{sizeInclNull}]";
                        }
                    }
                    last;
                }
            }

            if($type eq "")
            {
                fatal("Unsupported simpleType child element for "
                 . "attribute $attribute->{id}.  Keys are ("
                 . join(',',sort(keys %{$simpleType})) . ")");
            }
        }
        elsif(exists $attribute->{nativeType})
        {
            $type = $attribute->{nativeType}->{name};
        }
        elsif(exists $attribute->{complexType})
        {
            $type = calculateStructName($attribute->{id});
        }
        else
        {
            fatal("Could not determine attribute data type for attribute "
                . "$attribute->{id}.");
        }

        # Add traits definition to output

        print $outFile "template<>\n";
        print $outFile "class AttributeTraits<ATTR_",$attribute->{id},">\n";
        print $outFile "{\n";
        print $outFile "    public:\n";
        print $outFile "        enum {",$traits," };\n";
        print $outFile "        typedef ", $type, " Type$dimensions;\n";
        print $outFile "};\n\n";

        $typedefs .= "// Type aliases and/or sizes for ATTR_"
                   . "$attribute->{id} attribute\n";

        $typedefs .= "typedef " . $type .
            " $attribute->{id}" . "_ATTR" . $dimensions . ";\n";

        # Append a more friendly type alias for attribute
        $typedefs .= "typedef " . $type .
            " ATTR_" . "$attribute->{id}" . "_type" . $dimensions . ";\n";

        # If a string, append max # of characters for the string
        if(   (exists $attribute->{simpleType})
           && (exists $attribute->{simpleType}->{string}))
        {
            my $size = $attribute->{simpleType}->{string}->{sizeInclNull} - 1;
            $typedefs .= "const size_t ATTR_"
                      .  "$attribute->{id}" . "_max_chars = "
                      .  "$size"
                      . ";\n";
        }
        $typedefs .= "\n";
    };

    print $outFile "/**\n";
    print $outFile wrapBrief("Mapping of alias type name to underlying type");
    print $outFile " */\n";
    print $outFile $typedefs ."\n";
}

################################################################################
# Writes the trait file footer
################################################################################

sub writeTraitFileFooter {
    my($outFile) = @_;

    print $outFile <<VERBATIM;
} // End namespace TARGETING

#endif // TARG_ATTRIBUTETRAITS_H

VERBATIM
}

######
#Create a .C file to put attributes into the errlog
#####
sub writeAttrErrlCFile {
    my($attributes,$outFile) = @_;

    #First setup the includes and function definition
    print $outFile "#include <stdint.h>\n";
    print $outFile "#include <stdio.h>\n";
    print $outFile "#include <string.h>\n";
    print $outFile "#include <errludattribute.H>\n";
    print $outFile "#include <targeting/common/targetservice.H>\n";
    print $outFile "#include <targeting/common/trace.H>\n";
    print $outFile "\n";
    print $outFile "namespace ERRORLOG\n";
    print $outFile "{\n";
    print $outFile "using namespace TARGETING;\n";
    print $outFile "extern TARG_TD_t g_trac_errl;\n";

    # loop through every attribute to create the local dump function
    foreach my $attribute (@{$attributes->{attribute}})
    {
        # things we'll skip:
        if(!(exists $attribute->{readable}) ||  # write-only attributes
           !(exists $attribute->{writeable}) || # read-only attributes
           (exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{hbmutex})) # mutex attributes
          ) {
            next;
        }
        # any complicated types just get dumped as raw hex binary
        elsif(exists $attribute->{complexType}) {
            #print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            #print $outFile "{   //complexType\n";
            #print $outFile "    uint32_t retSize = 0;\n";
            #print $outFile "    AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
            #print $outFile "    if( i_pTarget->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
            #print $outFile "        retSize = 1 + sprintf(i_buffer, \" \", &tmp, sizeof(tmp));\n";
            #print $outFile "    }\n";
            #print $outFile "    return(retSize);\n";
            #print $outFile "}\n";
            print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            print $outFile "{   //complexType\n";
            print $outFile "    TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: ",$attribute->{id}," skipped -- complexType\");\n";
            print $outFile "    return(0);\n";
            print $outFile "}\n";
        }
        # Enums
        elsif(exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{enumeration}) ) {
            print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            print $outFile "{   //simpleType:enum\n";
            print $outFile "    //TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: ",$attribute->{id}," entry\");\n";
            print $outFile "    uint32_t retSize = 0;\n";
            print $outFile "    AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
            print $outFile "    if( i_pTarget->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
            print $outFile "        memcpy(i_buffer, &tmp, sizeof(tmp));\n";
            print $outFile "        retSize = sizeof(tmp);\n";
            print $outFile "    }\n";
            print $outFile "    return(retSize);\n";
            print $outFile "}\n";
        }
        # signed and unsigned ints
        elsif(exists $attribute->{simpleType} &&
              ( (exists $attribute->{simpleType}->{uint8_t}) ||
                (exists $attribute->{simpleType}->{uint16_t}) ||
                (exists $attribute->{simpleType}->{uint32_t}) ||
                (exists $attribute->{simpleType}->{uint64_t}) ||
                (exists $attribute->{simpleType}->{int8_t}) ||
                (exists $attribute->{simpleType}->{int16_t}) ||
                (exists $attribute->{simpleType}->{int32_t}) ||
                (exists $attribute->{simpleType}->{int64_t})
              )
             )
        {
            print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            print $outFile "{   //simpleType:uint :int\n";
            print $outFile "    //TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: ",$attribute->{id}," entry\");\n";
            print $outFile "    uint32_t retSize = 0;\n";
            print $outFile "    AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
            print $outFile "    if( i_pTarget->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
            print $outFile "        memcpy(i_buffer, &tmp, sizeof(tmp));\n";
            print $outFile "        retSize = sizeof(tmp);\n";
            print $outFile "    }\n";
            print $outFile "    return(retSize);\n";
            print $outFile "}\n";
        }
        # dump the enums for EntityPaths
        elsif(exists $attribute->{nativeType} && ($attribute->{nativeType}->{name} eq "EntityPath")) {
            print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            print $outFile "{   //nativeType:EntityPath\n";
            print $outFile "    //TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: ",$attribute->{id}," entry\");\n";
            print $outFile "    uint32_t retSize = 0;\n";
            print $outFile "    AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
            print $outFile "    if( i_pTarget->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
            print $outFile "        // data is PATH_TYPE, Number of elements, [ Element, Instance# ]\n";
            print $outFile "        EntityPath::PATH_TYPE lPtype = tmp.type();\n";
            print $outFile "        memcpy(i_buffer + retSize,&lPtype,sizeof(lPtype));\n";
            print $outFile "        retSize += sizeof(lPtype);\n";
            print $outFile "        uint8_t lSize = tmp.size();\n";
            print $outFile "        memcpy(i_buffer + retSize,&lSize,sizeof(lSize));\n";
            print $outFile "        retSize += sizeof(lSize);\n";
            print $outFile "        for (uint32_t i=0;i<lSize;i++) {\n";
            print $outFile "            EntityPath::PathElement lType = tmp[i];\n";
            print $outFile "            memcpy(i_buffer + retSize,&tmp[i],sizeof(tmp[i]));\n";
            print $outFile "            retSize += sizeof(tmp[i]);\n";
            print $outFile "        }\n";
            print $outFile "    }\n";
            print $outFile "    return(retSize);\n";
            print $outFile "}\n";
        }
        # any other nativeTypes are just decimals...  (I never saw one)
        elsif(exists $attribute->{nativeType}) {
            print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            print $outFile "{   //nativeType\n";
            print $outFile "    //TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: ",$attribute->{id}," entry\");\n";
            print $outFile "    uint32_t retSize = 0;\n";
            print $outFile "    AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
            print $outFile "    if( i_pTarget->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
            print $outFile "        memcpy(i_buffer, &tmp, sizeof(tmp));\n";
            print $outFile "        retSize = sizeof(tmp);\n";
            print $outFile "    }\n";
            print $outFile "    return(retSize);\n";
            print $outFile "}\n";
        }
        # just in case, add a dummy function
        else
        {
            print $outFile "uint32_t dump_ATTR_",$attribute->{id},"(const Target * i_pTarget, char *i_buffer)\n";
            print $outFile "{   //unknown attributes\n";
            print $outFile "    TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: ",$attribute->{id}," UNKNOWN\");\n";
            print $outFile "    return(0);\n";
            print $outFile "}\n";
        }
    }

    # build function that takes adds 1 attribute to the output
    print $outFile "\n";
    print $outFile "void ErrlUserDetailsAttribute::addData(\n";
    print $outFile "    uint32_t i_attr)\n";
    print $outFile "{\n";
    print $outFile "    char *tmpBuffer = new char[1024];\n";
    print $outFile "    uint32_t attrSize = 0;\n";
    print $outFile "\n";
    print $outFile "    switch (i_attr) {\n";

    # loop through every attribute to make the swith/case
    foreach my $attribute (@{$attributes->{attribute}})
    {
        # things we'll skip:
        if(!(exists $attribute->{readable}) ||  # write-only attributes
           !(exists $attribute->{writeable}) || # read-only attributes
           (exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{hbmutex})) # mutex attributes
          ) {
            print $outFile "        case (ATTR_",$attribute->{id},"): { break; }\n";
            next;
        }
        print $outFile "        case (ATTR_",$attribute->{id},"): {\n";
        print $outFile "            attrSize = dump_ATTR_",$attribute->{id},"(iv_pTarget,tmpBuffer); break;\n";
        print $outFile "        }\n";
    }

    print $outFile "        default: { //Shouldn't be anything here!!\n";
    print $outFile "            TRACDCOMP( g_trac_errl, \"ErrlUserDetailsAttribute: UNKNOWN i_attr %x\", i_attr);\n";
    print $outFile "            break;\n";
    print $outFile "        }\n";
    print $outFile "    } //switch\n";
    print $outFile "\n";
    print $outFile "    // if we generated one, copy the string into the buffer\n";
    print $outFile "    if (attrSize) { // we have something to output\n";
    print $outFile "        // resize buffer and copy string into it\n";
    print $outFile "        uint8_t * pBuf;\n";
    print $outFile "        pBuf = reinterpret_cast<uint8_t *>(reallocUsrBuf(iv_dataSize + attrSize + sizeof(i_attr) ));\n";
    print $outFile "        memcpy(pBuf + iv_dataSize, &i_attr, sizeof(i_attr)); // first dump the attr enum\n";
    print $outFile "        iv_dataSize += sizeof(i_attr);\n";
    print $outFile "        memcpy(pBuf + iv_dataSize, tmpBuffer, attrSize); // copy into iv_pBuffer\n";
    print $outFile "        iv_dataSize += attrSize;\n";
    print $outFile "    }\n";
    print $outFile "    delete [] tmpBuffer;\n";
    print $outFile "}\n";
    print $outFile "\n";

    # build constructor that dumps 1 attribute
    print $outFile "\n";
    print $outFile "//------------------------------------------------------------------------------\n";
    print $outFile "ErrlUserDetailsAttribute::ErrlUserDetailsAttribute(\n";
    print $outFile "    const Target * i_pTarget, uint32_t i_attr)\n";
    print $outFile "    : iv_pTarget(i_pTarget), iv_dataSize(0)\n";
    print $outFile "{\n";
    print $outFile "    // Set up ErrlUserDetails instance variables\n";
    print $outFile "    iv_CompId = HBERRL_COMP_ID;\n";
    print $outFile "    iv_Version = 1;\n";
    print $outFile "    iv_SubSection = HBERRL_UDT_ATTRIBUTE;\n";
    print $outFile "    iv_merge = true;\n";
    print $outFile "\n";
    print $outFile "    // first, write out the HUID\n";
    print $outFile "    addData(ATTR_HUID);\n";
    print $outFile "    if (i_attr != ATTR_HUID) {\n";
    print $outFile "        addData(i_attr);\n";
    print $outFile "    }\n";
    print $outFile "}\n";
    print $outFile "\n";

    # build constructor that dumps all attributes
    print $outFile "//------------------------------------------------------------------------------\n";
    print $outFile "ErrlUserDetailsAttribute::ErrlUserDetailsAttribute(\n";
    print $outFile "    const Target * i_pTarget)\n";
    print $outFile "    : iv_pTarget(i_pTarget), iv_dataSize(0)\n";
    print $outFile "{\n";
    print $outFile "    // Set up ErrlUserDetails instance variables\n";
    print $outFile "    iv_CompId = HBERRL_COMP_ID;\n";
    print $outFile "    iv_Version = 1;\n";
    print $outFile "    iv_SubSection = HBERRL_UDT_ATTRIBUTE;\n";
    print $outFile "    // override the default of false\n";
    print $outFile "    iv_merge = true;\n";
    print $outFile "\n";
    print $outFile "    dumpAll();\n";
    print $outFile "}\n";
    print $outFile "\n";

    # build internal function that dumps all attributes
    print $outFile "//------------------------------------------------------------------------------\n";
    print $outFile "void ErrlUserDetailsAttribute::dumpAll()\n";
    print $outFile "{\n";
    print $outFile "    // write out the HUID first and always\n";
    print $outFile "    addData(ATTR_HUID);\n";

    # loop through every attribute to make the swith/case
    foreach my $attribute (@{$attributes->{attribute}})
    {
        # skip the HUID that we already added
        if( $attribute->{id} =~ /HUID/ ) {
            next;
        }
        # things we'll skip:
        if(!(exists $attribute->{readable}) ||  # write-only attributes
           !(exists $attribute->{writeable}) || # read-only attributes
           (exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{hbmutex})) # mutex attributes
          ) {
            next;
        }
        print $outFile "    addData(ATTR_",$attribute->{id},");\n";
    }
    print $outFile "}\n";

    print $outFile "\n";

    print $outFile "//------------------------------------------------------------------------------\n";
    print $outFile "ErrlUserDetailsAttribute::~ErrlUserDetailsAttribute()\n";
    print $outFile "{ }\n";
    print $outFile "} // namespace\n";
} # sub writeAttrErrlCFile


######
#Create a .H file to parse attributes out of the errlog
#####
sub writeAttrErrlHFile {
    my($attributes,$outFile) = @_;

    #First setup the includes and function definition
    print $outFile "\n";
    print $outFile "#ifndef ERRL_UDATTRIBUTE_H\n";
    print $outFile "#define ERRL_UDATTRIBUTE_H\n";
    print $outFile "\n";
    print $outFile "#include <errl/errluserdetails.H>\n";
    print $outFile "\n";
    print $outFile "#ifndef PARSER\n";
    print $outFile "\n";
    print $outFile "namespace TARGETING // Forward reference\n";
    print $outFile "{ class Target; }\n";
    print $outFile "\n";
    print $outFile "namespace ERRORLOG\n";
    print $outFile "{\n";
    print $outFile "class ErrlUserDetailsAttribute : public ErrlUserDetails {\n";
    print $outFile "public:\n";
    print $outFile "\n";
    print $outFile "    ErrlUserDetailsAttribute(const TARGETING::Target * i_pTarget, uint32_t i_attr);\n";
    print $outFile "    ErrlUserDetailsAttribute(const TARGETING::Target * i_pTarget);\n";
    print $outFile "    void addData(uint32_t i_attr);\n";
    print $outFile "    virtual ~ErrlUserDetailsAttribute();\n";
    print $outFile "\n";
    print $outFile "private:\n";
    print $outFile "\n";
    print $outFile "    // Disabled\n";
    print $outFile "    ErrlUserDetailsAttribute(const ErrlUserDetailsAttribute &);\n";
    print $outFile "    ErrlUserDetailsAttribute & operator=(const ErrlUserDetailsAttribute &);\n";
    print $outFile "\n";
    print $outFile "    // internal function\n";
    print $outFile "    void dumpAll();\n";
    print $outFile "\n";
    print $outFile "    const TARGETING::Target * iv_pTarget;\n";
    print $outFile "    uint32_t iv_dataSize;\n";
    print $outFile "};\n";
    print $outFile "}\n";
    print $outFile "#else // if PARSER defined\n";
    print $outFile "\n";
    print $outFile "namespace ERRORLOG\n";
    print $outFile "{\n";
    print $outFile "class ErrlUserDetailsParserAttribute : public ErrlUserDetailsParser {\n";
    print $outFile "public:\n";
    print $outFile "\n";
    print $outFile "    ErrlUserDetailsParserAttribute() {}\n";
    print $outFile "\n";
    print $outFile "    virtual ~ErrlUserDetailsParserAttribute() {}\n";
    print $outFile "/**\n";
    print $outFile " *  \@brief Parses Attribute user detail data from an error log\n";
    print $outFile " *  \@param  i_version Version of the data\n";
    print $outFile " *  \@param  i_parse   ErrlUsrParser object for outputting information\n";
    print $outFile " *  \@param  i_pBuffer Pointer to buffer containing detail data\n";
    print $outFile " *  \@param  i_buflen  Length of the buffer\n";
    print $outFile " */\n";
    print $outFile "  virtual void parse(errlver_t i_version,\n";
    print $outFile "                        ErrlUsrParser & i_parser,\n";
    print $outFile "                        void * i_pBuffer,\n";
    print $outFile "                        const uint32_t i_buflen) const\n";
    print $outFile "  {\n";
    print $outFile "    const char *pLabel;\n";
    print $outFile "    uint8_t *l_ptr = static_cast<uint8_t *>(i_pBuffer);\n";
    print $outFile "    std::vector<char> l_traceEntry(128);\n";
    print $outFile "\n";
    print $outFile "        // first 4 bytes is the attr enum\n";
    print $outFile "        uint32_t attrEnum = *(uint32_t *)l_ptr;\n";
    print $outFile "        uint32_t dataSize = 0;\n";
    print $outFile "        l_ptr += sizeof(attrEnum);\n";
    print $outFile "\n";
    print $outFile "        switch (attrEnum) {\n";

    # loop through every attribute to make the swith/case
    foreach my $attribute (@{$attributes->{attribute}})
    {
        my $attrVal = sprintf "0x%08X", $attribute->{value};
        print $outFile "          case ",$attrVal,": {\n";

        # things we'll skip:
        if(!(exists $attribute->{readable}) ||  # write-only attributes
           !(exists $attribute->{writeable}) || # read-only attributes
           (exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{hbmutex})) # mutex attributes
          ) {
            print $outFile "              //not readable\n";
        }
        # Enums have strings defined already, use them
        elsif(exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{enumeration}) ) {
            print $outFile "              //simpleType:enum\n";
            print $outFile "              pLabel = \"ATTR_",$attribute->{id},"\";\n";
            foreach my $enumerationType (@{$attributes->{enumerationType}})
            {
                if ($enumerationType->{id} eq $attribute->{id})
                {
                print $outFile "              switch (*l_ptr) {\n";
                foreach my $enumerator (@{$enumerationType->{enumerator}})
                {
                    my $enumName = $attribute->{id} . "_" . $enumerator->{name};
                    my $enumHex = sprintf "0x%08X", enumNameToValue($enumerationType,$enumerator->{name});
                    print $outFile "                  case ",$enumHex,": {\n";
                    print $outFile "                      // get the length and add one for the null terminator ";
                    print $outFile "                      dataSize = 1  + sprintf(&(l_traceEntry[0]), \"",$enumName,"\");\n";
                    print $outFile "                      break;\n";
                    print $outFile "                  }\n";
                }
                print $outFile "                  default: break;\n";
                print $outFile "              }\n";
                }
            }
        }
        # makes no sense to dump mutex attributes, so skipping
        elsif(exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{hbmutex}) ) {
            print $outFile "            //Mutex attributes - skipping\n";
        }
        # any complicated types just get dumped as raw hex binary
        elsif(exists $attribute->{complexType}) {
            #print $outFile "         //complexType\n";
            #print $outFile "         uint32_t<ATTR_",$attribute->{id},">::Type tmp;\n";
            #print $outFile "         if( i_pTarget->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
            #print $outFile "           dataSize = sprintf(i_buffer, \" \", &tmp, sizeof(tmp));\n";
            #print $outFile "         }\n";
            print $outFile "              //complexType - skipping\n";
        }
        # unsigned ints dump as hex, signed as decimals
        elsif(exists $attribute->{simpleType} &&
              ( (exists $attribute->{simpleType}->{uint8_t}) ||
                (exists $attribute->{simpleType}->{uint16_t}) ||
                (exists $attribute->{simpleType}->{uint32_t}) ||
                (exists $attribute->{simpleType}->{uint64_t}) ||
                (exists $attribute->{simpleType}->{int8_t}) ||
                (exists $attribute->{simpleType}->{int16_t}) ||
                (exists $attribute->{simpleType}->{int32_t}) ||
                (exists $attribute->{simpleType}->{int64_t})
              )
             )
        {
            print $outFile "              //simpleType:uint\n";
            print $outFile "              pLabel = \"ATTR_",$attribute->{id},"\";\n";
            if (exists $attribute->{simpleType}->{uint8_t}) 
            {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"0x%.2X\", *((uint8_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{uint16_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"0x%.4X\", *((uint16_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{uint32_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"0x%.8X\", *((uint32_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{uint64_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"0x%.16llX\", *((uint64_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{int8_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"%d\", *((int8_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{int16_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"%d\", *((int16_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{int32_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"%d\", *((int32_t *)l_ptr));\n";
            }
            elsif (exists $attribute->{simpleType}->{int64_t}) {
                print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"%d\", *((int64_t *)l_ptr));\n";
            }
            if(exists $attribute->{array})
            {
                ### need to do loop for types that are ARRAYS!
            }
        }
        # EntityPaths
        elsif(exists $attribute->{nativeType} && ($attribute->{nativeType}->{name} eq "EntityPath")) {
            print $outFile "              //nativeType:EntityPath\n";
            print $outFile "              pLabel = \"ATTR_",$attribute->{id},"\";\n";
            # data is PATH_TYPE, Number of elements, [ Element, Instance# ]
            # output is PathType:/ElementInstance/ElementInstance/ElementInstance
            print $outFile "              const char *pathString;\n";
            print $outFile "              // from targeting/common/entitypath.[CH]\n";
            print $outFile "              const uint8_t lPtype = *l_ptr; // PATH_TYPE\n";
            print $outFile "              switch (lPtype) {\n";
            print $outFile "                  case 0x01: pathString = \"Logical:\"; break;\n";
            print $outFile "                  case 0x02: pathString = \"Physical:\"; break;\n";
            print $outFile "                  case 0x03: pathString = \"Device:\"; break;\n";
            print $outFile "                  case 0x04: pathString = \"Power:\"; break;\n";
            print $outFile "                  default:   pathString = \"Unknown:\"; break;\n";
            print $outFile "              }\n";
            print $outFile "              dataSize = sprintf(&(l_traceEntry[0]), \"%s\",pathString);\n";
            print $outFile "              const uint8_t lSize = *(l_ptr + 1); // number of elements\n";
            print $outFile "              uint8_t *lElementInstance = (l_ptr + 2);\n";
            print $outFile "              for (uint32_t i=0;i<lSize;i += 2) {\n";
            print $outFile "                  switch (lElementInstance[i]) {\n";

            # TODO: RTC 50828: make these build-time dynamic based
            #  on values in obj/genfiles/attributeenums.H
            print $outFile "                      case 0x01: pathString = \"/Sys\"; break;\n";
            print $outFile "                      case 0x02: pathString = \"/Node\"; break;\n";
            print $outFile "                      case 0x03: pathString = \"/DIMM\"; break;\n";
            print $outFile "                      case 0x04: pathString = \"/Membuf\"; break;\n";
            print $outFile "                      case 0x05: pathString = \"/Proc\"; break;\n";
            print $outFile "                      case 0x06: pathString = \"/EX\"; break;\n";
            print $outFile "                      case 0x07: pathString = \"/Core\"; break;\n";
            print $outFile "                      case 0x08: pathString = \"/L2\"; break;\n";
            print $outFile "                      case 0x09: pathString = \"/L3\"; break;\n";
            print $outFile "                      case 0x0A: pathString = \"/L4\"; break;\n";
            print $outFile "                      case 0x0B: pathString = \"/MCS\"; break;\n";
            print $outFile "                      case 0x0C: pathString = \"/MBS\"; break;\n";
            print $outFile "                      case 0x0D: pathString = \"/MBA\"; break;\n";
            print $outFile "                      case 0x0E: pathString = \"/XBUS\"; break;\n";
            print $outFile "                      case 0x0F: pathString = \"/ABUS\"; break;\n";
            print $outFile "                      case 0x10: pathString = \"/PCI\"; break;\n";
            print $outFile "                      case 0x11: pathString = \"/DPSS\"; break;\n";
            print $outFile "                      case 0x12: pathString = \"/APSS\"; break;\n";
            print $outFile "                      case 0x13: pathString = \"/OCC\"; break;\n";
            print $outFile "                      case 0x14: pathString = \"/PSI\"; break;\n";
            print $outFile "                      case 0x15: pathString = \"/FSP\"; break;\n";
            print $outFile "                      case 0x16: pathString = \"/PNOR\"; break;\n";
            print $outFile "                      default: pathString = \"/Unknown\"; break;\n";
            print $outFile "                  } // switch\n";
            print $outFile "                  // copy next part in, overwritting previous terminator\n";
            print $outFile "                  dataSize += sprintf(&(l_traceEntry[0]) + dataSize, \"%s%d\",pathString,lElementInstance[i+1]);\n";
            print $outFile "              } // for\n";
            print $outFile "              dataSize++; // account for last NULL terminator\n";
        }
        # any other nativeTypes are just decimals...  (I never saw one)
        elsif(exists $attribute->{nativeType}) {
            print $outFile "              //nativeType\n";
            print $outFile "              pLabel = \"ATTR_",$attribute->{id},"\";\n";
            print $outFile "              dataSize = 1 + sprintf(&(l_traceEntry[0]), \"%d\", *((int32_t *)l_ptr));\n";
        }
        # just in case, nothing..
        else
        {
            #print $outFile "              //unknown attributes\n";
        }


        print $outFile "              break;\n";
        print $outFile "          }\n";
    }
    print $outFile "          default: {\n";
    print $outFile "              pLabel = \"unknown Attribute\";\n";
    print $outFile "              break;\n";
    print $outFile "          }\n";
    print $outFile "        } // switch\n";
    print $outFile "\n";
    print $outFile "        // pointing to something - print it.\n";
    print $outFile "        if (dataSize != 0) {\n";
    print $outFile "            if (l_traceEntry.size() < dataSize + 2) {\n";
    print $outFile "                l_traceEntry.resize(dataSize + 2);\n";
    print $outFile "            }\n";
    print $outFile "            i_parser.PrintString(pLabel, &(l_traceEntry[0]));\n";
    print $outFile "        }\n";
    print $outFile "        l_ptr += dataSize;\n";
    print $outFile "    } // for\n\n";
    print $outFile "private:\n";
    print $outFile "\n";
    print $outFile "// Disabled\n";
    print $outFile "ErrlUserDetailsParserAttribute(const ErrlUserDetailsParserAttribute &);\n";
    print $outFile "ErrlUserDetailsParserAttribute & operator=(const ErrlUserDetailsParserAttribute &);\n";
    print $outFile "};\n";
    print $outFile "} // namespace\n";
    print $outFile "#endif\n";
    print $outFile "#endif\n";
} # sub writeAttrErrlHFile



#fixme-Remove when RTC:38197 is done
######
#Create a .C file to dump all possible attributes
#####
sub writeDumpFile {
    my($attributes,$outFile) = @_;

    #First setup the includes and function definition
    print $outFile "#include <targeting/common/targetservice.H>\n";
    print $outFile "#include <targeting/common/trace.H>\n";
    print $outFile "#include <stdio.h>\n";
    print $outFile "\n";
    print $outFile "namespace TARGETING\n";
    print $outFile "{\n";
    print $outFile "    void dumpAllAttributes( TARG_TD_t i_trac, uint32_t i_huid )\n";
    print $outFile "    {\n";
    print $outFile "        using namespace TARGETING;\n";
    print $outFile "\n";
    print $outFile "        bool foundit = false;\n";
    print $outFile "        TargetService& l_targetService = targetService();\n";
    print $outFile "\n";
    print $outFile "        // Loop through every Target\n";
    print $outFile "        for( TargetIterator l_targ = l_targetService.begin();\n";
    print $outFile "             l_targ != l_targetService.end();\n";
    print $outFile "             ++l_targ )\n";
    print $outFile "        {\n";

    # add a HUID check first so we can act on a single target
    print $outFile "            { //HUID Check\n";
    print $outFile "                AttributeTraits<ATTR_HUID>::Type huid;\n";
    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_HUID>(huid) ) {\n";
    print $outFile "                    if( (i_huid != huid) && (i_huid != 0) )\n";
    print $outFile "                    {\n";
    print $outFile "                        //skip this target\n";
    print $outFile "                        continue;\n";
    print $outFile "                    }\n";
    print $outFile "                    else\n";
    print $outFile "                    {\n";
    print $outFile "                        foundit = true;\n";
    print $outFile "                    }\n";
    print $outFile "                }\n";
    print $outFile "            }\n";

    # add the physical path first so we know where we are
    print $outFile "            { //Physical Path\n";
    print $outFile "                AttributeTraits<ATTR_PHYS_PATH>::Type tmp;\n";
    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_PHYS_PATH>(tmp) ) {\n";
    print $outFile "                    char* tmpstring = tmp.toString();\n";
    print $outFile "                    TRACFCOMP( i_trac, \"DUMP: --ATTR_PHYS_PATH=%s--\", tmpstring );\n";
    print $outFile "                    free(tmpstring);\n";
    print $outFile "                }\n";
    print $outFile "            }\n";

    # loop through every attribute
    foreach my $attribute (@{$attributes->{attribute}})
    {
	# skip write-only attributes
	if(!(exists $attribute->{readable})) {
	    next;
	}

	# skip the PHYS_PATH that we already added
	if( $attribute->{id} =~ /PHYS_PATH/ ) {
	    next;
	}

	# Enums have strings defined already, use them
	if(exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{enumeration}) ) {
	    print $outFile "            { //simpleType:enum\n";
	    print $outFile "                AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
	    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
	    print $outFile "                    const char* tmpstr = (*l_targ)->getAttrAsString<ATTR_",$attribute->{id},">();\n";
	    print $outFile "                    TRACFCOMP( i_trac, \"DUMP: ",$attribute->{id},"=%s\", tmpstr );\n";
	    print $outFile "                }\n";
	    print $outFile "            }\n";
	}
	# signed ints dump as decimals
	elsif(exists $attribute->{simpleType}
	      && ( (exists $attribute->{simpleType}->{int8_t}) ||
		  (exists $attribute->{simpleType}->{int16_t}) ||
		  (exists $attribute->{simpleType}->{int32_t}) ||
		  (exists $attribute->{simpleType}->{int64_t})
		  )
		)
	{
	    print $outFile "            { //simpleType:int\n";
	    print $outFile "                AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
	    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
	    print $outFile "                    TRACFCOMP( i_trac, \"DUMP: ",$attribute->{id},"=%d\", tmp );\n";
	    print $outFile "                }\n";
	    print $outFile "            }\n";
	}
	# unsigned ints dump as hex
	elsif(exists $attribute->{simpleType}
	      && ( (exists $attribute->{simpleType}->{uint8_t}) ||
		  (exists $attribute->{simpleType}->{uint16_t}) ||
		  (exists $attribute->{simpleType}->{uint32_t}) ||
		  (exists $attribute->{simpleType}->{uint64_t})
		  )
		)
	{
	    print $outFile "            { //simpleType:uint\n";
	    print $outFile "                AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
	    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
	    print $outFile "                    TRACFCOMP( i_trac, \"DUMP: ",$attribute->{id},"=0x%X\", tmp );\n";
	    print $outFile "                }\n";
	    print $outFile "            }\n";
	}
	# makes no sense to dump mutex attributes, so skipping
	elsif(exists $attribute->{simpleType} && (exists $attribute->{simpleType}->{hbmutex}) ) {
	    print $outFile "            //Skipping Mutex ",$attribute->{id},"\n";
	}
	# use the built-in stringifier for EntityPaths
	elsif(exists $attribute->{nativeType} && ($attribute->{nativeType}->{name} eq "EntityPath")) {
	    print $outFile "            { //nativeType:EntityPath\n";
	    print $outFile "                AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
	    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
	    print $outFile "                    char* tmpstring = tmp.toString();\n";
	    print $outFile "                    TRACFCOMP( i_trac, \"DUMP: ",$attribute->{id},"=%s\", tmpstring );\n";
	    print $outFile "                    free(tmpstring);\n";
	    print $outFile "                }\n";
	    print $outFile "            }\n";
	}
	# any other nativeTypes are just decimals...  (I never saw one)
	elsif(exists $attribute->{nativeType}) {
	    print $outFile "            { //nativeType\n";
	    print $outFile "                AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
	    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
	    print $outFile "                    TRACFCOMP( i_trac, \"DUMP: ",$attribute->{id},"=%d\", tmp );\n";
	    print $outFile "                }\n";
	    print $outFile "            }\n";
	}
	# any complicated types just get dumped as raw hex binary
	elsif(exists $attribute->{complexType}) {
	    print $outFile "            { //complexType\n";
	    print $outFile "                AttributeTraits<ATTR_",$attribute->{id},">::Type tmp;\n";
	    print $outFile "                if( (*l_targ)->tryGetAttr<ATTR_",$attribute->{id},">(tmp) ) {\n";
	    print $outFile "                    TRACFBIN( i_trac, \"DUMP: ",$attribute->{id},"=\", &tmp, sizeof(tmp) );\n";
	    print $outFile "                }\n";
	    print $outFile "            }\n";
	}
	# just in case, add a comment about missing types
	else
	{
	    print $outFile "            //Skipping ",$attribute->{id},"\n";
	}
    }

    print $outFile "        }\n";
    print $outFile "\n";
    print $outFile "        if( !foundit )\n";
    print $outFile "        {\n";
    print $outFile "            TRACFCOMP( i_trac, \"DUMP: No Target found matching HUID=%.8X\", i_huid );\n";
    print $outFile "        }\n";
    print $outFile "    }\n";
    print $outFile "\n";

    # add another prototype that is easier to call from debug framework
    print $outFile "    void dumpAllAttributes2( trace_desc_t** i_trac, uint32_t i_huid )\n";
    print $outFile "    {\n";
    print $outFile "        dumpAllAttributes( *i_trac, i_huid );\n";
    print $outFile "    }\n";
    print $outFile "\n";

    print $outFile "}\n";
    print $outFile "\n";
}

sub UTILITY_FUNCTIONS { }

################################################################################
# Get generated enumeration describing attribute IDs
################################################################################

sub getAttributeIdEnumeration {
  my($attributes) = @_;

    my $attributeValue = 0;
    my $enumeration = { } ;

    # add the N/A value
    $enumeration->{description} = "Internal enum for attribute IDs\n";
    $enumeration->{default} = "NA";
    $enumeration->{enumerator}->[0]->{name} = "NA";
    $enumeration->{enumerator}->[0]->{value} = 0;

    foreach my $attribute (@{$attributes->{attribute}})
    {
        $attributeValue++;
        $enumeration->{enumerator}->[$attributeValue]->{name}
            = $attribute->{id};
        $enumeration->{enumerator}->[$attributeValue]->{value}
            = sprintf "%u",$attributeValue;
        $attribute->{value} = $attributeValue;
    }

    return $enumeration;
}

################################################################################
# If value is hex, convert to regular number
###############################################################################

sub unhexify {
    my($val) = @_;
    if($val =~ m/^0[xX][01234567890A-Fa-f]+$/)
    {
        $val = hex($val);
    }
    return $val;
}

################################################################################
# Pack 8 byte value into a buffer using configured endianness
################################################################################

sub pack8byte {
    my($quad) = @_;

    my $value = unhexify($quad);

    my $binaryData;
    if($cfgBigEndian)
    {
        $binaryData = pack("NN" , (($value >> 32) & 0xFFFFFFFF),
                                    ($value & 0xFFFFFFFF));
    }
    else # Little endian
    {
        # Invert the words, then reverse them individually
        $binaryData = pack("VV" , ($value & 0xFFFFFFFF),
                                     (($value >> 32) & 0xFFFFFFFF));
    }

    return $binaryData;
}

################################################################################
# Pack 4 byte value into a buffer using configured endianness
################################################################################

sub pack4byte {
    my($value) = @_;

    my $binaryData;
    if($cfgBigEndian)
    {
        $binaryData = pack("N",$value);
    }
    else # Little endian
    {
        $binaryData = pack("V",$value);
    }

    return $binaryData;
}

################################################################################
# Pack 2 byte value into a buffer using configured endianness
################################################################################

sub pack2byte {
    my($value) = @_;

    my $binaryData;
    if($cfgBigEndian)
    {
        $binaryData = pack("n",$value);
    }
    else # Little endian
    {
        $binaryData = pack("v",$value);
    }

    return $binaryData;
}

################################################################################
# Pack 1 byte value into a buffer using configured endianness
################################################################################

sub pack1byte {
    my($value) = @_;

    my $binaryData = pack("C",$value);

    return $binaryData;
}

################################################################################
# Pack string into buffer
################################################################################

sub packString{
    my($value,$attribute) = @_;

    # Proper attribute tags already verified, no need to do checking again
    my $sizeInclNull = $attribute->{simpleType}->{string}->{sizeInclNull};

    # print "String content (before fixup) is [$value]\n";

    # For sanity, remove all white space from front and end of string
    $value =~ s/^\s+//g;
    $value =~ s/\s+$//g;

    my $length = length($value);

    # print "String content (after fixup) is [$value]\n";
    # print "String length is $length\n";
    # print "String container size is $sizeInclNull\n";

    if(($length + 1) > $sizeInclNull)
    {
        fatal("ERROR: Supplied string exceeds allows length");
    }

    return pack("Z$sizeInclNull",$value);
}

################################################################################
# Get space required to store an enum, based on the max value
################################################################################

sub enumSpace {
    my($maxEnumVal) = @_;
    if($maxEnumVal == 0)
    {
        # Enum needs at least one byte
        $maxEnumVal++;
    }

    # NOTE: Pass --noshort-enums command line option to force the code generator
    # to generate 4-byte enums instead of optimized enums.  Note there are a few
    # enumerations (primarily in PNOR header, etc.) that do not change size.
    # That is intentional in order to make this the single point of control over
    # binary compatibility.  Note that both FSP and Hostboot should always have
    # this policy in sync.  Also note that when Hostboot and FSP use optimized
    # enums, they must also be compiled with -fshort-enums compile option

    my $space = ($cfgShortEnums == 1) ?
        ceil(log($maxEnumVal+1) / (8 * log(2))) : 4;

    return $space;
}

################################################################################
# Get mininum # of bytes, in block size chunks, able to contain the input data
################################################################################

sub sizeBlockAligned {
    my ($size,$blockSize,$oneBlockMinimum) = @_;

    if( (!defined $size)
       || (!defined $blockSize)
       || (!defined $oneBlockMinimum) )
    {
        fatal("Caller must specify 'size', 'blockSize', 'oneBlockMinimum' "
            . "args.");
    }

    if(!$blockSize)
    {
        fatal("'blockSize' arg must be > 0.");
    }

    if(($size % $blockSize) || (($size==0) && $oneBlockMinimum) )
    {
        $size += ($blockSize - ($size % $blockSize));
    }

    return $size;
}

################################################################################
# Strips off leading and trailing whitespace from a string and returns it
################################################################################

sub stripLeadingAndTrailingWhitespace {
    my($string) = @_;

    $string =~ s/^\s+|\s+$//g;

    return $string;
}

################################################################################
# Optimize white space for C++/doxygen documentation
################################################################################

sub optWhiteSpace {
    my($text) = @_;

    # Remove leading, trailing white space, then collapse excess internal
    # whitespace
    $text =~ s/^\s+|\s+$//g;
    $text =~ s/\s+/ /g;

    return $text;
}

################################################################################
# Wrap text into a C++/doxygen brief description
################################################################################

sub wrapBrief {
    my($text) = @_;

    my $brief_start      = " *  \@brief ";
    my $brief_continue   = " *      ";

    return wrap($brief_start,$brief_continue, optWhiteSpace($text))."\n";
}

################################################################################
# Wrap text into a C++ style comment
################################################################################

sub wrapComment {
    my($text) = @_;

    my $comment_start    = "    // ";
    my $comment_continue = "    // ";

    return wrap($comment_start,$comment_continue,optWhiteSpace($text))."\n";
}

################################################################################
# Calculate struct type name for a header file, based on its ID
################################################################################

sub calculateStructName {
    my($id) = @_;

    my $type = "";

    # Struct name is original ID with underscores removed and first letter of
    # each word capitalized
    my @words = split(/_/,$id);
    foreach my $word (@words)
    {
        $type .= ucfirst( lc($word) );
    }

    return $type;
}

################################################################################
# Return array containing only distinct target types that are actally in use
################################################################################

sub getInstantiatedTargetTypes {
    my($attributes) = @_;

    my %seen = ();
    my @uniqueTargetTypes = ();

    foreach my $targetInstance (@{$attributes->{targetInstance}})
    {
        push (@uniqueTargetTypes, $targetInstance->{type})
            unless $seen{$targetInstance->{type}}++;
    }

    return @uniqueTargetTypes;
}

################################################################################
# Return default value of zero for an attribute which is a POD numerical type
################################################################################

sub defaultZero {
    my($attributes,$typeInstance) = @_;

    # print STDOUT "Attribute's default value is 0\n";

    return 0;
}

################################################################################
# Return string default (empty string)
################################################################################

sub defaultString {
    my($attributes,$typeInstance) = @_;

    return "";
}

################################################################################
# Return default value for an attribute whose type is 'enumeration'
################################################################################

sub defaultEnum {
    my($attributes,$enumerationInstance) = @_;

    my $enumerationType = getEnumerationType(
        $attributes,$enumerationInstance->{id});

    # print STDOUT "Attribute enumeration's " .
    #    "(\"$enumerationType->{id}\") default is: " .
    #        $enumerationType->{default} . "\n";

    return $enumerationType->{default};
}

################################################################################
# Do nothing
################################################################################

sub null {

}

################################################################################
# Enforce special host boot mutex restrictions
################################################################################

sub enforceHbMutex {
    my($attribute,$value) = @_;

    if($value != 0)
    {
        fatal("HB mutex attribute default must always be 0, "
              . "was $value instead.");
    }

    if($attribute->{persistency} ne "volatile-zeroed")
    {
        fatal("HB mutex attribute persistency must be volatile-zeroed, "
              . "was $attribute->{persistency} instead");
    }
}

################################################################################
# Enforce string restrictions
################################################################################

sub enforceString {
    my($attribute,$value) = @_;

    if(!exists $attribute->{simpleType})
    {
        fatal("ERROR: Tried to enforce string policies on a non-simple type");
    }

    if(!exists $attribute->{simpleType}->{string})
    {
        fatal("ERROR: Did not find expected string element");
    }

    if(!exists $attribute->{simpleType}->{string}->{sizeInclNull})
    {
        fatal("ERROR: Did not find expected string sizeInclNull element");
    }

    my $size = $attribute->{simpleType}->{string}->{sizeInclNull};
    if($size <= 1)
    {
        fatal("ERROR: String size must be > 1 (string of size one is "
            . "only big enough to hold the empty string, which is not "
            . "useful)");
    }
}

################################################################################
# Get hash ref to supported simple types and their properties
################################################################################
my $g_simpleTypeProperties_cache = 0;

sub simpleTypeProperties {

    return $g_simpleTypeProperties_cache if ($g_simpleTypeProperties_cache);

    my %typesHoH = ();

    # Intentionally didn't wrap these to 80 columns to keep them lined up and
    # more readable/editable
    $typesHoH{"string"}      = { supportsArray => 0, canBeHex => 0, complexTypeSupport => 0, typeName => "char"                       , bytes => 1, bits => 8 , default => \&defaultString, alignment => 1, specialPolicies =>\&enforceString,  packfmt =>\&packString};
    $typesHoH{"int8_t"}      = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "int8_t"                     , bytes => 1, bits => 8 , default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt => "C" };
    $typesHoH{"int16_t"}     = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "int16_t"                    , bytes => 2, bits => 16, default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt =>\&pack2byte};
    $typesHoH{"int32_t"}     = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "int32_t"                    , bytes => 4, bits => 32, default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt =>\&pack4byte};
    $typesHoH{"int64_t"}     = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "int64_t"                    , bytes => 8, bits => 64, default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt =>\&pack8byte};
    $typesHoH{"uint8_t"}     = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "uint8_t"                    , bytes => 1, bits => 8 , default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt => "C" };
    $typesHoH{"uint16_t"}    = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "uint16_t"                   , bytes => 2, bits => 16, default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt =>\&pack2byte};
    $typesHoH{"uint32_t"}    = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "uint32_t"                   , bytes => 4, bits => 32, default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt =>\&pack4byte};
    $typesHoH{"uint64_t"}    = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 1, typeName => "uint64_t"                   , bytes => 8, bits => 64, default => \&defaultZero  , alignment => 1, specialPolicies =>\&null,           packfmt =>\&pack8byte};
    $typesHoH{"enumeration"} = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 0, typeName => "XMLTOHB_USE_PARENT_ATTR_ID" , bytes => 0, bits => 0 , default => \&defaultEnum  , alignment => 1, specialPolicies =>\&null,           packfmt => "packEnumeration"};
    $typesHoH{"hbmutex"}     = { supportsArray => 1, canBeHex => 1, complexTypeSupport => 0, typeName => "mutex_t*"                   , bytes => 8, bits => 64, default => \&defaultZero  , alignment => 8, specialPolicies =>\&enforceHbMutex, packfmt =>\&pack8byte};
    $typesHoH{"Target_t"}    = { supportsArray => 0, canBeHex => 1, complexTypeSupport => 0, typeName => "TARGETING::Target*"         , bytes => 8, bits => 64, default => \&defaultZero  , alignment => 8, specialPolicies =>\&null,           packfmt =>\&pack8byte};

    $g_simpleTypeProperties_cache = \%typesHoH;

    return $g_simpleTypeProperties_cache;
}

################################################################################
# Get attribute default
################################################################################

sub getAttributeDefault {
    my($attributeId,$attributes) = @_;

    my $default = "";
    my $simpleTypeProperties = simpleTypeProperties();

    foreach my $attribute (@{$attributes->{attribute}})
    {
        if ($attribute->{id} eq $attributeId)
        {
            if(exists $attribute->{simpleType})
            {
                for my $type (sort(keys %{$simpleTypeProperties}))
                {
                    # Note: must check for 'type' before 'default', otherwise
                    # might add value to the hash
                    if(exists $attribute->{simpleType}->{$type} )
                    {
                        # If attribute exists, or is not a HASH val (which can
                        # occur if the default element is omitted), then just
                        # grab the supplied value, otherwise use the default for
                        # the type
                        if(   (exists $attribute->{simpleType}->{$type}->
                                   {default})
                           && (ref ($attribute->{simpleType}->{$type}->
                                   {default})
                               ne "HASH") )
                        {
                            $default =
                                $attribute->{simpleType}->{$type}->{default};
                        }
                        else
                        {
                           $default = $simpleTypeProperties->{$type}{default}->(
                                $attributes,$attribute->{simpleType}->{$type} );
                        }
                        last;
                    }
                }
            }
            elsif(exists $attribute->{complexType})
            {
                my $cplxDefault = { } ;
                my $i = 0;
                foreach my $field (@{$attribute->{complexType}->{field}})
                {
                    $cplxDefault->{field}->[$i]->{id} = $field->{name};
                    $cplxDefault->{field}->[$i]->{value} = $field->{default};
                    $i++;
                }
                return $cplxDefault;
            }
            elsif(exists $attribute->{nativeType})
            {
                if(   exists $attribute->{nativeType}->{name}
                   && ($attribute->{nativeType}->{name} eq "EntityPath"))
                {
                    $default =  "MustBeOverriddenByTargetInstance";
                }
                else
                {
                    fatal("Cannot provide default for unsupported nativeType.");
                }
            }
            else
            {
                fatal("Unrecognized value type.");
            }

            last;
        }
    }

    return $default;
}

################################################################################
# Get target attributes
################################################################################

sub getTargetAttributes {
    my($type,$attributes,$attrhasha) = @_;

    foreach my $targetType (@{$attributes->{targetType}})
    {
        if($targetType->{id} eq $type)
        {
            if(exists $targetType->{parent})
            {
                getTargetAttributes($targetType->{parent},
                    $attributes,$attrhasha);
            }

            foreach my $attr (@{$targetType->{attribute}})
            {
                $attrhasha->{ $attr->{id} } = $attr;

                if(!exists $attrhasha->{ $attr->{id}}->{default})
                {
                   my $default = getAttributeDefault($attr->{id},$attributes);
                   $attrhasha->{ $attr->{id}}->{default} = $default;
                }
            }

            last;
        }
    }
}

################################################################################
# Compute maximum enumerator value for a given enumeration
################################################################################

sub maxEnumValue {
    my($enumeration) = @_;

    my $max = 0;
    my $candidateMax = 0;
    foreach my $enumerator (@{$enumeration->{enumerator}})
    {
        my $candidateMax = enumNameToValue($enumeration,$enumerator->{name});
        if($candidateMax > $max)
        {
            $max = $candidateMax;
        }
    }

    return $max;
}

################################################################################
# Serialize an enumeration to data buffer
################################################################################

sub packEnumeration {
    my($enumeration,$value) = @_;

    my $binaryData;

    # Determine space required for max enum
    my $bytes = enumSpace( maxEnumValue($enumeration) );

    $value = unhexify($value);

    # Encode the value
    for (my $count=$bytes-1; $count >= 0; $count--)
    {
        if($cfgBigEndian)
        {
            $binaryData .= pack1byte(0xFF & ($value >> (8*$count)));
        }
        else # Little endian
        {
            $binaryData .= pack1byte(
                    0xFF & ($value >> (8*($bytes - 1 - $count))));
        }
    }

    if( (length $binaryData) < 1)
    {
        fatal("Failed to write binary data for enumeration.");
    }

    #print "           Enum description: ", $enumeration->{description}, "\n";
    #print "Enum storage space required: ", $bytes, "\n";
    #print "              Value encoded: ", $value, "\n";
    #print "     Final length of encode: ", (length $binaryData), "\n";

    return $binaryData;
}

################################################################################
# Convert enumerator name into equivalent enumerator value for given enumeration
################################################################################

sub enumNameToValue {
    my ($enumeration,$enumeratorName) = @_;

    my $nextEnumeratorValue = 0;
    my $found = 0;
    my $enumeratorValue;

    if (defined $enumeration->{__optimized})
    {
        if (defined $enumeration->{__optimized}->{$enumeratorName})
        {
            $found = 1;
            $enumeratorValue = $enumeration->{__optimized}->{$enumeratorName};
        }
    }
    else
    {
        foreach my $enumerator (@{$enumeration->{enumerator}})
        {
            my $currentEnumeratorValue;
            if(exists $enumerator->{value} )
            {
                $currentEnumeratorValue = unhexify($enumerator->{value});
                $nextEnumeratorValue = $currentEnumeratorValue + 1;
            }
            else
            {
                $currentEnumeratorValue = $nextEnumeratorValue;
                $nextEnumeratorValue += 1;
            }

            $enumeration->{__optimized}->{$enumerator->{name}}
                = $currentEnumeratorValue;

            if($enumerator->{name} eq $enumeratorName)
            {
                $found = 1;
                $enumeratorValue = $currentEnumeratorValue;
            }
        }
    }

    if(!$found)
    {
        my $enumerationName = $enumeration->{id};

        fatal("Could not convert enumerator name \"$enumeratorName\"into "
            . "enumerator value in \"$enumerationName\".");
    }

    return $enumeratorValue;
}

################################################################################
# Query if target instance is an FSP target
################################################################################

my %g_fspTargetTypesCache = ();

sub isFspTargetInstance {
    my($attributes,$targetInstance) = @_;
    my $fspTargetInstance = 0;

    if(%g_fspTargetTypesCache)
    {
        $fspTargetInstance = %g_fspTargetTypesCache->{$targetInstance->{type}};
    }
    else
    {
        %g_fspTargetTypesCache =
            map { $_->{id} => exists $_->{fspOnly} ? 1:0 } 
                @{$attributes->{targetType}};
        $fspTargetInstance = %g_fspTargetTypesCache->{$targetInstance->{type}};
    }
    
    return $fspTargetInstance;
}

################################################################################
# Object which accumulates/flushes bit field data
################################################################################

{

package Accumulator;

################################################################################
# Constructor; create a new Accumulator object
################################################################################

sub new {
    my ($class) = @_;
    my $self = { _currentType => "", _accumulator => "", _bits => 0 };

    bless $self, $class;
    return $self;
}

################################################################################
# Accumulate a new bit field
################################################################################

sub accumulate {
    my($self,$type,$bits,$value) = @_;

    my $binaryData;
    my $simpleTypeProperties = main::simpleTypeProperties();

    if($bits > $simpleTypeProperties->{$type}{bits})
    {
        main::fatal("Too many bits ($bits) for type ($type).");
    }

    if($self->{_currentType} eq "")
    {
        $self->{_currentType} = $type;
        $self->{_bits} = $bits;
    }
    elsif($self->{_currentType} eq $type)
    {
        if($self->{_bits} + $bits >
            $simpleTypeProperties->{$self->{_currentType}}{bits})
        {
            $binaryData = $self->releaseAndClear();
            $self->{_currentType} = $type;
            $self->{_bits} = $bits;
        }
        else
        {
            $self->{_bits} += $bits;
        }
    }
    else
    {
         $binaryData = $self->releaseAndClear();
         $self->{_currentType} = $type;
         $self->{_bits} = $bits;
    }

    for(my $count = 0; $count < $bits; $count++)
    {
        if($cfgBigEndian)
        {
            if( 1 & ($value >> $bits - $count - 1))
            {
                $self->{_accumulator} .= "1";
            }
            else
            {
                $self->{_accumulator} .= "0";
            }
        }
        else
        {
            if( 1 & ($value >> $count))
            {
                $self->{_accumulator} .= "1";
            }
            else
            {
                $self->{_accumulator} .= "0";
            }
        }
    }

    return $binaryData;
}

################################################################################
# Release the accumulator (if non-empty) to the caller and clear
################################################################################

sub releaseAndClear {
    my($self) = @_;

    my $binaryData;

    if($self->{_currentType} ne "")
    {
        my $simpleTypeProperties = main::simpleTypeProperties();

        if($cfgBigEndian)
        {
            $binaryData = pack
            ("B$simpleTypeProperties->{$self->{_currentType}}{bits}",
                $self->{_accumulator});
        }
        else # Little endian, inverse order
        {
            $binaryData = pack
            ("b$simpleTypeProperties->{$self->{_currentType}}{bits}",
                $self->{_accumulator});
        }

        $self->{_accumulator} = "";
        $self->{_currentType} = "";
        $self->{_bits} = 0;
    }

    return $binaryData;
}

1;

}

################################################################################
# Pack a complex type into a binary data stream
################################################################################

sub packComplexType {
    my ($attributes,$complexType,$attributeDefault) = @_;

    my $binaryData;
    my $simpleTypeProperties = simpleTypeProperties();

    my $accumulator = new Accumulator();

    # Build using each field
    foreach my $field (@{$complexType->{field}})
    {
        # print STDERR "Field   = ", $field->{name}, "\n";
        # print STDERR "Default = ", $field->{default}, "\n";
        # print STDERR "Bits    = ", $field->{bits}, "\n";
        # print STDERR "Type    = ", $field->{type}, "\n";

        my $found = 0;
        foreach my $default (@{$attributeDefault->{field}})
        {
            if($default->{id} eq $field->{name})
            {
                $found = 1;
                if(exists $field->{bits})
                {
                    $binaryData .= $accumulator->accumulate(
                        $field->{type},unhexify($field->{bits}),
                           unhexify($default->{value}));
                }
                # If non-bitfield
                else
                {
                    $binaryData .= $accumulator->releaseAndClear();

                    # If native "EntityPath" type, process accordingly
                    if($field->{type} eq "EntityPath")
                    {
                         $binaryData .= packEntityPath($attributes,
                            $default->{value});
                    }
                    # If not a defined simple type, process as an enumeration
                    elsif(!exists $simpleTypeProperties->{$field->{type}})
                    {
                        my $enumerationType = getEnumerationType(
                            $attributes,$field->{type});
                        my $enumeratorValue = enumNameToValue($enumerationType,
                            $default->{value});
                        $binaryData .= packEnumeration($enumerationType,
                            $enumeratorValue);
                    }
                    # Pack easy types using 'pack', otherwise invoke appropriate
                    # (possibly workaround) callback function
                    elsif(exists $simpleTypeProperties->{$field->{type}}
                       && $simpleTypeProperties->{$field->{type}}
                            {complexTypeSupport})
                    {
                        my $defaultValue = $default->{value};
                        if($simpleTypeProperties->{$field->{type}}{canBeHex})
                        {
                            $defaultValue = unhexify($defaultValue);
                        }

                        if(ref ($simpleTypeProperties->{$field->{type}}
                            {packfmt}) eq "CODE")
                        {
                            $binaryData .=
                                $simpleTypeProperties->{$field->{type}}
                                    {packfmt}->($defaultValue);
                        }
                        else
                        {
                            $binaryData .= pack(
                                $simpleTypeProperties->{$field->{type}}
                                    {packfmt},$defaultValue);
                        }
                    }
                    else
                    {
                        fatal("Field type $field->{type} not supported in "
                            . "complex type.");
                    }
                }

                last;
            }
        }

        if(!$found)
        {
            fatal("Could not find value for field $field->{name} of type $field->{type}");
        }
    }

    $binaryData .= $accumulator->releaseAndClear();

    return $binaryData;
}

################################################################################
# Pack an entity path into a binary data stream
################################################################################

sub packEntityPath {
    my($attributes,$value) = @_;

    my $binaryData;

    my $maxPathElements = 10;
    my ($typeStr,$path) = split(/:/,$value);
    my (@paths) = split(/\//,$path);

    my $type = 0;

    # Trim whitespace from the type
    $typeStr =~ s/^\s+|\s+$//g;
    if($typeStr eq "physical")
    {
        $type = 2;
    }
    elsif($typeStr eq "affinity")
    {
        $type = 1;
    }
    else
    {
        fatal("Unsupported enity path type of [$value], [$typeStr], [$path].");
    }

    if( (scalar @paths) > $maxPathElements)
    {
        fatal("Path elements cannot be greater than $maxPathElements.");
    }

    if($cfgBigEndian)
    {
        $binaryData .= pack1byte((0xF0 & ($type << 4)) +
            (0x0F & (scalar @paths)));
    }
    else # Little endian
    {
        $binaryData .= pack1byte((0x0F & ($type)) +
            (0xF0 & ((scalar @paths) << 4)));
    }

    foreach my $pathElement (@paths)
    {
        my ($pathType,$pathInstance) = split(/-/,$pathElement);
        $pathType = uc($pathType);

        foreach my $attr (@{$attributes->{attribute}})
        {
            if($attr->{id} eq "TYPE")
            {
                $pathType =
                enumNameToValue(
                  getEnumerationType($attributes,
                   $attr->{simpleType}->{enumeration}->{id}),$pathType);
                $binaryData .= pack1byte($pathType);
                $binaryData .= pack1byte($pathInstance);
                last;
            }
        }
    }

    if($maxPathElements > (scalar @paths))
    {
        $binaryData .= pack("C".(($maxPathElements - scalar @paths)*2));
    }

    return $binaryData;
}

################################################################################
# Pack a single, simple attribute into a binary data stream
################################################################################

sub packSingleSimpleTypeAttribute {
    my($binaryDataRef,$attributesRef,$attributeRef,$typeName,$value) = @_;

    my $simpleType = $$attributeRef->{simpleType};
    my $simpleTypeProperties = simpleTypeProperties();

    if($typeName eq "enumeration")
    {
        my $enumeration = getEnumerationType($$attributesRef,$simpleType->
            {enumeration}->{id});

        # Here $value is the enumerator name
        my $enumeratorValue = enumNameToValue($enumeration,$value);
        $$binaryDataRef .= packEnumeration($enumeration,$enumeratorValue);
    }
    else
    {
        if($simpleTypeProperties->{$typeName}{canBeHex})
        {
            $value = unhexify($value);
        }

        # Apply special policy enforcement, if any
        $simpleTypeProperties->{$typeName}{specialPolicies}->($$attributeRef,
            $value);

        if(ref ($simpleTypeProperties->{$typeName}{packfmt}) eq "CODE")
        {
            $$binaryDataRef .= $simpleTypeProperties->{$typeName}{packfmt}->
                               ($value,$$attributeRef);
        }
        else
        {
            $$binaryDataRef .= pack($simpleTypeProperties->{$typeName}{packfmt},
                                    $value);
        }
    }
}

################################################################################
# Pack generic attribute into a binary data stream
################################################################################

sub packAttribute {
    my($attributes,$attribute,$value) = @_;

    $value = stripLeadingAndTrailingWhitespace($value);

    my $binaryData;

    my $alignment = 1;
    if(exists $attribute->{simpleType})
    {
        my $simpleType = $attribute->{simpleType};
        my $simpleTypeProperties = simpleTypeProperties();

        for my $typeName (sort(keys %{$simpleType}))
        {
            if(exists $simpleTypeProperties->{$typeName})
            {
                $alignment = $simpleTypeProperties->{$typeName}{alignment};

                if (($simpleTypeProperties->{$typeName}{supportsArray}) &&
                    (exists $simpleType->{array}))
                {
                    # This is an array attribute, handle the value parameter as
                    # an array, if there are not enough values for the whole
                    # array then use the last value to fill in the remainder

                    # Figure out the array size (possibly multidimensional)
                    my $arraySize = 1;
                    my @bounds = split(/,/,$simpleType->{array});
                    foreach my $bound (@bounds)
                    {
                        $arraySize *= $bound;
                    }

                    # Split the values into an array
                    my @values = split(/,/,$value);
                    my $valueArraySize = scalar(@values);

                    # Iterate over the entire array creating values
                    my $val = "";
                    for (my $i = 0; $i < $arraySize; $i++)
                    {
                        if ($i < $valueArraySize)
                        {
                            # Get the value from the value array and strip any
                            # remaining leading/trailing whitespace that
                            # surrounded the value after the original split
                            $val = stripLeadingAndTrailingWhitespace($values[$i]);
                        }
                        # else use the last value

                        packSingleSimpleTypeAttribute(\$binaryData,
                            \$attributes, \$attribute, $typeName, $val);
                    }
                }
                else
                {
                    # Not an array attribute
                    packSingleSimpleTypeAttribute(\$binaryData,
                        \$attributes, \$attribute,$typeName, $value);
                }

                last;
            }
        }

        if( (length $binaryData) < 1)
        {
            fatal("Error requested simple type not supported.  Keys are ("
                . join(',',sort(keys %{$simpleType})) . ")");
        }
    }
    elsif(exists $attribute->{complexType})
    {
        if(ref ($value) eq "HASH" )
        {
            $binaryData = packComplexType($attributes,$attribute->{complexType},
                $value);
        }
        else
        {
            fatal("Warning cannot serialize non-hash complex type.");
        }
    }
    elsif(exists $attribute->{nativeType})
    {
        if($attribute->{nativeType}->{name} eq "EntityPath")
        {
            $binaryData = packEntityPath($attributes,$value);
        }
        else
        {
            fatal("Error nativeType not supported on attribute ID = "
                . "$attribute->{id}.");
        }
    }
    else
    {
        fatal("Unsupported attribute type on attribute ID = $attribute->{id}.");
    }

    if( (length $binaryData) < 1)
    {
        fatal("Serialization failed for attribute ID = $attribute->{id}.");
    }

    return ($binaryData,$alignment);
}

################################################################################
# Get the PNOR base address from host boot code
################################################################################

sub getPnorBaseAddress {
    my($vmmConstsFile) = @_;
    my $pnorBaseAddress = 0;

    open(VMM_CONSTS_FILE,"<$vmmConstsFile")
      or fatal ("VMM Constants file: \"$vmmConstsFile\" could not be opened.");

    foreach my $line (<VMM_CONSTS_FILE>)
    {
        chomp($line);
        if( $line =~ /VMM_VADDR_ATTR_RP/)
        {
            $line =~ s/[^0-9\*]//g;
            $pnorBaseAddress = eval $line;
            last;
        }
    }

    if($pnorBaseAddress == 0)
    {
        fatal("PNOR base address was zero!");
    }

    return $pnorBaseAddress;
}

################################################################################
# Write the PNOR targeting image
################################################################################

sub generateTargetingImage {
    my($vmmConstsFile, $attributes, $Target_t) = @_;

    # 128 MB virtual memory offset between sections
    #@TODO Need the final value after full host boot support is implemented.
    my $vmmSectionOffset = 128 * 1024 * 1024; # 128MB

    # Virtual memory addresses corresponding to the start of the targeting image
    # PNOR/heap sections
    my $pnorRoBaseAddress    = getPnorBaseAddress($vmmConstsFile);
    my $pnorRwBaseAddress    = $pnorRoBaseAddress    + $vmmSectionOffset;
    my $heapPnorInitBaseAddr = $pnorRwBaseAddress    + $vmmSectionOffset;
    my $heapZeroInitBaseAddr = $heapPnorInitBaseAddr + $vmmSectionOffset;
    my $hbHeapZeroInitBaseAddr = $heapZeroInitBaseAddr + $vmmSectionOffset;

    # Split "fsp" into additional sections
    my $fspP0DefaultedFromZeroBaseAddr   = $hbHeapZeroInitBaseAddr + $vmmSectionOffset;
    my $fspP0DefaultedFromP3BaseAddr  = $fspP0DefaultedFromZeroBaseAddr + $vmmSectionOffset;
    my $fspP3RoBaseAddr         = $fspP0DefaultedFromP3BaseAddr + $vmmSectionOffset;
    my $fspP3RwBaseAddr         = $fspP3RoBaseAddr + $vmmSectionOffset;
    my $fspP1DefaultedFromZeroBaseAddr   = $fspP3RwBaseAddr + $vmmSectionOffset;
    my $fspP1DefaultedFromP3BaseAddr  = $fspP1DefaultedFromZeroBaseAddr + $vmmSectionOffset;

    # Reserve 256 bytes for the header, then keep track of PNOR RO offset
    my $headerSize = 256;
    my $offset = $headerSize;

    # Reserve space for the pointer to the # of targets, update later;
    my $numTargetsPointer = 0;
    my $numTargetsPointerBinData = pack8byte($numTargetsPointer);
    $offset += (length $numTargetsPointerBinData);

    ############################################################################
    # Build the attribute list for each unique CTM
    ############################################################################

    # Get an array of only the unique types of targets actually used by the
    # aggregation of target instances.
    my @targetTypes = getInstantiatedTargetTypes($attributes);

    my $attributeIdEnumeration = getAttributeIdEnumeration($attributes);

    my %attributeListTypeHoH = ();
    my $attributeListBinData;

    # For each unique type of target modeled, create the attribute list
    foreach my $targetType (@targetTypes)
    {
        # Create the attribute list associated with each target type
        #@TODO Eventually we'll need criteria to order the attributes
        # for code update
        my %attrhash = ();
        getTargetAttributes($targetType, $attributes,\%attrhash);

        # Serialize per target type attribute list
        my $perTargetTypeAttrBinData;
        for my $attributeId (sort(keys %attrhash))
        {
            $perTargetTypeAttrBinData .= packEnumeration(
                $attributeIdEnumeration,
                enumNameToValue($attributeIdEnumeration,$attributeId));
        }

        # Save offset of the attribute list, tied to the type
        $attributeListTypeHoH{$targetType}{offset} = $offset;
        $attributeListTypeHoH{$targetType}{elements} = scalar keys %attrhash;
        $attributeListTypeHoH{$targetType}{size} =
            (length $perTargetTypeAttrBinData);

        #print "Target type: $targetType\n";
        #print "   elements: $attributeListTypeHoH{$targetType}{elements}\n";
        #print "     offset: $attributeListTypeHoH{$targetType}{offset}\n";
        #print "       size: $attributeListTypeHoH{$targetType}{size}\n";

        # Append attribute data for this part to the attribute list subsection
        $attributeListBinData .= $perTargetTypeAttrBinData;

        # Increment the offset
        $offset += (length $perTargetTypeAttrBinData);
    }

    # For each target instance ...

    #@TODO Eventually we'll need criteria to order the attributes
    # for code update.  At minimum, ensure that we always process at this level
    # in the given order
    my @targetsAoH = ();
    foreach my $targetInstance (@{$attributes->{targetInstance}})
    {
        push(@targetsAoH, $targetInstance);
    }
    my $numTargets = @targetsAoH;

    my $numAttributes = 0;
    foreach my $targetInstance (@targetsAoH)
    {
        my %attrhash = ();
        getTargetAttributes($targetInstance->{type}, $attributes,\%attrhash);
        $numAttributes += keys %attrhash;
    }

    # Reserve # pointers * sizeof(pointer)
    my $startOfAttributePointers = $offset;
    # print "Total attributes = $numAttributes\n";
    $offset += ($numAttributes * (length pack8byte(0) ));

    # Now we can determine the pointer to the number of targets
    # Don't increment the offset; already accounted for
    $numTargetsPointer = $pnorRoBaseAddress + $offset;
    $numTargetsPointerBinData = pack8byte($numTargetsPointer);
    my $numTargetsBinData = pack4byte($numTargets);
    $offset += (length $numTargetsBinData);

    my $firstTgtPtr = $pnorRoBaseAddress + $offset;
    my $roAttrBinData;
    my $heapZeroInitOffset = 0;
    my $heapZeroInitBinData;
    my $heapPnorInitOffset = 0;
    my $heapPnorInitBinData;
    my $rwAttrBinData;
    my $rwOffset = 0;

    # Split into more granular sections
    my $fspP0DefaultedFromZeroOffset = 0;
    my $fspP0DefaultedFromZeroBinData;
    my $fspP0DefaultedFromP3Offset = 0;
    my $fspP0DefaultedFromP3BinData;
    my $fspP1DefaultedFromZeroOffset = 0;
    my $fspP1DefaultedFromZeroBinData;
    my $fspP1DefaultedFromP3Offset = 0;
    my $fspP1DefaultedFromP3BinData;
    my $fspP3RoOffset = 0;
    my $fspP3RoBinData;
    my $fspP3RwOffset = 0;
    my $fspP3RwBinData;

    # Hostboot specific section
    my $hbHeapZeroInitOffset = 0;
    my $hbHeapZeroInitBinData;

    my $attributePointerBinData;
    my $targetsBinData;

    # Ensure consistent ordering of target instances
    my $attrAddr = $pnorRoBaseAddress + $startOfAttributePointers;

    foreach my $targetInstance (@targetsAoH)
    {
        my $data;

         # print "TargetInstance: $targetInstance->{id}\n";
         # print "    Attributes:  ",
         # $attributeListTypeHoH{$targetInstance->{type}}{elements}, "\n" ;
         # print "        offset:  ",
         # $attributeListTypeHoH{$targetInstance->{type}}{offset}, "\n" ;

        # Create target record
        $data .= pack4byte(
            $attributeListTypeHoH{$targetInstance->{type}}{elements});
        $data .= pack8byte(
              $attributeListTypeHoH{$targetInstance->{type}}{offset}
            + $pnorRoBaseAddress);
        $data .= pack8byte($attrAddr);
        $attrAddr += $attributeListTypeHoH{$targetInstance->{type}}{elements}
            * (length pack8byte(0));

        # Increment the offset
        $offset += (length $data);

        # Add it to the target sub-section
        $targetsBinData .= $data;
    }

    my $pnorRoOffset = $offset;
    my $attributesWritten = 0;

    foreach my $targetInstance (@targetsAoH)
    {
        my $data;
        my %attrhash = ();
        my @AoH = ();

        # Ensure consistent ordering of attributes for each target type
        # Get the attribute list associated with each target type
        #@TODO Attributes must eventually be ordered correctly for code update
        getTargetAttributes($targetInstance->{type}, $attributes,\%attrhash);

        # Update hash with any per-instance overrides, but only if that
        # attribute has already been defined
        foreach my $attr (@{$targetInstance->{attribute}})
        {
            if(exists $attrhash{$attr->{id}})
            {
                $attrhash{ $attr->{id} } = $attr;
            }
            else
            {
                fatal("Target instance \"$targetInstance->{id}\" cannot "
                    . "override attribute \"$attr->{id}\" unless "
                    . "the attribute has already been defined in the target "
                    . "type inheritance chain.");
            }
        }

        # Flag if target is FSP specific; in that case store all of its 
        # attributes in the FSP section, regardless of whether they are 
        # themselves FSP specific.  Only need to do this 1x per target instance
        my $fspTarget = isFspTargetInstance($attributes,$targetInstance);
 
        my %attributeDefCache =
            map { $_->{id} => $_} @{$attributes->{attribute}};

        for my $attributeId (sort(keys %attrhash))
        {
            my $attributeDef = $attributeDefCache{$attributeId};
            if (not defined $attributeDef)
            {
                fatal("Attribute $attributeId is not found.");
            }

            my $section;
            # Split "fsp" into more sections later
            if(   (exists $attributeDef->{fspOnly})
               || ($fspTarget))
            {
                if( $attributeDef->{persistency} eq "volatile-zeroed"  )
                {
                    $section = "fspP0DefaultedFromZero";
                }
                elsif( $attributeDef->{persistency} eq "volatile" )
                {
                    $section = "fspP0DefaultedFromP3";
                }
                elsif( !exists $attributeDef->{writeable}
                       && $attributeDef->{persistency} eq "non-volatile" )
                {
                    $section = "fspP3Ro";
                }
                elsif( exists $attributeDef->{writeable}
                       && $attributeDef->{persistency} eq "non-volatile" ) 
                {
                    $section = "fspP3Rw";
                }
                elsif( $attributeDef->{persistency} eq "semi-non-volatile-zeroed" )
                {
                    $section = "fspP1DefaultedFromZero";
                }
                elsif( $attributeDef->{persistency} eq "semi-non-volatile" ) 
                {
                    $section = "fspP1DefaultedFromP3";
                }
                else
                {
                    fatal("Persistency '$attributeDef->{persistency}' is not "
                          . "supported for fspOnly attribute '$attributeId'.");
                }
            }
            elsif( exists $attributeDef->{hbOnly} )
            {
                if( $attributeDef->{persistency} eq "volatile-zeroed" )
                {
                    $section = "hb-heap-zero-initialized";
                }
                else
                {
                    fatal("Persistency '$attributeDef->{persistency}' is not "
                          . "supported for hbOnly attribute '$attributeId'.");
                }
            }
            elsif( exists $attributeDef->{writeable}
                    && $attributeDef->{persistency} eq "non-volatile" )
            {
                $section = "pnor-rw";
            }
            elsif ( !exists $attributeDef->{writeable}
                    && $attributeDef->{persistency} eq "non-volatile")
            {
                $section = "pnor-ro";
            }
            elsif ($attributeDef->{persistency} eq "volatile" )
            {
                $section = "heap-pnor-initialized";
            }
            elsif($attributeDef->{persistency} eq "volatile-zeroed")
            {
                $section = "heap-zero-initialized";
            }
            else
            {
                fatal("Persistency '$attributeDef->{persistency}' is not "
                      . "supported for attribute '$attributeId'.");
            }

            if($section eq "pnor-ro")
            {
                if ((exists ${$Target_t}{$attributeId}) &&
                    ($attrhash{$attributeId}->{default} != 0))
                {
                    my $index = $attrhash{$attributeId}->{default} - 1;
                    $index *= 20; # length(N + quad + quad)
                    $attrhash{$attributeId}->{default} = $index + $firstTgtPtr;
                }

                my ($rodata,$alignment) = packAttribute($attributes,
                        $attributeDef,
                        $attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($offset % $alignment))
                    % $alignment;
                $roAttrBinData .= pack ("@".$pads);
                $offset += $pads;

                $attributePointerBinData .= pack8byte(
                    $offset + $pnorRoBaseAddress);

                $offset += (length $rodata);

                $roAttrBinData .= $rodata;
            }
            elsif($section eq "pnor-rw")
            {
                my ($rwdata,$alignment) = packAttribute($attributes,
                        $attributeDef,
                        $attrhash{$attributeId}->{default});

                #print "Wrote to pnor-rw value ",$attributeDef->{id}, ",
                #", $attrhash{$attributeId}->{default}," \n";

                # Align the data as necessary
                my $pads = ($alignment - ($rwOffset % $alignment))
                    % $alignment;
                $rwAttrBinData .= pack ("@".$pads);
                $rwOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $rwOffset + $pnorRwBaseAddress);

                $rwOffset += (length $rwdata);

                $rwAttrBinData .= $rwdata;

            }
            elsif($section eq "heap-zero-initialized")
            {
                my ($heapZeroInitData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($heapZeroInitOffset
                            % $alignment)) % $alignment;
                $heapZeroInitBinData .= pack ("@".$pads);
                $heapZeroInitOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $heapZeroInitOffset + $heapZeroInitBaseAddr);

                $heapZeroInitOffset += (length $heapZeroInitData);

                $heapZeroInitBinData .= $heapZeroInitData;

            }
            elsif($section eq "heap-pnor-initialized")
            {
                my ($heapPnorInitData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($heapPnorInitOffset
                            % $alignment)) % $alignment;
                $heapPnorInitBinData .= pack ("@".$pads);
                $heapPnorInitOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $heapPnorInitOffset + $heapPnorInitBaseAddr);

                $heapPnorInitOffset += (length $heapPnorInitData);

                $heapPnorInitBinData .= $heapPnorInitData;
            }
            # Split FSP section into more granular sections
            elsif($section eq "fspP0DefaultedFromZero")
            {
                my ($fspP0ZeroData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($fspP0DefaultedFromZeroOffset
                            % $alignment)) % $alignment;
                $fspP0DefaultedFromZeroBinData .= pack ("@".$pads);
                $fspP0DefaultedFromZeroOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $fspP0DefaultedFromZeroOffset + $fspP0DefaultedFromZeroBaseAddr);

                $fspP0DefaultedFromZeroOffset += (length $fspP0ZeroData);

                $fspP0DefaultedFromZeroBinData .= $fspP0ZeroData;
            }
            elsif($section eq "fspP0DefaultedFromP3")
            {
                my ($fspP0FlashData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($fspP0DefaultedFromP3Offset
                            % $alignment)) % $alignment;
                $fspP0DefaultedFromP3BinData .= pack ("@".$pads);
                $fspP0DefaultedFromP3Offset += $pads;

                $attributePointerBinData .= pack8byte(
                    $fspP0DefaultedFromP3Offset + $fspP0DefaultedFromP3BaseAddr);

                $fspP0DefaultedFromP3Offset += (length $fspP0FlashData);

                $fspP0DefaultedFromP3BinData .= $fspP0FlashData;
            }
            elsif($section eq "fspP3Ro")
            {
                my ($fspP3RoData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($fspP3RoOffset
                            % $alignment)) % $alignment;
                $fspP3RoBinData .= pack ("@".$pads);
                $fspP3RoOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $fspP3RoOffset + $fspP3RoBaseAddr);

                $fspP3RoOffset += (length $fspP3RoData);

                $fspP3RoBinData .= $fspP3RoData;
            }
            elsif($section eq "fspP3Rw")
            {
                my ($fspP3RwData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($fspP3RwOffset
                            % $alignment)) % $alignment;
                $fspP3RwBinData .= pack ("@".$pads);
                $fspP3RwOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $fspP3RwOffset + $fspP3RwBaseAddr);

                $fspP3RwOffset += (length $fspP3RwData);

                $fspP3RwBinData .= $fspP3RwData;
            }
            elsif($section eq "fspP1DefaultedFromZero")
            {
                my ($fspP1ZeroData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($fspP1DefaultedFromZeroOffset
                            % $alignment)) % $alignment;
                $fspP1DefaultedFromZeroBinData .= pack ("@".$pads);
                $fspP1DefaultedFromZeroOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $fspP1DefaultedFromZeroOffset + $fspP1DefaultedFromZeroBaseAddr);

                $fspP1DefaultedFromZeroOffset += (length $fspP1ZeroData);

                $fspP1DefaultedFromZeroBinData .= $fspP1ZeroData;
            }
            elsif($section eq "fspP1DefaultedFromP3")
            {
                my ($fspP1FlashData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($fspP1DefaultedFromP3Offset
                            % $alignment)) % $alignment;
                $fspP1DefaultedFromP3BinData .= pack ("@".$pads);
                $fspP1DefaultedFromP3Offset += $pads;

                $attributePointerBinData .= pack8byte(
                    $fspP1DefaultedFromP3Offset + $fspP1DefaultedFromP3BaseAddr);

                $fspP1DefaultedFromP3Offset += (length $fspP1FlashData);

                $fspP1DefaultedFromP3BinData .= $fspP1FlashData;
            }
            # Hostboot specific section
            elsif($section eq "hb-heap-zero-initialized")
            {
                my ($hbHeapZeroInitData,$alignment) = packAttribute(
                        $attributes,
                        $attributeDef,$attrhash{$attributeId}->{default});

                # Align the data as necessary
                my $pads = ($alignment - ($hbHeapZeroInitOffset
                            % $alignment)) % $alignment;
                $hbHeapZeroInitBinData .= pack ("@".$pads);
                $hbHeapZeroInitOffset += $pads;

                $attributePointerBinData .= pack8byte(
                    $hbHeapZeroInitOffset + $hbHeapZeroInitBaseAddr);

                $hbHeapZeroInitOffset += (length $hbHeapZeroInitData);

                $hbHeapZeroInitBinData .= $hbHeapZeroInitData;
            }

            else
            {
                fatal("Could not find a suitable section.");
            }

            $attributesWritten++;

        } # End attribute loop

    } # End target instance loop

    if($numAttributes != $attributesWritten)
    {
        fatal("Number of attributes expected, $numAttributes, does not match "
              . "what was written to PNOR, $attributesWritten.");
    }

    # Build header data

    my $headerBinData;
    my $blockSize = 4*1024;

    my %sectionHoH = ();
    $sectionHoH{ pnorRo }{ offset } = 0;
    $sectionHoH{ pnorRo }{ type   } = 0;
    $sectionHoH{ pnorRo }{ size   } = sizeBlockAligned($offset,$blockSize,1);

    $sectionHoH{ pnorRw }{ offset } =
        $sectionHoH{pnorRo}{offset} + $sectionHoH{pnorRo}{size};
    $sectionHoH{ pnorRw }{ type   } = 1;
    $sectionHoH{ pnorRw }{ size   } = sizeBlockAligned($rwOffset,$blockSize,1);

    $sectionHoH{ heapPnorInit }{ offset } =
        $sectionHoH{pnorRw}{offset} + $sectionHoH{pnorRw}{size};
    $sectionHoH{ heapPnorInit }{ type   } = 2;
    $sectionHoH{ heapPnorInit }{ size   } =
        sizeBlockAligned($heapPnorInitOffset,$blockSize,1);

    $sectionHoH{ heapZeroInit }{ offset } =
        $sectionHoH{heapPnorInit}{offset} + $sectionHoH{heapPnorInit}{size};
    $sectionHoH{ heapZeroInit }{ type   } = 3;
    $sectionHoH{ heapZeroInit }{ size   } =
        sizeBlockAligned($heapZeroInitOffset,$blockSize,1);
  
    # zeroInitSection occupies no space in the binary, so set the
    # Hostboot section address to that of the zeroInitSection
    $sectionHoH{ hbHeapZeroInit }{ offset } =
        $sectionHoH{heapZeroInit}{ offset };
    $sectionHoH{ hbHeapZeroInit }{ type } = 10;
    $sectionHoH{ hbHeapZeroInit }{ size } =
        sizeBlockAligned($hbHeapZeroInitOffset,$blockSize,1);

    # Split "fsp" into additional sections
    if($cfgIncludeFspAttributes)
    {
        # zeroInitSection occupies no space in the binary, so set the FSP
        # section address to that of the zeroInitSection
        $sectionHoH{ fspP0DefaultedFromZero }{ offset } =
             $sectionHoH{heapZeroInit}{offset};
        $sectionHoH{ fspP0DefaultedFromZero }{ type } = 4;
        $sectionHoH{ fspP0DefaultedFromZero }{ size } =
            sizeBlockAligned($fspP0DefaultedFromZeroOffset,$blockSize,1);

        $sectionHoH{ fspP0DefaultedFromP3 }{ offset } =
             $sectionHoH{fspP0DefaultedFromZero}{offset} +
             $sectionHoH{fspP0DefaultedFromZero}{size};
        $sectionHoH{ fspP0DefaultedFromP3 }{ type } = 5;
        $sectionHoH{ fspP0DefaultedFromP3 }{ size } =
            sizeBlockAligned($fspP0DefaultedFromP3Offset,$blockSize,1);

        $sectionHoH{ fspP3Ro }{ offset } =
             $sectionHoH{fspP0DefaultedFromP3}{offset} +
             $sectionHoH{fspP0DefaultedFromP3}{size};
        $sectionHoH{ fspP3Ro }{ type } = 6;
        $sectionHoH{ fspP3Ro }{ size } =
            sizeBlockAligned($fspP3RoOffset,$blockSize,1);

        $sectionHoH{ fspP3Rw }{ offset } =
             $sectionHoH{fspP3Ro}{offset} + $sectionHoH{fspP3Ro}{size};
        $sectionHoH{ fspP3Rw }{ type } = 7;
        $sectionHoH{ fspP3Rw }{ size } =
            sizeBlockAligned($fspP3RwOffset,$blockSize,1);

        $sectionHoH{ fspP1DefaultedFromZero }{ offset } =
             $sectionHoH{fspP3Rw}{offset} + $sectionHoH{fspP3Rw}{size};
        $sectionHoH{ fspP1DefaultedFromZero }{ type } = 8;
        $sectionHoH{ fspP1DefaultedFromZero }{ size } =
            sizeBlockAligned($fspP1DefaultedFromZeroOffset,$blockSize,1);

        $sectionHoH{ fspP1DefaultedFromP3 }{ offset } =
             $sectionHoH{fspP1DefaultedFromZero}{offset} +
             $sectionHoH{fspP1DefaultedFromZero}{size};
        $sectionHoH{ fspP1DefaultedFromP3 }{ type } = 9;
        $sectionHoH{ fspP1DefaultedFromP3 }{ size } =
            sizeBlockAligned($fspP1DefaultedFromP3Offset,$blockSize,1);
    }

    my $numSections = keys %sectionHoH;

    # Version 1.0 to start with
    my $headerMajorMinorVersion = 0x00010000;
    my $eyeCatcher = 0x54415247; # TARG
    my $sizeOfSection = 9;
    my $offsetToSections = 0;

    $headerBinData .= pack4byte($eyeCatcher);
    $headerBinData .= pack4byte($headerMajorMinorVersion);
    $headerBinData .= pack4byte($headerSize);
    $headerBinData .= pack4byte($vmmSectionOffset);
    $headerBinData .= pack8byte($pnorRoBaseAddress);
    $headerBinData .= pack4byte($sizeOfSection);
    $headerBinData .= pack4byte($numSections);
    $headerBinData .= pack4byte($offsetToSections);

    # Split "fsp" into additional sections
    my @sections = ("pnorRo","pnorRw","heapPnorInit","heapZeroInit", "hbHeapZeroInit");
    if($cfgIncludeFspAttributes)
    {
        push(@sections,"fspP0DefaultedFromZero");
        push(@sections,"fspP0DefaultedFromP3");
        push(@sections,"fspP3Ro");
        push(@sections,"fspP3Rw");
        push(@sections,"fspP1DefaultedFromZero");
        push(@sections,"fspP1DefaultedFromP3");
    }

    foreach my $section (@sections)
    {
        $headerBinData .= pack1byte($sectionHoH{$section}{type});
        $headerBinData .= pack4byte($sectionHoH{$section}{offset});
        $headerBinData .= pack4byte($sectionHoH{$section}{size});
    }

    # Serialize PNOR RO section to multiple of 4k page size (pad if necessary)

    # First 256 bytes is  RO header (pad if necessary)
    if((length $headerBinData) > $headerSize)
    {
        fatal("Header data of length " . (length $headerBinData) . " is larger "
            . "than allocated amount of $headerSize.");
    }

    my $outFile;
    $outFile .= $headerBinData;
    my $padSize = sizeBlockAligned((length $headerBinData),$headerSize,1)
        - (length $headerBinData);
    $outFile .= pack ("@".$padSize);

    # Remaining data belongs to targeting
    $outFile .= $numTargetsPointerBinData;
    $outFile .= $attributeListBinData;
    $outFile .= $attributePointerBinData;
    $outFile .= $numTargetsBinData;
    $outFile .= $targetsBinData;
    $outFile .= $roAttrBinData;
    $outFile .= pack ("@".($sectionHoH{pnorRo}{size} - $offset));

    # Serialize PNOR RW section to multiple of 4k page size (pad if necessary)
    $outFile .= $rwAttrBinData;
    $outFile .= pack("@".($sectionHoH{pnorRw}{size} - $rwOffset));

    # Serialize PNOR initiated heap section to multiple of 4k page size (pad if
    # necessary)
    $outFile .= $heapPnorInitBinData;
    $outFile .= pack("@".($sectionHoH{heapPnorInit}{size}
        - $heapPnorInitOffset));

    # Serialize FSP section to multiple of 4k page size (pad if
    # necessary)
    if($cfgIncludeFspAttributes)
    {
        $outFile .= $fspP0DefaultedFromZeroBinData;
        $outFile .= pack("@".($sectionHoH{fspP0DefaultedFromZero}{size}
            - $fspP0DefaultedFromZeroOffset));

        $outFile .= $fspP0DefaultedFromP3BinData;
        $outFile .= pack("@".($sectionHoH{fspP0DefaultedFromP3}{size}
            - $fspP0DefaultedFromP3Offset));

        $outFile .= $fspP3RoBinData;
        $outFile .= pack("@".($sectionHoH{fspP3Ro}{size}
            - $fspP3RoOffset));

        $outFile .= $fspP3RwBinData;
        $outFile .= pack("@".($sectionHoH{fspP3Rw}{size}
            - $fspP3RwOffset));

        $outFile .= $fspP1DefaultedFromZeroBinData;
        $outFile .= pack("@".($sectionHoH{fspP1DefaultedFromZero}{size}
            - $fspP1DefaultedFromZeroOffset));

        $outFile .= $fspP1DefaultedFromP3BinData;
        $outFile .= pack("@".($sectionHoH{fspP1DefaultedFromP3}{size}
            - $fspP1DefaultedFromP3Offset));
    }

    return $outFile;
}

__END__

=head1 NAME

xmltohb.pl

=head1 SYNOPSIS

xmltohb.pl [options] [file ...]

=head1 OPTIONS

=over 8

=item B<--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<--hb-xml-file>

File containing the intermediate representation of the host boot XML just prior
to compilation down to images and source files (Default is ./hb.xml)

=item B<--fapi-attributes-xml-file>

File containing the FAPI HWP attributes, for purposes of configuring the
attribute mappings between FAPI and targeting code

=item B<--src-output-dir>=DIRECTORY

Sets the output directory for generated source files (default is the current
directory)

=item B<--img-output-dir>=DIRECTORY

Sets the output directory for generated binary files
(default is the current directory)

=item B<--img-output-file>=FILE

Sets the file to receive the PNOR targeting image output (default
./targeting.bin).  Only used when generating the PNOR targeting image

=item B<--vmm-consts-file>=FILE

Indicates the file containing the base virtual address of the attributes
(default is src/include/usr/vmmconst.h).  Only used when generating the PNOR
targeting image

=item B<--big-endian>

Writes data structures to file in big endian format (default)

=item B<--nobig-endian>

Writes data structures to targeting image in little endian format (override to
default).  Supports x86 environments.

=item B<--short-enums>

Writes optimially sized enumerations to binary image (default). Any code which
uses the binary image or enumerations from generated header files must also
be compiled with short enumeration support.  This saves at minimum 0 and at most
3 bytes for each enumeration value.

=item B<--noshort-enums>

Writes maximum sized enumerations to binary image (default). Any code which
uses the binary image or enumerations from generated header files must not
be compiled with short enumeration support.  Every enumeration will consume 4
bytes by default

=item B<--include-fsp-attributes>

Emits FSP specific attributes and targets into the generated binaries and
generated code.  

=item B<--noinclude-fsp-attributes>

Omits FSP specific attributes and targets from the generated binaries and
generated code.  This is the default behavior.

=item B<--verbose>

Prints out some internal workings

=back

=head1 DESCRIPTION

B<xmltohb.pl> will process a set of input .xml files and emit source files and
a PNOR targeting image binary to facilitate compiling and configuring host boot
respectively.

=cut


OpenPOWER on IntegriCloud