File: ffsparser.cpp

package info (click to toggle)
uefitool 0.28.0%2BA73-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,728 kB
  • sloc: ansic: 55,322; cpp: 23,375; sh: 43; xml: 23; makefile: 5
file content (6728 lines) | stat: -rw-r--r-- 327,322 bytes parent folder | download
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
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
/* ffsparser.cpp
 
 Copyright (c) 2018, Nikolaj Schlej. All rights reserved.
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
 http://opensource.org/licenses/bsd-license.php
 
 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
 WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 */

#include "ffsparser.h"

#include <map>
#include <algorithm>
#include <iostream>

#include "descriptor.h"
#include "ffs.h"
#include "gbe.h"
#include "me.h"
#include "intel_fit.h"
#include "nvram.h"
#include "peimage.h"
#include "parsingdata.h"
#include "types.h"
#include "utility.h"

#include "nvramparser.h"
#include "meparser.h"
#include "fitparser.h"

#include "digest/sha1.h"
#include "digest/sha2.h"
#include "digest/sm3.h"

#include "umemstream.h"
#include "kaitai/kaitaistream.h"
#include "generated/insyde_fdm.h"

#ifdef U_ENABLE_NVRAM_PARSING_SUPPORT
#include "generated/dell_dvar.h"
#endif

// Constructor
FfsParser::FfsParser(TreeModel* treeModel) : model(treeModel),
imageBase(0), addressDiff(0x100000000ULL), protectedRegionsBase(0),
pspSpiRomBase(0), pspMaxOffset(0) {
    fitParser = new FitParser(treeModel, this);
    nvramParser = new NvramParser(treeModel, this);
    meParser = new MeParser(treeModel, this);
}

// Destructor
FfsParser::~FfsParser() {
    delete nvramParser;
    delete meParser;
    delete fitParser;
}

// Obtain parser messages
std::vector<std::pair<UString, UModelIndex> > FfsParser::getMessages() const {
    std::vector<std::pair<UString, UModelIndex> > meVector = meParser->getMessages();
    std::vector<std::pair<UString, UModelIndex> > nvramVector = nvramParser->getMessages();
    std::vector<std::pair<UString, UModelIndex> > fitVector = fitParser->getMessages();
    std::vector<std::pair<UString, UModelIndex> > resultVector = messagesVector;
    resultVector.insert(resultVector.end(), meVector.begin(), meVector.end());
    resultVector.insert(resultVector.end(), nvramVector.begin(), nvramVector.end());\
    resultVector.insert(resultVector.end(), fitVector.begin(), fitVector.end());
    return resultVector;
}

// Obtain FIT table from FIT parser
std::vector<std::pair<std::vector<UString>, UModelIndex> > FfsParser::getFitTable() const
{
    return fitParser->getFitTable();
}

// Obtain security info from FIT parser
UString FfsParser::getSecurityInfo() const {
    return securityInfo + fitParser->getSecurityInfo();
}

// Firmware image parsing functions
USTATUS FfsParser::parse(const UByteArray & buffer)
{
    UModelIndex root;
    
    // Reset global parser state
    openedImage = buffer;
    imageBase = 0;
    addressDiff = 0x100000000ULL;
    indexesAddressDiffs.clear();
    pspFilesList.clear();
    protectedRegionsBase = 0;
    securityInfo = "";
    protectedRanges.clear();
    lastVtf = UModelIndex();
    dxeCore = UModelIndex();
    
    // Parse input buffer
    USTATUS result = performFirstPass(buffer, root);
    if (result == U_SUCCESS) {
        if (lastVtf.isValid()) {
            result = performSecondPass(root);
        }
        else {
            msg(usprintf("%s: not a single Volume Top File is found, the image may be corrupted", __FUNCTION__));
        }
    }
    
    addInfoRecursive(root);
    return result;
}

USTATUS FfsParser::performFirstPass(const UByteArray & buffer, UModelIndex & index)
{
    // Sanity check
    if (buffer.isEmpty()) {
        return U_INVALID_PARAMETER;
    }
    
    // Try parsing as UEFI Capsule
    if (U_SUCCESS == parseCapsule(buffer, 0, UModelIndex(), index)) {
        return U_SUCCESS;
    }
    // Try parsing as some image
    return parseImage(buffer, 0, UModelIndex(), index);
}
    
USTATUS FfsParser::parseImage(const UByteArray& buffer, const UINT32 localOffset, const UModelIndex& parent, UModelIndex& index)
{
    // Try parsing as Intel image
    USTATUS result = parseIntelImage(buffer, localOffset, parent, index);
    if (U_SUCCESS != result) {
        // Try parsing as AMD image
        result = parseAMDImage(buffer, localOffset, parent, index);
        if (U_SUCCESS != result) {
            // Parse as generic UEFI image or file
            result = parseGenericImage(buffer, localOffset, parent, index);
        }
    }
    
    return result;
}

USTATUS FfsParser::parseGenericImage(const UByteArray & buffer, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Parse as generic UEFI image
    UString name("UEFI image");
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)buffer.size(), (UINT32)buffer.size());
    
    // Add tree item
    index = model->addItem(localOffset, Types::Image, Subtypes::UefiImage, name, UString(), info, UByteArray(), buffer, UByteArray(), Fixed, parent);
    
    // Parse the image as raw area
    imageBase = model->base(parent) + localOffset;
    protectedRegionsBase = imageBase;
    return parseRawArea(index);
}

USTATUS FfsParser::parseCapsule(const UByteArray & capsule, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check buffer size to be more than or equal to size of EFI_CAPSULE_HEADER
    if ((UINT32)capsule.size() < sizeof(EFI_CAPSULE_HEADER)) {
        return U_ITEM_NOT_FOUND;
    }
    
    UINT32 capsuleHeaderSize = 0;
    // Check buffer for being normal EFI capsule header
    if (capsule.startsWith(EFI_CAPSULE_GUID)
        || capsule.startsWith(EFI_FMP_CAPSULE_GUID)
        || capsule.startsWith(INTEL_CAPSULE_GUID)
        || capsule.startsWith(LENOVO_CAPSULE_GUID)
        || capsule.startsWith(LENOVO2_CAPSULE_GUID)) {
        // Get info
        const EFI_CAPSULE_HEADER* capsuleHeader = (const EFI_CAPSULE_HEADER*)capsule.constData();
        
        // Check sanity of HeaderSize and CapsuleImageSize values
        if (capsuleHeader->HeaderSize == 0 || capsuleHeader->HeaderSize > (UINT32)capsule.size()
            || capsuleHeader->HeaderSize > capsuleHeader->CapsuleImageSize) {
            msg(usprintf("%s: UEFI capsule header size of %Xh (%u) bytes is invalid", __FUNCTION__,
                         capsuleHeader->HeaderSize,
                         capsuleHeader->HeaderSize));
            return U_INVALID_CAPSULE;
        }
        if (capsuleHeader->CapsuleImageSize > (UINT32)capsule.size()) {
            msg(usprintf("%s: UEFI capsule image size of %Xh (%u) bytes is invalid", __FUNCTION__,
                         capsuleHeader->CapsuleImageSize,
                         capsuleHeader->CapsuleImageSize));
            return U_INVALID_CAPSULE;
        }
        
        capsuleHeaderSize = capsuleHeader->HeaderSize;
        UByteArray header = capsule.left(capsuleHeaderSize);
        UByteArray body = capsule.mid(capsuleHeaderSize);
        UString name("UEFI capsule");
        UString info = UString("Capsule GUID: ") + guidToUString(capsuleHeader->CapsuleGuid, false) +
        usprintf("\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nImage size: %Xh (%u)\nFlags: %08Xh",
                 (UINT32)capsule.size(), (UINT32)capsule.size(),
                 capsuleHeaderSize, capsuleHeaderSize,
                 capsuleHeader->CapsuleImageSize - capsuleHeaderSize, capsuleHeader->CapsuleImageSize - capsuleHeaderSize,
                 capsuleHeader->Flags);
        
        // Add tree item
        index = model->addItem(localOffset, Types::Capsule, Subtypes::UefiCapsule, name, UString(), info, header, body, UByteArray(), Fixed, parent);
    }
    // Check buffer for being Toshiba capsule header
    else if (capsule.startsWith(TOSHIBA_CAPSULE_GUID)) {
        // Get info
        const TOSHIBA_CAPSULE_HEADER* capsuleHeader = (const TOSHIBA_CAPSULE_HEADER*)capsule.constData();
        
        // Check sanity of HeaderSize and FullSize values
        if (capsuleHeader->HeaderSize == 0 || capsuleHeader->HeaderSize > (UINT32)capsule.size()
            || capsuleHeader->HeaderSize > capsuleHeader->FullSize) {
            msg(usprintf("%s: Toshiba capsule header size of %Xh (%u) bytes is invalid", __FUNCTION__,
                         capsuleHeader->HeaderSize, capsuleHeader->HeaderSize));
            return U_INVALID_CAPSULE;
        }
        if (capsuleHeader->FullSize > (UINT32)capsule.size()) {
            msg(usprintf("%s: Toshiba capsule full size of %Xh (%u) bytes is invalid", __FUNCTION__,
                         capsuleHeader->FullSize, capsuleHeader->FullSize));
            return U_INVALID_CAPSULE;
        }
        
        capsuleHeaderSize = capsuleHeader->HeaderSize;
        UByteArray header = capsule.left(capsuleHeaderSize);
        UByteArray body = capsule.mid(capsuleHeaderSize);
        UString name("Toshiba capsule");
        UString info = UString("Capsule GUID: ") + guidToUString(capsuleHeader->CapsuleGuid, false) +
        usprintf("\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nImage size: %Xh (%u)\nFlags: %08Xh",
                 (UINT32)capsule.size(), (UINT32)capsule.size(),
                 capsuleHeaderSize, capsuleHeaderSize,
                 capsuleHeader->FullSize - capsuleHeaderSize, capsuleHeader->FullSize - capsuleHeaderSize,
                 capsuleHeader->Flags);
        
        // Add tree item
        index = model->addItem(localOffset, Types::Capsule, Subtypes::ToshibaCapsule, name, UString(), info, header, body, UByteArray(), Fixed, parent);
    }
    // Check buffer for being extended Aptio capsule header
    else if (capsule.startsWith(APTIO_SIGNED_CAPSULE_GUID)
             || capsule.startsWith(APTIO_UNSIGNED_CAPSULE_GUID)) {
        bool signedCapsule = capsule.startsWith(APTIO_SIGNED_CAPSULE_GUID);
        
        if ((UINT32)capsule.size() <= sizeof(APTIO_CAPSULE_HEADER)) {
            msg(usprintf("%s: AMI capsule image file is smaller than minimum size of 20h (32) bytes", __FUNCTION__));
            return U_INVALID_CAPSULE;
        }
        
        // Get info
        const APTIO_CAPSULE_HEADER* capsuleHeader = (const APTIO_CAPSULE_HEADER*)capsule.constData();
        
        // Check sanity of RomImageOffset and CapsuleImageSize values
        if (capsuleHeader->RomImageOffset == 0 || capsuleHeader->RomImageOffset > (UINT32)capsule.size()
            || capsuleHeader->RomImageOffset > capsuleHeader->CapsuleHeader.CapsuleImageSize) {
            msg(usprintf("%s: AMI capsule image offset of %Xh (%u) bytes is invalid", __FUNCTION__,
                         capsuleHeader->RomImageOffset, capsuleHeader->RomImageOffset));
            return U_INVALID_CAPSULE;
        }
        if (capsuleHeader->CapsuleHeader.CapsuleImageSize > (UINT32)capsule.size()) {
            msg(usprintf("%s: AMI capsule image size of %Xh (%u) bytes is invalid", __FUNCTION__,
                         capsuleHeader->CapsuleHeader.CapsuleImageSize,
                         capsuleHeader->CapsuleHeader.CapsuleImageSize));
            return U_INVALID_CAPSULE;
        }
        
        capsuleHeaderSize = capsuleHeader->RomImageOffset;
        UByteArray header = capsule.left(capsuleHeaderSize);
        UByteArray body = capsule.mid(capsuleHeaderSize);
        UString name("AMI Aptio capsule");
        UString info = UString("Capsule GUID: ") + guidToUString(capsuleHeader->CapsuleHeader.CapsuleGuid, false) +
        usprintf("\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nImage size: %Xh (%u)\nFlags: %08Xh",
                 (UINT32)capsule.size(), (UINT32)capsule.size(),
                 capsuleHeaderSize, capsuleHeaderSize,
                 capsuleHeader->CapsuleHeader.CapsuleImageSize - capsuleHeaderSize, capsuleHeader->CapsuleHeader.CapsuleImageSize - capsuleHeaderSize,
                 capsuleHeader->CapsuleHeader.Flags);
        
        // Add tree item
        index = model->addItem(localOffset, Types::Capsule, signedCapsule ? Subtypes::AptioSignedCapsule : Subtypes::AptioUnsignedCapsule, name, UString(), info, header, body, UByteArray(), Fixed, parent);
        
        // Show message about possible Aptio signature break
        if (signedCapsule) {
            msg(usprintf("%s: Aptio capsule signature may become invalid after image modifications", __FUNCTION__), index);
        }
    }
    
    // Capsule present
    if (capsuleHeaderSize > 0) {
        UModelIndex imageIndex;
        
        // Try parsing as some image
        return parseImage(capsule.mid(capsuleHeaderSize), capsuleHeaderSize, index, imageIndex);
    }
    
    return U_ITEM_NOT_FOUND;
}

USTATUS FfsParser::parseIntelImage(const UByteArray & intelImage, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check for buffer size to be greater or equal to descriptor region size
    if (intelImage.size() < FLASH_DESCRIPTOR_SIZE) {
        msg(usprintf("%s: input file is smaller than minimum descriptor size of %Xh (%u) bytes", __FUNCTION__, FLASH_DESCRIPTOR_SIZE, FLASH_DESCRIPTOR_SIZE));
        return U_ITEM_NOT_FOUND;
    }
    
    // Store the beginning of descriptor as descriptor base address
    const FLASH_DESCRIPTOR_HEADER* descriptor = (const FLASH_DESCRIPTOR_HEADER*)intelImage.constData();
    
    // Check descriptor signature
    if (descriptor->Signature != FLASH_DESCRIPTOR_SIGNATURE) {
        return U_ITEM_NOT_FOUND;
    }
    
    // Parse descriptor map
    const FLASH_DESCRIPTOR_MAP* descriptorMap = (const FLASH_DESCRIPTOR_MAP*)((UINT8*)descriptor + sizeof(FLASH_DESCRIPTOR_HEADER));
    const FLASH_DESCRIPTOR_UPPER_MAP* upperMap = (const FLASH_DESCRIPTOR_UPPER_MAP*)((UINT8*)descriptor + FLASH_DESCRIPTOR_UPPER_MAP_BASE);
    
    // Check sanity of base values
    if (descriptorMap->MasterBase > FLASH_DESCRIPTOR_MAX_BASE
        || descriptorMap->MasterBase == descriptorMap->RegionBase
        || descriptorMap->MasterBase == descriptorMap->ComponentBase) {
        msg(usprintf("%s: invalid descriptor master base %02Xh", __FUNCTION__, descriptorMap->MasterBase));
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    if (descriptorMap->RegionBase > FLASH_DESCRIPTOR_MAX_BASE
        || descriptorMap->RegionBase == descriptorMap->ComponentBase) {
        msg(usprintf("%s: invalid descriptor region base %02Xh", __FUNCTION__, descriptorMap->RegionBase));
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    if (descriptorMap->ComponentBase > FLASH_DESCRIPTOR_MAX_BASE) {
        msg(usprintf("%s: invalid descriptor component base %02Xh", __FUNCTION__, descriptorMap->ComponentBase));
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    
    const FLASH_DESCRIPTOR_REGION_SECTION* regionSection = (const FLASH_DESCRIPTOR_REGION_SECTION*)calculateAddress8((UINT8*)descriptor, descriptorMap->RegionBase);
    const FLASH_DESCRIPTOR_COMPONENT_SECTION* componentSection = (const FLASH_DESCRIPTOR_COMPONENT_SECTION*)calculateAddress8((UINT8*)descriptor, descriptorMap->ComponentBase);
    
    UINT8 descriptorVersion = 2;
    // Check descriptor version by getting hardcoded value of zero in FlashParameters.ReadClockFrequency
    if (componentSection->FlashParameters.ReadClockFrequency == 0)
        descriptorVersion = 1;
    
    // Regions
    std::vector<REGION_INFO> regions;
    
    // ME region
    REGION_INFO me;
    me.type = Subtypes::MeRegion;
    me.offset = 0;
    me.length = 0;
    if (regionSection->MeLimit) {
        me.offset = calculateRegionOffset(regionSection->MeBase);
        me.length = calculateRegionSize(regionSection->MeBase, regionSection->MeLimit);
        if ((UINT32)intelImage.size() < me.offset + me.length) {
            msg(usprintf("%s: ", __FUNCTION__)
                + itemSubtypeToUString(Types::Region, me.type)
                + UString(" region is located outside of the opened image. If your system uses dual-chip storage, please append another part to the opened image"),
                index);
            if ((UINT32)intelImage.size() > me.offset)
                return U_TRUNCATED_IMAGE;
        }
        else {
            me.data = intelImage.mid(me.offset, me.length);
            regions.push_back(me);
        }
    }
    
    // BIOS region
    if (regionSection->BiosLimit) {
        REGION_INFO bios;
        bios.type = Subtypes::BiosRegion;
        bios.offset = calculateRegionOffset(regionSection->BiosBase);
        bios.length = calculateRegionSize(regionSection->BiosBase, regionSection->BiosLimit);
        
        // Check for Gigabyte specific descriptor map
        if (bios.length == (UINT32)intelImage.size()) {
            if (!me.offset) {
                msg(usprintf("%s: can't determine BIOS region start from Gigabyte-specific descriptor", __FUNCTION__));
                return U_INVALID_FLASH_DESCRIPTOR;
            }
            // Use ME region end as BIOS region offset
            bios.offset = me.offset + me.length;
            bios.length = (UINT32)intelImage.size() - bios.offset;
        }

        if ((UINT32)intelImage.size() < bios.offset + bios.length) {
            msg(usprintf("%s: ", __FUNCTION__)
                + itemSubtypeToUString(Types::Region, bios.type)
                + UString(" region is located outside of the opened image. If your system uses dual-chip storage, please append another part to the opened image"),
                index);
            return U_TRUNCATED_IMAGE;
        }
        bios.data = intelImage.mid(bios.offset, bios.length);
        regions.push_back(bios);
    }
    else {
        msg(usprintf("%s: descriptor parsing failed, BIOS region not found in descriptor", __FUNCTION__));
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    
    // Add all other regions
    for (UINT8 i = Subtypes::GbeRegion; i <= Subtypes::PttRegion; i++) {
        if (descriptorVersion == 1 && i == Subtypes::MicrocodeRegion)
            break; // Do not parse Microcode and other following regions for legacy descriptors
        
        const UINT16* RegionBase = ((const UINT16*)regionSection) + 2 * i;
        const UINT16* RegionLimit = ((const UINT16*)regionSection) + 2 * i + 1;
        if (*RegionLimit && !(*RegionBase == 0xFFFF && *RegionLimit == 0xFFFF)) {
            REGION_INFO region;
            region.type = i;
            region.offset = calculateRegionOffset(*RegionBase);
            region.length = calculateRegionSize(*RegionBase, *RegionLimit);
            if (region.length != 0) {
                if ((UINT32)intelImage.size() < region.offset + region.length) {
                    msg(usprintf("%s: ", __FUNCTION__)
                        + itemSubtypeToUString(Types::Region, region.type)
                        + UString(" region is located outside of the opened image. If your system uses dual-chip storage, please append another part to the opened image"),
                        index);
                    return U_TRUNCATED_IMAGE;
                }
                region.data = intelImage.mid(region.offset, region.length);
                regions.push_back(region);
            }
        }
    }
    
    // Regions can not be empty here
    if (regions.empty()) {
        msg(usprintf("%s: descriptor parsing failed, no regions found", __FUNCTION__));
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    
    // Sort regions in ascending order
    std::sort(regions.begin(), regions.end());
    
    // Check for intersections and paddings between regions
    REGION_INFO region;
    // Check intersection with the descriptor
    if (regions.front().offset < FLASH_DESCRIPTOR_SIZE) {
        msg(usprintf("%s: ", __FUNCTION__)
            + itemSubtypeToUString(Types::Region, regions.front().type)
            + UString(" region has intersection with flash descriptor"),
            index);
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    // Check for padding between descriptor and the first region
    else if (regions.front().offset > FLASH_DESCRIPTOR_SIZE) {
        region.offset = FLASH_DESCRIPTOR_SIZE;
        region.length = regions.front().offset - FLASH_DESCRIPTOR_SIZE;
        region.data = intelImage.mid(region.offset, region.length);
        region.type = getPaddingType(region.data);
        regions.insert(regions.begin(), region);
    }
    // Check for intersections/paddings between regions
    for (size_t i = 1; i < regions.size(); i++) {
        UINT32 previousRegionEnd = regions[i-1].offset + regions[i-1].length;
        // Check for intersection with previous region
        if (regions[i].offset < previousRegionEnd) {
            msg(usprintf("%s: ", __FUNCTION__)
                + itemSubtypeToUString(Types::Region, regions[i].type)
                + UString(" region has intersection with ") + itemSubtypeToUString(Types::Region, regions[i - 1].type)
                + UString(" region"),
                index);
            return U_INVALID_FLASH_DESCRIPTOR;
        }
        // Check for padding between current and previous regions
        else if (regions[i].offset > previousRegionEnd) {
            region.offset = previousRegionEnd;
            region.length = regions[i].offset - previousRegionEnd;
            region.data = intelImage.mid(region.offset, region.length);
            region.type = getPaddingType(region.data);
            std::vector<REGION_INFO>::iterator iter = regions.begin();
            std::advance(iter, i);
            regions.insert(iter, region);
        }
    }
    // Check for padding after the last region
    if ((UINT64)regions.back().offset + (UINT64)regions.back().length < (UINT64)intelImage.size()) {
        region.offset = regions.back().offset + regions.back().length;
        region.length = (UINT32)(intelImage.size() - region.offset);
        region.data = intelImage.mid(region.offset, region.length);
        region.type = getPaddingType(region.data);
        regions.push_back(region);
    }
    
    // Region map is consistent
    
    // Intel image
    UString name("Intel image");
    UString info = usprintf("Full size: %Xh (%u)\nFlash chips: %u\nRegions: %u\nMasters: %u\nPCH straps: %u\nPROC straps: %u",
                            (UINT32)intelImage.size(), (UINT32)intelImage.size(),
                            descriptorMap->NumberOfFlashChips + 1, //
                            descriptorMap->NumberOfRegions + 1,    // Zero-based numbers in storage
                            descriptorMap->NumberOfMasters + 1,    //
                            descriptorMap->NumberOfPchStraps,
                            descriptorMap->NumberOfProcStraps);
    
    // Set image base
    imageBase = model->base(parent) + localOffset;
    
    // Add Intel image tree item
    index = model->addItem(localOffset, Types::Image, Subtypes::IntelImage, name, UString(), info, UByteArray(), intelImage, UByteArray(), Fixed, parent);
    
    // Descriptor
    // Get descriptor info
    UByteArray body = intelImage.left(FLASH_DESCRIPTOR_SIZE);
    name = UString("Descriptor region");
    info = usprintf("ReservedVector:\n%02X %02X %02X %02X %02X %02X %02X %02X\n"
                    "%02X %02X %02X %02X %02X %02X %02X %02X\nFull size: %Xh (%u)",
                    descriptor->ReservedVector[0],  descriptor->ReservedVector[1],  descriptor->ReservedVector[2],  descriptor->ReservedVector[3],
                    descriptor->ReservedVector[4],  descriptor->ReservedVector[5],  descriptor->ReservedVector[6],  descriptor->ReservedVector[7],
                    descriptor->ReservedVector[8],  descriptor->ReservedVector[9],  descriptor->ReservedVector[10], descriptor->ReservedVector[11],
                    descriptor->ReservedVector[12], descriptor->ReservedVector[13], descriptor->ReservedVector[14], descriptor->ReservedVector[15],
                    FLASH_DESCRIPTOR_SIZE, FLASH_DESCRIPTOR_SIZE);
    
    // Add offsets of actual regions
    for (size_t i = 0; i < regions.size(); i++) {
        if (regions[i].type != Subtypes::ZeroPadding && regions[i].type != Subtypes::OnePadding && regions[i].type != Subtypes::DataPadding)
            info += "\n" + itemSubtypeToUString(Types::Region, regions[i].type)
            + usprintf(" region offset: %Xh", regions[i].offset + localOffset);
    }
    
    // Region access settings
    if (descriptorVersion == 1) {
        const FLASH_DESCRIPTOR_MASTER_SECTION* masterSection = (const FLASH_DESCRIPTOR_MASTER_SECTION*)calculateAddress8((UINT8*)descriptor, descriptorMap->MasterBase);
        info += UString("\nRegion access settings:");
        info += usprintf("\nBIOS: %02Xh %02Xh ME: %02Xh %02Xh\nGbE:  %02Xh %02Xh",
                         masterSection->BiosRead,
                         masterSection->BiosWrite,
                         masterSection->MeRead,
                         masterSection->MeWrite,
                         masterSection->GbeRead,
                         masterSection->GbeWrite);
        
        // BIOS access table
        info  += UString("\nBIOS access table:")
        + UString("\n      Read  Write")
        + usprintf("\nDesc  %s  %s",  masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_DESC ? "Yes " : "No  ",
                   masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_DESC ? "Yes " : "No  ");
        info  += UString("\nBIOS  Yes   Yes")
        + usprintf("\nME    %s  %s",  masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_ME   ? "Yes " : "No  ",
                   masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_ME   ? "Yes " : "No  ");
        info += usprintf("\nGbE   %s  %s",  masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_GBE  ? "Yes " : "No  ",
                         masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_GBE  ? "Yes " : "No  ");
        info += usprintf("\nPDR   %s  %s",  masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_PDR  ? "Yes " : "No  ",
                         masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_PDR  ? "Yes " : "No  ");
    }
    else if (descriptorVersion == 2) {
        const FLASH_DESCRIPTOR_MASTER_SECTION_V2* masterSection = (const FLASH_DESCRIPTOR_MASTER_SECTION_V2*)calculateAddress8((UINT8*)descriptor, descriptorMap->MasterBase);
        info += UString("\nRegion access settings:");
        info += usprintf("\nBIOS: %03Xh %03Xh"
                         "\nME:   %03Xh %03Xh"
                         "\nGbE:  %03Xh %03Xh"
                         "\nEC:   %03Xh %03Xh",
                         masterSection->BiosRead,
                         masterSection->BiosWrite,
                         masterSection->MeRead,
                         masterSection->MeWrite,
                         masterSection->GbeRead,
                         masterSection->GbeWrite,
                         masterSection->EcRead,
                         masterSection->EcWrite);
        
        // BIOS access table
        info  += UString("\nBIOS access table:")
        + UString("\n      Read  Write")
        + usprintf("\nDesc  %s  %s",
                   masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_DESC ? "Yes " : "No  ",
                   masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_DESC ? "Yes " : "No  ");
        info  += UString("\nBIOS  Yes   Yes")
        + usprintf("\nME    %s  %s",
                   masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_ME ? "Yes " : "No  ",
                   masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_ME ? "Yes " : "No  ");
        info += usprintf("\nGbE   %s  %s",
                         masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_GBE ? "Yes " : "No  ",
                         masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_GBE ? "Yes " : "No  ");
        info += usprintf("\nPDR   %s  %s",
                         masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_PDR ? "Yes " : "No  ",
                         masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_PDR ? "Yes " : "No  ");
        info += usprintf("\nEC    %s  %s",
                         masterSection->BiosRead  & FLASH_DESCRIPTOR_REGION_ACCESS_EC ? "Yes " : "No  ",
                         masterSection->BiosWrite & FLASH_DESCRIPTOR_REGION_ACCESS_EC ? "Yes " : "No  ");
        
        // Prepend descriptor version if present
        if (descriptorMap->DescriptorVersion != FLASH_DESCRIPTOR_VERSION_INVALID) {
            const FLASH_DESCRIPTOR_VERSION* version = (const FLASH_DESCRIPTOR_VERSION*)&descriptorMap->DescriptorVersion;
            UString versionStr = usprintf("Flash descriptor version: %d.%d", version->Major, version->Minor);
            if (version->Major != FLASH_DESCRIPTOR_VERSION_MAJOR || version->Minor != FLASH_DESCRIPTOR_VERSION_MINOR) {
                versionStr += ", unknown";
                msg(usprintf("%s: unknown flash descriptor version %d.%d", __FUNCTION__, version->Major, version->Minor));
            }
            info = versionStr + "\n" + info;
        }
    }
    
    // VSCC table
    const VSCC_TABLE_ENTRY* vsccTableEntry = (const VSCC_TABLE_ENTRY*)((UINT8*)descriptor + ((UINT16)upperMap->VsccTableBase << 4));
    info += UString("\nFlash chips in VSCC table:");
    UINT8 vsscTableSize = upperMap->VsccTableSize * sizeof(UINT32) / sizeof(VSCC_TABLE_ENTRY);
    for (UINT8 i = 0; i < vsscTableSize; i++) {
        UString jedecId = jedecIdToUString(vsccTableEntry->VendorId, vsccTableEntry->DeviceId0, vsccTableEntry->DeviceId1);
        info += usprintf("\n%02X%02X%02X (", vsccTableEntry->VendorId, vsccTableEntry->DeviceId0, vsccTableEntry->DeviceId1)
        + jedecId
        + UString(")");
        if (jedecId.startsWith("Unknown")) {
            msg(usprintf("%s: SPI flash with unknown JEDEC ID %02X%02X%02X found in VSCC table", __FUNCTION__,
                         vsccTableEntry->VendorId, vsccTableEntry->DeviceId0, vsccTableEntry->DeviceId1), index);
        }
        vsccTableEntry++;
    }
    
    // Add descriptor tree item
    UModelIndex regionIndex = model->addItem(localOffset, Types::Region, Subtypes::DescriptorRegion, name, UString(), info, UByteArray(), body, UByteArray(), Fixed, index);
    
    // Parse regions
    USTATUS result = U_SUCCESS;
    USTATUS parseResult = U_SUCCESS;
    for (size_t i = 0; i < regions.size(); i++) {
        region = regions[i];
        switch (region.type) {
            case Subtypes::BiosRegion:
                result = parseBiosRegion(region.data, region.offset, index, regionIndex);
                break;
            case Subtypes::MeRegion:
                result = parseMeRegion(region.data, region.offset, index, regionIndex);
                break;
            case Subtypes::GbeRegion:
                result = parseGbeRegion(region.data, region.offset, index, regionIndex);
                break;
            case Subtypes::PdrRegion:
                result = parsePdrRegion(region.data, region.offset, index, regionIndex);
                break;
            case Subtypes::DevExp1Region:
                result = parseDevExp1Region(region.data, region.offset, index, regionIndex);
                break;
            case Subtypes::Bios2Region:
            case Subtypes::MicrocodeRegion:
            case Subtypes::EcRegion:
            case Subtypes::DevExp2Region:
            case Subtypes::IeRegion:
            case Subtypes::Tgbe1Region:
            case Subtypes::Tgbe2Region:
            case Subtypes::Reserved1Region:
            case Subtypes::Reserved2Region:
            case Subtypes::PttRegion:
                result = parseGenericRegion(region.type, region.data, region.offset, index, regionIndex);
                break;
            case Subtypes::ZeroPadding:
            case Subtypes::OnePadding:
            case Subtypes::DataPadding: {
                // Add padding between regions
                UByteArray padding = intelImage.mid(region.offset, region.length);
                
                // Get info
                name = UString("Padding");
                info = usprintf("Full size: %Xh (%u)",
                                (UINT32)padding.size(), (UINT32)padding.size());
                
                // Add tree item
                regionIndex = model->addItem(region.offset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
                result = U_SUCCESS;
            } break;
            default:
                msg(usprintf("%s: region of unknown type found", __FUNCTION__), index);
                result = U_INVALID_FLASH_DESCRIPTOR;
        }
        // Store the first failed result as a final result
        if (!parseResult && result) {
            parseResult = result;
        }
    }
    
    return parseResult;
}

USTATUS FfsParser::parseGbeRegion(const UByteArray & gbe, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check sanity
    if (gbe.isEmpty())
        return U_EMPTY_REGION;
    if ((UINT32)gbe.size() < GBE_VERSION_OFFSET + sizeof(GBE_VERSION))
        return U_INVALID_REGION;
    
    // Get info
    UString name("GbE region");
    const GBE_MAC_ADDRESS* mac = (const GBE_MAC_ADDRESS*)gbe.constData();
    const GBE_VERSION* version = (const GBE_VERSION*)(gbe.constData() + GBE_VERSION_OFFSET);
    UString info = usprintf("Full size: %Xh (%u)\nMAC: %02X:%02X:%02X:%02X:%02X:%02X\nVersion: %u.%u",
                            (UINT32)gbe.size(), (UINT32)gbe.size(),
                            mac->vendor[0], mac->vendor[1], mac->vendor[2],
                            mac->device[0], mac->device[1], mac->device[2],
                            version->major,
                            version->minor);
    
    // Add tree item
    index = model->addItem(localOffset, Types::Region, Subtypes::GbeRegion, name, UString(), info, UByteArray(), gbe, UByteArray(), Fixed, parent);
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseMeRegion(const UByteArray & me, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check sanity
    if (me.isEmpty())
        return U_EMPTY_REGION;
    
    // Get info
    UString name("ME region");
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)me.size(), (UINT32)me.size());
    
    // Parse region
    bool versionFound = true;
    bool emptyRegion = false;
    // Check for empty region
    auto c = uniformByte(me);
    if (c <= UINT8_MAX) {
        // Further parsing not needed
        emptyRegion = true;
        info += usprintf("\nState: empty (%02Xh)", (UINT8)c);
    }
    else {
        // Search for new signature
        UINT32 sig2Value = ME_VERSION_SIGNATURE2;
        UByteArray sig2((const char*)&sig2Value, sizeof(sig2Value));
        INT32 versionOffset = (INT32)me.indexOf(sig2);
        if (versionOffset < 0) { // New signature not found
            // Search for old signature
            UINT32 sigValue = ME_VERSION_SIGNATURE;
            UByteArray sig((const char*)&sigValue, sizeof(sigValue));
            versionOffset = (INT32)me.indexOf(sig);
            if (versionOffset < 0) {
                info += ("\nVersion: unknown");
                versionFound = false;
            }
        }
        
        // Add version information
        if (versionFound) {
            if ((UINT32)me.size() < (UINT32)versionOffset + sizeof(ME_VERSION))
                return U_INVALID_REGION;
        
            const ME_VERSION* version = (const ME_VERSION*)(me.constData() + versionOffset);
            info += usprintf("\nVersion: %u.%u.%u.%u",
                             version->Major,
                             version->Minor,
                             version->Bugfix,
                             version->Build);
        }
    }
    
    // Add tree item
    index = model->addItem(localOffset, Types::Region, Subtypes::MeRegion, name, UString(), info, UByteArray(), me, UByteArray(), Fixed, parent);
    
    // Show messages
    if (emptyRegion) {
        msg(usprintf("%s: ME region is empty", __FUNCTION__), index);
    }
    else if (!versionFound) {
        msg(usprintf("%s: ME version is unknown, it can be damaged", __FUNCTION__), index);
    }
    else {
        meParser->parseMeRegionBody(index);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parsePdrRegion(const UByteArray & pdr, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check sanity
    if (pdr.isEmpty())
        return U_EMPTY_REGION;
    
    // Get info
    UString name("PDR region");
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)pdr.size(), (UINT32)pdr.size());
    
    // Check for empty region
    bool emptyRegion = false;
    auto c = uniformByte(pdr);
    if (c <= UINT8_MAX) {
        // Further parsing not needed
        emptyRegion = true;
        info += usprintf("\nState: empty (%02Xh)", (UINT8)c);
    }

    // Add tree item
    index = model->addItem(localOffset, Types::Region, Subtypes::PdrRegion, name, UString(), info, UByteArray(), pdr, UByteArray(), Fixed, parent);
    
    if (!emptyRegion) {
        // Parse PDR region as BIOS space
        USTATUS result = parseRawArea(index);
        if (result && result != U_VOLUMES_NOT_FOUND && result != U_INVALID_VOLUME && result != U_STORES_NOT_FOUND)
            return result;
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseDevExp1Region(const UByteArray & devExp1, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check sanity
    if (devExp1.isEmpty())
        return U_EMPTY_REGION;
    
    // Get info
    UString name("DevExp1 region");
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)devExp1.size(), (UINT32)devExp1.size());
    
    // Check for empty region
    bool emptyRegion = false;
    auto c = uniformByte(devExp1);
    if (c <= UINT8_MAX) {
        // Further parsing not needed
        emptyRegion = true;
        info += usprintf("\nState: empty (%02Xh)", (UINT8)c);
    }
    
    // Add tree item
    index = model->addItem(localOffset, Types::Region, Subtypes::DevExp1Region, name, UString(), info, UByteArray(), devExp1, UByteArray(), Fixed, parent);
    
    if (!emptyRegion) {
        meParser->parseMeRegionBody(index);
    }
    return U_SUCCESS;
}

USTATUS FfsParser::parseGenericRegion(const UINT8 subtype, const UByteArray & region, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check sanity
    if (region.isEmpty())
        return U_EMPTY_REGION;
    
    // Get info
    UString name = itemSubtypeToUString(Types::Region, subtype) + UString(" region");
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)region.size(), (UINT32)region.size());
    
    // Check for empty region
    bool emptyRegion = false;
    auto c = uniformByte(region);
    if (c <= UINT8_MAX) {
        // Further parsing not needed
        emptyRegion = true;
        info += usprintf("\nState: empty (%02Xh)", (UINT8)c);
    }

    // Add tree item
    index = model->addItem(localOffset, Types::Region, subtype, name, UString(), info, UByteArray(), region, UByteArray(), Fixed, parent);
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseBiosRegion(const UByteArray & bios, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Sanity check
    if (bios.isEmpty())
        return U_EMPTY_REGION;
    
    // Get info
    UString name("BIOS region");
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)bios.size(), (UINT32)bios.size());
    
    // Add tree item
    index = model->addItem(localOffset, Types::Region, Subtypes::BiosRegion, name, UString(), info, UByteArray(), bios, UByteArray(), Fixed, parent);
    
    return parseRawArea(index);
}

USTATUS FfsParser::parseRawArea(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Get item data
    UByteArray data = model->body(index);
    UINT32 headerSize = (UINT32)model->header(index).size();
    
    // Obtain required information from parent volume, if it exists
    UINT8 emptyByte = 0xFF;
    UModelIndex parentVolumeIndex = model->findParentOfType(index, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        emptyByte = pdata->emptyByte;
    }
    
    USTATUS result;
    UString name;
    UString info;
    
    // Search for the first item
    UINT8  prevItemType = 0;
    UINT32 prevItemOffset = 0;
    UINT32 prevItemSize = 0;
    UINT32 prevItemAltSize = 0;
    
    result = findNextRawAreaItem(index, 0, prevItemType, prevItemOffset, prevItemSize, prevItemAltSize);
    if (result) {
        // No need to parse further
        return U_STORES_NOT_FOUND;
    }
    
    // Set base of protected regions to be the first volume
    if (model->type(index) == Types::Region
        && model->subtype(index) == Subtypes::BiosRegion) {
        protectedRegionsBase = (UINT64)model->base(index) + prevItemOffset;
    }
    
    // First item is not at the beginning of this raw area
    if (prevItemOffset > 0) {
        // Get info
        UByteArray padding = data.left(prevItemOffset);
        name = UString("Padding");
        info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
        
        // Add tree item
        model->addItem(headerSize, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
    }
    
    // Search for and parse all items
    UINT8  itemType = prevItemType;
    UINT32 itemOffset = prevItemOffset;
    UINT32 itemSize = prevItemSize;
    UINT32 itemAltSize = prevItemAltSize;
    
    while (!result) {
        // Padding between items
        if (itemOffset > prevItemOffset + prevItemSize) {
            UINT32 paddingOffset = prevItemOffset + prevItemSize;
            UINT32 paddingSize = itemOffset - paddingOffset;
            UByteArray padding = data.mid(paddingOffset, paddingSize);
            
            // Get info
            name = UString("Padding");
            info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
            
            // Add tree item
            model->addItem(headerSize + paddingOffset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
        }
        
        // Check that item is fully present in input
        if (itemSize > (UINT32)data.size() || itemOffset + itemSize > (UINT32)data.size()) {
            // Mark the rest as padding and finish parsing
            UByteArray padding = data.mid(itemOffset);
            
            // Get info
            name = UString("Padding");
            info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
            
            // Add tree item
            UModelIndex paddingIndex = model->addItem(headerSize + itemOffset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
            msg(usprintf("%s: one of objects inside overlaps the end of data", __FUNCTION__), paddingIndex);
            
            // Update variables
            prevItemOffset = itemOffset;
            prevItemSize = (UINT32)padding.size();
            break;
        }
        
        // Parse current volume header
        if (itemType == Types::Volume) {
            UModelIndex volumeIndex;
            UByteArray volume = data.mid(itemOffset, itemSize);
            result = parseVolumeHeader(volume, headerSize + itemOffset, index, volumeIndex);
            if (result) {
                msg(usprintf("%s: volume header parsing failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            } else {
                // Show messages
                if (itemSize != itemAltSize)
                    msg(usprintf("%s: volume size stored in header %Xh differs from calculated using block map %Xh", __FUNCTION__, itemSize, itemAltSize), volumeIndex);
                
                // Parse volume body
                parseVolumeBody(volumeIndex);
            }
        }
        else if (itemType == Types::Microcode) {
            UModelIndex microcodeIndex;
            UByteArray microcode = data.mid(itemOffset, itemSize);
            result = parseIntelMicrocodeHeader(microcode, headerSize + itemOffset, index, microcodeIndex);
            if (result) {
                msg(usprintf("%s: microcode header parsing failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            }
        }
        else if (itemType == Types::BpdtStore) {
            UByteArray bpdtStore = data.mid(itemOffset, itemSize);
            
            // Get info
            name = UString("BPDT region");
            info = usprintf("Full size: %Xh (%u)", (UINT32)bpdtStore.size(), (UINT32)bpdtStore.size());
            
            // Add tree item
            UModelIndex bpdtIndex = model->addItem(headerSize + itemOffset, Types::BpdtStore, 0, name, UString(), info, UByteArray(), bpdtStore, UByteArray(), Fixed, index);
            
            // Parse BPDT region
            UModelIndex bpdtPtIndex;
            result = parseBpdtRegion(bpdtStore, 0, 0, bpdtIndex, bpdtPtIndex);
            if (result) {
                msg(usprintf("%s: BPDT store parsing failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            }
        }
        else if (itemType == Types::InsydeFlashDeviceMapStore) {
            try {
                UByteArray fdm = data.mid(itemOffset, itemSize);
                umemstream is(fdm.constData(), fdm.size());
                kaitai::kstream ks(&is);
                insyde_fdm_t parsed(&ks);
                UINT32 storeSize = (UINT32)fdm.size();
                
                // Construct header and body
                UByteArray header = fdm.left(parsed.data_offset());
                UByteArray body = fdm.mid(header.size(), storeSize - header.size());
                
                // Add info
                UString name = UString("Insyde H2O FlashDeviceMap");
                UString info = usprintf("Signature: HFDM\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nEntry size: %Xh (%u)\nEntry format: %02Xh\nRevision: %02Xh\nExtension count: %u\nFlash descriptor base address: %08Xh\nChecksum: %02Xh",
                                        storeSize, storeSize,
                                        (UINT32)header.size(), (UINT32)header.size(),
                                        (UINT32)body.size(), (UINT32)body.size(),
                                        parsed.entry_size(), parsed.entry_size(),
                                        parsed.entry_format(),
                                        parsed.revision(),
                                        parsed.num_extensions(),
                                        (UINT32)parsed.fd_base_address(),
                                        parsed.checksum());
                
                // Check header checksum
                {
                    UByteArray tempHeader = data.mid(itemOffset, sizeof(INSYDE_FLASH_DEVICE_MAP_HEADER));
                    INSYDE_FLASH_DEVICE_MAP_HEADER* tempFdmHeader = (INSYDE_FLASH_DEVICE_MAP_HEADER*)tempHeader.data();
                    tempFdmHeader->Checksum = 0;
                    UINT8 calculated = calculateChecksum8((const UINT8*)tempFdmHeader, (UINT32)tempHeader.size());
                    if (calculated == parsed.checksum()) {
                        info += UString(", valid");
                    }
                    else {
                        info += usprintf(", invalid, should be %02Xh", calculated);
                    }
                }
                
                // Add board IDs
                if (!parsed._is_null_board_ids()) {
                    info += usprintf("\nRegion index: %Xh\nBoardId Count: %u",
                                     parsed.board_ids()->region_index(),
                                     parsed.board_ids()->num_board_ids());
                    UINT32 i = 0;
                    for (const auto & boardId : *parsed.board_ids()->board_ids()) {
                        info += usprintf("\nBoardId #%u: %" PRIX64 "\n", i++, boardId);
                    }
                }
                
                // Add header tree item
                UModelIndex headerIndex = model->addItem(headerSize + itemOffset, Types::InsydeFlashDeviceMapStore, 0, name, UString(), info, header, body, UByteArray(), Fixed, index);
                
                // Add entries
                UINT32 entryOffset = parsed.data_offset();
                bool protectedRangeFound = false;
                for (const auto & entry : *parsed.entries()->entries()) {
                    const EFI_GUID guid = readUnaligned((const EFI_GUID*)entry->guid().c_str());
                    name = insydeFlashDeviceMapEntryTypeGuidToUString(guid);
                    UString text;
                    header = data.mid(itemOffset + entryOffset, sizeof(INSYDE_FLASH_DEVICE_MAP_ENTRY));
                    body = data.mid(itemOffset + entryOffset + header.size(), parsed.entry_size() - header.size());
                    
                    // Add info
                    UINT32 entrySize = (UINT32)header.size() + (UINT32)body.size();
                    info = UString("Region type: ") + guidToUString(guid, false) + "\n";
                    info += UString("Region id: ");
                    for (UINT8 i = 0; i < 16; i++) {
                        info += usprintf("%02X", *(const UINT8*)(entry->region_id().c_str() + i));
                    }
                    info += usprintf("\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nRegion address: %08Xh\nRegion size: %08Xh\nAttributes: %08Xh",
                                     entrySize, entrySize,
                                     (UINT32)header.size(), (UINT32)header.size(),
                                     (UINT32)body.size(), (UINT32)body.size(),
                                     (UINT32)entry->region_base(),
                                     (UINT32)entry->region_size(),
                                     entry->attributes());
                    
                    if ((entry->attributes() & INSYDE_FLASH_DEVICE_MAP_ENTRY_ATTRIBUTE_MODIFIABLE) == 0) {
                        if (!protectedRangeFound) {
                            securityInfo += usprintf("Insyde Flash Device Map found at base %08Xh\nProtected ranges:\n", model->base(headerIndex));
                            protectedRangeFound = true;
                        }
                        
                        // TODO: make sure that the only hash possible here is SHA256
                        
                        // Add this region to the list of Insyde protected regions
                        PROTECTED_RANGE range = {};
                        range.Offset = (UINT32)entry->region_base();
                        range.Size = (UINT32)entry->region_size();
                        range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                        range.Type = PROTECTED_RANGE_VENDOR_HASH_INSYDE;
                        range.Hash = body;
                        protectedRanges.push_back(range);
                        
                        securityInfo += usprintf("Address: %08Xh Size: %Xh\nHash: ", range.Offset, range.Size) + UString(body.toHex().constData()) + "\n";
                    }
                    
                    // Add tree item
                    model->addItem(entryOffset, Types::InsydeFlashDeviceMapEntry, 0, name, text, info, header, body, UByteArray(), Fixed, headerIndex);
                    
                    entryOffset += entrySize;
                }
                
                if (protectedRangeFound) {
                    securityInfo += "\n";
                }
            }
            catch (...) {
                // Parsing failed, need to add the candidate as Padding
                UByteArray padding = data.mid(itemOffset, itemSize);
                
                // Get info
                name = UString("Padding");
                info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
                
                // Add tree item
                model->addItem(headerSize + itemOffset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
            }
        }
#ifdef U_ENABLE_NVRAM_PARSING_SUPPORT
        else if (itemType == Types::DellDvarStore) {
            try {
                UByteArray dvar = data.mid(itemOffset, itemSize);
                umemstream is(dvar.constData(), dvar.size());
                kaitai::kstream ks(&is);
                dell_dvar_t parsed(&ks);
                UINT32 storeSize = (UINT32)dvar.size();
                
                // Construct header and body
                UByteArray header = dvar.left(parsed.data_offset());
                UByteArray body = dvar.mid(header.size(), storeSize - header.size());
                
                // Add info
                UString name = UString("Dell DVAR Store");
                UString info = usprintf("Signature: DVAR\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nFlags: %02Xh",
                                        storeSize, storeSize,
                                        (UINT32)header.size(), (UINT32)header.size(),
                                        (UINT32)body.size(), (UINT32)body.size(),
                                        parsed.flags());
                
                // Add header tree item
                UModelIndex headerIndex = model->addItem(headerSize + itemOffset, Types::DellDvarStore, 0, name, UString(), info, header, body, UByteArray(), Fixed, index);
                
                // Add entries
                std::map<UINT16, EFI_GUID> guidMap;
                UINT32 entryOffset = parsed.data_offset();
                for (const auto & entry : *parsed.entries()) {
                    // This is the terminating entry, needs special processing
                    if (entry->_is_null_flags_c()) {
                        // Add free space or padding after all entries, if needed
                        if (entryOffset < storeSize) {
                            UByteArray freeSpace = dvar.mid(entryOffset, storeSize - entryOffset);
                            // Add info
                            info = usprintf("Full size: %Xh (%u)", (UINT32)freeSpace.size(), (UINT32)freeSpace.size());
                            
                            // Check that remaining unparsed bytes are actually empty
                            if (isUniformByte(freeSpace, emptyByte)) { // Free space
                                // Add tree item
                                model->addItem(entryOffset, Types::FreeSpace, 0, UString("Free space"), UString(), info, UByteArray(), freeSpace, UByteArray(), Fixed, headerIndex);
                            }
                            else {
                                // Add tree item
                                model->addItem(entryOffset, Types::Padding, getPaddingType(freeSpace), UString("Padding"), UString(), info, UByteArray(), freeSpace, UByteArray(), Fixed, headerIndex);
                            }
                        }
                        break;
                    }
                    
                    // Check entry format to be known
                    bool formatKnown = true;
                    // Check state to be known
                    if (entry->state() != DVAR_ENTRY_STATE_STORING &&
                        entry->state() != DVAR_ENTRY_STATE_STORED &&
                        entry->state() != DVAR_ENTRY_STATE_DELETING &&
                        entry->state() != DVAR_ENTRY_STATE_DELETED){
                        formatKnown = false;
                        msg(usprintf("%s: DVAR entry with unknown state %02X", __FUNCTION__, entry->state()), headerIndex);
                    }
                    
                    // Check flags to be known
                    if (entry->flags() != DVAR_ENTRY_FLAG_NAME_ID &&
                        entry->flags() != DVAR_ENTRY_FLAG_NAME_ID + DVAR_ENTRY_FLAG_NAMESPACE_GUID) {
                        formatKnown = false;
                        msg(usprintf("%s: DVAR entry with unknown flags %02X", __FUNCTION__, entry->flags()), headerIndex);
                    }
                    
                    // Check type to be known
                    if (entry->type() != DVAR_ENTRY_TYPE_NAME_ID_8_DATA_SIZE_8 &&
                        entry->type() != DVAR_ENTRY_TYPE_NAME_ID_16_DATA_SIZE_8 &&
                        entry->type() != DVAR_ENTRY_TYPE_NAME_ID_16_DATA_SIZE_16) {
                        formatKnown = false;
                        msg(usprintf("%s: DVAR entry with unknown type %02X", __FUNCTION__, entry->type()), headerIndex);
                    }
                    
                    // This is an unknown entry
                    if (!formatKnown) {
                        // No way to continue from here, because we can not be sure that the rest of the store got parsed correctly
                        UByteArray padding = data.mid(entryOffset, storeSize - entryOffset);
                        
                        // Get info
                        name = UString("Padding");
                        info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
                        
                        // Add tree item
                        model->addItem(entryOffset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, headerIndex);
                    }
                    // This is a normal entry
                    else {
                        UINT32 headerSize;
                        UINT32 bodySize;
                        UINT32 entrySize;
                        UINT32 nameId;
                        UINT8 subtype;
                        UString text;
                        
                        // NamespaceGUID entry
                        if (entry->flags() == DVAR_ENTRY_FLAG_NAME_ID + DVAR_ENTRY_FLAG_NAMESPACE_GUID) {
                            // State of this variable only applies to the NameId part, not the NamespaceGuid part
                            // This kind of variables with deleted state till need to be shown as valid
                            subtype = Subtypes::NamespaceGuidDvarEntry;
                            EFI_GUID guid = *(const EFI_GUID*)(entry->namespace_guid().c_str());
                            headerSize = sizeof(DVAR_ENTRY_HEADER) + sizeof(EFI_GUID);
                            if (entry->type() == DVAR_ENTRY_TYPE_NAME_ID_8_DATA_SIZE_8) {
                                nameId = entry->name_id_8();
                                bodySize = entry->len_data_8();
                                headerSize += sizeof(UINT8) + sizeof(UINT8);
                            }
                            else if (entry->type() == DVAR_ENTRY_TYPE_NAME_ID_16_DATA_SIZE_8) {
                                nameId = entry->name_id_16();
                                bodySize = entry->len_data_8();
                                headerSize += sizeof(UINT16) + sizeof(UINT8);
                            }
                            else if (entry->type() == DVAR_ENTRY_TYPE_NAME_ID_16_DATA_SIZE_16) {
                                nameId = entry->name_id_16();
                                bodySize = entry->len_data_16();
                                headerSize += sizeof(UINT16) + sizeof(UINT16);
                            }
                            
                            entrySize = headerSize + bodySize;
                            header = dvar.mid(entryOffset, headerSize);
                            body = dvar.mid(entryOffset + headerSize, bodySize);
                            
                            name = guidToUString(guid);
                            text = usprintf("%X", nameId);
                            info = usprintf("Full size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nState: %02Xh\nFlags: %02Xh\nType: %02Xh\nNamespaceId: %Xh\nNameId: %Xh\n",
                                            entrySize, entrySize,
                                            (UINT32)header.size(), (UINT32)header.size(),
                                            (UINT32)body.size(), (UINT32)body.size(),
                                            entry->state(),
                                            entry->flags(),
                                            entry->type(),
                                            entry->namespace_id(),
                                            nameId)
                            + UString("NamespaceGuid: ") + guidToUString(guid, false);
                            
                            guidMap.insert(std::pair<UINT8, EFI_GUID>(entry->namespace_id(), guid));
                        }
                        // NameId entry
                        else {
                            subtype = Subtypes::NameIdDvarEntry;
                            headerSize = sizeof(DVAR_ENTRY_HEADER);
                            if (entry->type() == DVAR_ENTRY_TYPE_NAME_ID_8_DATA_SIZE_8) {
                                nameId = entry->name_id_8();
                                bodySize = entry->len_data_8();
                                headerSize += sizeof(UINT8) + sizeof(UINT8);
                            }
                            else if (entry->type() == DVAR_ENTRY_TYPE_NAME_ID_16_DATA_SIZE_8) {
                                nameId = entry->name_id_16();
                                bodySize = entry->len_data_8();
                                headerSize += sizeof(UINT16) + sizeof(UINT8);
                            }
                            else if (entry->type() == DVAR_ENTRY_TYPE_NAME_ID_16_DATA_SIZE_16) {
                                nameId = entry->name_id_16();
                                bodySize = entry->len_data_16();
                                headerSize += sizeof(UINT16) + sizeof(UINT16);
                            }
                            
                            entrySize = headerSize + bodySize;
                            header = dvar.mid(entryOffset, headerSize);
                            body = dvar.mid(entryOffset + headerSize, bodySize);
                            
                            name.clear();
                            text = usprintf("%X", nameId);
                            info = usprintf("Full size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nState: %02Xh\nFlags: %02Xh\nType: %02Xh\nNamespaceId: %Xh\nNameId: %Xh\n",
                                            entrySize, entrySize,
                                            (UINT32)header.size(), (UINT32)header.size(),
                                            (UINT32)body.size(), (UINT32)body.size(),
                                            entry->state(),
                                            entry->flags(),
                                            entry->type(),
                                            entry->namespace_id(),
                                            nameId);
                        }
                        
                        // Mark NameId entries that are not stored as Invalid
                        if (entry->flags() != DVAR_ENTRY_FLAG_NAME_ID + DVAR_ENTRY_FLAG_NAMESPACE_GUID &&
                            (entry->state() == DVAR_ENTRY_STATE_STORING ||
                             entry->state() == DVAR_ENTRY_STATE_DELETING ||
                             entry->state() == DVAR_ENTRY_STATE_DELETED)) {
                            subtype = Subtypes::InvalidDvarEntry;
                            name = UString("Invalid");
                            text.clear();
                        }
                        
                        // Add tree item
                        model->addItem(entryOffset, Types::DellDvarEntry, subtype, name, text, info, header, body, UByteArray(), Fixed, headerIndex);
                        
                        entryOffset += entrySize;
                    }
                }
                
                // Reparse all NameId variables to detect invalid ones and assign name and text to valid ones
                for (int i = 0; i < model->rowCount(headerIndex); i++) {
                    UModelIndex current = headerIndex.model()->index(i, 0, headerIndex);
                    
                    if (model->subtype(current) == Subtypes::NameIdDvarEntry) {
                        UByteArray header = model->header(current);
                        const DVAR_ENTRY_HEADER* nameIdHeader = (const DVAR_ENTRY_HEADER*)header.constData();
                        UINT8 id = 0xFF - nameIdHeader->NamespaceIdC;
                        UString guid;
                        if (guidMap.count(id))
                            guid = guidToUString(guidMap[id]);
                        
                        // Check for variable validity
                        if (guid.isEmpty()) { // Guid not found
                            model->setName(current, UString("Invalid"));
                            model->setText(current, UString());
                            msg(usprintf("%s: NameId variable with invalid NamespaceGuid", __FUNCTION__), current);
                        }
                        else { // Variable is OK, rename it
                            model->setName(current, guid);
                            model->addInfo(current, UString("NamespaceGuid: ") + guidToUString(guidMap[id], false));
                        }
                    }
                }
            }
            catch (...) {
                // Parsing failed, need to add the candidate as Padding
                UByteArray padding = data.mid(itemOffset, itemSize);
                
                // Get info
                name = UString("Padding");
                info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
                
                // Add tree item
                model->addItem(headerSize + itemOffset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
            }
        }
#endif
        else {
            return U_UNKNOWN_ITEM_TYPE;
        }
        
        // Go to next item
        prevItemOffset = itemOffset;
        prevItemSize = itemSize;
        prevItemType = itemType;
        result = findNextRawAreaItem(index, itemOffset + prevItemSize, itemType, itemOffset, itemSize, itemAltSize);
        
        // Silence value not used after assignment warning
        (void)prevItemType;
    }
    
    // Padding at the end of raw area
    itemOffset = prevItemOffset + prevItemSize;
    if ((UINT32)data.size() > itemOffset) {
        UByteArray padding = data.mid(itemOffset);
        
        // Get info
        name = UString("Padding");
        info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
        
        // Add tree item
        model->addItem(headerSize + itemOffset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseVolumeHeader(const UByteArray & volume, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Sanity check
    if (volume.isEmpty())
        return U_INVALID_PARAMETER;
    
    // Check that there is space for the volume header
    if ((UINT32)volume.size() < sizeof(EFI_FIRMWARE_VOLUME_HEADER)) {
        msg(usprintf("%s: input volume size %Xh (%u) is smaller than volume header size 40h (64)", __FUNCTION__, (UINT32)volume.size(), (UINT32)volume.size()));
        return U_INVALID_VOLUME;
    }
    
    // Populate volume header
    const EFI_FIRMWARE_VOLUME_HEADER* volumeHeader = (const EFI_FIRMWARE_VOLUME_HEADER*)(volume.constData());
    
    // Check sanity of HeaderLength value
    if ((UINT32)ALIGN8(volumeHeader->HeaderLength) > (UINT32)volume.size()) {
        msg(usprintf("%s: volume header overlaps the end of data", __FUNCTION__));
        return U_INVALID_VOLUME;
    }
    // Check sanity of ExtHeaderOffset value
    if (volumeHeader->Revision > 1 && volumeHeader->ExtHeaderOffset
        && (UINT32)ALIGN8(volumeHeader->ExtHeaderOffset + sizeof(EFI_FIRMWARE_VOLUME_EXT_HEADER)) > (UINT32)volume.size()) {
        msg(usprintf("%s: extended volume header overlaps the end of data", __FUNCTION__));
        return U_INVALID_VOLUME;
    }
    
    // Calculate volume header size
    UINT32 headerSize;
    EFI_GUID extendedHeaderGuid = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0 }};
    bool hasExtendedHeader = false;
    if (volumeHeader->Revision > 1 && volumeHeader->ExtHeaderOffset) {
        hasExtendedHeader = true;
        const EFI_FIRMWARE_VOLUME_EXT_HEADER* extendedHeader = (const EFI_FIRMWARE_VOLUME_EXT_HEADER*)(volume.constData() + volumeHeader->ExtHeaderOffset);
        headerSize = volumeHeader->ExtHeaderOffset + extendedHeader->ExtHeaderSize;
        extendedHeaderGuid = extendedHeader->FvName;
    }
    else {
        headerSize = volumeHeader->HeaderLength;
    }
    
    // Extended header end can be unaligned
    headerSize = ALIGN8(headerSize);
    
    // Check for volume structure to be known
    bool isUnknown = true;
    bool isNvramVolume = false;
    bool isMicrocodeVolume = false;
    UINT8 ffsVersion = 0;
    
    // Check for FFS v2 volume
    UByteArray guid = UByteArray((const char*)&volumeHeader->FileSystemGuid, sizeof(EFI_GUID));
    if (std::find(FFSv2Volumes.begin(), FFSv2Volumes.end(), guid) != FFSv2Volumes.end()) {
        isUnknown = false;
        ffsVersion = 2;
    }
    // Check for FFS v3 volume
    else if (std::find(FFSv3Volumes.begin(), FFSv3Volumes.end(), guid) != FFSv3Volumes.end()) {
        isUnknown = false;
        ffsVersion = 3;
    }
    // Check for VSS NVRAM volume
    else if (guid == NVRAM_MAIN_STORE_VOLUME_GUID || guid == NVRAM_ADDITIONAL_STORE_VOLUME_GUID) {
        isUnknown = false;
        isNvramVolume = true;
    }
    // Check for Microcode volume
    else if (guid == EFI_APPLE_MICROCODE_VOLUME_GUID) {
        isUnknown = false;
        isMicrocodeVolume = true;
        headerSize = EFI_APPLE_MICROCODE_VOLUME_HEADER_SIZE;
    }
    
    // Check volume revision and alignment
    bool msgAlignmentBitsSet = false;
    bool msgUnaligned = false;
    bool msgUnknownRevision = false;
    UINT32 alignment = 0x10000; // Default volume alignment is 64K
    if (volumeHeader->Revision == 1) {
        // Acquire alignment capability bit
        bool alignmentCap = (volumeHeader->Attributes & EFI_FVB_ALIGNMENT_CAP) != 0;
        if (!alignmentCap) {
            if (volumeHeader->Attributes & 0xFFFF0000)
                msgAlignmentBitsSet = true;
        }
        // Do not check for volume alignment on revision 1 volumes
        // No one gives a single damn about setting it correctly
    }
    else if (volumeHeader->Revision == 2) {
        // Acquire alignment
        alignment = (UINT32)(1UL << ((volumeHeader->Attributes & EFI_FVB2_ALIGNMENT) >> 16));
        // Check alignment
        if (!isUnknown
            && !model->compressed(parent) // Alignment checks don't really make sense for compressed volumes because they have to be extracted into memory, and by that point it's unlikely that the module doing such extraction will misalign them
            && ((model->base(parent) + localOffset - imageBase) % alignment) != 0) // Explicit "is not zero" here for better code readability
            msgUnaligned = true;
    }
    else {
        msgUnknownRevision = true;
    }
    
    // Check attributes
    // Determine value of empty byte
    UINT8 emptyByte = volumeHeader->Attributes & EFI_FVB_ERASE_POLARITY ? 0xFF : 0x00;
    
    // Check for AppleCRC32 and UsedSpace in ZeroVector
    bool hasAppleCrc32 = false;
    UINT32 volumeSize = (UINT32)volume.size();
    UINT32 appleCrc32 = *(UINT32*)(volume.constData() + 8);
    UINT32 usedSpace = *(UINT32*)(volume.constData() + 12);
    if (appleCrc32 != 0) {
        // Calculate CRC32 of the volume body
        UINT32 crc = (UINT32)crc32(0, (const UINT8*)(volume.constData() + volumeHeader->HeaderLength), volumeSize - volumeHeader->HeaderLength);
        if (crc == appleCrc32) {
            hasAppleCrc32 = true;
        }
    }
    
    // Check header checksum by recalculating it
    bool msgInvalidChecksum = false;

    if (volumeHeader->HeaderLength < sizeof(EFI_FIRMWARE_VOLUME_HEADER)) {
        msg(usprintf("%s: input volume header length %04Xh (%hu) is smaller than volume header size", __FUNCTION__, volumeHeader->HeaderLength, volumeHeader->HeaderLength));
        return U_INVALID_VOLUME;
    }
    UByteArray tempHeader((const char*)volumeHeader, volumeHeader->HeaderLength);
    ((EFI_FIRMWARE_VOLUME_HEADER*)tempHeader.data())->Checksum = 0;
    UINT16 calculated = calculateChecksum16((const UINT16*)tempHeader.constData(), volumeHeader->HeaderLength);
    if (volumeHeader->Checksum != calculated)
        msgInvalidChecksum = true;
    
    // Get info
    if (headerSize >= (UINT32)volume.size()) {
        return U_INVALID_VOLUME;
    }
    UByteArray header = volume.left(headerSize);
    UByteArray body = volume.mid(headerSize);
    UString name = guidToUString(volumeHeader->FileSystemGuid);
    UString info = usprintf("ZeroVector:\n%02X %02X %02X %02X %02X %02X %02X %02X\n"
                            "%02X %02X %02X %02X %02X %02X %02X %02X\nSignature: _FVH\nFileSystem GUID: ",
                            volumeHeader->ZeroVector[0], volumeHeader->ZeroVector[1], volumeHeader->ZeroVector[2], volumeHeader->ZeroVector[3],
                            volumeHeader->ZeroVector[4], volumeHeader->ZeroVector[5], volumeHeader->ZeroVector[6], volumeHeader->ZeroVector[7],
                            volumeHeader->ZeroVector[8], volumeHeader->ZeroVector[9], volumeHeader->ZeroVector[10], volumeHeader->ZeroVector[11],
                            volumeHeader->ZeroVector[12], volumeHeader->ZeroVector[13], volumeHeader->ZeroVector[14], volumeHeader->ZeroVector[15])
    + guidToUString(volumeHeader->FileSystemGuid, false) \
    + usprintf("\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nRevision: %u\nAttributes: %08Xh\nErase polarity: %u\nChecksum: %04Xh",
               volumeSize, volumeSize,
               headerSize, headerSize,
               volumeSize - headerSize, volumeSize - headerSize,
               volumeHeader->Revision,
               volumeHeader->Attributes,
               (emptyByte ? 1 : 0),
               volumeHeader->Checksum) +
    (msgInvalidChecksum ? usprintf(", invalid, should be %04Xh", calculated) : UString(", valid"));
    
    // Block size and blocks number
    const EFI_FV_BLOCK_MAP_ENTRY* entry = (const EFI_FV_BLOCK_MAP_ENTRY*)(volume.constData() + sizeof(EFI_FIRMWARE_VOLUME_HEADER));
    UString infoNumBlocks = usprintf("NumBlocks: %Xh (%u)", entry->NumBlocks, entry->NumBlocks);
    UString infoLength = usprintf("Length: %Xh (%u)", entry->Length, entry->Length);
    if (entry->NumBlocks == 0) {
        infoNumBlocks += UString(", invalid, can not be zero");
    }
    if (entry->Length == 0)  {
        infoLength += UString(", invalid, can not be zero");
    }
    if (entry->NumBlocks != 0 && entry->Length != 0) {
        UINT32 volumeAltSize = entry->NumBlocks * entry->Length;
        if (volumeSize != volumeAltSize) {
            if (volumeAltSize % entry->Length == 0 && volumeSize % entry->Length == 0) {
                infoNumBlocks += usprintf(", invalid, should be %Xh", volumeSize / entry->Length);
                infoLength += ", valid";
            }
            else if (volumeAltSize % entry->NumBlocks == 0 && volumeSize % entry->NumBlocks == 0) {
                infoNumBlocks += ", valid";
                infoLength += usprintf(", invalid, should be %Xh", volumeSize / entry->NumBlocks);
            }
        }
        else {
            infoNumBlocks += ", valid";
            infoLength += ", valid";
        }
    }
    info += "\n" + infoNumBlocks + "\n" + infoLength;
    
    // Extended header
    if (volumeHeader->Revision > 1 && volumeHeader->ExtHeaderOffset) {
        if ((UINT32)volume.size() < volumeHeader->ExtHeaderOffset + sizeof(EFI_FIRMWARE_VOLUME_EXT_HEADER)) {
            return U_INVALID_VOLUME;
        }
        const EFI_FIRMWARE_VOLUME_EXT_HEADER* extendedHeader = (const EFI_FIRMWARE_VOLUME_EXT_HEADER*)(volume.constData() + volumeHeader->ExtHeaderOffset);
        info += usprintf("\nExtended header size: %Xh (%u)\nVolume GUID: ",
                         extendedHeader->ExtHeaderSize, extendedHeader->ExtHeaderSize) + guidToUString(extendedHeader->FvName, false);
        name = guidToUString(extendedHeader->FvName); // Replace FFS GUID with volume GUID
    }
    
    // Add text
    UString text;
    if (hasAppleCrc32)
        text += UString("AppleCRC32 ");
    
    // Add tree item
    UINT8 subtype = Subtypes::UnknownVolume;
    if (!isUnknown) {
        if (ffsVersion == 2)
            subtype = Subtypes::Ffs2Volume;
        else if (ffsVersion == 3)
            subtype = Subtypes::Ffs3Volume;
        else if (isNvramVolume)
            subtype = Subtypes::NvramVolume;
        else if (isMicrocodeVolume)
            subtype = Subtypes::MicrocodeVolume;
    }
    index = model->addItem(localOffset, Types::Volume, subtype, name, text, info, header, body, UByteArray(), Movable, parent);
    
    // Set parsing data for created volume
    VOLUME_PARSING_DATA pdata = {};
    pdata.emptyByte = emptyByte;
    pdata.ffsVersion = ffsVersion;
    pdata.hasExtendedHeader = hasExtendedHeader ? TRUE : FALSE;
    pdata.extendedHeaderGuid = extendedHeaderGuid;
    pdata.alignment = alignment;
    pdata.revision = volumeHeader->Revision;
    pdata.hasAppleCrc32 = hasAppleCrc32;
    pdata.hasValidUsedSpace = FALSE; // Will be updated later, if needed
    pdata.usedSpace = usedSpace;
    pdata.isWeakAligned = (volumeHeader->Revision > 1 && (volumeHeader->Attributes & EFI_FVB2_WEAK_ALIGNMENT));
    model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
    
    // Show messages
    if (isUnknown)
        msg(usprintf("%s: unknown file system ", __FUNCTION__) + guidToUString(volumeHeader->FileSystemGuid), index);
    if (msgInvalidChecksum)
        msg(usprintf("%s: volume header checksum is invalid", __FUNCTION__), index);
    if (msgAlignmentBitsSet)
        msg(usprintf("%s: alignment bits set on volume without alignment capability", __FUNCTION__), index);
    if (msgUnaligned)
        msg(usprintf("%s: unaligned volume", __FUNCTION__), index);
    if (msgUnknownRevision)
        msg(usprintf("%s: unknown volume revision %u", __FUNCTION__, volumeHeader->Revision), index);
    
    return U_SUCCESS;
}

bool FfsParser::microcodeHeaderValid(const INTEL_MICROCODE_HEADER* ucodeHeader)
{
    bool reservedBytesValid = true;
    
    // Check data size to be multiple of 4 and less than 0x1000000
    if (ucodeHeader->DataSize % 4 != 0 ||
        ucodeHeader->DataSize > 0xFFFFFF) {
        return false;
    }
    
    // Check TotalSize to be greater or equal than DataSize and less than 0x1000000
    if (ucodeHeader->TotalSize < ucodeHeader->DataSize ||
        ucodeHeader->TotalSize > 0xFFFFFF) {
        return false;
    }
    
    // Check date to be sane
    // Check day to be in 0x01-0x09, 0x10-0x19, 0x20-0x29, 0x30-0x31
    if (ucodeHeader->DateDay < 0x01 ||
        (ucodeHeader->DateDay > 0x09 && ucodeHeader->DateDay < 0x10) ||
        (ucodeHeader->DateDay > 0x19 && ucodeHeader->DateDay < 0x20) ||
        (ucodeHeader->DateDay > 0x29 && ucodeHeader->DateDay < 0x30) ||
        ucodeHeader->DateDay > 0x31) {
        return false;
    }
    // Check month to be in 0x01-0x09, 0x10-0x12
    if (ucodeHeader->DateMonth < 0x01 ||
        (ucodeHeader->DateMonth > 0x09 && ucodeHeader->DateMonth < 0x10) ||
        ucodeHeader->DateMonth > 0x12) {
        return FALSE;
    }
    // Check year to be in 0x1990-0x1999, 0x2000-0x2009, 0x2010-0x2019, 0x2020-0x2029, 0x2030-0x2030, 0x2040-0x2049
    if (ucodeHeader->DateYear < 0x1990 ||
        (ucodeHeader->DateYear > 0x1999 && ucodeHeader->DateYear < 0x2000) ||
        (ucodeHeader->DateYear > 0x2009 && ucodeHeader->DateYear < 0x2010) ||
        (ucodeHeader->DateYear > 0x2019 && ucodeHeader->DateYear < 0x2020) ||
        (ucodeHeader->DateYear > 0x2029 && ucodeHeader->DateYear < 0x2030) ||
        (ucodeHeader->DateYear > 0x2039 && ucodeHeader->DateYear < 0x2040) ||
        ucodeHeader->DateYear > 0x2049) {
        return FALSE;
    }
    // Check HeaderType to be 1.
    if (ucodeHeader->HeaderType != 1) {
        return FALSE;
    }
    // Check LoaderRevision to be 1.
    if (ucodeHeader->LoaderRevision != 1) {
        return FALSE;
    }
    
    return TRUE;
}

USTATUS FfsParser::findNextRawAreaItem(const UModelIndex & index, const UINT32 localOffset, UINT8 & nextItemType, UINT32 & nextItemOffset, UINT32 & nextItemSize, UINT32 & nextItemAlternativeSize)
{
    UByteArray data = model->body(index);
    UINT32 dataSize = (UINT32)data.size();
    
    if (dataSize < sizeof(UINT32))
        return U_STORES_NOT_FOUND;
    
    UINT32 offset = localOffset;
    for (; offset < dataSize - sizeof(UINT32); offset++) {
        const UINT32* currentPos = (const UINT32*)(data.constData() + offset);
        UINT32 restSize = dataSize - offset;
        if (readUnaligned(currentPos) == INTEL_MICROCODE_HEADER_VERSION_1) { // Intel microcode
            // Check data size
            if (restSize < sizeof(INTEL_MICROCODE_HEADER)) {
                continue;
            }
            
            // Check microcode header candidate
            const INTEL_MICROCODE_HEADER* ucodeHeader = (const INTEL_MICROCODE_HEADER*)currentPos;
            if (FALSE == microcodeHeaderValid(ucodeHeader)) {
                continue;
            }
            
            // Check size candidate
            if (ucodeHeader->TotalSize == 0)
                continue;
            
            // All checks passed, microcode found
            nextItemType = Types::Microcode;
            nextItemSize = ucodeHeader->TotalSize;
            nextItemAlternativeSize = ucodeHeader->TotalSize;
            nextItemOffset = offset;
            break;
        }
        else if (readUnaligned(currentPos) == EFI_FV_SIGNATURE) {
            if (offset < EFI_FV_SIGNATURE_OFFSET)
                continue;

            // Prevent OOB access
            if (restSize + EFI_FV_SIGNATURE_OFFSET < sizeof(EFI_FIRMWARE_VOLUME_HEADER)) {
                continue;
            }
            const EFI_FIRMWARE_VOLUME_HEADER* volumeHeader = (const EFI_FIRMWARE_VOLUME_HEADER*)(data.constData() + offset - EFI_FV_SIGNATURE_OFFSET);
            restSize -= sizeof(EFI_FIRMWARE_VOLUME_HEADER);
            if (volumeHeader->FvLength < sizeof(EFI_FIRMWARE_VOLUME_HEADER) + 2 * sizeof(EFI_FV_BLOCK_MAP_ENTRY) || volumeHeader->FvLength >= 0xFFFFFFFFUL) {
                continue;
            }
            if (volumeHeader->Revision != 1 && volumeHeader->Revision != 2) {
                continue;
            }
            
            // Calculate alternative volume size using its BlockMap
            nextItemAlternativeSize = 0;

            // Prevent OOB access
            if (restSize + EFI_FV_SIGNATURE_OFFSET < sizeof(EFI_FIRMWARE_VOLUME_HEADER)) {
                continue;
            }
            const EFI_FV_BLOCK_MAP_ENTRY* entry = (const EFI_FV_BLOCK_MAP_ENTRY*)(data.constData() + offset - EFI_FV_SIGNATURE_OFFSET + sizeof(EFI_FIRMWARE_VOLUME_HEADER));
            restSize -= sizeof(EFI_FV_BLOCK_MAP_ENTRY);
            while (entry->NumBlocks != 0 && entry->Length != 0) {
                // Check if we are past the end of the volume
                if (restSize + EFI_FV_SIGNATURE_OFFSET < sizeof(EFI_FV_BLOCK_MAP_ENTRY)) {
                    // This volume is broken, but we can't use continue here because we need to continue the outer loop
                    goto continue_searching;
                }
                
                nextItemAlternativeSize += entry->NumBlocks * entry->Length;
                restSize -= sizeof(EFI_FV_BLOCK_MAP_ENTRY);
                entry += 1;
            }
            
            // All checks passed, volume found
            nextItemType = Types::Volume;
            nextItemSize = (UINT32)volumeHeader->FvLength;
            nextItemOffset = offset - EFI_FV_SIGNATURE_OFFSET;
            break;
continue_searching: {}
        }
        else if (readUnaligned(currentPos) == BPDT_GREEN_SIGNATURE
                 || readUnaligned(currentPos) == BPDT_YELLOW_SIGNATURE) {
            // Check data size
            if (restSize < sizeof(BPDT_HEADER))
                continue;
            
            const BPDT_HEADER *bpdtHeader = (const BPDT_HEADER *)currentPos;
                        
            // Check NumEntries to be sane
            if (bpdtHeader->NumEntries > 0x100)
                continue;
            
            // Check HeaderVersion to be 1
            if (bpdtHeader->HeaderVersion != BPDT_HEADER_VERSION_1) // Check only for IFWI 2.0 headers in raw areas
                continue;
            
            // Check RedundancyFlag to be 0 or 1
            if (bpdtHeader->RedundancyFlag != 0 && bpdtHeader->RedundancyFlag != 1) // Check only for IFWI 2.0 headers in raw areas
                continue;
            
            UINT32 ptBodySize = bpdtHeader->NumEntries * sizeof(BPDT_ENTRY);
            UINT32 ptSize = sizeof(BPDT_HEADER) + ptBodySize;
            // Check data size again
            if (restSize < ptSize)
                continue;
            
            UINT32 sizeCandidate = 0;
            // Parse partition table
            const BPDT_ENTRY* firstPtEntry = (const BPDT_ENTRY*)((const UINT8*)bpdtHeader + sizeof(BPDT_HEADER));
            for (UINT16 i = 0; i < bpdtHeader->NumEntries; i++) {
                // Populate entry header
                const BPDT_ENTRY* ptEntry = firstPtEntry + i;
                // Check that entry is present in the image
                if (ptEntry->Offset != 0
                    && ptEntry->Offset != 0xFFFFFFFF
                    && ptEntry->Size != 0
                    && sizeCandidate < ptEntry->Offset + ptEntry->Size) {
                    sizeCandidate = ptEntry->Offset + ptEntry->Size;
                }
            }
            
            // Check size candidate
            if (sizeCandidate == 0 || sizeCandidate > restSize) {
                msg(usprintf("%s: invalid BpdtStore size (sizeCandidate = %Xh, restSize = %Xh)", __FUNCTION__, sizeCandidate, restSize), index);
                continue;
            }
            
            // All checks passed, BPDT found
            nextItemType = Types::BpdtStore;
            nextItemSize = sizeCandidate;
            nextItemAlternativeSize = sizeCandidate;
            nextItemOffset = offset;
            break;
        }
        else if (readUnaligned(currentPos) == INSYDE_FLASH_DEVICE_MAP_SIGNATURE) {
            // Check data size
            if (restSize < sizeof(INSYDE_FLASH_DEVICE_MAP_HEADER))
                continue;
            
            const INSYDE_FLASH_DEVICE_MAP_HEADER *fdmHeader = (const INSYDE_FLASH_DEVICE_MAP_HEADER *)currentPos;
            
            if (restSize < fdmHeader->Size)
                continue;
            
            if (fdmHeader->Revision > 4) {
                msg(usprintf("%s: Insyde Flash Device Map candidate with unknown revision %u", __FUNCTION__, fdmHeader->Revision), index);
                continue;
            }
            
            // All checks passed, FDM found
            nextItemType = Types::InsydeFlashDeviceMapStore;
            nextItemSize = fdmHeader->Size;
            nextItemAlternativeSize = fdmHeader->Size;
            nextItemOffset = offset;
            break;
        }
#ifdef U_ENABLE_NVRAM_PARSING_SUPPORT
        else if (readUnaligned(currentPos) == DVAR_STORE_SIGNATURE) {
            // Check data size
            if (restSize < sizeof(DVAR_STORE_HEADER))
                continue;
            
            const DVAR_STORE_HEADER *dvarHeader = (const DVAR_STORE_HEADER *)currentPos;
            UINT32 storeSize = 0xFFFFFFFF - dvarHeader->StoreSizeC;
            if (restSize < storeSize)
                continue;
            
            // All checks passed, FDM found
            nextItemType = Types::DellDvarStore;
            nextItemSize = storeSize;
            nextItemAlternativeSize = storeSize;
            nextItemOffset = offset;
            break;
        }
#endif
    }
    
    // No more stores found
    if (offset >= dataSize - sizeof(UINT32)) {
        return U_STORES_NOT_FOUND;
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseVolumeNonUefiData(const UByteArray & data, const UINT32 localOffset, const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Get info
    UString info = usprintf("Full size: %Xh (%u)", (UINT32)data.size(), (UINT32)data.size());
    
    // Add padding tree item
    UModelIndex paddingIndex = model->addItem(localOffset, Types::Padding, Subtypes::DataPadding, UString("Non-UEFI data"), UString(), info, UByteArray(), data, UByteArray(), Fixed, index);
    msg(usprintf("%s: non-UEFI data found in volume free space", __FUNCTION__), paddingIndex);
    
    // Parse contents as raw area
    return parseRawArea(paddingIndex);
}

USTATUS FfsParser::parseVolumeBody(const UModelIndex & index, const bool probe)
{
    // Sanity check
    if (!index.isValid()) {
        return U_INVALID_PARAMETER;
    }
    
    // Get volume header size and body
    UByteArray volumeBody = model->body(index);
    UINT32 volumeHeaderSize = (UINT32)model->header(index).size();
    
    // Parse NVRAM volume with a dedicated function
    if (model->subtype(index) == Subtypes::NvramVolume) {
        return nvramParser->parseNvramVolumeBody(index);
    }
    
    // Parse Microcode volume with a dedicated function
    if (model->subtype(index) == Subtypes::MicrocodeVolume) {
        return parseMicrocodeVolumeBody(index);
    }
    
    // Get required values from parsing data
    UINT8 emptyByte = 0xFF;
    UINT8 ffsVersion = 2;
    UINT32 usedSpace = 0;
    UINT8 revision = 2;
    if (model->hasEmptyParsingData(index) == false) {
        UByteArray data = model->parsingData(index);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        emptyByte = pdata->emptyByte;
        ffsVersion = pdata->ffsVersion;
        usedSpace = pdata->usedSpace;
        revision = pdata->revision;
    }
    
    // Check for unknown FFS version
    if (ffsVersion != 2 && ffsVersion != 3) {
        msg(usprintf("%s: unknown FFS version %d", __FUNCTION__, ffsVersion), index);
        return U_SUCCESS;
    }
    
    // Search for and parse all files
    UINT32 volumeBodySize = (UINT32)volumeBody.size();
    UINT32 fileOffset = 0;
    
    while (fileOffset < volumeBodySize) {
        UINT32 fileSize = getFileSize(volumeBody, fileOffset, ffsVersion, revision);
        
        if (fileSize == 0) {
            msg(usprintf("%s: file header parsing failed with invalid size", __FUNCTION__), index);
            break; // Exit from parsing loop
        }
        
        // Check that we are at the empty space
        UByteArray header = volumeBody.mid(fileOffset, (int)std::min(sizeof(EFI_FFS_FILE_HEADER), (size_t)volumeBodySize - fileOffset));
        if (isUniformByte(header, emptyByte)) { // Empty space
            // Check volume usedSpace entry to be valid
            if (usedSpace > 0 && usedSpace == fileOffset + volumeHeaderSize) {
                if (model->hasEmptyParsingData(index) == false) {
                    UByteArray data = model->parsingData(index);
                    VOLUME_PARSING_DATA* pdata = (VOLUME_PARSING_DATA*)data.data();
                    pdata->hasValidUsedSpace = TRUE;
                    model->setParsingData(index, data);
                    model->setText(index, model->text(index) + "UsedSpace ");
                }
            }
            
            // Check free space to be actually free
            UByteArray freeSpace = volumeBody.mid(fileOffset);
            if (!isUniformByte(freeSpace, emptyByte)) {
                // Search for the first non-empty byte
                UINT32 i;
                UINT32 size = (UINT32)freeSpace.size();
                const UINT8* current = (UINT8*)freeSpace.constData();
                for (i = 0; i < size; i++) {
                    if (*current++ != emptyByte) {
                        break; // Exit from parsing loop
                    }
                }
                
                // Align found index to file alignment
                // It must be possible because minimum 16 bytes of empty were found before
                if (i != ALIGN8(i)) {
                    i = ALIGN8(i) - 8;
                }
                
                // Add all bytes before as free space
                if (i > 0) {
                    if (probe)
                        return U_STORES_NOT_FOUND;
                    UByteArray free = freeSpace.left(i);
                    
                    // Get info
                    UString info = usprintf("Full size: %Xh (%u)", (UINT32)free.size(), (UINT32)free.size());
                    
                    // Add free space item
                    model->addItem(volumeHeaderSize + fileOffset, Types::FreeSpace, 0, UString("Volume free space"), UString(), info, UByteArray(), free, UByteArray(), Movable, index);
                }
                
                // Parse non-UEFI data
                parseVolumeNonUefiData(freeSpace.mid(i), volumeHeaderSize + fileOffset + i, index);
            }
            else {
                // Get info
                UString info = usprintf("Full size: %Xh (%u)", (UINT32)freeSpace.size(), (UINT32)freeSpace.size());
                
                // Add free space item
                model->addItem(volumeHeaderSize + fileOffset, Types::FreeSpace, 0, UString("Volume free space"), UString(), info, UByteArray(), freeSpace, UByteArray(), Movable, index);
            }
            
            break; // Exit from parsing loop
        }
        
        // We aren't at the end of empty space
        // Check that the remaining space can still have a file in it
        if (volumeBodySize - fileOffset < sizeof(EFI_FFS_FILE_HEADER) // Remaining space is smaller than the smallest possible file
            || volumeBodySize - fileOffset < fileSize) { // Remaining space is smaller than non-empty file size
            if (probe)
                return U_STORES_NOT_FOUND;
            // Parse non-UEFI data
            parseVolumeNonUefiData(volumeBody.mid(fileOffset), volumeHeaderSize + fileOffset, index);
            
            break; // Exit from parsing loop
        }
        
        // Parse current file's header
        UModelIndex fileIndex;
        USTATUS result = parseFileHeader(volumeBody.mid(fileOffset, fileSize), volumeHeaderSize + fileOffset, index, fileIndex, probe);
        if (result) {
            msg(usprintf("%s: file header parsing failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
        }
        
        // Move to next file
        fileOffset += fileSize;
        // TODO: check that alignment bytes are all of erase polarity bit, warn if not so
        fileOffset = ALIGN8(fileOffset);
    }
    
    // Check for duplicate GUIDs
    for (int i = 0; i < model->rowCount(index); i++) {
        UModelIndex current = index.model()->index(i, 0, index);
        
        // Skip non-file entries and padding files
        if (model->type(current) != Types::File
            || model->subtype(current) == EFI_FV_FILETYPE_PAD) {
            continue;
        }
        
        // Get current file GUID
        UByteArray currentGuid(model->header(current).constData(), sizeof(EFI_GUID));
        
        // Check files after current for having an equal GUID
        for (int j = i + 1; j < model->rowCount(index); j++) {
            UModelIndex another = index.model()->index(j, 0, index);
            
            // Skip non-file entries
            if (model->type(another) != Types::File) {
                continue;
            }
            
            // Get another file GUID
            UByteArray anotherGuid(model->header(another).constData(), sizeof(EFI_GUID));
            
            // Check GUIDs for being equal
            if (currentGuid == anotherGuid) {
                msg(usprintf("%s: file with duplicate GUID ", __FUNCTION__) + guidToUString(readUnaligned((EFI_GUID*)(anotherGuid.data()))), another);
            }
        }
    }
    
    // Parse bodies
    for (int i = 0; i < model->rowCount(index); i++) {
        UModelIndex current = index.model()->index(i, 0, index);
        
        switch (model->type(current)) {
            case Types::File:
                parseFileBody(current);
                break;
            case Types::Padding:
            case Types::FreeSpace:
                // No parsing required
                break;
            default:
                return U_UNKNOWN_ITEM_TYPE;
        }
    }
    
    return U_SUCCESS;
}

UINT32 FfsParser::getFileSize(const UByteArray & volume, const UINT32 fileOffset, const UINT8 ffsVersion, const UINT8 revision)
{
    if ((UINT32)volume.size() < fileOffset + sizeof(EFI_FFS_FILE_HEADER)) {
        return 0;
    }
    
    const EFI_FFS_FILE_HEADER* fileHeader = (const EFI_FFS_FILE_HEADER*)(volume.constData() + fileOffset);
    
    if (ffsVersion == 2) {
        UINT32 size = uint24ToUint32(fileHeader->Size);
        // Special case of Lenovo large file insize FFSv2 Rev2 volume
        if (revision == 2 && (fileHeader->Attributes & FFS_ATTRIB_LARGE_FILE)) {
            if ((UINT32)volume.size() < fileOffset + sizeof(EFI_FFS_FILE_HEADER2_LENOVO)) {
                return 0;
            }
            
            const EFI_FFS_FILE_HEADER2_LENOVO* fileHeader2Lenovo = (const EFI_FFS_FILE_HEADER2_LENOVO*)(volume.constData() + fileOffset);
            return (UINT32)fileHeader2Lenovo->ExtendedSize;
        }
        
        return size;
    }
    else if (ffsVersion == 3) {
        if (fileHeader->Attributes & FFS_ATTRIB_LARGE_FILE) {
            if ((UINT32)volume.size() < fileOffset + sizeof(EFI_FFS_FILE_HEADER2)) {
                return 0;
            }
            
            const EFI_FFS_FILE_HEADER2* fileHeader2 = (const EFI_FFS_FILE_HEADER2*)(volume.constData() + fileOffset);
            return (UINT32)fileHeader2->ExtendedSize;
        }
        
        return uint24ToUint32(fileHeader->Size);
    }
    
    return 0;
}

USTATUS FfsParser::parseFileHeader(const UByteArray & file, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Sanity check
    if (file.isEmpty()) {
        return U_INVALID_PARAMETER;
    }
    if ((UINT32)file.size() < sizeof(EFI_FFS_FILE_HEADER)) {
        return U_INVALID_FILE;
    }
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    bool isWeakAligned = false;
    UINT32 volumeAlignment = 0xFFFFFFFF;
    UINT8 volumeRevision = 2;
    UModelIndex parentVolumeIndex = model->type(parent) == Types::Volume ? parent : model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
        volumeAlignment = pdata->alignment;
        volumeRevision = pdata->revision;
        isWeakAligned = pdata->isWeakAligned;
    }
    
    // Get file header
    UByteArray header = file.left(sizeof(EFI_FFS_FILE_HEADER));
    EFI_FFS_FILE_HEADER* tempFileHeader = (EFI_FFS_FILE_HEADER*)header.data();
    if (tempFileHeader->Attributes & FFS_ATTRIB_LARGE_FILE) {
        if (ffsVersion == 2 && volumeRevision == 2) {
            if ((UINT32)file.size() < sizeof(EFI_FFS_FILE_HEADER2_LENOVO))
                return U_INVALID_FILE;
            header = file.left(sizeof(EFI_FFS_FILE_HEADER2_LENOVO));
        }
        if (ffsVersion == 3) {
            if ((UINT32)file.size() < sizeof(EFI_FFS_FILE_HEADER2))
                return U_INVALID_FILE;
            header = file.left(sizeof(EFI_FFS_FILE_HEADER2));
        }
    }
    const EFI_FFS_FILE_HEADER* fileHeader = (const EFI_FFS_FILE_HEADER*)header.constData();
    
    // Check file alignment
    bool msgUnalignedFile = false;
    UINT8 alignmentPower = ffsAlignmentTable[(fileHeader->Attributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3];
    if (volumeRevision > 1 && (fileHeader->Attributes & FFS_ATTRIB_DATA_ALIGNMENT2)) {
        alignmentPower = ffsAlignment2Table[(fileHeader->Attributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3];
    }
    
    UINT32 alignment = (UINT32)(1UL << alignmentPower);
    if ((localOffset + header.size()) % alignment) {
        msgUnalignedFile = true;
    }
    
    // Check file alignment against volume alignment
    bool msgFileAlignmentIsGreaterThanVolumeAlignment = false;
    if (!isWeakAligned && volumeAlignment < alignment) {
        msgFileAlignmentIsGreaterThanVolumeAlignment = true;
    }
    
    // Get file body
    UByteArray body = file.mid(header.size());
    
    // Check for file tail presence
    UByteArray tail;
    bool msgInvalidTailValue = false;
    if (volumeRevision == 1 && (fileHeader->Attributes & FFS_ATTRIB_TAIL_PRESENT)) {
        //Check file tail;
        UINT16 tailValue = *(UINT16*)body.right(sizeof(UINT16)).constData();
        if (fileHeader->IntegrityCheck.TailReference != (UINT16)~tailValue)
            msgInvalidTailValue = true;
        
        // Get tail and remove it from file body
        tail = body.right(sizeof(UINT16));
        body = body.left(body.size() - sizeof(UINT16));
    }
    
    // Check header checksum
    UINT8 calculatedHeader = 0x100 - (calculateSum8((const UINT8*)header.constData(), (UINT32)header.size()) - fileHeader->IntegrityCheck.Checksum.Header - fileHeader->IntegrityCheck.Checksum.File - fileHeader->State);
    bool msgInvalidHeaderChecksum = false;
    if (fileHeader->IntegrityCheck.Checksum.Header != calculatedHeader) {
        msgInvalidHeaderChecksum = true;
    }
    
    // Check data checksum
    // Data checksum must be calculated
    bool msgInvalidDataChecksum = false;
    UINT8 calculatedData = 0;
    if (fileHeader->Attributes & FFS_ATTRIB_CHECKSUM) {
        calculatedData = calculateChecksum8((const UINT8*)body.constData(), (UINT32)body.size());
    }
    // Data checksum must be one of predefined values
    else if (volumeRevision == 1) {
        calculatedData = FFS_FIXED_CHECKSUM;
    }
    else {
        calculatedData = FFS_FIXED_CHECKSUM2;
    }
    
    if (fileHeader->IntegrityCheck.Checksum.File != calculatedData) {
        msgInvalidDataChecksum = true;
    }
    
    // Check file type
    bool msgUnknownType = false;
    if (fileHeader->Type > EFI_FV_FILETYPE_MM_CORE_STANDALONE && fileHeader->Type != EFI_FV_FILETYPE_PAD) {
        msgUnknownType = true;
    };
    
    // Get info
    UString name;
    UString info;
    if (fileHeader->Type != EFI_FV_FILETYPE_PAD) {
        name = guidToUString(fileHeader->Name);
    } else {
        name = UString("Padding file");
    }
    
    info = UString("File GUID: ") + guidToUString(fileHeader->Name, false) +
    usprintf("\nType: %02Xh\nAttributes: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nTail size: %Xh (%u)\nState: %02Xh",
             fileHeader->Type,
             fileHeader->Attributes,
             (UINT32)(header.size() + body.size() + tail.size()), (UINT32)(header.size() + body.size() + tail.size()),
             (UINT32)header.size(), (UINT32)header.size(),
             (UINT32)body.size(), (UINT32)body.size(),
             (UINT32)tail.size(), (UINT32)tail.size(),
             fileHeader->State) +
    usprintf("\nHeader checksum: %02Xh", fileHeader->IntegrityCheck.Checksum.Header) + (msgInvalidHeaderChecksum ? usprintf(", invalid, should be %02Xh", calculatedHeader) : UString(", valid")) +
    usprintf("\nData checksum: %02Xh", fileHeader->IntegrityCheck.Checksum.File) + (msgInvalidDataChecksum ? usprintf(", invalid, should be %02Xh", calculatedData) : UString(", valid"));
    
    UString text;
    bool isVtf = false;
    bool isDxeCore = false;
    // Check if the file is a Volume Top File
    UByteArray fileGuid = UByteArray((const char*)&fileHeader->Name, sizeof(EFI_GUID));
    if (fileGuid == EFI_FFS_VOLUME_TOP_FILE_GUID) {
        // Mark it as the last VTF
        // This information will later be used to determine memory addresses of uncompressed image elements
        // Because the last byte of the last VFT is mapped to 0xFFFFFFFF physical memory address
        isVtf = true;
        text = UString("Volume Top File");
    }
    // Check if the file is the first DXE Core
    else if (fileGuid == EFI_DXE_CORE_GUID || fileGuid == AMI_CORE_DXE_GUID) {
        // Mark is as first DXE core
        // This information may be used to determine DXE volume offset for old AMI or post-IBB protected ranges
        isDxeCore = true;
    }
    
    // Construct fixed state
    ItemFixedState fixed = (ItemFixedState)((fileHeader->Attributes & FFS_ATTRIB_FIXED) != 0);
    
    // Add tree item
    index = model->addItem(localOffset, Types::File, fileHeader->Type, name, text, info, header, body, tail, fixed, parent);
    
    // Set parsing data for created file
    FILE_PARSING_DATA pdata = {};
    pdata.emptyByte = (fileHeader->State & EFI_FILE_ERASE_POLARITY) ? 0xFF : 0x00;
    pdata.guid = fileHeader->Name;
    model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
    
    // Override lastVtf index, if needed
    if (isVtf) {
        lastVtf = index;
    }
    
    // Override first DXE core index, if needed
    if (isDxeCore && !dxeCore.isValid()) {
        dxeCore = index;
    }
    
    // Show messages
    if (msgUnalignedFile)
        msg(usprintf("%s: unaligned file", __FUNCTION__), index);
    if (msgFileAlignmentIsGreaterThanVolumeAlignment)
        msg(usprintf("%s: file alignment %Xh is greater than parent volume alignment %Xh", __FUNCTION__, alignment, volumeAlignment), index);
    if (msgInvalidHeaderChecksum)
        msg(usprintf("%s: invalid header checksum %02Xh, should be %02Xh", __FUNCTION__, fileHeader->IntegrityCheck.Checksum.Header, calculatedHeader), index);
    if (msgInvalidDataChecksum)
        msg(usprintf("%s: invalid data checksum %02Xh, should be %02Xh", __FUNCTION__, fileHeader->IntegrityCheck.Checksum.File, calculatedData), index);
    if (msgInvalidTailValue)
        msg(usprintf("%s: invalid tail value %04Xh", __FUNCTION__, *(const UINT16*)tail.constData()), index);
    if (msgUnknownType)
        msg(usprintf("%s: unknown file type %02Xh", __FUNCTION__, fileHeader->Type), index);
    
    return U_SUCCESS;
}

UINT32 FfsParser::getSectionSize(const UByteArray & file, const UINT32 sectionOffset, const UINT8 ffsVersion)
{
    if ((UINT32)file.size() < sectionOffset + sizeof(EFI_COMMON_SECTION_HEADER)) {
        return 0;
    }
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(file.constData() + sectionOffset);
    
    if (ffsVersion == 2) {
        return uint24ToUint32(sectionHeader->Size);
    }
    else if (ffsVersion == 3) {
        UINT32 size = uint24ToUint32(sectionHeader->Size);
        if (size == EFI_SECTION2_IS_USED) {
            if ((UINT32)file.size() < sectionOffset + sizeof(EFI_COMMON_SECTION_HEADER2)) {
                return 0;
            }
            const EFI_COMMON_SECTION_HEADER2* sectionHeader2 = (const EFI_COMMON_SECTION_HEADER2*)(file.constData() + sectionOffset);
            return sectionHeader2->ExtendedSize;
        }
        
        return size;
    }
    
    return 0;
}

USTATUS FfsParser::parseFileBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Do not parse non-file bodies
    if (model->type(index) != Types::File)
        return U_SUCCESS;
    
    // Parse padding file body
    if (model->subtype(index) == EFI_FV_FILETYPE_PAD)
        return parsePadFileBody(index);
    
    // Parse raw files as raw areas
    if (model->subtype(index) == EFI_FV_FILETYPE_RAW || model->subtype(index) == EFI_FV_FILETYPE_ALL) {
        UByteArray fileGuid = UByteArray(model->header(index).constData(), sizeof(EFI_GUID));
        
        // Parse NVAR store
        if (fileGuid == NVRAM_NVAR_STORE_FILE_GUID) {
            model->setText(index, UString("NVAR store"));
            return nvramParser->parseNvarStore(index);
        }
        else if (fileGuid == NVRAM_NVAR_PEI_EXTERNAL_DEFAULTS_FILE_GUID) {
            model->setText(index, UString("NVRAM external defaults"));
            return nvramParser->parseNvarStore(index);
        }
        else if (fileGuid == NVRAM_NVAR_BB_DEFAULTS_FILE_GUID) {
            model->setText(index, UString("NVAR BB defaults"));
            return nvramParser->parseNvarStore(index);
        }
        // Parse vendor hash file
        else if (fileGuid == PROTECTED_RANGE_VENDOR_HASH_FILE_GUID_PHOENIX) {
            return parseVendorHashFile(fileGuid, index);
        }
        // Parse AMI ROM hole
        else if (fileGuid == AMI_ROM_HOLE_FILE_GUID_0
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_1
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_2
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_3
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_4
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_5
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_6
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_7
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_8
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_9
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_10
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_11
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_12
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_13
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_14
                 || fileGuid == AMI_ROM_HOLE_FILE_GUID_15) {
            model->setText(index, UString("AMI ROM hole"));
            // Mark ROM hole file as Fixed in the image
            model->setFixed(index, Fixed);
            // No need to parse further
            return U_SUCCESS;
        }
        
        if (parseSections(model->body(index), index, true) != U_SUCCESS) {
            return parseRawArea(index);
        }
    }
    
    // Parse sections
    return parseSections(model->body(index), index);
}

USTATUS FfsParser::parsePadFileBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    UByteArray body = model->body(index);
    
    // Check if all bytes of the file are empty
    // Obtain required information from parent file
    UINT8 emptyByte = 0xFF;
    UModelIndex parentFileIndex = model->findParentOfType(index, Types::File);
    if (parentFileIndex.isValid() && model->hasEmptyParsingData(parentFileIndex) == false) {
        UByteArray data = model->parsingData(index);
        const FILE_PARSING_DATA* pdata = (const FILE_PARSING_DATA*)data.constData();
        emptyByte = pdata->emptyByte;
    }
    
    // Check if the whole padding file is empty
    if (isUniformByte(body, emptyByte))
        return U_SUCCESS;
    
    // Search for the first non-empty byte
    UINT32 nonEmptyByteOffset;
    UINT32 size = (UINT32)body.size();
    const UINT8* current = (const UINT8*)body.constData();
    for (nonEmptyByteOffset = 0; nonEmptyByteOffset < size; nonEmptyByteOffset++) {
        if (*current++ != emptyByte)
            break;
    }
    
    // Add all bytes before as free space...
    UINT32 headerSize = (UINT32)model->header(index).size();
    if (nonEmptyByteOffset >= 8) {
        // Align free space to 8 bytes boundary
        if (nonEmptyByteOffset != ALIGN8(nonEmptyByteOffset))
            nonEmptyByteOffset = ALIGN8(nonEmptyByteOffset) - 8;
        
        UByteArray free = body.left(nonEmptyByteOffset);
        
        // Get info
        UString info = usprintf("Full size: %Xh (%u)", (UINT32)free.size(), (UINT32)free.size());
        
        // Add tree item
        model->addItem(headerSize, Types::FreeSpace, 0, UString("Free space"), UString(), info, UByteArray(), free, UByteArray(), Movable, index);
    }
    else {
        nonEmptyByteOffset = 0;
    }
    
    // ... and all bytes after as a padding
    UByteArray padding = body.mid(nonEmptyByteOffset);
    
    // Check for that data to be recovery startup AP data for x86
    // https://github.com/tianocore/edk2/blob/stable/202011/BaseTools/Source/C/GenFv/GenFvInternalLib.c#L106
    if (padding.left(RECOVERY_STARTUP_AP_DATA_X86_SIZE) == RECOVERY_STARTUP_AP_DATA_X86_128K) {
        // Get info
        UString info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
        
        // Add tree item
        (void)model->addItem(headerSize + nonEmptyByteOffset, Types::StartupApDataEntry, Subtypes::x86128kStartupApDataEntry, UString("Startup AP data"), UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
        
        // Rename the file
        model->setName(index, UString("Startup AP data padding file"));
        
        // Do not parse contents
        return U_SUCCESS;
    }
    else { // Not a data array
        // Get info
        UString info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
        
        // Add tree item
        UModelIndex dataIndex = model->addItem(headerSize + nonEmptyByteOffset, Types::Padding, Subtypes::DataPadding, UString("Non-UEFI data"), UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
        
        // Show message
        msg(usprintf("%s: non-UEFI data found in padding file", __FUNCTION__), dataIndex);
        
        // Rename the file
        model->setName(index, UString("Non-empty padding file"));
        
        // Do not parse contents
        return U_SUCCESS;
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseSections(const UByteArray & sections, const UModelIndex & index, const bool probe)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Search for and parse all sections
    UINT32 bodySize = (UINT32)sections.size();
    UINT32 headerSize = (UINT32)model->header(index).size();
    UINT32 sectionOffset = 0;
    USTATUS result = U_SUCCESS;
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(index, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Iterate over sections
    UINT32 sectionSize = 0;
    while (sectionOffset < bodySize) {
        // Get section size
        sectionSize = getSectionSize(sections, sectionOffset, ffsVersion);
        
        // Check section size to be sane
        if (sectionSize < sizeof(EFI_COMMON_SECTION_HEADER)
            || sectionSize > (bodySize - sectionOffset)) {
            // Final parsing
            if (!probe) {
                // Add padding to fill the rest of sections
                UByteArray padding = sections.mid(sectionOffset);
                
                // Get info
                UString info = usprintf("Full size: %Xh (%u)", (UINT32)padding.size(), (UINT32)padding.size());
                
                // Add tree item
                UModelIndex dataIndex = model->addItem(headerSize + sectionOffset, Types::Padding, Subtypes::DataPadding, UString("Non-UEFI data"), UString(), info, UByteArray(), padding, UByteArray(), Fixed, index);
                
                // Show message
                msg(usprintf("%s: non-UEFI data found in sections area", __FUNCTION__), dataIndex);
                
                // Exit from parsing loop
                break;
            }
            // Preliminary parsing
            else {
                return U_INVALID_SECTION;
            }
        }
        
        // Parse section header
        UModelIndex sectionIndex;
        result = parseSectionHeader(sections.mid(sectionOffset, sectionSize), headerSize + sectionOffset, index, sectionIndex, probe);
        if (result) {
            if (!probe)
                msg(usprintf("%s: section header parsing failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            else
                return U_INVALID_SECTION;
        }
        
        // Move to next section
        sectionOffset += sectionSize;
        // TODO: verify that alignment bytes are actually zero as per PI spec
        sectionOffset = ALIGN4(sectionOffset);
    }
    
#if 0 // Do not enable this in production for now, as it needs further investigation.
    // The PI spec requires sections to be aligned by 4 byte boundary with bytes that are all exactly zeroes
    // Some images interpret "must be aligned by 4" as "every section needs to be padded for sectionSize to be divisible by 4".
    // Detecting this case can be done by checking for the very last section to have sectionSize not divisible by 4, while the total bodySize is.
    // However, such detection for a single file is unreliable because in 1/4 random cases the last section will be divisible by 4.
    // We also know that either PEI core or DXE core is entity that does file and section parsing,
    // so every single file in the volume should behave consistently.
    // This makes the probability of unsuccessful detection here to be 1/(4^numFilesInVolume),
    // which is low enough for real images out there.
    // It should also be noted that enabling this section alignment quirk for an image that doesn't require it
    // will not make the image unbootable, but will waste some space and possibly require to move some files around
    if (sectionOffset == bodySize) {
        // We are now at the very end of the file body, and sectionSize is the size of the last section
        if ((sectionSize % 4 != 0) // sectionSize of the very last section is not divisible by 4
            && (bodySize % 4 == 0)) { // yet bodySize is, meaning that there are indeed some padding bytes added after the last section
            msg(usprintf("%s: section alignment quirk found", __FUNCTION__), index);
        }
    }
#endif
    
    // Parse bodies, will be skipped if probing
    for (int i = 0; i < model->rowCount(index); i++) {
        UModelIndex current = index.model()->index(i, 0, index);
        
        switch (model->type(current)) {
            case Types::Section:
                parseSectionBody(current);
                break;
            case Types::Padding:
                // No parsing required
                break;
            default:
                return U_UNKNOWN_ITEM_TYPE;
        }
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER)) {
        return U_INVALID_SECTION;
    }
    
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    switch (sectionHeader->Type) {
            // Special
        case EFI_SECTION_COMPRESSION:           return parseCompressedSectionHeader(section, localOffset, parent, index, probe);
        case EFI_SECTION_GUID_DEFINED:          return parseGuidedSectionHeader(section, localOffset, parent, index, probe);
        case EFI_SECTION_FREEFORM_SUBTYPE_GUID: return parseFreeformGuidedSectionHeader(section, localOffset, parent, index, probe);
        case EFI_SECTION_VERSION:               return parseVersionSectionHeader(section, localOffset, parent, index, probe);
        case PHOENIX_SECTION_POSTCODE:
        case INSYDE_SECTION_POSTCODE:           return parsePostcodeSectionHeader(section, localOffset, parent, index, probe);
            // Common
        case EFI_SECTION_DISPOSABLE:
        case EFI_SECTION_DXE_DEPEX:
        case EFI_SECTION_PEI_DEPEX:
        case EFI_SECTION_MM_DEPEX:
        case EFI_SECTION_PE32:
        case EFI_SECTION_PIC:
        case EFI_SECTION_TE:
        case EFI_SECTION_COMPATIBILITY16:
        case EFI_SECTION_USER_INTERFACE:
        case EFI_SECTION_FIRMWARE_VOLUME_IMAGE:
        case EFI_SECTION_RAW:                   return parseCommonSectionHeader(section, localOffset, parent, index, probe);
            // Unknown
        default:
            USTATUS result = parseCommonSectionHeader(section, localOffset, parent, index, probe);
            if (!probe)
                msg(usprintf("%s: section with unknown type %02Xh", __FUNCTION__, sectionHeader->Type), index);
            return result;
    }
}

USTATUS FfsParser::parseCommonSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER)) {
        return U_INVALID_SECTION;
    }
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Obtain header fields
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    UINT32 headerSize = sizeof(EFI_COMMON_SECTION_HEADER);
    if (ffsVersion == 3 && uint24ToUint32(sectionHeader->Size) == EFI_SECTION2_IS_USED)
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER2);
    UINT8 type = sectionHeader->Type;
    
    // Check sanity again
    if ((UINT32)section.size() < headerSize) {
        return U_INVALID_SECTION;
    }
    
    UByteArray header = section.left(headerSize);
    UByteArray body = section.mid(headerSize);
    
    // Get info
    UString name = sectionTypeToUString(type) + UString(" section");
    UString info = usprintf("Type: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)",
                            type,
                            (UINT32)section.size(), (UINT32)section.size(),
                            headerSize, headerSize,
                            (UINT32)body.size(), (UINT32)body.size());
    
    // Add tree item
    if (!probe) {
        index = model->addItem(localOffset, Types::Section, type, name, UString(), info, header, body, UByteArray(), Movable, parent);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseCompressedSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER))
        return U_INVALID_SECTION;
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Obtain header fields
    UINT32 headerSize;
    UINT8 compressionType;
    UINT32 uncompressedLength;
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    const EFI_COMMON_SECTION_HEADER2* section2Header = (const EFI_COMMON_SECTION_HEADER2*)(section.constData());
    
    if (ffsVersion == 3 && uint24ToUint32(sectionHeader->Size) == EFI_SECTION2_IS_USED) { // Check for extended header section
        const EFI_COMPRESSION_SECTION* compressedSectionHeader = (const EFI_COMPRESSION_SECTION*)(section2Header + 1);
        if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_COMPRESSION_SECTION))
            return U_INVALID_SECTION;
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_COMPRESSION_SECTION);
        compressionType = compressedSectionHeader->CompressionType;
        uncompressedLength = compressedSectionHeader->UncompressedLength;
    }
    else { // Normal section
        const EFI_COMPRESSION_SECTION* compressedSectionHeader = (const EFI_COMPRESSION_SECTION*)(sectionHeader + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER) + sizeof(EFI_COMPRESSION_SECTION);
        compressionType = compressedSectionHeader->CompressionType;
        uncompressedLength = compressedSectionHeader->UncompressedLength;
    }
    
    // Check sanity again
    if ((UINT32)section.size() < headerSize) {
        return U_INVALID_SECTION;
    }
    
    UByteArray header = section.left(headerSize);
    UByteArray body = section.mid(headerSize);
    
    // Get info
    UString name = sectionTypeToUString(sectionHeader->Type) + UString(" section");
    UString info = usprintf("Type: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nCompression type: %02Xh\nDecompressed size: %Xh (%u)",
                            sectionHeader->Type,
                            (UINT32)section.size(), (UINT32)section.size(),
                            headerSize, headerSize,
                            (UINT32)body.size(), (UINT32)body.size(),
                            compressionType,
                            uncompressedLength, uncompressedLength);
    
    // Add tree item
    if (!probe) {
        index = model->addItem(localOffset, Types::Section, sectionHeader->Type, name, UString(), info, header, body, UByteArray(), Movable, parent);
        
        // Set section parsing data
        COMPRESSED_SECTION_PARSING_DATA pdata = {};
        pdata.compressionType = compressionType;
        pdata.uncompressedSize = uncompressedLength;
        model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseGuidedSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER))
        return U_INVALID_SECTION;
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Obtain header fields
    UINT32 headerSize;
    EFI_GUID guid;
    UINT16 dataOffset;
    UINT16 attributes;
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    const EFI_COMMON_SECTION_HEADER2* section2Header = (const EFI_COMMON_SECTION_HEADER2*)(section.constData());
    
    if (ffsVersion == 3 && uint24ToUint32(sectionHeader->Size) == EFI_SECTION2_IS_USED) { // Check for extended header section
        const EFI_GUID_DEFINED_SECTION* guidDefinedSectionHeader = (const EFI_GUID_DEFINED_SECTION*)(section2Header + 1);
        if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_GUID_DEFINED_SECTION))
            return U_INVALID_SECTION;
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_GUID_DEFINED_SECTION);
        guid = guidDefinedSectionHeader->SectionDefinitionGuid;
        dataOffset = guidDefinedSectionHeader->DataOffset;
        attributes = guidDefinedSectionHeader->Attributes;
    }
    else { // Normal section
        const EFI_GUID_DEFINED_SECTION* guidDefinedSectionHeader = (const EFI_GUID_DEFINED_SECTION*)(sectionHeader + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER) + sizeof(EFI_GUID_DEFINED_SECTION);
        guid = guidDefinedSectionHeader->SectionDefinitionGuid;
        dataOffset = guidDefinedSectionHeader->DataOffset;
        attributes = guidDefinedSectionHeader->Attributes;
    }
    // Check sanity again
    if ((UINT32)section.size() < headerSize)
        return U_INVALID_SECTION;
    
    // Check for special GUIDed sections
    UString additionalInfo;
    UByteArray baGuid((const char*)&guid, sizeof(EFI_GUID));
    bool msgSignedSectionFound = false;
    bool msgNoAuthStatusAttribute = false;
    bool msgNoProcessingRequiredAttributeCompressed = false;
    bool msgNoProcessingRequiredAttributeSigned = false;
    bool msgInvalidCrc = false;
    bool msgUnknownCertType = false;
    bool msgUnknownCertSubtype = false;
    bool msgProcessingRequiredAttributeOnUnknownGuidedSection = false;
    bool msgInvalidCompressedSize = false;
    if (baGuid == EFI_GUIDED_SECTION_CRC32) {
        if ((attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) == 0) { // Check that AuthStatusValid attribute is set on compressed GUIDed sections
            msgNoAuthStatusAttribute = true;
        }
        
        if ((UINT32)section.size() < headerSize + sizeof(UINT32))
            return U_INVALID_SECTION;
        
        UINT32 crc = *(UINT32*)(section.constData() + headerSize);
        additionalInfo += UString("\nChecksum type: CRC32");
        // Calculate CRC32 of section data
        UINT32 calculated = (UINT32)crc32(0, (const UINT8*)section.constData() + dataOffset, (uInt)(section.size() - dataOffset));
        if (crc == calculated) {
            additionalInfo += usprintf("\nChecksum: %08Xh, valid", crc);
        }
        else {
            additionalInfo += usprintf("\nChecksum: %08Xh, invalid, should be %08Xh", crc, calculated);
            msgInvalidCrc = true;
        }
        // No need to change dataOffset here
    }
    else if (baGuid == EFI_GUIDED_SECTION_LZMA
        || baGuid == EFI_GUIDED_SECTION_LZMA_HP
        || baGuid == EFI_GUIDED_SECTION_LZMA_MS
        || baGuid == EFI_GUIDED_SECTION_LZMAF86
        || baGuid == EFI_GUIDED_SECTION_TIANO
        || baGuid == EFI_GUIDED_SECTION_GZIP) {
        if ((attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == 0) { // Check that ProcessingRequired attribute is set on compressed GUIDed sections
            msgNoProcessingRequiredAttributeCompressed = true;
        }
        // No need to change dataOffset here
    }
    else if (baGuid == EFI_GUIDED_SECTION_ZLIB_AMD) {
        if ((attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == 0) { // Check that ProcessingRequired attribute is set on compressed GUIDed sections
            msgNoProcessingRequiredAttributeCompressed = true;
        }

        if ((UINT32)section.size() < headerSize + sizeof(EFI_AMD_ZLIB_SECTION_HEADER))
            return U_INVALID_SECTION;

        const EFI_AMD_ZLIB_SECTION_HEADER* amdZlibSectionHeader = (const EFI_AMD_ZLIB_SECTION_HEADER*)(section.constData() + headerSize);

        // Check the compressed size to be sane
        if ((UINT32)section.size() != headerSize + sizeof(EFI_AMD_ZLIB_SECTION_HEADER) + amdZlibSectionHeader->CompressedSize) {
            msgInvalidCompressedSize = true;
        }

        // Adjust dataOffset
        dataOffset += sizeof(EFI_AMD_ZLIB_SECTION_HEADER);
    }
    else if (baGuid == EFI_GUIDED_SECTION_BROTLI)
    {
        if ((attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == 0) { // Check that ProcessingRequired attribute is set on compressed GUIDed sections
            msgNoProcessingRequiredAttributeCompressed = true;
        }

        if ((UINT32)section.size() < headerSize + sizeof(EFI_BROTLI_SECTION_HEADER))
            return U_INVALID_SECTION;

        // Adjust dataOffset
        dataOffset += sizeof(EFI_BROTLI_SECTION_HEADER);
    }
    else if (baGuid == EFI_CERT_TYPE_RSA2048_SHA256_GUID) {
        if ((attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == 0) { // Check that ProcessingRequired attribute is set on signed GUIDed sections
            msgNoProcessingRequiredAttributeSigned = true;
        }
        
        // Get certificate type and length
        if ((UINT32)section.size() < headerSize + sizeof(EFI_CERT_BLOCK_RSA2048_SHA256))
            return U_INVALID_SECTION;
        
        // Adjust dataOffset
        dataOffset += sizeof(EFI_CERT_BLOCK_RSA2048_SHA256);
        additionalInfo += UString("\nCertificate type: RSA2048/SHA256");
        msgSignedSectionFound = true;
    }
    else if (baGuid == EFI_FIRMWARE_CONTENTS_SIGNED_GUID) {
        if ((attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == 0) { // Check that ProcessingRequired attribute is set on signed GUIDed sections
            msgNoProcessingRequiredAttributeSigned = true;
        }
        
        // Get certificate type and length
        if ((UINT32)section.size() < headerSize + sizeof(WIN_CERTIFICATE))
            return U_INVALID_SECTION;
        
        const WIN_CERTIFICATE* winCertificate = (const WIN_CERTIFICATE*)(section.constData() + headerSize);
        UINT32 certLength = winCertificate->Length;
        UINT16 certType = winCertificate->CertificateType;
        
        // Adjust dataOffset
        dataOffset += certLength;
        
        // Check section size once again
        if ((UINT32)section.size() < dataOffset)
            return U_INVALID_SECTION;
        
        // Check certificate type
        if (certType == WIN_CERT_TYPE_EFI_GUID) {
            additionalInfo += UString("\nCertificate type: UEFI");
            
            // Get certificate GUID
            const WIN_CERTIFICATE_UEFI_GUID* winCertificateUefiGuid = (const WIN_CERTIFICATE_UEFI_GUID*)(section.constData() + headerSize);
            UByteArray certTypeGuid((const char*)&winCertificateUefiGuid->CertType, sizeof(EFI_GUID));
            
            if (certTypeGuid == EFI_CERT_TYPE_RSA2048_SHA256_GUID) {
                additionalInfo += UString("\nCertificate subtype: RSA2048/SHA256");
            }
            else {
                additionalInfo += UString("\nCertificate subtype: unknown, GUID ") + guidToUString(winCertificateUefiGuid->CertType);
                msgUnknownCertSubtype = true;
            }
        }
        else {
            additionalInfo += usprintf("\nCertificate type: unknown (%04Xh)", certType);
            msgUnknownCertType = true;
        }
        msgSignedSectionFound = true;
    }
    // Check that ProcessingRequired attribute is not set on GUIDed sections with unknown GUID
    else if ((attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) == EFI_GUIDED_SECTION_PROCESSING_REQUIRED) {
        msgProcessingRequiredAttributeOnUnknownGuidedSection = true;
    }
    
    UByteArray header = section.left(dataOffset);
    UByteArray body = section.mid(dataOffset);
    
    // Get info
    UString name = guidToUString(guid);
    UString info = UString("Section GUID: ") + guidToUString(guid, false) +
    usprintf("\nType: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nAttributes: %04Xh",
             sectionHeader->Type,
             (UINT32)section.size(), (UINT32)section.size(),
             (UINT32)header.size(), (UINT32)header.size(),
             (UINT32)body.size(), (UINT32)body.size(),
             attributes);
    
    // Append additional info
    info += additionalInfo;
    
    // Add tree item
    if (!probe) {
        index = model->addItem(localOffset, Types::Section, sectionHeader->Type, name, UString(), info, header, body, UByteArray(), Movable, parent);
        
        // Set parsing data
        GUIDED_SECTION_PARSING_DATA pdata = {};
        pdata.guid = guid;
        model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
        
        // Show messages
        if (msgSignedSectionFound)
            msg(usprintf("%s: GUIDed section signature may become invalid after modification", __FUNCTION__), index);
        if (msgNoAuthStatusAttribute)
            msg(usprintf("%s: CRC32 GUIDed section without AuthStatusValid attribute", __FUNCTION__), index);
        if (msgNoProcessingRequiredAttributeCompressed)
            msg(usprintf("%s: compressed GUIDed section without ProcessingRequired attribute", __FUNCTION__), index);
        if (msgNoProcessingRequiredAttributeSigned)
            msg(usprintf("%s: signed GUIDed section without ProcessingRequired attribute", __FUNCTION__), index);
        if (msgInvalidCrc)
            msg(usprintf("%s: CRC32 GUIDed section with invalid checksum", __FUNCTION__), index);
        if (msgUnknownCertType)
            msg(usprintf("%s: signed GUIDed section with unknown certificate type", __FUNCTION__), index);
        if (msgUnknownCertSubtype)
            msg(usprintf("%s: signed GUIDed section with unknown certificate subtype", __FUNCTION__), index);
        if (msgProcessingRequiredAttributeOnUnknownGuidedSection)
            msg(usprintf("%s: processing required bit set for GUIDed section with unknown GUID", __FUNCTION__), index);
        if (msgInvalidCompressedSize)
            msg(usprintf("%s: AMD Zlib-compressed section with invalid compressed size", __FUNCTION__), index);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseFreeformGuidedSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER))
        return U_INVALID_SECTION;
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Obtain header fields
    UINT32 headerSize;
    EFI_GUID guid;
    UINT8 type;
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    const EFI_COMMON_SECTION_HEADER2* section2Header = (const EFI_COMMON_SECTION_HEADER2*)(section.constData());
    
    if (ffsVersion == 3 && uint24ToUint32(sectionHeader->Size) == EFI_SECTION2_IS_USED) { // Check for extended header section
        const EFI_FREEFORM_SUBTYPE_GUID_SECTION* fsgSectionHeader = (const EFI_FREEFORM_SUBTYPE_GUID_SECTION*)(section2Header + 1);
        if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_FREEFORM_SUBTYPE_GUID_SECTION))
            return U_INVALID_SECTION;
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_FREEFORM_SUBTYPE_GUID_SECTION);
        guid = fsgSectionHeader->SubTypeGuid;
        type = section2Header->Type;
    }
    else { // Normal section
        const EFI_FREEFORM_SUBTYPE_GUID_SECTION* fsgSectionHeader = (const EFI_FREEFORM_SUBTYPE_GUID_SECTION*)(sectionHeader + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER) + sizeof(EFI_FREEFORM_SUBTYPE_GUID_SECTION);
        guid = fsgSectionHeader->SubTypeGuid;
        type = sectionHeader->Type;
    }
    
    // Check sanity again
    if ((UINT32)section.size() < headerSize)
        return U_INVALID_SECTION;
    
    UByteArray header = section.left(headerSize);
    UByteArray body = section.mid(headerSize);
    
    // Get info
    UString name = sectionTypeToUString(type) + (" section");
    UString info = usprintf("Type: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nSubtype GUID: ",
                            type,
                            (UINT32)section.size(), (UINT32)section.size(),
                            (UINT32)header.size(), (UINT32)header.size(),
                            (UINT32)body.size(), (UINT32)body.size())
    + guidToUString(guid, false);
    
    // Add tree item
    if (!probe) {
        index = model->addItem(localOffset, Types::Section, type, name, UString(), info, header, body, UByteArray(), Movable, parent);
        
        // Set parsing data
        FREEFORM_GUIDED_SECTION_PARSING_DATA pdata = {};
        pdata.guid = guid;
        model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
        
        // Rename section
        model->setName(index, guidToUString(guid));
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseVersionSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER))
        return U_INVALID_SECTION;
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Obtain header fields
    UINT32 headerSize;
    UINT16 buildNumber;
    UINT8 type;
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    const EFI_COMMON_SECTION_HEADER2* section2Header = (const EFI_COMMON_SECTION_HEADER2*)(section.constData());
    
    if (ffsVersion == 3 && uint24ToUint32(sectionHeader->Size) == EFI_SECTION2_IS_USED) { // Check for extended header section
        const EFI_VERSION_SECTION* versionHeader = (const EFI_VERSION_SECTION*)(section2Header + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(EFI_VERSION_SECTION);
        buildNumber = versionHeader->BuildNumber;
        type = section2Header->Type;
    }
    else { // Normal section
        const EFI_VERSION_SECTION* versionHeader = (const EFI_VERSION_SECTION*)(sectionHeader + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER) + sizeof(EFI_VERSION_SECTION);
        buildNumber = versionHeader->BuildNumber;
        type = sectionHeader->Type;
    }
    
    // Check sanity again
    if ((UINT32)section.size() < headerSize)
        return U_INVALID_SECTION;
    
    UByteArray header = section.left(headerSize);
    UByteArray body = section.mid(headerSize);
    
    // Get info
    UString name = sectionTypeToUString(type) + (" section");
    UString info = usprintf("Type: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nBuild number: %u",
                            type,
                            (UINT32)section.size(), (UINT32)section.size(),
                            (UINT32)header.size(), (UINT32)header.size(),
                            (UINT32)body.size(), (UINT32)body.size(),
                            buildNumber);
    
    // Add tree item
    if (!probe) {
        index = model->addItem(localOffset, Types::Section, type, name, UString(), info, header, body, UByteArray(), Movable, parent);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parsePostcodeSectionHeader(const UByteArray & section, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    // Check sanity
    if ((UINT32)section.size() < sizeof(EFI_COMMON_SECTION_HEADER))
        return U_INVALID_SECTION;
    
    // Obtain required information from parent volume
    UINT8 ffsVersion = 2;
    UModelIndex parentVolumeIndex = model->findParentOfType(parent, Types::Volume);
    if (parentVolumeIndex.isValid() && model->hasEmptyParsingData(parentVolumeIndex) == false) {
        UByteArray data = model->parsingData(parentVolumeIndex);
        const VOLUME_PARSING_DATA* pdata = (const VOLUME_PARSING_DATA*)data.constData();
        ffsVersion = pdata->ffsVersion;
    }
    
    // Obtain header fields
    UINT32 headerSize;
    UINT32 postCode;
    UINT8 type;
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(section.constData());
    const EFI_COMMON_SECTION_HEADER2* section2Header = (const EFI_COMMON_SECTION_HEADER2*)(section.constData());
    
    if (ffsVersion == 3 && uint24ToUint32(sectionHeader->Size) == EFI_SECTION2_IS_USED) { // Check for extended header section
        const POSTCODE_SECTION* postcodeHeader = (const POSTCODE_SECTION*)(section2Header + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER2) + sizeof(POSTCODE_SECTION);
        postCode = postcodeHeader->Postcode;
        type = section2Header->Type;
    }
    else { // Normal section
        const POSTCODE_SECTION* postcodeHeader = (const POSTCODE_SECTION*)(sectionHeader + 1);
        headerSize = sizeof(EFI_COMMON_SECTION_HEADER) + sizeof(POSTCODE_SECTION);
        postCode = postcodeHeader->Postcode;
        type = sectionHeader->Type;
    }
    
    // Check sanity again
    if ((UINT32)section.size() < headerSize)
        return U_INVALID_SECTION;
    
    UByteArray header = section.left(headerSize);
    UByteArray body = section.mid(headerSize);
    
    // Get info
    UString name = sectionTypeToUString(type) + (" section");
    UString info = usprintf("Type: %02Xh\nFull size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nPostcode: %Xh",
                            type,
                            (UINT32)section.size(), (UINT32)section.size(),
                            (UINT32)header.size(), (UINT32)header.size(),
                            (UINT32)body.size(), (UINT32)body.size(),
                            postCode);
    
    // Add tree item
    if (!probe) {
        index = model->addItem(localOffset, Types::Section, sectionHeader->Type, name, UString(), info, header, body, UByteArray(), Movable, parent);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    UByteArray header = model->header(index);
    if ((UINT32)header.size() < sizeof(EFI_COMMON_SECTION_HEADER))
        return U_INVALID_SECTION;
    
    const EFI_COMMON_SECTION_HEADER* sectionHeader = (const EFI_COMMON_SECTION_HEADER*)(header.constData());
    
    switch (sectionHeader->Type) {
        // Encapsulation
        case EFI_SECTION_COMPRESSION:           return parseCompressedSectionBody(index);
        case EFI_SECTION_GUID_DEFINED:          return parseGuidedSectionBody(index);
        case EFI_SECTION_DISPOSABLE:            return parseSections(model->body(index), index);
        // Leaf
        case EFI_SECTION_FREEFORM_SUBTYPE_GUID: return parseRawArea(index);
        case EFI_SECTION_VERSION:               return parseVersionSectionBody(index);
        case EFI_SECTION_DXE_DEPEX:
        case EFI_SECTION_PEI_DEPEX:
        case EFI_SECTION_MM_DEPEX:              return parseDepexSectionBody(index);
        case EFI_SECTION_TE:                    return parseTeImageSectionBody(index);
        case EFI_SECTION_PE32:
        case EFI_SECTION_PIC:                   return parsePeImageSectionBody(index);
        case EFI_SECTION_USER_INTERFACE:        return parseUiSectionBody(index);
        case EFI_SECTION_FIRMWARE_VOLUME_IMAGE: return parseRawArea(index);
        case EFI_SECTION_RAW:                   return parseRawSectionBody(index);
        // No parsing needed
        case EFI_SECTION_COMPATIBILITY16:
        case PHOENIX_SECTION_POSTCODE:
        case INSYDE_SECTION_POSTCODE:
        default:
            return U_SUCCESS;
    }
}

USTATUS FfsParser::parseCompressedSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Obtain required information from parsing data
    UINT8 compressionType = EFI_NOT_COMPRESSED;
    UINT32 uncompressedSize = (UINT32)model->body(index).size();
    if (model->hasEmptyParsingData(index) == false) {
        UByteArray data = model->parsingData(index);
        const COMPRESSED_SECTION_PARSING_DATA* pdata = (const COMPRESSED_SECTION_PARSING_DATA*)data.constData();
        compressionType = readUnaligned(pdata).compressionType;
        uncompressedSize = readUnaligned(pdata).uncompressedSize;
    }
    
    // Decompress section
    UINT8 algorithm = COMPRESSION_ALGORITHM_NONE;
    UINT32 dictionarySize = 0;
    UByteArray decompressed;
    UByteArray efiDecompressed;
    USTATUS result = decompress(model->body(index), compressionType, algorithm, dictionarySize, decompressed, efiDecompressed);
    if (result) {
        msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
        return U_SUCCESS;
    }
    
    // Check reported uncompressed size
    if (uncompressedSize != (UINT32)decompressed.size()) {
        msg(usprintf("%s: decompressed size stored in header %Xh (%u) differs from actual %Xh (%u)",
                     __FUNCTION__,
                     uncompressedSize, uncompressedSize,
                     (UINT32)decompressed.size(), (UINT32)decompressed.size()),
            index);
        model->addInfo(index, usprintf("\nActual decompressed size: %Xh (%u)", (UINT32)decompressed.size(), (UINT32)decompressed.size()));
    }
    
    // Check for undecided compression algorithm, this is a special case
    if (algorithm == COMPRESSION_ALGORITHM_UNDECIDED) {
        // Try preparse of sections decompressed with Tiano algorithm
        if (U_SUCCESS == parseSections(decompressed, index, true)) {
            algorithm = COMPRESSION_ALGORITHM_TIANO;
        }
        // Try preparse of sections decompressed with EFI 1.1 algorithm
        else if (U_SUCCESS == parseSections(efiDecompressed, index, true)) {
            algorithm = COMPRESSION_ALGORITHM_EFI11;
            decompressed = efiDecompressed;
        }
        else {
            msg(usprintf("%s: can't guess the correct decompression algorithm, both preparse steps are failed", __FUNCTION__), index);
        }
    }
    
    // Add info
    model->addInfo(index, UString("\nCompression algorithm: ") + compressionTypeToUString(algorithm));
    if (algorithm == COMPRESSION_ALGORITHM_LZMA || algorithm == COMPRESSION_ALGORITHM_LZMA_INTEL_LEGACY) {
        model->addInfo(index, usprintf("\nLZMA dictionary size: %Xh", dictionarySize));
    }
    
    // Set compression data
    if (algorithm != COMPRESSION_ALGORITHM_NONE) {
        model->setUncompressedData(index, decompressed);
        model->setCompressed(index, true);
    }
    
    // Set parsing data
    COMPRESSED_SECTION_PARSING_DATA pdata = {};
    pdata.algorithm = algorithm;
    pdata.dictionarySize = dictionarySize;
    pdata.compressionType = compressionType;
    pdata.uncompressedSize = uncompressedSize;
    model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
    
    // Parse decompressed data
    return parseSections(decompressed, index);
}

USTATUS FfsParser::parseGuidedSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Obtain required information from parsing data
    EFI_GUID guid = { 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0 }};
    if (model->hasEmptyParsingData(index) == false) {
        UByteArray data = model->parsingData(index);
        const GUIDED_SECTION_PARSING_DATA* pdata = (const GUIDED_SECTION_PARSING_DATA*)data.constData();
        guid = readUnaligned(pdata).guid;
    }
    
    // Check if section requires processing
    UByteArray processed = model->body(index);
    UByteArray efiDecompressed;
    UString info;
    bool parseCurrentSection = true;
    UINT8 algorithm = COMPRESSION_ALGORITHM_NONE;
    UINT32 dictionarySize = 0;
    UByteArray baGuid = UByteArray((const char*)&guid, sizeof(EFI_GUID));
    // Tiano compressed section
    if (baGuid == EFI_GUIDED_SECTION_TIANO) {
        USTATUS result = decompress(model->body(index), EFI_STANDARD_COMPRESSION, algorithm, dictionarySize, processed, efiDecompressed);
        if (result) {
            msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            return U_SUCCESS;
        }
        
        // Check for undecided compression algorithm, this is a special case
        if (algorithm == COMPRESSION_ALGORITHM_UNDECIDED) {
            // Try preparse of sections decompressed with Tiano algorithm
            if (U_SUCCESS == parseSections(processed, index, true)) {
                algorithm = COMPRESSION_ALGORITHM_TIANO;
            }
            // Try preparse of sections decompressed with EFI 1.1 algorithm
            else if (U_SUCCESS == parseSections(efiDecompressed, index, true)) {
                algorithm = COMPRESSION_ALGORITHM_EFI11;
                processed = efiDecompressed;
            }
            else {
                msg(usprintf("%s: can't guess the correct decompression algorithm, both preparse steps are failed", __FUNCTION__), index);
                parseCurrentSection = false;
            }
        }
        
        info += UString("\nCompression algorithm: ") + compressionTypeToUString(algorithm);
        info += usprintf("\nDecompressed size: %Xh (%u)", (UINT32)processed.size(), (UINT32)processed.size());
    }
    // LZMA compressed section
    else if (baGuid == EFI_GUIDED_SECTION_LZMA
             || baGuid == EFI_GUIDED_SECTION_LZMA_HP
             || baGuid == EFI_GUIDED_SECTION_LZMA_MS) {
        USTATUS result = decompress(model->body(index), EFI_CUSTOMIZED_COMPRESSION, algorithm, dictionarySize, processed, efiDecompressed);
        if (result) {
            msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            return U_SUCCESS;
        }
        
        if (algorithm == COMPRESSION_ALGORITHM_LZMA) {
            info += UString("\nCompression algorithm: LZMA");
            info += usprintf("\nDecompressed size: %Xh (%u)", (UINT32)processed.size(), (UINT32)processed.size());
            info += usprintf("\nLZMA dictionary size: %Xh", dictionarySize);
        }
        else {
            info += UString("\nCompression algorithm: unknown");
            parseCurrentSection = false;
        }
    }
    // LZMAF86 compressed section
    else if (baGuid == EFI_GUIDED_SECTION_LZMAF86) {
        USTATUS result = decompress(model->body(index), EFI_CUSTOMIZED_COMPRESSION_LZMAF86, algorithm, dictionarySize, processed, efiDecompressed);
        if (result) {
            msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            return U_SUCCESS;
        }
        
        if (algorithm == COMPRESSION_ALGORITHM_LZMAF86) {
            info += UString("\nCompression algorithm: LZMAF86");
            info += usprintf("\nDecompressed size: %Xh (%u)", (UINT32)processed.size(), (UINT32)processed.size());
            info += usprintf("\nLZMA dictionary size: %Xh", dictionarySize);
        }
        else {
            info += UString("\nCompression algorithm: unknown");
            parseCurrentSection = false;
        }
    }
    // GZip compressed section
    else if (baGuid == EFI_GUIDED_SECTION_GZIP) {
        USTATUS result = gzipDecompress(model->body(index), processed);
        if (result) {
            msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            return U_SUCCESS;
        }

        algorithm = COMPRESSION_ALGORITHM_GZIP;
        info += UString("\nCompression algorithm: GZip");
        info += usprintf("\nDecompressed size: %Xh (%u)", (UINT32)processed.size(), (UINT32)processed.size());
    }
    // Zlib compressed section
    else if (baGuid == EFI_GUIDED_SECTION_ZLIB_AMD) {
        USTATUS result = zlibDecompress(model->body(index), processed);
        if (result) {
            msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            return U_SUCCESS;
        }

        algorithm = COMPRESSION_ALGORITHM_ZLIB;
        info += UString("\nCompression algorithm: Zlib");
        info += usprintf("\nDecompressed size: %Xh (%u)", (UINT32)processed.size(), (UINT32)processed.size());
    }
    // Brotli compressed section
    else if (baGuid == EFI_GUIDED_SECTION_BROTLI)
    {
        USTATUS result = brotliDecompress(model->body(index), processed);
        if (result) {
            msg(usprintf("%s: decompression failed with error ", __FUNCTION__) + errorCodeToUString(result), index);
            return U_SUCCESS;
        }

        algorithm = COMPRESSION_ALGORITHM_BROTLI;
        info += UString("\nCompression algorithm: Brotli");
        info += usprintf("\nDecompressed size: %Xh (%u)", (UINT32)processed.size(), (UINT32)processed.size());
    }
    
    // Add info
    model->addInfo(index, info);
    
    // Set parsing data
    GUIDED_SECTION_PARSING_DATA pdata = {};
    pdata.dictionarySize = dictionarySize;
    model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
    
    // Set compression data
    if (algorithm != COMPRESSION_ALGORITHM_NONE) {
        model->setUncompressedData(index, processed);
        model->setCompressed(index, true);
    }
    
    if (!parseCurrentSection) {
        msg(usprintf("%s: GUID defined section can not be processed", __FUNCTION__), index);
        return U_SUCCESS;
    }
    
    return parseSections(processed, index, false);
}

USTATUS FfsParser::parseVersionSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Add info
    model->addInfo(index, UString("\nVersion string: ") + uFromUcs2(model->body(index).constData()));
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseDepexSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    UByteArray body = model->body(index);
    UString parsed;
    
    // Check data to be present
    if (body.size() < 2) { // 2 is a minimal sane value, i.e TRUE + END
        msg(usprintf("%s: DEPEX section too short", __FUNCTION__), index);
        return U_DEPEX_PARSE_FAILED;
    }
    
    const EFI_GUID * guid;
    const UINT8* current = (const UINT8*)body.constData();
    
    // Special cases of first opcode
    switch (*current) {
        case EFI_DEP_BEFORE:
            if (body.size() != 2 * EFI_DEP_OPCODE_SIZE + sizeof(EFI_GUID)) {
                msg(usprintf("%s: DEPEX section too long for a section starting with BEFORE opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            guid = (const EFI_GUID*)(current + EFI_DEP_OPCODE_SIZE);
            parsed += UString("\nBEFORE ") + guidToUString(readUnaligned(guid));
            current += EFI_DEP_OPCODE_SIZE + sizeof(EFI_GUID);
            if (*current != EFI_DEP_END){
                msg(usprintf("%s: DEPEX section ends with non-END opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            // No further parsing required
            return U_SUCCESS;
        case EFI_DEP_AFTER:
            if (body.size() != 2 * EFI_DEP_OPCODE_SIZE + sizeof(EFI_GUID)){
                msg(usprintf("%s: DEPEX section too long for a section starting with AFTER opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            guid = (const EFI_GUID*)(current + EFI_DEP_OPCODE_SIZE);
            parsed += UString("\nAFTER ") + guidToUString(readUnaligned(guid));
            current += EFI_DEP_OPCODE_SIZE + sizeof(EFI_GUID);
            if (*current != EFI_DEP_END) {
                msg(usprintf("%s: DEPEX section ends with non-END opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            // No further parsing required
            return U_SUCCESS;
        case EFI_DEP_SOR:
            if (body.size() <= 2 * EFI_DEP_OPCODE_SIZE) {
                msg(usprintf("%s: DEPEX section too short for a section starting with SOR opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            parsed += UString("\nSOR");
            current += EFI_DEP_OPCODE_SIZE;
            break;
    }
    
    // Parse the rest of depex
    while (current - (const UINT8*)body.constData() < body.size()) {
        switch (*current) {
            case EFI_DEP_BEFORE: {
                msg(usprintf("%s: misplaced BEFORE opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            case EFI_DEP_AFTER: {
                msg(usprintf("%s: misplaced AFTER opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            case EFI_DEP_SOR: {
                msg(usprintf("%s: misplaced SOR opcode", __FUNCTION__), index);
                return U_SUCCESS;
            }
            case EFI_DEP_PUSH:
                // Check that the rest of depex has correct size
                if ((UINT32)body.size() - (UINT32)(current - (const UINT8*)body.constData()) <= EFI_DEP_OPCODE_SIZE + sizeof(EFI_GUID)) {
                    parsed.clear();
                    msg(usprintf("%s: the rest of DEPEX section too short for PUSH opcode", __FUNCTION__), index);
                    return U_SUCCESS;
                }
                guid = (const EFI_GUID*)(current + EFI_DEP_OPCODE_SIZE);
                parsed += UString("\nPUSH ") + guidToUString(readUnaligned(guid));
                current += EFI_DEP_OPCODE_SIZE + sizeof(EFI_GUID);
                break;
            case EFI_DEP_AND:
                parsed += UString("\nAND");
                current += EFI_DEP_OPCODE_SIZE;
                break;
            case EFI_DEP_OR:
                parsed += UString("\nOR");
                current += EFI_DEP_OPCODE_SIZE;
                break;
            case EFI_DEP_NOT:
                parsed += UString("\nNOT");
                current += EFI_DEP_OPCODE_SIZE;
                break;
            case EFI_DEP_TRUE:
                parsed += UString("\nTRUE");
                current += EFI_DEP_OPCODE_SIZE;
                break;
            case EFI_DEP_FALSE:
                parsed += UString("\nFALSE");
                current += EFI_DEP_OPCODE_SIZE;
                break;
            case EFI_DEP_END:
                parsed += UString("\nEND");
                current += EFI_DEP_OPCODE_SIZE;
                // Check that END is the last opcode
                if (current - (const UINT8*)body.constData() < body.size()) {
                    parsed.clear();
                    msg(usprintf("%s: DEPEX section ends with non-END opcode", __FUNCTION__), index);
                }
                break;
            default:
                msg(usprintf("%s: unknown opcode %02Xh", __FUNCTION__, *current), index);
                // No further parsing required
                return U_SUCCESS;
        }
    }
    
    // Add info
    model->addInfo(index, UString("\nParsed expression:") + parsed);
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseUiSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    UString text = uFromUcs2(model->body(index).constData());
    
    // Add info
    model->addInfo(index, UString("\nText: ") + text);
    
    // Rename parent file
    model->setText(model->findParentOfType(index, Types::File), text);
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseAprioriRawSection(const UByteArray & body, UString & parsed)
{
    // Sanity check
    if (body.size() % sizeof(EFI_GUID)) {
        msg(usprintf("%s: apriori file has size that is not a multiple of 16", __FUNCTION__));
    }
    parsed.clear();
    UINT32 count = (UINT32)(body.size() / sizeof(EFI_GUID));
    if (count > 0) {
        for (UINT32 i = 0; i < count; i++) {
            const EFI_GUID* guid = (const EFI_GUID*)body.constData() + i;
            parsed += "\n" + guidToUString(readUnaligned(guid));
        }
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseRawSectionBody(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Check for apriori file
    UModelIndex parentFile = model->findParentOfType(index, Types::File);
    if (!parentFile.isValid())
        return U_INVALID_RAW_AREA;
    
    // Get parent file parsing data
    UByteArray parentFileGuid(model->header(parentFile).constData(), sizeof(EFI_GUID));
    if (parentFileGuid == EFI_PEI_APRIORI_FILE_GUID) { // PEI apriori file
        // Set parent file text
        model->setText(parentFile, UString("PEI apriori file"));
        // Parse apriori file list
        UString str;
        USTATUS result = parseAprioriRawSection(model->body(index), str);
        if (!result && !str.isEmpty())
            model->addInfo(index, UString("\nFile list:") + str);
        return result;
    }
    else if (parentFileGuid == EFI_DXE_APRIORI_FILE_GUID) { // DXE apriori file
        // Rename parent file
        model->setText(parentFile, UString("DXE apriori file"));
        // Parse apriori file list
        UString str;
        USTATUS result = parseAprioriRawSection(model->body(index), str);
        if (!result && !str.isEmpty())
            model->addInfo(index, UString("\nFile list:") + str);
        return result;
    }
    else if (parentFileGuid == NVRAM_NVAR_EXTERNAL_DEFAULTS_FILE_GUID) { // AMI NVRAM external defaults
        // Rename parent file
        model->setText(parentFile, UString("NVRAM external defaults"));
        // Parse NVAR area
        return nvramParser->parseNvarStore(index);
    }
    else if (parentFileGuid == PROTECTED_RANGE_VENDOR_HASH_FILE_GUID_AMI) { // AMI vendor hash file
        // Parse AMI vendor hash file
        return parseVendorHashFile(parentFileGuid, index);
    }
    else if (nvramParser->parseNvarStore(index, true) == U_SUCCESS) {
        // Rename parent file
        model->setName(index, UString(sectionTypeToUString(EFI_SECTION_RAW) + " section with NVAR store"));
        return U_SUCCESS;
    }
    else if (parsePeImageSectionBody(index, true) == U_SUCCESS) {
        // Rename parent file
        model->setName(index, UString(sectionTypeToUString(EFI_SECTION_RAW) + " section with PE32 image"));
        return U_SUCCESS;
    }
    else if (parseTeImageSectionBody(index, true) == U_SUCCESS) {
        // Rename parent file
        model->setName(index, UString(sectionTypeToUString(EFI_SECTION_RAW) + " section with TE image"));
        return U_SUCCESS;
    }

    // Parse as raw area
    return parseRawArea(index);
}


USTATUS FfsParser::parsePeImageSectionBody(const UModelIndex & index, const bool probe)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Get section body
    UByteArray body = model->body(index);
    if ((UINT32)body.size() < sizeof(EFI_IMAGE_DOS_HEADER)) {
        if (probe)
            return U_INVALID_IMAGE;
        msg(usprintf("%s: section body size is smaller than DOS header size", __FUNCTION__), index);
        return U_SUCCESS;
    }
    
    UString info;
    const EFI_IMAGE_DOS_HEADER* dosHeader = (const EFI_IMAGE_DOS_HEADER*)body.constData();
    if (dosHeader->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
        if (probe)
            return U_INVALID_IMAGE;
        info += usprintf("\nDOS signature: %04Xh, invalid", dosHeader->e_magic);
        msg(usprintf("%s: PE32 image with invalid DOS signature", __FUNCTION__), index);
        model->addInfo(index, info);
        return U_SUCCESS;
    }
    
    const EFI_IMAGE_PE_HEADER* peHeader = (EFI_IMAGE_PE_HEADER*)(body.constData() + dosHeader->e_lfanew);
    if (body.size() < (UINT8*)peHeader - (UINT8*)dosHeader) {
        if (probe)
            return U_INVALID_IMAGE;
        info += UString("\nDOS header: invalid");
        msg(usprintf("%s: PE32 image with invalid DOS header", __FUNCTION__), index);
        model->addInfo(index, info);
        return U_SUCCESS;
    }
    
    if (peHeader->Signature != EFI_IMAGE_PE_SIGNATURE) {
        if (probe)
            return U_INVALID_IMAGE;
        info += usprintf("\nPE signature: %08Xh, invalid", peHeader->Signature);
        msg(usprintf("%s: PE32 image with invalid PE signature", __FUNCTION__), index);
        model->addInfo(index, info);
        return U_SUCCESS;
    }
    
    const EFI_IMAGE_FILE_HEADER* imageFileHeader = (const EFI_IMAGE_FILE_HEADER*)(peHeader + 1);
    if (body.size() < (UINT8*)imageFileHeader - (UINT8*)dosHeader) {
        if (probe)
            return U_INVALID_IMAGE;
        info += UString("\nPE header: invalid");
        msg(usprintf("%s: PE32 image with invalid PE header", __FUNCTION__), index);
        model->addInfo(index, info);
        return U_SUCCESS;
    }
    
    info += usprintf("\nDOS signature: %04Xh\nPE signature: %08Xh",
                     dosHeader->e_magic,
                     peHeader->Signature) +
    UString("\nMachine type: ") + machineTypeToUString(imageFileHeader->Machine) +
    usprintf("\nNumber of sections: %u\nCharacteristics: %04Xh",
             imageFileHeader->NumberOfSections,
             imageFileHeader->Characteristics);
    
    EFI_IMAGE_OPTIONAL_HEADER_POINTERS_UNION optionalHeader = {};
    optionalHeader.H32 = (const EFI_IMAGE_OPTIONAL_HEADER32*)(imageFileHeader + 1);
    if (body.size() < (UINT8*)optionalHeader.H32 - (UINT8*)dosHeader) {
        if (probe)
            return U_INVALID_IMAGE;
        info += UString("\nPE optional header: invalid");
        msg(usprintf("%s: PE32 image with invalid PE optional header", __FUNCTION__), index);
        model->addInfo(index, info);
        return U_SUCCESS;
    }
    
    if (optionalHeader.H32->Magic == EFI_IMAGE_PE_OPTIONAL_HDR32_MAGIC) {
        info += usprintf("\nOptional header signature: %04Xh\nSubsystem: %04Xh\nAddress of entry point: %Xh\nBase of code: %Xh\nImage base: %Xh",
                         optionalHeader.H32->Magic,
                         optionalHeader.H32->Subsystem,
                         optionalHeader.H32->AddressOfEntryPoint,
                         optionalHeader.H32->BaseOfCode,
                         optionalHeader.H32->ImageBase);
    }
    else if (optionalHeader.H32->Magic == EFI_IMAGE_PE_OPTIONAL_HDR64_MAGIC) {
        info += usprintf("\nOptional header signature: %04Xh\nSubsystem: %04Xh\nAddress of entry point: %Xh\nBase of code: %Xh\nImage base: %" PRIX64 "h",
                         optionalHeader.H64->Magic,
                         optionalHeader.H64->Subsystem,
                         optionalHeader.H64->AddressOfEntryPoint,
                         optionalHeader.H64->BaseOfCode,
                         optionalHeader.H64->ImageBase);
    }
    else {
        if (probe)
            return U_INVALID_IMAGE;
        info += usprintf("\nOptional header signature: %04Xh, unknown", optionalHeader.H32->Magic);
        msg(usprintf("%s: PE32 image with invalid optional PE header signature", __FUNCTION__), index);
    }
    
    model->addInfo(index, info);
    return U_SUCCESS;
}


USTATUS FfsParser::parseTeImageSectionBody(const UModelIndex & index, const bool probe)
{
    // Check sanity
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Get section body
    UByteArray body = model->body(index);
    if ((UINT32)body.size() < sizeof(EFI_IMAGE_TE_HEADER)) {
        if (probe)
            return U_INVALID_IMAGE;
        msg(usprintf("%s: section body size is smaller than TE header size", __FUNCTION__), index);
        return U_SUCCESS;
    }
    
    UString info;
    const EFI_IMAGE_TE_HEADER* teHeader = (const EFI_IMAGE_TE_HEADER*)body.constData();
    if (teHeader->Signature != EFI_IMAGE_TE_SIGNATURE) {
        if (probe)
            return U_INVALID_IMAGE;
        info += usprintf("\nSignature: %04Xh, invalid", teHeader->Signature);
        msg(usprintf("%s: TE image with invalid TE signature", __FUNCTION__), index);
    }
    else {
        info += usprintf("\nSignature: %04Xh", teHeader->Signature) +
        UString("\nMachine type: ") + machineTypeToUString(teHeader->Machine) +
        usprintf("\nNumber of sections: %u\nSubsystem: %02Xh\nStripped size: %Xh (%u)\n"
                 "Base of code: %Xh\nAddress of entry point: %Xh\nImage base: %" PRIX64 "h\nAdjusted image base: %" PRIX64 "h",
                 teHeader->NumberOfSections,
                 teHeader->Subsystem,
                 teHeader->StrippedSize, teHeader->StrippedSize,
                 teHeader->BaseOfCode,
                 teHeader->AddressOfEntryPoint,
                 teHeader->ImageBase,
                 teHeader->ImageBase + teHeader->StrippedSize - sizeof(EFI_IMAGE_TE_HEADER));
    }
    
    // Update parsing data
    TE_IMAGE_SECTION_PARSING_DATA pdata = {};
    pdata.imageBaseType = EFI_IMAGE_TE_BASE_OTHER; // Will be determined later
    pdata.originalImageBase = (UINT32)teHeader->ImageBase;
    pdata.adjustedImageBase = (UINT32)(teHeader->ImageBase + teHeader->StrippedSize - sizeof(EFI_IMAGE_TE_HEADER));
    model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
    
    // Add TE info
    model->addInfo(index, info);
    
    return U_SUCCESS;
}


USTATUS FfsParser::performSecondPass(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid() || !lastVtf.isValid())
        return U_INVALID_PARAMETER;
    
    // Check for compressed lastVtf
    if (model->compressed(lastVtf)) {
        msg(usprintf("%s: the last VTF appears inside compressed item, the image may be damaged", __FUNCTION__), lastVtf);
        return U_SUCCESS;
    }
    
    // Calculate address difference
    const UINT32 vtfSize = (UINT32)(model->entire(lastVtf).size());
    addressDiff = 0xFFFFFFFFULL - model->base(lastVtf) - vtfSize + 1;
    
    // Parse reset vector data
    parseResetVectorData();
    
    // Find and parse FIT
    fitParser->parseFit(index);
    
    // Check protected ranges
    checkProtectedRanges(index);
    
    // Check TE files to have original or adjusted base
    checkTeImageBase(index);
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseResetVectorData()
{
    // Sanity check
    if (!lastVtf.isValid())
        return U_SUCCESS;
    
    // Check VTF to have enough space at the end to fit Reset Vector Data
    UByteArray vtf = model->entire(lastVtf);
    if ((UINT32)vtf.size() < sizeof(X86_RESET_VECTOR_DATA))
        return U_SUCCESS;
    
    const X86_RESET_VECTOR_DATA* resetVectorData = (const X86_RESET_VECTOR_DATA*)(vtf.constData() + vtf.size() - sizeof(X86_RESET_VECTOR_DATA));
    
    // Add info
    UString info = usprintf("\nAP entry vector: %02X %02X %02X %02X %02X %02X %02X %02X\n"
                            "Reset vector: %02X %02X %02X %02X %02X %02X %02X %02X\n"
                            "PEI core entry point: %08Xh\n"
                            "AP startup segment: %08Xh\n"
                            "BootFV base address: %08Xh\n",
                            resetVectorData->ApEntryVector[0], resetVectorData->ApEntryVector[1], resetVectorData->ApEntryVector[2], resetVectorData->ApEntryVector[3],
                            resetVectorData->ApEntryVector[4], resetVectorData->ApEntryVector[5], resetVectorData->ApEntryVector[6], resetVectorData->ApEntryVector[7],
                            resetVectorData->ResetVector[0], resetVectorData->ResetVector[1], resetVectorData->ResetVector[2], resetVectorData->ResetVector[3],
                            resetVectorData->ResetVector[4], resetVectorData->ResetVector[5], resetVectorData->ResetVector[6], resetVectorData->ResetVector[7],
                            resetVectorData->PeiCoreEntryPoint,
                            resetVectorData->ApStartupSegment,
                            resetVectorData->BootFvBaseAddress);
    
    model->addInfo(lastVtf, info);
    return U_SUCCESS;
}

USTATUS FfsParser::checkTeImageBase(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid()) {
        return U_INVALID_PARAMETER;
    }
    
    // Determine relocation type of uncompressed TE image sections
    if (model->compressed(index) == false
        && model->type(index) == Types::Section
        && model->subtype(index) == EFI_SECTION_TE) {
        // Obtain required values from parsing data
        UINT32 originalImageBase = 0;
        UINT32 adjustedImageBase = 0;
        UINT8  imageBaseType = EFI_IMAGE_TE_BASE_OTHER;
        if (model->hasEmptyParsingData(index) == false) {
            UByteArray data = model->parsingData(index);
            const TE_IMAGE_SECTION_PARSING_DATA* pdata = (const TE_IMAGE_SECTION_PARSING_DATA*)data.constData();
            originalImageBase = readUnaligned(pdata).originalImageBase;
            adjustedImageBase = readUnaligned(pdata).adjustedImageBase;
        }
        
        if (originalImageBase != 0 || adjustedImageBase != 0) {
            // Check data memory address to be equal to either OriginalImageBase or AdjustedImageBase
            UINT64 address = addressDiff + model->base(index);
            UINT32 base = (UINT32)(address + model->header(index).size());
            
            if (originalImageBase == base) {
                imageBaseType = EFI_IMAGE_TE_BASE_ORIGINAL;
            }
            else if (adjustedImageBase == base) {
                imageBaseType = EFI_IMAGE_TE_BASE_ADJUSTED;
            }
            else {
                // Check for one-bit difference
                UINT32 xored = base ^ originalImageBase; // XOR result can't be zero
                if ((xored & (xored - 1)) == 0) { // Check that XOR result is a power of 2, i.e. has exactly one bit set
                    imageBaseType = EFI_IMAGE_TE_BASE_ORIGINAL;
                }
                else { // The same check for adjustedImageBase
                    xored = base ^ adjustedImageBase;
                    if ((xored & (xored - 1)) == 0) {
                        imageBaseType = EFI_IMAGE_TE_BASE_ADJUSTED;
                    }
                }
            }
            
            // Show message if imageBaseType is still unknown
            if (imageBaseType == EFI_IMAGE_TE_BASE_OTHER) {
                msg(usprintf("%s: TE image base is neither zero, nor original, nor adjusted, nor top-swapped", __FUNCTION__), index);
            }
            
            // Update parsing data
            TE_IMAGE_SECTION_PARSING_DATA pdata = {};
            pdata.imageBaseType = imageBaseType;
            pdata.originalImageBase = originalImageBase;
            pdata.adjustedImageBase = adjustedImageBase;
            model->setParsingData(index, UByteArray((const char*)&pdata, sizeof(pdata)));
        }
    }
    
    // Process child items
    for (int i = 0; i < model->rowCount(index); i++) {
        checkTeImageBase(index.model()->index(i, 0, index));
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::addInfoRecursive(const UModelIndex & index, bool enableCpuAddresses)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // Add offset
    model->addInfo(index, usprintf("Offset: %Xh\n", model->offset(index)), false);

    // Add current base if the element is not compressed
    // or it's compressed, but its parent isn't
    if ((!model->compressed(index)) || (index.parent().isValid() && !model->compressed(index.parent()))) {
        if (!enableCpuAddresses)
            enableCpuAddresses = (model->type(index) == Types::Image && model->subtype(index) == Subtypes::UefiImage)
                || (model->type(index) == Types::Region && model->subtype(index) == Subtypes::BiosRegion);
        if (enableCpuAddresses) {
            // Add physical address of the whole item or its header and data portions separately
            UINT64 address = addressDiff + model->base(index);
            for (int i = 0; i < indexesAddressDiffs.size(); i++) {
                if (model->base(index) >= model->base(indexesAddressDiffs.at(i).first))
                    address = indexesAddressDiffs.at(i).second + model->base(index);
            }
            if (address <= 0xFFFFFFFFUL) {
                UINT32 headerSize = (UINT32)model->header(index).size();
                if (headerSize) {
                    model->addInfo(index, usprintf("Data address: %08Xh\n", (UINT32)address + headerSize), false);
                    model->addInfo(index, usprintf("Header address: %08Xh\n", (UINT32)address), false);
                }
                else {
                    model->addInfo(index, usprintf("Address: %08Xh\n", (UINT32)address), false);
                }
            }
        }
        // Add base
        model->addInfo(index, usprintf("Base: %Xh\n", model->base(index)), false);
    }
    model->addInfo(index, usprintf("Fixed: %s\n", model->fixed(index) ? "Yes" : "No"), false);
    
    // Process child items
    for (int i = 0; i < model->rowCount(index); i++) {
        addInfoRecursive(index.model()->index(i, 0, index), enableCpuAddresses);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::checkProtectedRanges(const UModelIndex & index)
{
    // Sanity check
    if (!index.isValid())
        return U_INVALID_PARAMETER;
    
    // QByteArray (Qt builds) supports obtaining data from invalid offsets in QByteArray,
    // so mid() here doesn't throw anything for UEFITool, just returns ranges with all zeroes
    // UByteArray (non-Qt builds) throws an exception that needs to be caught every time or the tools will crash.
    
    // Calculate digest for BG-protected ranges
    UByteArray protectedParts;
    bool bgProtectedRangeFound = false;
    try {
        for (UINT32 i = 0; i < (UINT32)protectedRanges.size(); i++) {
            if (protectedRanges[i].Type == PROTECTED_RANGE_INTEL_BOOT_GUARD_IBB) {
                bgProtectedRangeFound = true;
                if ((UINT64)protectedRanges[i].Offset >= addressDiff) {
                    protectedRanges[i].Offset -= (UINT32)addressDiff;
                } else {
                    msg(usprintf("%s: suspicious protected range offset", __FUNCTION__), index);
                }
                protectedParts += openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                markProtectedRangeRecursive(index, protectedRanges[i]);
            }
        }
    } catch (...) {
        bgProtectedRangeFound = false;
    }
    
    if (bgProtectedRangeFound) {
        UINT8 digest[SHA512_HASH_SIZE] = {};
        UString digestString;
        UString ibbDigests;
        // SHA1
        digestString = "";
        sha1(protectedParts.constData(), protectedParts.size(), digest);
        for (UINT8 i = 0; i < SHA1_HASH_SIZE; i++) {
            digestString += usprintf("%02X", digest[i]);
        }
        ibbDigests += UString("Computed IBB Hash (SHA1): ") + digestString + "\n";
        // SHA256
        digestString = "";
        sha256(protectedParts.constData(), protectedParts.size(), digest);
        for (UINT8 i = 0; i < SHA256_HASH_SIZE; i++) {
            digestString += usprintf("%02X", digest[i]);
        }
        ibbDigests += UString("Computed IBB Hash (SHA256): ") + digestString + "\n";
        // SHA384
        digestString = "";
        sha384(protectedParts.constData(), protectedParts.size(), digest);
        for (UINT8 i = 0; i < SHA384_HASH_SIZE; i++) {
            digestString += usprintf("%02X", digest[i]);
        }
        ibbDigests += UString("Computed IBB Hash (SHA384): ") + digestString + "\n";
        // SHA512
        digestString = "";
        sha512(protectedParts.constData(), protectedParts.size(), digest);
        for (UINT8 i = 0; i < SHA512_HASH_SIZE; i++) {
            digestString += usprintf("%02X", digest[i]);
        }
        ibbDigests += UString("Computed IBB Hash (SHA512): ") + digestString + "\n";
        // SM3
        digestString = "";
        sm3(protectedParts.constData(), protectedParts.size(), digest);
        for (UINT8 i = 0; i < SM3_HASH_SIZE; i++) {
            digestString += usprintf("%02X", digest[i]);
        }
        ibbDigests += UString("Computed IBB Hash (SM3): ") + digestString + "\n";
        
        securityInfo += ibbDigests + "\n";
    }
    
    // Calculate digests for vendor-protected ranges
    for (UINT32 i = 0; i < (UINT32)protectedRanges.size(); i++) {
        if (protectedRanges[i].Type == PROTECTED_RANGE_INTEL_BOOT_GUARD_POST_IBB) {
            if (!dxeCore.isValid()) {
                msg(usprintf("%s: can't determine DXE volume offset, post-IBB protected range hash can't be checked", __FUNCTION__), index);
            }
            else {
                // Offset will be determined as the offset of root volume with first DXE core
                UModelIndex dxeRootVolumeIndex = model->findLastParentOfType(dxeCore, Types::Volume);
                if (!dxeRootVolumeIndex.isValid()) {
                    msg(usprintf("%s: can't determine DXE volume offset, post-IBB protected range hash can't be checked", __FUNCTION__), index);
                }
                else {
                    try {
                        protectedRanges[i].Offset = model->base(dxeRootVolumeIndex);
                        protectedRanges[i].Size = (UINT32)(model->entire(dxeRootVolumeIndex).size());
                        protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                        
                        // Calculate the hash
                        UByteArray digest(SHA512_HASH_SIZE, '\x00');
                        if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA1) {
                            sha1(protectedParts.constData(), protectedParts.size(), digest.data());
                            digest = digest.left(SHA1_HASH_SIZE);
                        }
                        else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA256) {
                            sha256(protectedParts.constData(), protectedParts.size(), digest.data());
                            digest = digest.left(SHA256_HASH_SIZE);
                        }
                        else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA384) {
                            sha384(protectedParts.constData(), protectedParts.size(), digest.data());
                            digest = digest.left(SHA384_HASH_SIZE);
                        }
                        else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA512) {
                            sha512(protectedParts.constData(), protectedParts.size(), digest.data());
                            digest = digest.left(SHA512_HASH_SIZE);
                        }
                        else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SM3) {
                            sm3(protectedParts.constData(), protectedParts.size(), digest.data());
                            digest = digest.left(SM3_HASH_SIZE);
                        }
                        else {
                            msg(usprintf("%s: post-IBB protected range [%Xh:%Xh] uses unknown hash algorithm %04Xh", __FUNCTION__,
                                         protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size, protectedRanges[i].AlgorithmId),
                                model->findByBase(protectedRanges[i].Offset));
                        }
                        
                        // Check the hash
                        if (digest != protectedRanges[i].Hash) {
                            msg(usprintf("%s: post-IBB protected range [%Xh:%Xh] hash mismatch, opened image may refuse to boot", __FUNCTION__,
                                         protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size),
                                model->findByBase(protectedRanges[i].Offset));
                        }
                        
                        markProtectedRangeRecursive(index, protectedRanges[i]);
                    }
                    catch(...) {
                        // Do nothing, this range is likely not found in the image
                    }
                }
            }
        }
        else if (protectedRanges[i].Type == PROTECTED_RANGE_VENDOR_HASH_AMI_V1) {
            if (!dxeCore.isValid()) {
                msg(usprintf("%s: can't determine DXE volume offset, AMI v1 protected range hash can't be checked", __FUNCTION__), index);
            }
            else {
                // Offset will be determined as the offset of root volume with first DXE core
                UModelIndex dxeRootVolumeIndex = model->findLastParentOfType(dxeCore, Types::Volume);
                if (!dxeRootVolumeIndex.isValid()) {
                    msg(usprintf("%s: can't determine DXE volume offset, AMI v1 protected range hash can't be checked", __FUNCTION__), index);
                }
                else {
                    try {
                        protectedRanges[i].Offset = model->base(dxeRootVolumeIndex);
                        protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);

                        UByteArray digest(SHA256_HASH_SIZE, '\x00');
                        sha256(protectedParts.constData(), protectedParts.size(), digest.data());

                        if (digest != protectedRanges[i].Hash) {
                            msg(usprintf("%s: AMI v1 protected range [%Xh:%Xh] hash mismatch, opened image may refuse to boot", __FUNCTION__,
                                protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size),
                                model->findByBase(protectedRanges[i].Offset));
                        }

                        markProtectedRangeRecursive(index, protectedRanges[i]);
                    }
                    catch (...) {
                        // Do nothing, this range is likely not found in the image
                    }
                }
            }
        }
        else if (protectedRanges[i].Type == PROTECTED_RANGE_VENDOR_HASH_AMI_V2) {
            try {
                protectedRanges[i].Offset -= (UINT32)addressDiff;
                protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                
                UByteArray digest(SHA256_HASH_SIZE, '\x00');
                sha256(protectedParts.constData(), protectedParts.size(), digest.data());
                
                if (digest != protectedRanges[i].Hash) {
                    msg(usprintf("%s: AMI v2 protected range [%Xh:%Xh] hash mismatch, opened image may refuse to boot", __FUNCTION__,
                                 protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size),
                        model->findByBase(protectedRanges[i].Offset));
                }
                
                markProtectedRangeRecursive(index, protectedRanges[i]);
            }
            catch(...) {
                // Do nothing, this range is likely not found in the image
            }
        }
        else if (protectedRanges[i].Type == PROTECTED_RANGE_VENDOR_HASH_AMI_V3) {
            try {
                protectedRanges[i].Offset -= (UINT32)addressDiff;
                protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                markProtectedRangeRecursive(index, protectedRanges[i]);

                // Process second range
                if (i + 1 < (UINT32)protectedRanges.size() && protectedRanges[i + 1].Type == PROTECTED_RANGE_VENDOR_HASH_AMI_V3) {
                    protectedRanges[i + 1].Offset -= (UINT32)addressDiff;
                    protectedParts += openedImage.mid(protectedRanges[i + 1].Offset, protectedRanges[i + 1].Size);
                    markProtectedRangeRecursive(index, protectedRanges[i + 1]);

                    // Process third range
                    if (i + 2 < (UINT32)protectedRanges.size() && protectedRanges[i + 2].Type == PROTECTED_RANGE_VENDOR_HASH_AMI_V3) {
                        protectedRanges[i + 2].Offset -= (UINT32)addressDiff;
                        protectedParts += openedImage.mid(protectedRanges[i + 2].Offset, protectedRanges[i + 2].Size);
                        markProtectedRangeRecursive(index, protectedRanges[i + 2]);

                        // Process fourth range
                        if (i + 3 < (UINT32)protectedRanges.size() && protectedRanges[i + 3].Type == PROTECTED_RANGE_VENDOR_HASH_AMI_V3) {
                            protectedRanges[i + 3].Offset -= (UINT32)addressDiff;
                            protectedParts += openedImage.mid(protectedRanges[i + 3].Offset, protectedRanges[i + 3].Size);
                            markProtectedRangeRecursive(index, protectedRanges[i + 3]);
                            i += 3; // Skip 3 already processed ranges
                        }
                        else {
                            i += 2; // Skip 2 already processed ranges
                        }
                    }
                    else {
                        i += 1;  // Skip 1 already processed range
                    }
                }

                UByteArray digest(SHA256_HASH_SIZE, '\x00');
                sha256(protectedParts.constData(), protectedParts.size(), digest.data());
                if (digest != protectedRanges[i].Hash) {
                    msg(usprintf("%s: AMI v3 protected ranges hash mismatch, opened image may refuse to boot", __FUNCTION__));
                }
            }
            catch (...) {
                // Do nothing, this range is likely not found in the image
            }
        }
        else if (protectedRanges[i].Type == PROTECTED_RANGE_VENDOR_HASH_PHOENIX) {
            try {
                protectedRanges[i].Offset += (UINT32)protectedRegionsBase;
                protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                
                UByteArray digest(SHA256_HASH_SIZE, '\x00');
                sha256(protectedParts.constData(), protectedParts.size(), digest.data());
                
                if (digest != protectedRanges[i].Hash) {
                    msg(usprintf("%s: Phoenix protected range [%Xh:%Xh] hash mismatch, opened image may refuse to boot", __FUNCTION__,
                                 protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size),
                        model->findByBase(protectedRanges[i].Offset));
                }
                
                markProtectedRangeRecursive(index, protectedRanges[i]);
            }
            catch(...) {
                // Do nothing, this range is likely not found in the image
            }
        }
        else if (protectedRanges[i].Type == PROTECTED_RANGE_VENDOR_HASH_MICROSOFT_PMDA) {
            try {
                protectedRanges[i].Offset -= (UINT32)addressDiff;
                protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                
                // Calculate the hash
                UByteArray digest(SHA512_HASH_SIZE, '\x00');
                if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA1) {
                    sha1(protectedParts.constData(), protectedParts.size(), digest.data());
                    digest = digest.left(SHA1_HASH_SIZE);
                }
                else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA256) {
                    sha256(protectedParts.constData(), protectedParts.size(), digest.data());
                    digest = digest.left(SHA256_HASH_SIZE);
                }
                else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA384) {
                    sha384(protectedParts.constData(), protectedParts.size(), digest.data());
                    digest = digest.left(SHA384_HASH_SIZE);
                }
                else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SHA512) {
                    sha512(protectedParts.constData(), protectedParts.size(), digest.data());
                    digest = digest.left(SHA512_HASH_SIZE);
                }
                else if (protectedRanges[i].AlgorithmId == TCG_HASH_ALGORITHM_ID_SM3) {
                    sm3(protectedParts.constData(), protectedParts.size(), digest.data());
                    digest = digest.left(SM3_HASH_SIZE);
                }
                else {
                    msg(usprintf("%s: Microsoft PMDA protected range [%Xh:%Xh] uses unknown hash algorithm %04Xh", __FUNCTION__,
                                 protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size, protectedRanges[i].AlgorithmId),
                        model->findByBase(protectedRanges[i].Offset));
                }
                
                // Check the hash
                if (digest != protectedRanges[i].Hash) {
                    msg(usprintf("%s: Microsoft PMDA protected range [%Xh:%Xh] hash mismatch, opened image may refuse to boot", __FUNCTION__,
                                 protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size),
                        model->findByBase(protectedRanges[i].Offset));
                }
                
                markProtectedRangeRecursive(index, protectedRanges[i]);
            }
            catch(...) {
                // Do nothing, this range is likely not found in the image
            }
        }
        else if (protectedRanges[i].Type == PROTECTED_RANGE_VENDOR_HASH_INSYDE) {
            try {
                protectedRanges[i].Offset -= (UINT32)addressDiff;
                protectedParts = openedImage.mid(protectedRanges[i].Offset, protectedRanges[i].Size);
                
                UByteArray digest(SHA256_HASH_SIZE, '\x00');
                sha256(protectedParts.constData(), protectedParts.size(), digest.data());
                
                if (digest != protectedRanges[i].Hash) {
                    msg(usprintf("%s: Insyde protected range [%Xh:%Xh] hash mismatch, opened image may refuse to boot", __FUNCTION__,
                                 protectedRanges[i].Offset, protectedRanges[i].Offset + protectedRanges[i].Size),
                        model->findByBase(protectedRanges[i].Offset));
                }
                
                markProtectedRangeRecursive(index, protectedRanges[i]);
            }
            catch(...) {
                // Do nothing, this range is likely not found in the image
            }
        }
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::markProtectedRangeRecursive(const UModelIndex & index, const PROTECTED_RANGE & range)
{
    if (!index.isValid())
        return U_SUCCESS;
    
    // Mark compressed items
    UModelIndex parentIndex = model->parent(index);
    if (parentIndex.isValid() && model->compressed(index) && model->compressed(parentIndex)) {
        model->setMarking(index, model->marking(parentIndex));
    }
    // Mark normal items
    else {
        UINT32 currentOffset = model->base(index);
        UINT32 currentSize = (UINT32)(model->entire(index).size());
        
        if (std::min(currentOffset + currentSize, range.Offset + range.Size) > std::max(currentOffset, range.Offset)) {
            if (range.Offset <= currentOffset && currentOffset + currentSize <= range.Offset + range.Size) { // Mark as fully in range
                if (range.Type == PROTECTED_RANGE_INTEL_BOOT_GUARD_IBB) {
                    model->setMarking(index, BootGuardMarking::BootGuardFullyInRange);
                }
                else {
                    model->setMarking(index, BootGuardMarking::VendorFullyInRange);
                }
            }
            else { // Mark as partially in range
                model->setMarking(index, BootGuardMarking::PartiallyInRange);
            }
        }
    }
    
    for (int i = 0; i < model->rowCount(index); i++) {
        markProtectedRangeRecursive(index.model()->index(i, 0, index), range);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseVendorHashFile(const UByteArray & fileGuid, const UModelIndex & index)
{
    // Check sanity
    if (!index.isValid()) {
        return U_INVALID_PARAMETER;
    }
    
    const UByteArray& body = model->body(index);
    UINT32 size = (UINT32)body.size();
    if (fileGuid == PROTECTED_RANGE_VENDOR_HASH_FILE_GUID_PHOENIX) {
        if (size < sizeof(PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_PHOENIX)) {
            msg(usprintf("%s: unknown or corrupted Phoenix protected ranges hash file", __FUNCTION__), index);
        }
        else {
            const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_PHOENIX* header = (const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_PHOENIX*)body.constData();
            if (header->Signature == BG_VENDOR_HASH_FILE_SIGNATURE_PHOENIX) {
                if (size < sizeof(PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_PHOENIX) + header->NumEntries * sizeof(PROTECTED_RANGE_VENDOR_HASH_FILE_ENTRY)) {
                    msg(usprintf("%s: unknown or corrupted Phoenix protected ranges hash file", __FUNCTION__), index);
                }
                else {
                    if (header->NumEntries > 0) {
                        bool protectedRangesFound = false;
                        for (UINT32 i = 0; i < header->NumEntries; i++) {
                            const PROTECTED_RANGE_VENDOR_HASH_FILE_ENTRY* entry = (const PROTECTED_RANGE_VENDOR_HASH_FILE_ENTRY*)(header + 1) + i;
                            if (entry->Base != 0xFFFFFFFF && entry->Size != 0 && entry->Size != 0xFFFFFFFF) {
                                protectedRangesFound = true;
                                PROTECTED_RANGE range = {};
                                range.Offset = entry->Base;
                                range.Size = entry->Size;
                                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                                range.Hash = UByteArray((const char*)entry->Hash, sizeof(entry->Hash));
                                range.Type = PROTECTED_RANGE_VENDOR_HASH_PHOENIX;
                                protectedRanges.push_back(range);
                            }
                        }

                        if (protectedRangesFound) {
                            securityInfo += usprintf("Phoenix hash file found at base %08Xh\nProtected ranges:\n", model->base(index));
                            for (UINT32 i = 0; i < header->NumEntries; i++) {
                                const PROTECTED_RANGE_VENDOR_HASH_FILE_ENTRY* entry = (const PROTECTED_RANGE_VENDOR_HASH_FILE_ENTRY*)(header + 1) + i;
                                securityInfo += usprintf("RelativeOffset: %08Xh Size: %Xh\nHash: ", entry->Base, entry->Size);
                                for (UINT8 j = 0; j < sizeof(entry->Hash); j++) {
                                    securityInfo += usprintf("%02X", entry->Hash[j]);
                                }
                                securityInfo += "\n";
                            }
                        }
                    }
                }
            }
        }

        model->setText(index, UString("Phoenix protected ranges hash file"));
    }
    else if (fileGuid == PROTECTED_RANGE_VENDOR_HASH_FILE_GUID_AMI) {
        UModelIndex fileIndex = model->parent(index);
        if (size == sizeof(PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V1)) {
            securityInfo += usprintf("AMI protected ranges hash file v1 found at base %08Xh\nProtected range:\n", model->base(fileIndex));
            const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V1* entry = (const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V1*)(body.constData());
            securityInfo += usprintf("Size: %Xh\nHash (SHA256): ", entry->Size);
            for (UINT8 i = 0; i < sizeof(entry->Hash); i++) {
                securityInfo += usprintf("%02X", entry->Hash[i]);
            }
            securityInfo += "\n";

            if (entry->Size != 0 && entry->Size != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = 0;
                range.Size = entry->Size;
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash, sizeof(entry->Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V1;
                protectedRanges.push_back(range);
            }

            model->setText(fileIndex, UString("AMI v1 protected ranges hash file"));
        }
        else if (size == sizeof(PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V2)) {
            const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V2* entry = (const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V2*)(body.constData());

            securityInfo += usprintf("AMI v2 protected ranges hash file found at base %08Xh\nProtected ranges:", model->base(fileIndex));
            securityInfo += usprintf("\nAddress: %08Xh, Size: %Xh\nHash (SHA256): ", entry->Hash0.Base, entry->Hash0.Size);
            for (UINT8 j = 0; j < sizeof(entry->Hash0.Hash); j++) {
                securityInfo += usprintf("%02X", entry->Hash0.Hash[j]);
            }
            securityInfo += usprintf("\nAddress: %08Xh, Size: %Xh\nHash (SHA256): ", entry->Hash1.Base, entry->Hash1.Size);
            for (UINT8 j = 0; j < sizeof(entry->Hash1.Hash); j++) {
                securityInfo += usprintf("%02X", entry->Hash1.Hash[j]);
            }
            securityInfo += "\n";

            if (entry->Hash0.Base != 0xFFFFFFFF && entry->Hash0.Size != 0 && entry->Hash0.Size != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = entry->Hash0.Base;
                range.Size = entry->Hash0.Size;
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash0.Hash, sizeof(entry->Hash0.Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V2;
                protectedRanges.push_back(range);
            }

            if (entry->Hash1.Base != 0xFFFFFFFF && entry->Hash1.Size != 0 && entry->Hash1.Size != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = entry->Hash1.Base;
                range.Size = entry->Hash1.Size;
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash1.Hash, sizeof(entry->Hash1.Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V2;
                protectedRanges.push_back(range);
            }

            model->setText(fileIndex, UString("AMI v2 protected ranges hash file"));
        }
        else if (size == sizeof(PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V3)) {
            const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V3* entry = (const PROTECTED_RANGE_VENDOR_HASH_FILE_HEADER_AMI_V3*)(body.constData());
            securityInfo += usprintf("AMI v3 protected ranges hash file found at base %08Xh\nProtected ranges:", model->base(fileIndex));
            securityInfo += usprintf("\nFvBaseSegment 0 Address: %08Xh, Size: %Xh", entry->FvMainSegmentBase[0], entry->FvMainSegmentSize[0]);
            securityInfo += usprintf("\nFvBaseSegment 1 Address: %08Xh, Size: %Xh", entry->FvMainSegmentBase[1], entry->FvMainSegmentSize[1]);
            securityInfo += usprintf("\nFvBaseSegment 2 Address: %08Xh, Size: %Xh", entry->FvMainSegmentBase[2], entry->FvMainSegmentSize[2]);
            securityInfo += usprintf("\nNestedFvBase Address: %08Xh, Size: %Xh", entry->NestedFvBase, entry->NestedFvSize);
            securityInfo += usprintf("\nHash (SHA256): ");
            for (UINT8 j = 0; j < sizeof(entry->Hash); j++) {
                securityInfo += usprintf("%02X", entry->Hash[j]);
            }
            securityInfo += "\n";

            if (entry->FvMainSegmentBase[0] != 0xFFFFFFFF && entry->FvMainSegmentSize[0] != 0 && entry->FvMainSegmentSize[0] != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = entry->FvMainSegmentBase[0];
                range.Size = entry->FvMainSegmentSize[0];
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash, sizeof(entry->Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V3;
                protectedRanges.push_back(range);
            }

            if (entry->FvMainSegmentBase[1] != 0xFFFFFFFF && entry->FvMainSegmentSize[1] != 0 && entry->FvMainSegmentSize[1] != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = entry->FvMainSegmentBase[1];
                range.Size = entry->FvMainSegmentSize[1];
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash, sizeof(entry->Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V3;
                protectedRanges.push_back(range);
            }

            if (entry->FvMainSegmentBase[2] != 0xFFFFFFFF && entry->FvMainSegmentSize[2] != 0 && entry->FvMainSegmentSize[2] != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = entry->FvMainSegmentBase[2];
                range.Size = entry->FvMainSegmentSize[2];
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash, sizeof(entry->Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V3;
                protectedRanges.push_back(range);
            }

            if (entry->NestedFvBase != 0xFFFFFFFF && entry->NestedFvSize != 0 && entry->NestedFvSize != 0xFFFFFFFF) {
                PROTECTED_RANGE range = {};
                range.Offset = entry->NestedFvBase;
                range.Size = entry->NestedFvSize;
                range.AlgorithmId = TCG_HASH_ALGORITHM_ID_SHA256;
                range.Hash = UByteArray((const char*)entry->Hash, sizeof(entry->Hash));
                range.Type = PROTECTED_RANGE_VENDOR_HASH_AMI_V3;
                protectedRanges.push_back(range);
            }

            model->setText(fileIndex, UString("AMI v3 protected ranges hash file"));
        }
        else {
            msg(usprintf("%s: unknown or corrupted AMI protected ranges hash file", __FUNCTION__), fileIndex);
        }
    }

    return U_SUCCESS;
}

USTATUS FfsParser::parseMicrocodeVolumeBody(const UModelIndex & index)
{
    const UINT32 headerSize = (UINT32)model->header(index).size();
    const UINT32 bodySize = (UINT32)model->body(index).size();
    UINT32 offset = 0;
    USTATUS result = U_SUCCESS;
    
    while(true) {
        // Parse current microcode
        UModelIndex currentMicrocode;
        UByteArray ucode = model->body(index).mid(offset);
        
        // Check for empty area
        if (getPaddingType(ucode) != Subtypes::DataPadding) {
            result = U_INVALID_MICROCODE;
        }
        else {
            result = parseIntelMicrocodeHeader(ucode, headerSize + offset, index, currentMicrocode);
        }
        
        // Add the rest as padding
        if (result) {
            if (offset < bodySize) {
                // Get info
                UString name = UString("Padding");
                UString info = usprintf("Full size: %Xh (%u)", (UINT32)ucode.size(), (UINT32)ucode.size());
                
                // Add tree item
                model->addItem(headerSize + offset, Types::Padding, getPaddingType(ucode), name, UString(), info, UByteArray(), ucode, UByteArray(), Fixed, index);
            }
            return U_SUCCESS;
        }
        
        // Get to next candidate
        offset += model->entire(currentMicrocode).size();
        if (offset >= bodySize)
            break;
    }
    return U_SUCCESS;
}

USTATUS FfsParser::parseIntelMicrocodeHeader(const UByteArray & microcode, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // We have enough data to fit the header
    if ((UINT32)microcode.size() <  sizeof(INTEL_MICROCODE_HEADER)) {
        return U_INVALID_MICROCODE;
    }
    
    const INTEL_MICROCODE_HEADER* ucodeHeader = (const INTEL_MICROCODE_HEADER*)microcode.constData();
    
    if (!microcodeHeaderValid(ucodeHeader)) {
        return U_INVALID_MICROCODE;
    }
    
    // We have enough data to fit the whole TotalSize
    if ((UINT32)microcode.size() < ucodeHeader->TotalSize) {
        return U_INVALID_MICROCODE;
    }
    
    // Valid microcode found
    UINT32 dataSize = ucodeHeader->DataSize;
    if (dataSize == 0) {
        dataSize = INTEL_MICROCODE_REAL_DATA_SIZE_ON_ZERO;
    }
    
    // Cross check DataSize and TotalSize
    if (ucodeHeader->TotalSize < sizeof(INTEL_MICROCODE_HEADER) + dataSize) {
        return U_INVALID_MICROCODE;
    }
    
    // Recalculate the whole microcode checksum
    UByteArray tempMicrocode = microcode;
    INTEL_MICROCODE_HEADER* tempUcodeHeader = (INTEL_MICROCODE_HEADER*)(tempMicrocode.data());
    tempUcodeHeader->Checksum = 0;
    UINT32 calculated = calculateChecksum32((const UINT32*)tempMicrocode.constData(), tempUcodeHeader->TotalSize);
    bool msgInvalidChecksum = (ucodeHeader->Checksum != calculated);
    
    // Construct header, body and tail
    UByteArray header = microcode.left(sizeof(INTEL_MICROCODE_HEADER));
    UByteArray body = microcode.mid(sizeof(INTEL_MICROCODE_HEADER), dataSize);
    UByteArray tail;
    
    // Check if the tail is present
    if (ucodeHeader->TotalSize > sizeof(INTEL_MICROCODE_HEADER) + dataSize) {
        tail = microcode.mid(sizeof(INTEL_MICROCODE_HEADER) + dataSize, ucodeHeader->TotalSize - (sizeof(INTEL_MICROCODE_HEADER) + dataSize));
    }
    
    // Check if we have extended header in the tail
    UString extendedHeaderInfo;
    bool msgUnknownOrDamagedMicrocodeTail = false;
    if ((UINT32)tail.size() >= sizeof(INTEL_MICROCODE_EXTENDED_HEADER)) {
        const INTEL_MICROCODE_EXTENDED_HEADER* extendedHeader = (const INTEL_MICROCODE_EXTENDED_HEADER*)tail.constData();
        
        // Reserved bytes are all zeroes
        bool extendedReservedBytesValid = true;
        for (UINT8 i = 0; i < sizeof(extendedHeader->Reserved); i++) {
            if (extendedHeader->Reserved[i] != 0x00) {
                extendedReservedBytesValid = false;
                break;
            }
        }
        
        // We have more than 0 entries and they are all in the tail
        if (extendedReservedBytesValid
            && extendedHeader->EntryCount > 0
            && (UINT32)tail.size() == sizeof(INTEL_MICROCODE_EXTENDED_HEADER) + extendedHeader->EntryCount * sizeof(INTEL_MICROCODE_EXTENDED_HEADER_ENTRY)) {
            // Recalculate extended header checksum
            INTEL_MICROCODE_EXTENDED_HEADER* tempExtendedHeader = (INTEL_MICROCODE_EXTENDED_HEADER*)(tempMicrocode.data() + sizeof(INTEL_MICROCODE_HEADER) + dataSize);
            tempExtendedHeader->Checksum = 0;
            UINT32 extendedCalculated = calculateChecksum32((const UINT32*)tempExtendedHeader, sizeof(INTEL_MICROCODE_EXTENDED_HEADER) + extendedHeader->EntryCount * sizeof(INTEL_MICROCODE_EXTENDED_HEADER_ENTRY));
            
            extendedHeaderInfo = usprintf("\nExtended header entries: %u\nExtended header checksum: %08Xh, ",
                                          extendedHeader->EntryCount,
                                          extendedHeader->Checksum)
            + (extendedHeader->Checksum == extendedCalculated ? UString("valid") : usprintf("invalid, should be %08Xh", extendedCalculated));
            
            const INTEL_MICROCODE_EXTENDED_HEADER_ENTRY* firstEntry = (const INTEL_MICROCODE_EXTENDED_HEADER_ENTRY*)(extendedHeader + 1);
            for (UINT32 i = 0; i < extendedHeader->EntryCount; i++) {
                const INTEL_MICROCODE_EXTENDED_HEADER_ENTRY* entry = (const INTEL_MICROCODE_EXTENDED_HEADER_ENTRY*)(firstEntry + i);
                
                // Recalculate checksum after patching
                tempUcodeHeader->Checksum = 0;
                tempUcodeHeader->PlatformIds = entry->PlatformIds;
                tempUcodeHeader->ProcessorSignature = entry->ProcessorSignature;
                UINT32 entryCalculated = calculateChecksum32((const UINT32*)tempMicrocode.constData(), sizeof(INTEL_MICROCODE_HEADER) + dataSize);
                
                extendedHeaderInfo += usprintf("\nCPU signature #%u: %08Xh\nCPU platform Id #%u: %08Xh\nChecksum #%u: %08Xh, ",
                                               i + 1, entry->ProcessorSignature,
                                               i + 1, entry->PlatformIds,
                                               i + 1, entry->Checksum)
                + (entry->Checksum == entryCalculated ? UString("valid") : usprintf("invalid, should be %08Xh", entryCalculated));
            }
        }
        else {
            msgUnknownOrDamagedMicrocodeTail = true;
        }
    }
    else if (tail.size() != 0) {
        msgUnknownOrDamagedMicrocodeTail = true;
    }
    
    // Get microcode binary
    UByteArray microcodeBinary = microcode.left(ucodeHeader->TotalSize);
    
    // Add info
    UString name("Intel microcode");
    UString info = usprintf("Full size: %Xh (%u)\nHeader size: 0h (0u)\nBody size: %Xh (%u)\nTail size: 0h (0u)\n"
                            "Date: %02X.%02X.%04x\nCPU signature: %08Xh\nRevision: %08Xh\nMinimal update revision: %08Xh\nCPU platform Id: %08Xh\nChecksum: %08Xh, ",
                            (UINT32)microcodeBinary.size(), (UINT32)microcodeBinary.size(),
                            (UINT32)microcodeBinary.size(), (UINT32)microcodeBinary.size(),
                            ucodeHeader->DateDay,
                            ucodeHeader->DateMonth,
                            ucodeHeader->DateYear,
                            ucodeHeader->ProcessorSignature,
                            ucodeHeader->UpdateRevision,
                            ucodeHeader->UpdateRevisionMin,
                            ucodeHeader->PlatformIds,
                            ucodeHeader->Checksum)
    + (ucodeHeader->Checksum == calculated ? UString("valid") : usprintf("invalid, should be %08Xh", calculated))
    + extendedHeaderInfo;
    
    // Add tree item
    index = model->addItem(localOffset, Types::Microcode, Subtypes::IntelMicrocode, name, UString(), info, UByteArray(), microcodeBinary, UByteArray(), Fixed, parent);
    if (msgInvalidChecksum)
        msg(usprintf("%s: invalid microcode checksum %08Xh, should be %08Xh", __FUNCTION__, ucodeHeader->Checksum, calculated), index);
    if (msgUnknownOrDamagedMicrocodeTail)
        msg(usprintf("%s: extended header of size %Xh (%u) found, but it's damaged or has unknown format", __FUNCTION__, (UINT32)tail.size(), (UINT32)tail.size()), index);
    
    // No need to parse the body further for now
    return U_SUCCESS;
}

USTATUS FfsParser::parseBpdtRegion(const UByteArray & region, const UINT32 localOffset, const UINT32 sbpdtOffsetFixup, const UModelIndex & parent, UModelIndex & index)
{
    UINT32 regionSize = (UINT32)region.size();
    
    // Check region size
    if (regionSize < sizeof(BPDT_HEADER)) {
        msg(usprintf("%s: BPDT region too small to fit BPDT partition table header", __FUNCTION__), parent);
        return U_INVALID_ME_PARTITION_TABLE;
    }
    
    // Populate partition table header
    const BPDT_HEADER* ptHeader = (const BPDT_HEADER*)(region.constData());
    
    // Check region size again
    UINT32 ptBodySize = ptHeader->NumEntries * sizeof(BPDT_ENTRY);
    UINT32 ptSize = sizeof(BPDT_HEADER) + ptBodySize;
    if (regionSize < ptSize) {
        msg(usprintf("%s: BPDT region too small to fit BPDT partition table", __FUNCTION__), parent);
        return U_INVALID_ME_PARTITION_TABLE;
    }
    
    // Get info
    UByteArray header = region.left(sizeof(BPDT_HEADER));
    UByteArray body = region.mid(sizeof(BPDT_HEADER), ptBodySize);
    
    UString name = UString("BPDT partition table");
    UString info = usprintf("Full size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\n"
                            "Number of entries: %u\nVersion: %02Xh\nRedundancyFlag: %Xh\n"
                            "IFWI version: %Xh\nFITC version: %u.%u.%u.%u",
                            ptSize, ptSize,
                            (UINT32)header.size(), (UINT32)header.size(),
                            ptBodySize, ptBodySize,
                            ptHeader->NumEntries,
                            ptHeader->HeaderVersion,
                            ptHeader->RedundancyFlag,
                            ptHeader->IfwiVersion,
                            ptHeader->FitcMajor, ptHeader->FitcMinor, ptHeader->FitcHotfix, ptHeader->FitcBuild);
    
    // Add tree item
    index = model->addItem(localOffset, Types::BpdtStore, 0, name, UString(), info, header, body, UByteArray(), Fixed, parent);
    
    // Adjust offset
    UINT32 offset = sizeof(BPDT_HEADER);
    
    // Add partition table entries
    std::vector<BPDT_PARTITION_INFO> partitions;
    const BPDT_ENTRY* firstPtEntry = (const BPDT_ENTRY*)((const UINT8*)ptHeader + sizeof(BPDT_HEADER));
    UINT16 numEntries = ptHeader->NumEntries;
    for (UINT16 i = 0; i < numEntries; i++) {
        // Populate entry header
        const BPDT_ENTRY* ptEntry = firstPtEntry + i;
        
        // Get info
        name = bpdtEntryTypeToUString(ptEntry->Type);
        info = usprintf("Full size: %Xh (%u)\nType: %Xh\nPartition offset: %Xh\nPartition length: %Xh",
                        (UINT32)sizeof(BPDT_ENTRY), (UINT32)sizeof(BPDT_ENTRY),
                        ptEntry->Type,
                        ptEntry->Offset,
                        ptEntry->Size) +
        UString("\nSplit sub-partition first part: ") + (ptEntry->SplitSubPartitionFirstPart ? "Yes" : "No") +
        UString("\nSplit sub-partition second part: ") + (ptEntry->SplitSubPartitionSecondPart ? "Yes" : "No") +
        UString("\nCode sub-partition: ") + (ptEntry->CodeSubPartition ? "Yes" : "No") +
        UString("\nUMA cacheable: ") + (ptEntry->UmaCacheable ? "Yes" : "No");
        
        // Add tree item
        UModelIndex entryIndex = model->addItem(localOffset + offset, Types::BpdtEntry, 0, name, UString(), info, UByteArray(), UByteArray((const char*)ptEntry, sizeof(BPDT_ENTRY)), UByteArray(), Fixed, index);
        
        // Adjust offset
        offset += sizeof(BPDT_ENTRY);
        
        if (ptEntry->Offset != 0 && ptEntry->Offset != 0xFFFFFFFF && ptEntry->Size != 0) {
            // Add to partitions vector
            BPDT_PARTITION_INFO partition = {};
            partition.type = Types::BpdtPartition;
            partition.ptEntry = *ptEntry;
            partition.ptEntry.Offset -= sbpdtOffsetFixup;
            partition.index = entryIndex;
            partitions.push_back(partition);
        }
    }
    
    // Check for empty set of partitions
    if (partitions.empty()) {
        // Add a single padding partition in this case
        BPDT_PARTITION_INFO padding = {};
        padding.ptEntry.Offset = offset;
        padding.ptEntry.Size = (UINT32)(region.size() - padding.ptEntry.Offset);
        padding.type = Types::Padding;
        partitions.push_back(padding);
    }
    
make_partition_table_consistent:
    if (partitions.empty()) {
        return U_INVALID_ME_PARTITION_TABLE;
    }
    // Sort partitions by offset
    std::sort(partitions.begin(), partitions.end());
    
    // Check for intersections and paddings between partitions
    BPDT_PARTITION_INFO padding = {};
    
    // Check intersection with the partition table header
    if (partitions.front().ptEntry.Offset < ptSize) {
        msg(usprintf("%s: BPDT partition has intersection with BPDT partition table, skipped", __FUNCTION__),
            partitions.front().index);
        partitions.erase(partitions.begin());
        goto make_partition_table_consistent;
    }
    // Check for padding between partition table and the first partition
    else if (partitions.front().ptEntry.Offset > ptSize) {
        padding.ptEntry.Offset = ptSize;
        padding.ptEntry.Size = partitions.front().ptEntry.Offset - padding.ptEntry.Offset;
        padding.type = Types::Padding;
        partitions.insert(partitions.begin(), padding);
    }
    // Check for intersections/paddings between partitions
    for (size_t i = 1; i < partitions.size(); i++) {
        UINT32 previousPartitionEnd = partitions[i - 1].ptEntry.Offset + partitions[i - 1].ptEntry.Size;
        
        // Check that partition is fully present in the image
        if ((UINT64)partitions[i].ptEntry.Offset + (UINT64)partitions[i].ptEntry.Size > regionSize) {
            if ((UINT64)partitions[i].ptEntry.Offset >= (UINT64)region.size()) {
                msg(usprintf("%s: BPDT partition is located outside of the opened image, skipped", __FUNCTION__), partitions[i].index);
                partitions.erase(partitions.begin() + i);
                goto make_partition_table_consistent;
            }
            else {
                msg(usprintf("%s: BPDT partition can't fit into its region, truncated", __FUNCTION__), partitions[i].index);
                partitions[i].ptEntry.Size = regionSize - (UINT32)partitions[i].ptEntry.Offset;
            }
        }
        
        // Check for intersection with previous partition
        if (partitions[i].ptEntry.Offset < previousPartitionEnd) {
            // Check if current partition is located inside previous one
            if (partitions[i].ptEntry.Offset + partitions[i].ptEntry.Size <= previousPartitionEnd) {
                msg(usprintf("%s: BPDT partition is located inside another BPDT partition, skipped", __FUNCTION__),
                    partitions[i].index);
                partitions.erase(partitions.begin() + i);
                goto make_partition_table_consistent;
            }
            else {
                msg(usprintf("%s: BPDT partition intersects with previous one, skipped", __FUNCTION__),
                    partitions[i].index);
                partitions.erase(partitions.begin() + i);
                goto make_partition_table_consistent;
            }
        }
        
        // Check for padding between current and previous partitions
        else if (partitions[i].ptEntry.Offset > previousPartitionEnd) {
            padding.ptEntry.Offset = previousPartitionEnd;
            padding.ptEntry.Size = partitions[i].ptEntry.Offset - previousPartitionEnd;
            padding.type = Types::Padding;
            std::vector<BPDT_PARTITION_INFO>::iterator iter = partitions.begin();
            std::advance(iter, i);
            partitions.insert(iter, padding);
        }
    }
    
    // Partition map is consistent
    for (size_t i = 0; i < partitions.size(); i++) {
        if (partitions[i].type == Types::BpdtPartition) {
            // Get info
            UString name = bpdtEntryTypeToUString(partitions[i].ptEntry.Type);
            UByteArray partition = region.mid(partitions[i].ptEntry.Offset, partitions[i].ptEntry.Size);
            UByteArray signature = partition.left(sizeof(UINT32));
            
            UString info = usprintf("Full size: %Xh (%u)\nType: %Xh",
                                    (UINT32)partition.size(), (UINT32)partition.size(),
                                    partitions[i].ptEntry.Type) +
            UString("\nSplit sub-partition first part: ") + (partitions[i].ptEntry.SplitSubPartitionFirstPart ? "Yes" : "No") +
            UString("\nSplit sub-partition second part: ") + (partitions[i].ptEntry.SplitSubPartitionSecondPart ? "Yes" : "No") +
            UString("\nCode sub-partition: ") + (partitions[i].ptEntry.CodeSubPartition ? "Yes" : "No") +
            UString("\nUMA cacheable: ") + (partitions[i].ptEntry.UmaCacheable ? "Yes" : "No");
            
            UString text = bpdtEntryTypeToUString(partitions[i].ptEntry.Type);
            
            // Add tree item
            UModelIndex partitionIndex = model->addItem(localOffset + partitions[i].ptEntry.Offset, Types::BpdtPartition, 0, name, text, info, UByteArray(), partition, UByteArray(), Fixed, parent);
            
            // Special case of S-BPDT
            if (partitions[i].ptEntry.Type == BPDT_ENTRY_TYPE_S_BPDT) {
                UModelIndex sbpdtIndex;
                parseBpdtRegion(partition, 0, partitions[i].ptEntry.Offset, partitionIndex, sbpdtIndex); // Third parameter is a fixup for S-BPDT offset entries, because they are calculated from the start of BIOS region
            }
            
            // Parse code partitions
            if (readUnaligned((const UINT32*)partition.constData()) == CPD_SIGNATURE) {
                // Parse code partition contents
                UModelIndex cpdIndex;
                parseCpdRegion(partition, 0, partitionIndex, cpdIndex);
            }
            
            // Check for entry type to be known
            if (partitions[i].ptEntry.Type > BPDT_ENTRY_TYPE_EFWP && partitions[i].ptEntry.Type != BPDT_ENTRY_TYPE_ADSP) {
                msg(usprintf("%s: BPDT entry of unknown type found", __FUNCTION__), partitionIndex);
            }
        }
        else if (partitions[i].type == Types::Padding) {
            UByteArray padding = region.mid(partitions[i].ptEntry.Offset, partitions[i].ptEntry.Size);
            
            // Get info
            name = UString("Padding");
            info = usprintf("Full size: %Xh (%u)",
                            (UINT32)padding.size(), (UINT32)padding.size());
            
            // Add tree item
            model->addItem(localOffset + partitions[i].ptEntry.Offset, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, parent);
        }
    }
    
    // Add padding after the last region
    if ((UINT64)partitions.back().ptEntry.Offset + (UINT64)partitions.back().ptEntry.Size < regionSize) {
        UINT64 usedSize = (UINT64)partitions.back().ptEntry.Offset + (UINT64)partitions.back().ptEntry.Size;
        UByteArray padding = region.mid(partitions.back().ptEntry.Offset + partitions.back().ptEntry.Size, (int)(regionSize - usedSize));
        
        // Get info
        name = UString("Padding");
        info = usprintf("Full size: %Xh (%u)",
                        (UINT32)padding.size(), (UINT32)padding.size());
        
        // Add tree item
        model->addItem(localOffset + partitions.back().ptEntry.Offset + partitions.back().ptEntry.Size, Types::Padding, getPaddingType(padding), name, UString(), info, UByteArray(), padding, UByteArray(), Fixed, parent);
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseCpdRegion(const UByteArray & region, const UINT32 localOffset, const UModelIndex & parent, UModelIndex & index)
{
    // Check directory size
    if ((UINT32)region.size() < sizeof(CPD_REV1_HEADER)) {
        msg(usprintf("%s: CPD too small to fit rev1 partition table header", __FUNCTION__), parent);
        return U_INVALID_ME_PARTITION_TABLE;
    }
    
    // Populate partition table header
    const CPD_REV1_HEADER* cpdHeader = (const CPD_REV1_HEADER*)region.constData();
    
    // Check header version to be known
    UINT32 ptHeaderSize = 0;
    if (cpdHeader->HeaderVersion == 2) {
        if ((UINT32)region.size() < sizeof(CPD_REV2_HEADER)) {
            msg(usprintf("%s: CPD too small to fit rev2 partition table header", __FUNCTION__), parent);
            return U_INVALID_ME_PARTITION_TABLE;
        }
        
        ptHeaderSize = sizeof(CPD_REV2_HEADER);
    }
    else if (cpdHeader->HeaderVersion == 1) {
        ptHeaderSize = sizeof(CPD_REV1_HEADER);
    }
    
    // Check directory size again
    UINT32 ptBodySize = cpdHeader->NumEntries * sizeof(CPD_ENTRY);
    UINT32 ptSize = ptHeaderSize + ptBodySize;
    if ((UINT32)region.size() < ptSize) {
        msg(usprintf("%s: CPD too small to fit the whole partition table", __FUNCTION__), parent);
        return U_INVALID_ME_PARTITION_TABLE;
    }
    
    // Get info
    UByteArray header = region.left(ptHeaderSize);
    UByteArray body = region.mid(ptHeaderSize, ptBodySize);
    UString name = usprintf("CPD partition table");
    UString info = usprintf("Full size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nNumber of entries: %u\n"
                            "Header version: %u\nEntry version: %u",
                            ptSize, ptSize,
                            (UINT32)header.size(), (UINT32)header.size(),
                            (UINT32)body.size(), (UINT32)body.size(),
                            cpdHeader->NumEntries,
                            cpdHeader->HeaderVersion,
                            cpdHeader->EntryVersion);
    
    // Add tree item
    index = model->addItem(localOffset, Types::CpdStore, 0, name, UString(), info, header, body, UByteArray(), Fixed, parent);
    
    // Add partition table entries
    std::vector<CPD_PARTITION_INFO> partitions;
    UINT32 offset = ptHeaderSize;
    const CPD_ENTRY* firstCpdEntry = (const CPD_ENTRY*)(body.constData());
    for (UINT32 i = 0; i < cpdHeader->NumEntries; i++) {
        // Populate entry header
        const CPD_ENTRY* cpdEntry = firstCpdEntry + i;
        UByteArray entry((const char*)cpdEntry, sizeof(CPD_ENTRY));
        
        // Get info
        name = usprintf("%.12s", cpdEntry->EntryName);
        info = usprintf("Full size: %Xh (%u)\nEntry offset: %Xh\nEntry length: %Xh\nHuffman compressed: ",
                        (UINT32)entry.size(), (UINT32)entry.size(),
                        cpdEntry->Offset.Offset,
                        cpdEntry->Length)
        + (cpdEntry->Offset.HuffmanCompressed ? "Yes" : "No");
        
        // Add tree item
        UModelIndex entryIndex = model->addItem(offset, Types::CpdEntry, 0, name, UString(), info, UByteArray(), entry, UByteArray(), Fixed, index);
        
        // Adjust offset
        offset += sizeof(CPD_ENTRY);
        
        if (cpdEntry->Offset.Offset != 0 && cpdEntry->Length != 0) {
            // Add to partitions vector
            CPD_PARTITION_INFO partition;
            partition.type = Types::CpdPartition;
            partition.ptEntry = *cpdEntry;
            partition.index = entryIndex;
            partition.hasMetaData = false;
            partitions.push_back(partition);
        }
    }
    
    // Add padding if there's no partions to add
    if (partitions.size() == 0) {
        UByteArray partition = region.mid(ptSize);
        
        // Get info
        name = UString("Padding");
        info = usprintf("Full size: %Xh (%u)",
                        (UINT32)partition.size(), (UINT32)partition.size());
        
        // Add tree item
        model->addItem(localOffset + ptSize, Types::Padding, getPaddingType(partition), name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, parent);
        
        return U_SUCCESS;
    }
    
    // Sort partitions by offset
    std::sort(partitions.begin(), partitions.end());
    
    // Because lengths for all Huffmann-compressed partitions mean nothing at all, we need to split all partitions into 2 classes:
    // 1. CPD manifest
    // 2. Metadata entries
    UINT32 i = 1; // manifest is index 0, .met partitions start at index 1
    while (i < partitions.size()) {
        name = usprintf("%.12s", partitions[i].ptEntry.EntryName);
        
        // Check if the current entry is metadata entry
        if (!name.endsWith(".met")) {
            // No need to parse further, all metadata partitions are parsed
            break;
        }
        
        // Parse into data block, find Module Attributes extension, and get compressed size from there
        UINT32 offset = 0;
        UINT32 length = 0xFFFFFFFF; // Special guardian value
        UByteArray partition = region.mid(partitions[i].ptEntry.Offset.Offset, partitions[i].ptEntry.Length);
        while (offset < (UINT32)partition.size()) {
            const CPD_EXTENTION_HEADER* extHeader = (const CPD_EXTENTION_HEADER*) (partition.constData() + offset);
            if (extHeader->Length <= ((UINT32)partition.size() - offset)) {
                if (extHeader->Type == CPD_EXT_TYPE_MODULE_ATTRIBUTES) {
                    const CPD_EXT_MODULE_ATTRIBUTES* attrHeader = (const CPD_EXT_MODULE_ATTRIBUTES*)(partition.constData() + offset);
                    length = attrHeader->CompressedSize;
                }
                offset += extHeader->Length;
            }
            else break;
        }
        
        // Search down for corresponding code partition
        // Construct its name by removing the .met suffix
        name.chop(4);
        
        // Search
        bool found = false;
        UINT32 j = 1;
        while (j < partitions.size()) {
            UString namej = usprintf("%.12s", partitions[j].ptEntry.EntryName);
            
            if (name == namej) {
                found = true;
                // Found it, update its Length if needed
                if (partitions[j].ptEntry.Offset.HuffmanCompressed) {
                    partitions[j].ptEntry.Length = length;
                }
                else if (length != 0xFFFFFFFF && partitions[j].ptEntry.Length != length) {
                    msg(usprintf("%s: partition size mismatch between partition table (%Xh) and partition metadata (%Xh)", __FUNCTION__,
                                 partitions[j].ptEntry.Length, length), partitions[j].index);
                    partitions[j].ptEntry.Length = length; // Believe metadata
                }
                partitions[j].hasMetaData = true;
                // No need to search further
                break;
            }
            // Check the next partition
            j++;
        }
        if (!found) {
            msg(usprintf("%s: no code partition", __FUNCTION__), partitions[i].index);
        }
        
        // Check the next partition
        i++;
    }
    
make_partition_table_consistent:
    if (partitions.empty()) {
        return U_INVALID_ME_PARTITION_TABLE;
    }
    // Sort partitions by offset
    std::sort(partitions.begin(), partitions.end());
    
    // Check for intersections and paddings between partitions
    CPD_PARTITION_INFO padding = {};
    
    // Check intersection with the partition table header
    if (partitions.front().ptEntry.Offset.Offset < ptSize) {
        msg(usprintf("%s: CPD partition has intersection with CPD partition table, skipped", __FUNCTION__),
            partitions.front().index);
        partitions.erase(partitions.begin());
        goto make_partition_table_consistent;
    }
    // Check for padding between partition table and the first partition
    else if (partitions.front().ptEntry.Offset.Offset > ptSize) {
        padding.ptEntry.Offset.Offset = ptSize;
        padding.ptEntry.Length = partitions.front().ptEntry.Offset.Offset - padding.ptEntry.Offset.Offset;
        padding.type = Types::Padding;
        partitions.insert(partitions.begin(), padding);
    }
    // Check for intersections/paddings between partitions
    for (size_t i = 1; i < partitions.size(); i++) {
        UINT32 previousPartitionEnd = partitions[i - 1].ptEntry.Offset.Offset + partitions[i - 1].ptEntry.Length;
        
        // Check that current region is fully present in the image
        if ((UINT64)partitions[i].ptEntry.Offset.Offset + (UINT64)partitions[i].ptEntry.Length > (UINT64)region.size()) {
            if ((UINT64)partitions[i].ptEntry.Offset.Offset >= (UINT64)region.size()) {
                msg(usprintf("%s: CPD partition is located outside of the opened image, skipped", __FUNCTION__), partitions[i].index);
                partitions.erase(partitions.begin() + i);
                goto make_partition_table_consistent;
            }
            else {
                if (!partitions[i].hasMetaData && partitions[i].ptEntry.Offset.HuffmanCompressed) {
                    msg(usprintf("%s: CPD partition is compressed but doesn't have metadata and can't fit into its region, length adjusted", __FUNCTION__),
                        partitions[i].index);
                }
                else {
                    msg(usprintf("%s: CPD partition can't fit into its region, truncated", __FUNCTION__), partitions[i].index);
                }
                partitions[i].ptEntry.Length = (UINT32)region.size() - (UINT32)partitions[i].ptEntry.Offset.Offset;
            }
        }
        
        // Check for intersection with previous partition
        if (partitions[i].ptEntry.Offset.Offset < previousPartitionEnd) {
            // Check if previous partition was compressed but did not have metadata
            if (!partitions[i - 1].hasMetaData && partitions[i - 1].ptEntry.Offset.HuffmanCompressed) {
                msg(usprintf("%s: CPD partition is compressed but doesn't have metadata, length adjusted", __FUNCTION__),
                    partitions[i - 1].index);
                partitions[i - 1].ptEntry.Length = (UINT32)partitions[i].ptEntry.Offset.Offset - (UINT32)partitions[i - 1].ptEntry.Offset.Offset;
                goto make_partition_table_consistent;
            }
            
            // Check if current partition is located inside previous one
            if (partitions[i].ptEntry.Offset.Offset + partitions[i].ptEntry.Length <= previousPartitionEnd) {
                msg(usprintf("%s: CPD partition is located inside another CPD partition, skipped", __FUNCTION__),
                    partitions[i].index);
                partitions.erase(partitions.begin() + i);
                goto make_partition_table_consistent;
            }
            else {
                msg(usprintf("%s: CPD partition intersects with previous one, skipped", __FUNCTION__),
                    partitions[i].index);
                partitions.erase(partitions.begin() + i);
                goto make_partition_table_consistent;
            }
        }
        // Check for padding between current and previous partitions
        else if (partitions[i].ptEntry.Offset.Offset > previousPartitionEnd) {
            padding.ptEntry.Offset.Offset = previousPartitionEnd;
            padding.ptEntry.Length = partitions[i].ptEntry.Offset.Offset - previousPartitionEnd;
            padding.type = Types::Padding;
            std::vector<CPD_PARTITION_INFO>::iterator iter = partitions.begin();
            std::advance(iter, i);
            partitions.insert(iter, padding);
        }
    }
    // Check for padding after the last region
    if ((UINT64)partitions.back().ptEntry.Offset.Offset + (UINT64)partitions.back().ptEntry.Length < (UINT64)region.size()) {
        padding.ptEntry.Offset.Offset = partitions.back().ptEntry.Offset.Offset + partitions.back().ptEntry.Length;
        padding.ptEntry.Length = (UINT32)region.size() - padding.ptEntry.Offset.Offset;
        padding.type = Types::Padding;
        partitions.push_back(padding);
    }
    
    // Partition map is consistent
    for (size_t i = 0; i < partitions.size(); i++) {
        if (partitions[i].type == Types::CpdPartition) {
            UByteArray partition = region.mid(partitions[i].ptEntry.Offset.Offset, partitions[i].ptEntry.Length);
            
            // Get info
            name = usprintf("%.12s", partitions[i].ptEntry.EntryName);
            
            // It's a manifest
            if (name.endsWith(".man")) {
                if (!partitions[i].ptEntry.Offset.HuffmanCompressed
                    && partitions[i].ptEntry.Length >= sizeof(CPD_MANIFEST_HEADER)) {
                    const CPD_MANIFEST_HEADER* manifestHeader = (const CPD_MANIFEST_HEADER*) partition.constData();
                    if (manifestHeader->HeaderId == ME_MANIFEST_HEADER_ID) {
                        UByteArray header = partition.left(manifestHeader->HeaderLength * sizeof(UINT32));
                        UByteArray body = partition.mid(manifestHeader->HeaderLength * sizeof(UINT32));
                        
                        info = usprintf("Full size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)"
                                        "\nHeader type: %u\nHeader length: %Xh (%u)\nHeader version: %Xh\nFlags: %08Xh\nVendor: %Xh\n"
                                        "Date: %Xh\nSize: %Xh (%u)\nVersion: %u.%u.%u.%u\nSecurity version number: %u\nModulus size: %Xh (%u)\nExponent size: %Xh (%u)",
                                        (UINT32)partition.size(), (UINT32)partition.size(),
                                        (UINT32)header.size(), (UINT32)header.size(),
                                        (UINT32)body.size(), (UINT32)body.size(),
                                        manifestHeader->HeaderType,
                                        manifestHeader->HeaderLength * (UINT32)sizeof(UINT32), manifestHeader->HeaderLength * (UINT32)sizeof(UINT32),
                                        manifestHeader->HeaderVersion,
                                        manifestHeader->Flags,
                                        manifestHeader->Vendor,
                                        manifestHeader->Date,
                                        manifestHeader->Size * (UINT32)sizeof(UINT32), manifestHeader->Size * (UINT32)sizeof(UINT32),
                                        manifestHeader->VersionMajor, manifestHeader->VersionMinor, manifestHeader->VersionBugfix, manifestHeader->VersionBuild,
                                        manifestHeader->SecurityVersion,
                                        manifestHeader->ModulusSize * (UINT32)sizeof(UINT32), manifestHeader->ModulusSize * (UINT32)sizeof(UINT32),
                                        manifestHeader->ExponentSize * (UINT32)sizeof(UINT32), manifestHeader->ExponentSize * (UINT32)sizeof(UINT32));
                        
                        // Add tree item
                        UModelIndex partitionIndex = model->addItem(localOffset + partitions[i].ptEntry.Offset.Offset, Types::CpdPartition, Subtypes::ManifestCpdPartition, name, UString(), info, header, body, UByteArray(), Fixed, parent);
                        
                        // Parse data as extensions area
                        // Add the header size as a local offset
                        // Since the body starts after the header length
                        parseCpdExtensionsArea(partitionIndex, (UINT32)header.size());
                    }
                }
            }
            // It's a metadata
            else if (name.endsWith(".met")) {
                info = usprintf("Full size: %Xh (%u)\nHuffman compressed: ",
                                (UINT32)partition.size(), (UINT32)partition.size())
                + (partitions[i].ptEntry.Offset.HuffmanCompressed ? "Yes" : "No");
                
                // Calculate SHA256 hash over the metadata and add it to its info
                UByteArray hash(SHA256_HASH_SIZE, '\x00');
                sha256(partition.constData(), partition.size(), hash.data());
                info += UString("\nMetadata hash: ") + UString(hash.toHex().constData());
                
                // Add three item
                UModelIndex partitionIndex = model->addItem(localOffset + partitions[i].ptEntry.Offset.Offset, Types::CpdPartition,  Subtypes::MetadataCpdPartition, name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, parent);
                
                // Parse data as extensions area
                parseCpdExtensionsArea(partitionIndex, 0);
            }
            // It's a code
            else {
                info = usprintf("Full size: %Xh (%u)\nHuffman compressed: ",
                                (UINT32)partition.size(), (UINT32)partition.size())
                + (partitions[i].ptEntry.Offset.HuffmanCompressed ? "Yes" : "No");
                
                // Calculate SHA256 hash over the code and add it to its info
                UByteArray hash(SHA256_HASH_SIZE, '\x00');
                sha256(partition.constData(), partition.size(), hash.data());
                info += UString("\nHash: ") + UString(hash.toHex().constData());
                
                UModelIndex codeIndex = model->addItem(localOffset + partitions[i].ptEntry.Offset.Offset, Types::CpdPartition, Subtypes::CodeCpdPartition, name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, parent);
                (void) parseRawArea(codeIndex);
            }
        }
        else if (partitions[i].type == Types::Padding) {
            UByteArray partition = region.mid(partitions[i].ptEntry.Offset.Offset, partitions[i].ptEntry.Length);
            
            // Get info
            name = UString("Padding");
            info = usprintf("Full size: %Xh (%u)", (UINT32)partition.size(), (UINT32)partition.size());
            
            // Add tree item
            model->addItem(localOffset + partitions[i].ptEntry.Offset.Offset, Types::Padding, getPaddingType(partition), name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, parent);
        }
        else {
            msg(usprintf("%s: CPD partition of unknown type found", __FUNCTION__), parent);
            return U_INVALID_ME_PARTITION_TABLE;
        }
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseCpdExtensionsArea(const UModelIndex & index, const UINT32 localOffset)
{
    if (!index.isValid()) {
        return U_INVALID_PARAMETER;
    }
    
    UByteArray body = model->body(index);
    UINT32 offset = 0;
    while (offset < (UINT32)body.size()) {
        const CPD_EXTENTION_HEADER* extHeader = (const CPD_EXTENTION_HEADER*) (body.constData() + offset);
        if (extHeader->Length > 0
            && extHeader->Length <= ((UINT32)body.size() - offset)) {
            UByteArray partition = body.mid(offset, extHeader->Length);
            
            UString name = cpdExtensionTypeToUstring(extHeader->Type);
            UString info = usprintf("Full size: %Xh (%u)\nType: %Xh", (UINT32)partition.size(), (UINT32)partition.size(), extHeader->Type);
            
            // Parse Signed Package Info a bit further
            UModelIndex extIndex;
            if (extHeader->Type == CPD_EXT_TYPE_SIGNED_PACKAGE_INFO) {
                UByteArray header = partition.left(sizeof(CPD_EXT_SIGNED_PACKAGE_INFO));
                UByteArray data = partition.mid(header.size());
                
                const CPD_EXT_SIGNED_PACKAGE_INFO* infoHeader = (const CPD_EXT_SIGNED_PACKAGE_INFO*)header.constData();
                
                info = usprintf("Full size: %Xh (%u)\nHeader size: %Xh (%u)\nBody size: %Xh (%u)\nType: %Xh\n"
                                "Package name: %.4s\nVersion control number: %Xh\nSecurity version number: %Xh\n"
                                "Usage bitmap: %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                                (UINT32)partition.size(), (UINT32)partition.size(),
                                (UINT32)header.size(), (UINT32)header.size(),
                                (UINT32)body.size(), (UINT32)body.size(),
                                infoHeader->ExtensionType,
                                infoHeader->PackageName,
                                infoHeader->Vcn,
                                infoHeader->Svn,
                                infoHeader->UsageBitmap[0],  infoHeader->UsageBitmap[1],  infoHeader->UsageBitmap[2],  infoHeader->UsageBitmap[3],
                                infoHeader->UsageBitmap[4],  infoHeader->UsageBitmap[5],  infoHeader->UsageBitmap[6],  infoHeader->UsageBitmap[7],
                                infoHeader->UsageBitmap[8],  infoHeader->UsageBitmap[9],  infoHeader->UsageBitmap[10], infoHeader->UsageBitmap[11],
                                infoHeader->UsageBitmap[12], infoHeader->UsageBitmap[13], infoHeader->UsageBitmap[14], infoHeader->UsageBitmap[15]);
                
                // Add tree item
                extIndex = model->addItem(offset + localOffset, Types::CpdExtension, 0, name, UString(), info, header, data, UByteArray(), Fixed, index);
                parseSignedPackageInfoData(extIndex);
            }
            // Parse IFWI Partition Manifest a bit further
            else if (extHeader->Type == CPD_EXT_TYPE_IFWI_PARTITION_MANIFEST) {
                const CPD_EXT_IFWI_PARTITION_MANIFEST* attrHeader = (const CPD_EXT_IFWI_PARTITION_MANIFEST*)partition.constData();
                
                // Check HashSize to be sane.
                UINT32 hashSize = attrHeader->HashSize;
                bool msgHashSizeMismatch = false;
                if (hashSize > sizeof(attrHeader->CompletePartitionHash)) {
                    hashSize = sizeof(attrHeader->CompletePartitionHash);
                    msgHashSizeMismatch = true;
                }
                
                // This hash is stored reversed
                // Need to reverse it back to normal
                UByteArray hash((const char*)&attrHeader->CompletePartitionHash, hashSize);
                std::reverse(hash.begin(), hash.end());
                
                info = usprintf("Full size: %Xh (%u)\nType: %Xh\n"
                                "Partition name: %.4s\nPartition length: %Xh\nPartition version major: %Xh\nPartition version minor: %Xh\n"
                                "Data format version: %Xh\nInstance ID: %Xh\nHash algorithm: %Xh\nHash size: %Xh\nAction on update: %Xh",
                                (UINT32)partition.size(), (UINT32)partition.size(),
                                attrHeader->ExtensionType,
                                attrHeader->PartitionName,
                                attrHeader->CompletePartitionLength,
                                attrHeader->PartitionVersionMajor, attrHeader->PartitionVersionMinor,
                                attrHeader->DataFormatVersion,
                                attrHeader->InstanceId,
                                attrHeader->HashAlgorithm,
                                attrHeader->HashSize,
                                attrHeader->ActionOnUpdate)
                + UString("\nSupport multiple instances: ") + (attrHeader->SupportMultipleInstances ? "Yes" : "No")
                + UString("\nSupport API version based update: ") + (attrHeader->SupportApiVersionBasedUpdate ? "Yes" : "No")
                + UString("\nObey full update rules: ") + (attrHeader->ObeyFullUpdateRules ? "Yes" : "No")
                + UString("\nIFR enable only: ") + (attrHeader->IfrEnableOnly ? "Yes" : "No")
                + UString("\nAllow cross point update: ") + (attrHeader->AllowCrossPointUpdate ? "Yes" : "No")
                + UString("\nAllow cross hotfix update: ") + (attrHeader->AllowCrossHotfixUpdate ? "Yes" : "No")
                + UString("\nPartial update only: ") + (attrHeader->PartialUpdateOnly ? "Yes" : "No")
                + UString("\nPartition hash: ") +  UString(hash.toHex().constData());
                
                // Add tree item
                extIndex = model->addItem(offset + localOffset, Types::CpdExtension, 0, name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, index);
                if (msgHashSizeMismatch) {
                    msg(usprintf("%s: IFWI Partition Manifest hash size is %u, maximum allowed is %u, truncated", __FUNCTION__, attrHeader->HashSize, (UINT32)sizeof(attrHeader->CompletePartitionHash)), extIndex);
                }
            }
            // Parse Module Attributes a bit further
            else if (extHeader->Type == CPD_EXT_TYPE_MODULE_ATTRIBUTES) {
                const CPD_EXT_MODULE_ATTRIBUTES* attrHeader = (const CPD_EXT_MODULE_ATTRIBUTES*)partition.constData();
                int hashSize = (UINT32)partition.size() - CpdExtModuleImageHashOffset;
                
                // This hash is stored reversed
                // Need to reverse it back to normal
                UByteArray hash((const char*)attrHeader + CpdExtModuleImageHashOffset, hashSize);
                std::reverse(hash.begin(), hash.end());
                
                info = usprintf("Full size: %Xh (%u)\nType: %Xh\n"
                                "Compression type: %Xh\nUncompressed size: %Xh (%u)\nCompressed size: %Xh (%u)\nGlobal module ID: %Xh\nImage hash: ",
                                (UINT32)partition.size(), (UINT32)partition.size(),
                                attrHeader->ExtensionType,
                                attrHeader->CompressionType,
                                attrHeader->UncompressedSize, attrHeader->UncompressedSize,
                                attrHeader->CompressedSize, attrHeader->CompressedSize,
                                attrHeader->GlobalModuleId) + UString(hash.toHex().constData());
                
                // Add tree item
                extIndex = model->addItem(offset + localOffset, Types::CpdExtension, 0, name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, index);
            }
            // Parse everything else
            else {
                // Add tree item, if needed
                extIndex = model->addItem(offset + localOffset, Types::CpdExtension, 0, name, UString(), info, UByteArray(), partition, UByteArray(), Fixed, index);
            }
            
            // There needs to be a more generic way to do it, but it is fine for now
            if (extHeader->Type > CPD_EXT_TYPE_TBT_METADATA
                && extHeader->Type != CPD_EXT_TYPE_GMF_CERTIFICATE
                && extHeader->Type != CPD_EXT_TYPE_GMF_BODY
                && extHeader->Type != CPD_EXT_TYPE_KEY_MANIFEST_EXT
                && extHeader->Type != CPD_EXT_TYPE_SIGNED_PACKAGE_INFO_EXT
                && extHeader->Type != CPD_EXT_TYPE_SPS_PLATFORM_ID) {
                msg(usprintf("%s: CPD extension of unknown type found", __FUNCTION__), extIndex);
            }
            
            offset += extHeader->Length;
        }
        else break;
        // TODO: add padding at the end
    }
    
    return U_SUCCESS;
}

USTATUS FfsParser::parseSignedPackageInfoData(const UModelIndex & index)
{
    if (!index.isValid()) {
        return U_INVALID_PARAMETER;
    }
    
    UByteArray body = model->body(index);
    UINT32 offset = 0;
    while (offset < (UINT32)body.size()) {
        const CPD_EXT_SIGNED_PACKAGE_INFO_MODULE* moduleHeader = (const CPD_EXT_SIGNED_PACKAGE_INFO_MODULE*)(body.constData() + offset);
        if (sizeof(CPD_EXT_SIGNED_PACKAGE_INFO_MODULE) <= ((UINT32)body.size() - offset)) {
            // TODO: check sanity of moduleHeader->HashSize
            UByteArray module((const char*)moduleHeader, CpdExtSignedPkgMetadataHashOffset + moduleHeader->HashSize);
            UString name = usprintf("%.12s", moduleHeader->Name);
            
            // This hash is stored reversed
            // Need to reverse it back to normal
            UByteArray hash((const char*)moduleHeader + CpdExtSignedPkgMetadataHashOffset, moduleHeader->HashSize);
            std::reverse(hash.begin(), hash.end());
            
            UString info = usprintf("Full size: %Xh (%u)\nType: %Xh\nHash algorithm: %Xh\nHash size: %Xh (%u)\nMetadata size: %Xh (%u)\nMetadata hash: ",
                                    (UINT32)module.size(), (UINT32)module.size(),
                                    moduleHeader->Type,
                                    moduleHeader->HashAlgorithm,
                                    moduleHeader->HashSize, moduleHeader->HashSize,
                                    moduleHeader->MetadataSize, moduleHeader->MetadataSize) + UString(hash.toHex().constData());
            // Add tree otem
            model->addItem(offset, Types::CpdSpiEntry, 0, name, UString(), info, UByteArray(), module, UByteArray(), Fixed, index);
            offset += module.size();
        }
        else break;
        // TODO: add padding at the end
    }
    
    return U_SUCCESS;
}

void FfsParser::outputInfo(void) {
    // Show ffsParser's messages
    std::vector<std::pair<UString, UModelIndex> > messages = getMessages();
    for (size_t i = 0; i < messages.size(); i++) {
        std::cout << (const char *)messages[i].first.toLocal8Bit() << std::endl;
    }
    
    // Get last VTF
    std::vector<std::pair<std::vector<UString>, UModelIndex > > fitTable = getFitTable();
    if (fitTable.size()) {
        std::cout << "---------------------------------------------------------------------------" << std::endl;
        std::cout << "     Address      |   Size    |  Ver  | CS  |          Type / Info          " << std::endl;
        std::cout << "---------------------------------------------------------------------------" << std::endl;
        for (size_t i = 0; i < fitTable.size(); i++) {
            std::cout
            << (const char *)fitTable[i].first[0].toLocal8Bit() << " | "
            << (const char *)fitTable[i].first[1].toLocal8Bit() << " | "
            << (const char *)fitTable[i].first[2].toLocal8Bit() << " | "
            << (const char *)fitTable[i].first[3].toLocal8Bit() << " | "
            << (const char *)fitTable[i].first[4].toLocal8Bit() << " | "
            << (const char *)fitTable[i].first[5].toLocal8Bit() << std::endl;
        }
    }
    
    // Get security info
    UString secInfo = getSecurityInfo();
    if (!secInfo.isEmpty()) {
        std::cout << "---------------------------------------------------------------------------"  << std::endl;
        std::cout << "Security Info" << std::endl;
        std::cout << "---------------------------------------------------------------------------"  << std::endl;
        std::cout << (const char *)secInfo.toLocal8Bit() << std::endl;
    }
}


// More or less AMD-specific, but can be used as common
USTATUS FfsParser::findByRange(const UINT32 base, const UINT32 size, const UModelIndex& index, UModelIndex& found)
{
    if (model->compressed(index))
        return U_ITEM_NOT_FOUND;

    // Sort by inserting
    for (int i = 0; i < model->rowCount(index); i++) {
        UModelIndex current = model->index(i, 0, index);
        UINT32 currentSize = (UINT32)model->entire(current).size();

        // Must be within the existing region
        if (base < model->base(current) || (base + size) >(model->base(current) + currentSize))
            continue;
        found = current;
        if ((base == model->base(current)) && (size == currentSize))
            return U_SUCCESS;

        findByRange(base, size, current, found);

        return U_SUCCESS;
    }
    return U_ITEM_NOT_FOUND;
}

USTATUS FfsParser::insertByRange(UINT32 offset, const UINT8 type, const UINT8 subtype,
    const UString name, const UString text, const UString info,
    const UINT32 hdrSize, const UINT32 bodySize, const UINT32 tailSize,
    const UModelIndex& parent, UModelIndex& index)
{
    UModelIndex containerIndex = imageIndex(parent);
    const UString parentName = model->type(parent) == Types::Image ? UString() : model->name(parent);
    const UINT32 imageBase = model->base(containerIndex) + offset;
    const UINT32 imageSize = (const UINT32)model->entire(containerIndex).size();
    const UINT32 fullSize = offset + hdrSize + bodySize + tailSize > imageSize ? imageSize - offset : hdrSize + bodySize + tailSize;

    UModelIndex foundIndex;
    USTATUS result = findByRange(imageBase, fullSize, containerIndex, foundIndex);
    UString parentInfo = UString("Parent: ");
    if (model->type(parent) == Types::DirectoryTableEntry) {
        parentInfo += model->name(model->parent(parent))
            + usprintf(" (entry %d)", static_cast<TreeItem*>(parent.internalPointer())->row() + 1)
            + usprintf(", base: %Xh\n", model->base(model->parent(parent)));
    }
    else
        parentInfo += model->name(parent) + usprintf(", base: %Xh\n", model->base(parent));
    if (result == U_SUCCESS && foundIndex.isValid()) {
        if (model->type(foundIndex) == type && model->subtype(foundIndex) == subtype
            && model->base(foundIndex) == imageBase && model->entire(foundIndex).size() == fullSize)
        {
            index = foundIndex;
            if (static_cast<TreeItem*>(parent.internalPointer()) != static_cast<TreeItem*>(index.internalPointer())->parent())
                model->addInfo(index, parentInfo);
            msg(usprintf("%s: skipping already added item at %Xh: ", __FUNCTION__, offset) + model->name(index), index);
            return U_DIR_ALREADY_EXIST;
        }
        containerIndex = foundIndex;
    }

    // Sort by inserting
    UINT8 mode = CREATE_MODE_APPEND;
    UModelIndex insertIndex = containerIndex;
    TreeItem* parentItem = static_cast<TreeItem*>(containerIndex.internalPointer());
    for (int i = 0; i < model->rowCount(containerIndex); i++) {
        UModelIndex current = model->index(i, 0, containerIndex);
        if (model->base(current) > imageBase) {
            mode = CREATE_MODE_BEFORE;
            insertIndex = current;
            parentItem = static_cast<TreeItem*>(containerIndex.internalPointer());
            break;
        }
    }

    const UINT32 realHdrSize = hdrSize > fullSize ? fullSize : hdrSize;
    const UINT32 realBodySize = bodySize > fullSize - realHdrSize ? fullSize - realHdrSize : bodySize;
    const UINT32 realTailSize = tailSize > fullSize - realHdrSize - realBodySize ? fullSize - realHdrSize - realBodySize : tailSize;
    UString itemInfo = usprintf("Full size: %Xh (%u)\n", fullSize, fullSize);
    if (realHdrSize > 0) {
        itemInfo += usprintf("Header size: %Xh (%u)\nBody size: %Xh (%u)\n",
            realHdrSize, realHdrSize, realBodySize, realBodySize);
        if (realTailSize > 0)
            itemInfo += usprintf("Tail size: %Xh (%u)\n", realTailSize, realTailSize);
    }
    itemInfo += info;
    if (static_cast<TreeItem*>(parent.internalPointer()) != parentItem)
        itemInfo += parentInfo;

    // Add directory file tree item
    const UINT32 hdrOffset = imageBase - model->base(containerIndex);
    const UINT32 bodyOffset = hdrOffset + realHdrSize;
    const UINT32 tailOffset = bodyOffset + realBodySize;
    const UByteArray containerImage = model->entire(containerIndex);
    index = model->addItem(hdrOffset, type, subtype, name, text, itemInfo,
        containerImage.mid(hdrOffset, realHdrSize), containerImage.mid(bodyOffset, realBodySize), containerImage.mid(tailOffset, realTailSize),
        Fixed, insertIndex, mode);

    return U_SUCCESS;
}


// Convert the ID to known file names
UString FfsParser::pspFileName(const UINT8 type, const UINT8 sub)
{
    UString fileName;

    switch (type) {
        // PSP types
        case AMD_FW_PSP_PUBKEY:         fileName = "PSP public key"; break;
        case AMD_FW_PSP_BOOTLOADER:     fileName = "PSP initial bootloader"; break;
        case AMD_FW_PSP_SECURED_OS:     fileName = "PSP secured OS"; break;
        case AMD_FW_PSP_RECOVERY:       fileName = "PSP recovery bootloader"; break;
        case AMD_FW_PSP_NVRAM:          fileName = "PSP NVRAM"; break;
        case AMD_FW_RTM_PUBKEY:         fileName = "BIOS RTM public key"; break;
        case AMD_FW_BIOS_RTM:           fileName = "BIOS RTM firmware"; break;
        case AMD_FW_PSP_SMU_FIRMWARE:   fileName = "SMU firmware"; break;
        case AMD_FW_PSP_SECURED_DEBUG:  fileName = "PSP secured debug"; break;
        case AMD_FW_ABL_PUBKEY:         fileName = "AGESA bootloader public key"; break;
        case AMD_PSP_FUSE_CHAIN:        fileName = "PSP fuse chain"; break;
        case AMD_FW_PSP_TRUSTLETS:      fileName = "PSP trustlets"; break;
        case AMD_FW_PSP_TRUSTLETKEY:    fileName = "PSP trustlet key"; break;
        case AMD_FW_AGESA_RESUME:       fileName = "AGESA resume firmware"; break;
        case AMD_FW_PSP_SMU_FIRMWARE2:  fileName = "SMU firmware 2"; break;
        case AMD_DEBUG_UNLOCK:          fileName = "PSP debug unlock"; break;
        case AMD_PSP_MCLF_TRUSTLETS:    fileName = "PSP MCLF trustlets"; break;
        case AMD_FW_PSP_TEEIPKEY:       fileName = "PSP TEE IP key"; break;
        case AMD_SEV_DRIVER:            fileName = "SEV driver"; break;
        case AMD_BOOT_DRIVER:           fileName = "Boot driver"; break;
        case AMD_SOC_DRIVER:            fileName = "SoC driver"; break;
        case AMD_DEBUG_DRIVER:          fileName = "Debug driver"; break;
        case AMD_INTERFACE_DRIVER:      fileName = "Interface driver"; break;
        case AMD_HW_IPCFG:              fileName = "HW IP configuration"; break;
        case AMD_WRAPPED_IKEK:          fileName = "Wrapped IKeK"; break;
        case AMD_TOKEN_UNLOCK:          fileName = "Token unlock"; break;
        case AMD_SEC_GASKET:            fileName = "Security gasket firmware"; break;
        case AMD_MP2_FW:                fileName = "MP2 firmware"; break;
        case AMD_DRIVER_ENTRIES:        fileName = "Driver entries"; break;
        case AMD_FW_KVM_IMAGE:          fileName = "KVM image"; break;
        case AMD_FW_MP5:                fileName = "MP5 firmware"; break;
        case AMD_S0I3_DRIVER:           fileName = "S0i3 driver"; break;
        case AMD_ABL0:                  fileName = "AGESA bootloader stage 0"; break;
        case AMD_ABL1:                  fileName = "AGESA bootloader stage 1"; break;
        case AMD_ABL2:                  fileName = "AGESA bootloader stage 2"; break;
        case AMD_ABL3:                  fileName = "AGESA bootloader stage 3"; break;
        case AMD_ABL4:                  fileName = "AGESA bootloader stage 4"; break;
        case AMD_ABL5:                  fileName = "AGESA bootloader stage 5"; break;
        case AMD_ABL6:                  fileName = "AGESA bootloader stage 6"; break;
        case AMD_ABL7:                  fileName = "AGESA bootloader stage 7"; break;
        case AMD_SEV_DATA:              fileName = "SEV data"; break;
        case AMD_SEV_CODE:              fileName = "SEV code"; break;
        case AMD_FW_PSP_WHITELIST:      fileName = "PSP whitelist"; break;
        case AMD_VBIOS_BTLOADER:        fileName = "Video BIOS bootloader"; break;
        case AMD_FW_L2_PTR:             fileName = "PSP L2 directory"; break;
        case AMD_FW_DXIO:               fileName = "DXIO firmware"; break;
        case AMD_FW_USB_PHY:            fileName = "USB PHY firmware"; break;
        case AMD_FW_TOS_SEC_POLICY:     fileName = "TOS security policy"; break;
        case AMD_EFS_BACKUP:            fileName = "EFS backup"; break;
        case AMD_FW_DRTM_TA:            fileName = "DRTM trusted application"; break;
        case AMD_FW_RECOVERYAB_A:       fileName = "RecoveryAB A"; break;
        case AMD_FW_RECOVERYAB_B:       fileName = "RecoveryAB B"; break;
        case AMD_FW_BIOS_TABLE:         fileName = "BIOS table"; break;
        case AMD_FW_KEYDB_BL:           fileName = "Bootloader key database"; break;
        case AMD_FW_KEYDB_TOS:          fileName = "TOS key database"; break;
        case AMD_FW_PSP_VERSTAGE:       fileName = "PSP verstage firmware"; break;
        case AMD_FW_VERSTAGE_SIG:       fileName = "Verstage signature"; break;
        case AMD_RPMC_NVRAM:            fileName = "Replay-protected NVRAM"; break;
        case AMD_FW_SPL:                fileName = "Security policy loader"; break;
        case AMD_FW_DMCU_ERAM:          fileName = "Embedded RAM display MCU"; break;
        case AMD_FW_DMCU_ISR:           fileName = "ISR display MCU"; break;
        case AMD_FW_MSMU:               fileName = "Management SMU microcode"; break;
        case AMD_FW_SPIROM_CFG:         fileName = "SPI ROM configuration"; break;
        case AMD_FW_MPIO:               fileName = "MPIO firmware"; break;
        case AMD_FW_TPMLITE:            fileName = "TPM lite"; break; // family 17h & 19h, family 15h & 16h: AMD_FW_PSP_SMUSCS "PSP SMU SCS"
        case AMD_FW_DMCUB:              fileName = "Display MCU-B firmware"; break;
        case AMD_FW_PSP_BOOTLOADER_AB:  fileName = "PSP recovery A/B bootloader"; break;
        case AMD_RIB:                   fileName = "RoT image bundle"; break;
        case AMD_FW_AMF_SRAM:           fileName = "AMF SRAM"; break;
        case AMD_FW_AMF_DRAM:           fileName = "AMF DRAM"; break;
        case AMD_FW_MFD_MPM:            fileName = "MFD MPM"; break;
        case AMD_FW_AMF_WLAN:           fileName = "AMF WLAN"; break;
        case AMD_FW_AMF_MFD:            fileName = "AMF MFD"; break;
        case AMD_FW_MPDMA_TF:           fileName = "MPDMA test firmware"; break;
        case AMD_TA_IKEK:               fileName = "TA IKeK"; break;
        case AMD_FW_MPCCX:              fileName = "MPCCX"; break;
        case AMD_FW_GMI3_PHY:           fileName = "GMI3 PHY"; break;
        case AMD_FW_MPDMA_PM:           fileName = "MPDMA power management"; break;
        case AMD_FW_LSDMA:              fileName = "LSDMA"; break;
        case AMD_FW_C20_MP:             fileName = "C20 MP"; break;
        case AMD_FW_FCFG_TABLE:         fileName = "Factory configuration"; break;
        case AMD_FW_MINIMSMU:           fileName = "Mini-SMU"; break;
        case AMD_FW_GFXIMU_0:           fileName = "GFX IMU 0"; break;
        case AMD_FW_GFXIMU_1:           fileName = "GFX IMU 1"; break;
        case AMD_FW_GFXIMU_2:           fileName = "GFX IMU 2"; break; // AMD_FW_SRAM_FW_EXT
        case AMD_FW_TOS_WL_BIN:         fileName = "TOS whitelist"; break;
        case AMD_FW_S3IMG:              fileName = "S3 image"; break;
        case AMD_FW_UMSMU:              fileName = "Unified management SMU"; break;
        case AMD_FW_USBDP:              fileName = "USB DisplayPort"; break;
        case AMD_FW_USBSS:              fileName = "USB SuperSpeed"; break;
        case AMD_FW_USB4:               fileName = "USB4"; break;
        // BIOS types
        case AMD_BIOS_SIG:              fileName = "BIOS signature"; break;
        case AMD_BIOS_APCB:             fileName = "AMD Platform Configuration Block"; break;
        case AMD_BIOS_APOB:             fileName = "AMD Platform Override Block"; break;
        case AMD_BIOS_BIN:              fileName = "BIOS binary"; break;
        case AMD_BIOS_APOB_NV:          fileName = "APOB non-volatile"; break;
        case AMD_BIOS_PMUI:             fileName = "PMU firmware"; break;
        case AMD_BIOS_PMUD:             fileName = "PMU data"; break;
        case AMD_BIOS_UCODE:            fileName = "CPU microcode patch"; break;
        case AMD_BIOS_FHP_DRIVER:       fileName = "FHP driver"; break;
        case AMD_BIOS_APCB_BK:          fileName = "APCB backup"; break;
        case AMD_BIOS_EARLY_VGA:        fileName = "Early video BIOS"; break;
        case AMD_BIOS_MP2_CFG:          fileName = "MP2 configuration"; break;
        case AMD_BIOS_PSP_SHARED_MEM:   fileName = "PSP shared memory descriptor"; break;
        case AMD_BIOS_L2_PTR:           fileName = "BIOS L2 directory"; break;
        // Unknown type
        default:                        fileName = usprintf("unknown"); break;
    }

    return fileName;
}

UINT32 FfsParser::pspDirectoryOffset(const UByteArray& amdImage, const UINT32 offset)
{
    AMD_ADDRESS_ADDRESSMODE am;
    am.Address = offset;
    am.AddrMode = AMD_ADDR_PHYSICAL;
    return pspFileOffset(amdImage, 0, 0, 4, am);
}

UINT32 FfsParser::pspFileOffset(const UByteArray& amdImage, const UINT32 offset, const UINT32 entryOffset,
    const UINT32 size, const AMD_ADDRESS_ADDRESSMODE& addressMode)
{
    // Since we are operating on the BIOS/bank image, physical address is converted relative to the start of the BIOS/bank image.
    UINT64 addr = addressMode.Address;
    if (addr >= UINT32_MAX || size < 4 || size == UINT32_MAX)
        return UINT32_MAX;
    switch (addressMode.AddrMode) {
        case AMD_ADDR_PHYSICAL:
            // CPU physical
            if (addr >= pspSpiRomBase && addr < UINT32_MAX)
                addr -= pspSpiRomBase;
            break;
        case AMD_ADDR_REL_TABLE:
            // relative to table = parent of an entry (slot)
            addr += offset;
            break;
        case AMD_ADDR_REL_SLOT:
            // relative to an entry (slot)
            addr += entryOffset;
            break;
        default: // same as case AMD_ADDR_REL_BIOS:
            // relative to a BIOS/bank image
            break;
    }

    if (pspMaxOffset < addr + size)
        pspMaxOffset = addr + size;

    if (addr > amdImage.size())
        return UINT32_MAX;

    return (UINT32)addr;
}

USTATUS FfsParser::decompressBios(const UByteArray& fileImage, UByteArray& decompressed)
{
    USTATUS result;

    if (fileImage.size() < 256) {
        return U_BUFFER_TOO_SMALL;
    }
    result = zlibDecompress(fileImage.mid(256, fileImage.size() - 256), decompressed);
    if (result) {
        return result;
    }

    return U_SUCCESS;
}

USTATUS FfsParser::pspParseISHDirectory(const UByteArray& amdImage, const UINT32 offset, const UModelIndex& parent, UModelIndex& index, const bool probe)
{
    if (offset + sizeof(AMD_ISH_DIRECTORY_TABLE) > amdImage.size())
        return U_BUFFER_TOO_SMALL;

    // Parse ISH table
    const AMD_ISH_DIRECTORY_TABLE* tbl = (const AMD_ISH_DIRECTORY_TABLE*)(amdImage.constData() + offset);
    const UINT32 length = sizeof(AMD_ISH_DIRECTORY_TABLE);

    // Checksum starts right after checksum field
    const UINT32 checksumOffset = offsetof(AMD_ISH_DIRECTORY_TABLE, Checksum) + sizeof(AMD_ISH_DIRECTORY_TABLE::Checksum); // Start after checksum field
    UByteArray data = amdImage.mid(offset + checksumOffset, length - checksumOffset);
    const UINT32 checksum = fletcher32(data);
    if (checksum != tbl->Checksum) {
        if (!probe)
            msg(usprintf("%s: ISH directory table at offset %Xh checksum is invalid", __FUNCTION__, offset), parent);
    }

    const UINT32 dirOffset = pspDirectoryOffset(amdImage, tbl->L2Address);
    if (checksum != tbl->Checksum && dirOffset == UINT32_MAX) {
        if (!probe)
            msg(usprintf("%s: unknown directory table at offset %Xh", __FUNCTION__, offset), parent);
        return U_INVALID_PARAMETER;
    }

    // Add ISH directory image tree item
    USTATUS result;
    if (!probe) {
        const UString dirName = "ISH directory table";
        if (model->type(parent) == Types::DirectoryTableEntry)
            model->setName(parent, model->name(parent) + dirName);
        const UString baseInfo = dirOffset < UINT32_MAX ? usprintf("base: %Xh\n", offsetToBase(parent, dirOffset)) : "invalid\n";
        UString details = usprintf("Checksum: %08Xh, ", tbl->Checksum)
            + (checksum == tbl->Checksum ? "valid\n" : usprintf("invalid, should be %08Xh\n", checksum))
            + usprintf("PSP L2 location: %Xh, ", tbl->L2Address) + baseInfo;
        details += usprintf("Boot priority: %08Xh (%s)\nSlot max size: %Xh (%u)\nPspId: %08Xh\n",
            tbl->BootPriority, tbl->BootPriority == 0xFFFFFFFF ? " (primary)" : tbl->BootPriority == 1 ? " (secondary)" : "",
            tbl->SlotMaxSize, tbl->SlotMaxSize,
            tbl->PspId);
        result = insertByRange(offset, Types::DirectoryTable, Subtypes::ISHDirectory,
            dirName, UString(), details,
            0, length, 0,
            parent, index);
        if (result != U_SUCCESS && result != U_DIR_ALREADY_EXIST)
            return result;
        if (result == U_DIR_ALREADY_EXIST)
            return U_SUCCESS;
    }

    if (dirOffset < UINT32_MAX) {
        // Add PSP L2 directory tree item
        UModelIndex childIndex;
        result = pspParseDirectory(amdImage, dirOffset, Subtypes::PSPDirectory, index, childIndex, probe);
        if (result != U_SUCCESS) {
            if (!probe)
                msg(usprintf("%s: failed to parse PSP directory table pointed to by ISH directory table", __FUNCTION__), index);
            return result;
        }
    }
    else {
        if (!probe)
            msg(usprintf("%s: PSP directory table location (%Xh) is invalid", __FUNCTION__, tbl->L2Address), parent);
    }

    return U_SUCCESS;
}

USTATUS FfsParser::pspParseComboEntries(const UByteArray& amdImage, const UINT32 offset, const UINT32 headerSize, const UINT32 numEntries,
    const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    const Subtypes::DirectorySubtypes type = Subtypes::ComboDirectory;

    for (int i = 0; i < numEntries; i++) {
        USTATUS result = U_ELEMENTS_NOT_FOUND;
        const UINT32 entryOffset = offset + headerSize + i * sizeof(AMD_PSP_COMBO_ENTRY);
        const AMD_PSP_COMBO_ENTRY& e = *(AMD_PSP_COMBO_ENTRY*)(amdImage.constData() + entryOffset);

        // Add PSP table entry image tree item
        UString entryText;
        UModelIndex childIndex;
        const UINT32 dirOffset = pspDirectoryOffset(amdImage, e.L2Address);
        if (!probe) {
            const UString baseInfo = dirOffset < UINT32_MAX ? usprintf("base: %Xh\n", offsetToBase(parent, dirOffset)) : "invalid\n";
            const UString entryInfo = usprintf("Full size: %Xh (%u)\nId select: %08Xh (by %sId)\nId: %08Xh\nL2 location: %Xh, ",
                (UINT32)sizeof(AMD_PSP_COMBO_ENTRY), (UINT32)sizeof(AMD_PSP_COMBO_ENTRY),
                e.IdSel, e.IdSel ? "Family" : "Psp", e.Id, e.L2Address) + baseInfo;
            entryText = usprintf("%sId %08Xh", e.IdSel == 0 ? "Psp" : "Family", e.Id);
            childIndex = model->addItem(
                entryOffset - offset, Types::DirectoryTableEntry, type,
                usprintf("%u - ", i + 1), entryText, entryInfo,
                UByteArray(), amdImage.mid(entryOffset, sizeof(AMD_PSP_COMBO_ENTRY)), UByteArray(),
                Fixed, parent);
        }
        UModelIndex entryIndex = childIndex;
        if (dirOffset < UINT32_MAX) {
            result = pspParseDirectory(amdImage, dirOffset, Subtypes::AnyDirectory, entryIndex, childIndex, probe);

            if (!probe) {
                if (result != U_SUCCESS)
                    msg(usprintf("%s: failed to parse directory table pointed to by Combo directory table (entry %u)", __FUNCTION__, i + 1), entryIndex);
                else {
                    UString itemText = model->text(childIndex);
                    model->setText(childIndex, itemText.isEmpty() ? entryText : itemText + ", " + entryText);
                }
            }
        }
        else {
            if (!probe)
                msg(usprintf("%s: directory table location (%Xh) pointed to by Combo directory table (entry %u) is invalid", __FUNCTION__, offset, i + 1), entryIndex);
        }
        if (result != U_SUCCESS)
            if (!probe)
                model->setName(entryIndex, model->name(entryIndex) + ": unknown directory table");
    }
    return U_SUCCESS;
}

USTATUS FfsParser::pspParseBIOSEntries(const UByteArray& amdImage, const UINT32 offset, const UINT32 headerSize, const UINT32 numEntries,
    const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    const Subtypes::DirectorySubtypes type = Subtypes::BIOSDirectory;

    for (int i = 0; i < numEntries; i++) {
        USTATUS result;
        const UINT32 entryOffset = offset + headerSize + i * sizeof(AMD_BIOS_DIRECTORY_ENTRY);
        const AMD_BIOS_DIRECTORY_ENTRY& e = *(AMD_BIOS_DIRECTORY_ENTRY*)(amdImage.constData() + entryOffset);

        const UString fileName = pspFileName(e.Type, e.SubProgram);
        const UINT32 fileOffset = pspFileOffset(amdImage, offset, entryOffset, e.Size, e.AddressMode);
        // Add BIOS table entry image tree item
        UModelIndex childIndex;
        if (!probe) {
            const UString baseInfo = fileOffset < UINT32_MAX ? usprintf("base: %Xh\n", offsetToBase(parent, fileOffset)) : "invalid\n";
            UString entryInfo = usprintf("Full size: %Xh (%u)\nType: %02Xh\nRegion type: %02Xh\nFlags: %04Xh\n"
                "  SubProgram: %01Xh\n  Instance: %01Xh\n  RomId: %01Xh\n  Reset-image: %s\n"
                "  Copy image: %s\n  Read only: %s\n  Writable: %s\n  Compressed: %s\n"
                "File size: %Xh (%u)\nFile location: %" PRIX64 "h, ",
                    (UINT32)sizeof(AMD_BIOS_DIRECTORY_ENTRY), (UINT32)sizeof(AMD_BIOS_DIRECTORY_ENTRY),
                    e.Type, e.RegionType, e.Flags.raw,
                    e.SubProgram, e.Instance, e.RomId,
                    (e.ResetImage) ? "true" : "false",
                    (e.CopyImage) ? "true" : "false",
                    (e.ReadOnly) ? "true" : "false",
                    (e.Writable) ? "true" : "false",
                    (e.Compressed) ? "true" : "false",
                    e.Size, e.Size, e.Address) + baseInfo;
            entryInfo += usprintf("Address mode: %01Xh\nDestination: %" PRIX64 "h\n", (UINT8)e.AddrMode, e.Destination);
            const UString entryText = usprintf("Type %02Xh", e.Type)
                + (e.SubProgram ? usprintf(", SubProgram %Xh", e.SubProgram) : "")
                + (e.Instance ? usprintf(", Instance %01Xh", e.Instance) : "");
            childIndex = model->addItem(entryOffset - offset, Types::DirectoryTableEntry, type,
                usprintf("%d - ", i + 1), entryText, entryInfo,
                UByteArray(), amdImage.mid(entryOffset, sizeof(AMD_BIOS_DIRECTORY_ENTRY)), UByteArray(),
                Fixed, parent);
        }
        const UModelIndex entryIndex = childIndex;

        UString nameTail = fileName + ((e.SubProgram != 0 || e.Instance != 0)
            ? usprintf(" (%X:%01X)", e.SubProgram, e.Instance) : "");
        if (fileOffset == UINT32_MAX) {
            if (!probe)
                msg(usprintf("%s: invalid location (%0" PRIX64 "h) or mode (%01Xh) for file: ", __FUNCTION__, e.Address, (UINT8)e.AddrMode) + fileName, entryIndex);
        }
        else {
            switch (e.Type) {
                case AMD_BIOS_L2_PTR:
                    result = pspParseDirectory(amdImage, fileOffset, Subtypes::BIOSDirectory, entryIndex, childIndex, probe);
                    if (result == U_SUCCESS)
                        nameTail.clear();
                    break;
                // BIOS directory regular file
                default:
                    pspFilesList.push_back({ fileOffset, e.Size, model->base(entryIndex), fileName, e.Flags.raw,
                        e.Type, (UINT8)e.SubProgram, (UINT8)e.Instance, (UINT8)e.RomId, (UINT8)e.Writable, 1,
                        (UINT8)e.ResetImage, (UINT8)e.CopyImage, (UINT8)e.ReadOnly, (UINT8)e.Compressed, e.RegionType, e.Destination });
                    result = U_SUCCESS;
                    break;
            }
            if (result != U_SUCCESS) {
                if (!probe)
                    msg(usprintf("%s: failed to parse BIOS directory file: ", __FUNCTION__) + fileName, entryIndex);
            }
        }
        if (!nameTail.isEmpty())
            if (!probe)
                model->setName(entryIndex, model->name(entryIndex) + nameTail);

    }

    return U_SUCCESS;
}

USTATUS FfsParser::pspParsePSPEntries(const UByteArray& amdImage, const UINT32 offset, const UINT32 headerSize, const UINT32 numEntries,
    const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    const Subtypes::DirectorySubtypes type = Subtypes::PSPDirectory;

    for (int i = 0; i < numEntries; i++) {
        USTATUS result;
        const UINT32 entryOffset = offset + headerSize + i * sizeof(AMD_PSP_DIRECTORY_ENTRY);
        const AMD_PSP_DIRECTORY_ENTRY& e = *(AMD_PSP_DIRECTORY_ENTRY*)(amdImage.constData() + entryOffset);

        const UString fileName = pspFileName(e.Type, e.SubProgram);
        const UINT32 fileOffset = pspFileOffset(amdImage, offset, entryOffset, e.Size, e.AddressMode);
        // Add PSP table entry image tree item
        UModelIndex childIndex;
        if (!probe) {
            const UString baseInfo = fileOffset < UINT32_MAX ? usprintf("base: %Xh\n", offsetToBase(parent, fileOffset)) : "invalid\n";
            UString entryInfo = usprintf("Full size: %Xh (%u)\nType: %02Xh\nSubProgram: %02Xh\nFlags: %04Xh\n"
                "  Instance: %01Xh\n  RomId: %01Xh\n  Writable: %s\n"
                "File size: %Xh (%u)\nFile location: %" PRIX64 "h, ",
                    (UINT32)sizeof(AMD_PSP_DIRECTORY_ENTRY), (UINT32)sizeof(AMD_PSP_DIRECTORY_ENTRY),
                    e.Type, e.SubProgram, e.Flags.raw,
                    e.Instance, e.RomId, (e.Writable) ? "true" : "false",
                    e.Size, e.Size, e.Address) + baseInfo;
            entryInfo += usprintf("Address mode: %01Xh\n", (UINT8)e.AddrMode);
            const UString entryText = usprintf("Type %02Xh", e.Type)
                + (e.SubProgram ? usprintf(", SubProgram %Xh", e.SubProgram) : "")
                + (e.Instance ? usprintf(", Instance %01Xh", e.Instance) : "");
            childIndex = model->addItem(entryOffset - offset, Types::DirectoryTableEntry, type,
                usprintf("%d - ", i + 1), entryText, entryInfo,
                UByteArray(), amdImage.mid(entryOffset, sizeof(AMD_PSP_DIRECTORY_ENTRY)), UByteArray(),
                Fixed, parent);
        }
        const UModelIndex entryIndex = childIndex;

        UString nameTail = fileName + ((e.SubProgram != 0 || e.Instance != 0)
            ? usprintf(" (%X:%01X)", e.SubProgram, e.Instance) : "");
        if (fileOffset == UINT32_MAX) {
            if (!probe)
                msg(usprintf("%s: invalid location (%0" PRIX64 "h) or mode (%01Xh) for file: ", __FUNCTION__, e.Address, (UINT8)e.AddrMode) + fileName, entryIndex);
        }
        else {
            switch (e.Type) {
                // Special files - tables
                case AMD_FW_L2_PTR:
                case AMD_FW_RECOVERYAB_A:
                case AMD_FW_RECOVERYAB_B:
                    // Can be a PSP directory or ISH table
                    result = pspParseDirectory(amdImage, fileOffset, Subtypes::PSPDirectory, entryIndex, childIndex, probe);
                    if (result != U_SUCCESS && e.Type != AMD_FW_L2_PTR)
                        result = pspParseISHDirectory(amdImage, fileOffset, entryIndex, childIndex, probe);
                    if (result == U_SUCCESS)
                        nameTail.clear();
                    break;
                case AMD_FW_BIOS_TABLE:
                    result = pspParseDirectory(amdImage, fileOffset, Subtypes::BIOSDirectory, entryIndex, childIndex, probe);
                    if (result == U_SUCCESS)
                        nameTail.clear();
                    break;
                // PSP directory regular file
                default:
                    pspFilesList.push_back({ fileOffset, e.Size, model->base(entryIndex), fileName, e.Flags.raw,
                        e.Type, (UINT8)e.SubProgram, (UINT8)e.Instance, (UINT8)e.RomId, (UINT8)e.Writable, 0, 0, 0, 0, 0, 0, 0 });
                    result = U_SUCCESS;
                    break;
            }
            if (result != U_SUCCESS) {
                if (!probe)
                    msg(usprintf("%s: failed to parse PSP directory file: ", __FUNCTION__) + fileName, entryIndex);
            }
        }
        if (!nameTail.isEmpty())
            if (!probe)
                model->setName(entryIndex, model->name(entryIndex) + nameTail);
    }

    return U_SUCCESS;
}

// Decodes any supported PSP table found at the specified offset
USTATUS FfsParser::pspParseDirectory(const UByteArray & amdImage, const UINT32 offset, const Subtypes::DirectorySubtypes expected,
    const UModelIndex & parent, UModelIndex & index, const bool probe)
{
    Subtypes::DirectorySubtypes type;
    Subtypes::RegionSubtypes subtype;
    UString typeName;

    if (offset % 16) {
        if (!probe)
            msg(usprintf("%s: invalid offset specified: %Xh", __FUNCTION__, offset), parent);
        return U_INVALID_PARAMETER;
    }

    if ((offset + sizeof(UINT32)) > amdImage.size()) {
        if (!probe)
            msg(usprintf("%s: directory table at offset %Xh is outside of the image", __FUNCTION__, offset), parent);
        return U_BUFFER_TOO_SMALL;
    }

    const UINT32* cookie = (const UINT32*)(amdImage.constData() + offset);
    switch (*cookie) {
        case AMD_PSP_DIRECTORY_HEADER_SIGNATURE:
            type = Subtypes::PSPDirectory;
            subtype = Subtypes::PspL1DirectoryRegion;
            typeName = "PSP";
            break;
        case AMD_PSPL2_DIRECTORY_HEADER_SIGNATURE:
            type = Subtypes::PSPDirectory;
            subtype = Subtypes::PspL2DirectoryRegion;
            typeName = "PSP L2";
            break;
        case AMD_BIOS_HEADER_SIGNATURE:
            type = Subtypes::BIOSDirectory;
            subtype = Subtypes::PspL1DirectoryRegion;
            typeName = "BIOS";
            break;
        case AMD_BHDL2_HEADER_SIGNATURE:
            type = Subtypes::BIOSDirectory;
            subtype = Subtypes::PspL2DirectoryRegion;
            typeName = "BIOS L2";
            break;
        case AMD_PSP_COMBO_DIRECTORY_HEADER_SIGNATURE:
            type = Subtypes::ComboDirectory;
            subtype = Subtypes::PspL1DirectoryRegion;
            typeName = "PSP Combo";
            break;
        case AMD_PSP_BHD2_DIRECTORY_HEADER_SIGNATURE:
            type = Subtypes::ComboDirectory;
            subtype = Subtypes::PspL1DirectoryRegion;
            typeName = "BIOS Combo";
            break;
        case 0:
        case 0xFFFFFFFF:
            if (!probe)
                msg(usprintf("%s: there is no directory table at offset %Xh", __FUNCTION__, offset), parent);
            return U_UNKNOWN_ITEM_TYPE;
        default:
            if (!probe)
                msg(usprintf("%s: directory table header at offset %Xh has unsupported cookie %08Xh", __FUNCTION__, offset, *cookie), parent);
            return U_UNKNOWN_ITEM_TYPE;
    }

    switch (expected) {
        case Subtypes::PSPDirectory:
        case Subtypes::BIOSDirectory:
        case Subtypes::ComboDirectory:
            if (expected != type) {
                if (!probe)
                    msg(usprintf("%s: ", __FUNCTION__) + typeName + usprintf(" directory table header is unexpected here"), parent);
                return U_INVALID_IMAGE;
            }
            break;
        default: // some other type - process any directory
            break;
    }

    USTATUS result;
    UINT32 spiEraseBlockSize = 0;
    UINT32 headerSize, tableSize, regionSize, numEntries;
    bool additionalInfoValid = true;
    switch (type) {
        case Subtypes::PSPDirectory:
        case Subtypes::BIOSDirectory:
        {
            const AMD_PSPBIOS_COMMON_HEADER* hdr = (const AMD_PSPBIOS_COMMON_HEADER*)(amdImage.constData() + offset);
            spiEraseBlockSize = 4096 << (hdr->Version ? hdr->v1.SpiBlockSize : hdr->SpiBlockSize);
            additionalInfoValid = spiEraseBlockSize < amdImage.size() / 2;
            headerSize = (hdr->Version && additionalInfoValid)
                ? (16 << hdr->v1.DirHeaderSize) : sizeof(AMD_PSPBIOS_COMMON_HEADER);
            numEntries = hdr->NumEntries;
            tableSize = headerSize + numEntries * (type == Subtypes::PSPDirectory
                ? sizeof(AMD_PSP_DIRECTORY_ENTRY) : sizeof(AMD_BIOS_DIRECTORY_ENTRY));
            regionSize = additionalInfoValid ? ((hdr->Version ? hdr->v1.DirSize : hdr->DirSize) << 12) : tableSize;
            break;
        }
        default:
            const AMD_PSP_COMBO_DIRECTORY_HEADER* hdr = (const AMD_PSP_COMBO_DIRECTORY_HEADER*)(amdImage.constData() + offset);
            headerSize = sizeof(AMD_PSP_COMBO_DIRECTORY_HEADER);
            numEntries = hdr->NumEntries;
            tableSize = headerSize + numEntries * sizeof(AMD_PSP_COMBO_ENTRY);
            regionSize = tableSize; // Combo table does not have a region
            break;
    }

    // Full header is part of image?
    if ((offset + headerSize) > amdImage.size()) {
        if (!probe)
            msg(usprintf("%s: ", __FUNCTION__) + typeName + usprintf(" directory table header at offset %Xh is not within the image", offset), parent);
        return U_BUFFER_TOO_SMALL;
    }

    // Full table is part of image?
    if ((offset + tableSize) > amdImage.size()) {
        if (!probe)
            msg(usprintf("%s: ", __FUNCTION__) + typeName + usprintf(" directory table at offset %Xh is not within the image", offset), parent);
        return U_BUFFER_TOO_SMALL;
    }

    // Validate table checksum ASAP
    const UINT32 checksum = ((AMD_COMMON_HEADER*)(amdImage.constData() + offset))->Checksum;
    const UINT32 checksumOffset = offsetof(AMD_COMMON_HEADER, Checksum) + sizeof(AMD_COMMON_HEADER::Checksum); // Start after checksum field
    const UINT32 calcChecksum = fletcher32(amdImage.mid(offset + checksumOffset, tableSize - checksumOffset));
    UINT64 crc = ((UINT64)calcChecksum << 32) + checksum;
    if (calcChecksum != checksum) {
        if (!probe)
            msg(usprintf("%s: ", __FUNCTION__) + typeName + usprintf(" directory table at offset %Xh checksum is invalid", offset), parent);
        // don't fail here because somebody may want to fix the checksum
    }

    // Validate table region size
    if (regionSize < tableSize)
        regionSize = tableSize;
    if (offset + regionSize > amdImage.size()) {
        if (!probe)
            msg(usprintf("%s: ", __FUNCTION__) + typeName + usprintf(" directory region at offset %Xh is not fully within the image", offset), parent);
        regionSize = (UINT32)amdImage.size() - offset;
        // shall we exit with an error here?
    }

    UModelIndex tableIndex, regionIndex = parent;

    if (!probe) {
        // Add directory region if exists
        bool regionAdded = false;
        if (regionSize > tableSize) {
            const UString dirName = typeName + UString(" directory region");
            result = insertByRange(offset, Types::Region, subtype,
                dirName, UString(), UString(),
                0, regionSize, 0,
                parent, index);
            if (result != U_SUCCESS && result != U_DIR_ALREADY_EXIST)
                return result;
            regionIndex = index;
            regionAdded = true;
        }

        // Add directory table
        const UString dirName = typeName + UString(" directory table");
        if (model->type(parent) == Types::DirectoryTableEntry)
            model->setName(parent, model->name(parent) + dirName);
        UString details = usprintf("Entry count: %u\nChecksum: %08Xh, ", numEntries, (UINT32)crc)
            + ((UINT32)crc == (crc >> 32) ? "valid\n" : usprintf("invalid, should be %08Xh\n", (UINT32)(crc >> 32)));
        switch (type) {
            case Subtypes::PSPDirectory:
            case Subtypes::BIOSDirectory:
            {
                const AMD_PSPBIOS_COMMON_HEADER* hdr = (const AMD_PSPBIOS_COMMON_HEADER*)(amdImage.constData() + offset);
                details += usprintf("Additional info: %08Xh", hdr->AdditionalInfo.raw)
                    + (!additionalInfoValid ? UString(", invalid or not present\n")
                        : usprintf("\n  Info version: %01u\n  SPI erase block size: %Xh (%u)\n  Address mode: %01Xh\n",
                            hdr->Version, spiEraseBlockSize, spiEraseBlockSize, hdr->Version ? hdr->v1.AddrMode : hdr->AddrMode));
                break;
            }
            default:
                break;
        }
        result = insertByRange(offset, Types::DirectoryTable, type,
            dirName, UString(), details,
            headerSize, tableSize - headerSize, 0,
            regionIndex, tableIndex);
        if (result != U_SUCCESS && result != U_DIR_ALREADY_EXIST)
            return result;
        if (result == U_DIR_ALREADY_EXIST)
            return U_SUCCESS;
        if (!regionAdded)
            index = tableIndex;
    }

    UModelIndex dummyIndex;
    switch (type) {
        case Subtypes::PSPDirectory:
            result = pspParsePSPEntries(amdImage, offset, headerSize, numEntries, tableIndex, dummyIndex, probe);
            break;
        case Subtypes::BIOSDirectory:
            result = pspParseBIOSEntries(amdImage, offset, headerSize, numEntries, tableIndex, dummyIndex, probe);
            break;
        case Subtypes::ComboDirectory:
            result = pspParseComboEntries(amdImage, offset, headerSize, numEntries, tableIndex, dummyIndex, probe);
            break;
        default:
            if (!probe)
                msg(usprintf("%s: unknown directory table", __FUNCTION__), parent);
            return U_UNKNOWN_ITEM_TYPE;
    }

    return result;
}

static UINT64 bitMaskFromValue(UINT64 x)
{
    x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x |= x >> 32;
    return x;
}

USTATUS FfsParser::pspParseEFStructure(const UByteArray & amdImage, const UINT32 offset, const UModelIndex & parent, UModelIndex& index, const bool probe)
{
    if (offset + offsetof(AMD_EMBEDDED_FIRMWARE, PSP_Directory) > amdImage.size())
        return U_INVALID_FLASH_DESCRIPTOR;

    AMD_EMBEDDED_FIRMWARE* fet = (AMD_EMBEDDED_FIRMWARE*)(amdImage.constData() + offset);
    if (fet->Signature != AMD_EMBEDDED_FIRMWARE_SIGNATURE)
        return U_INVALID_FLASH_DESCRIPTOR;

    pspFilesList.clear();
    UINT32 fetEndMarker = 1;

    // Try to detect FET real size
    auto fetCut = [&fetEndMarker](const char* ptr, const UINT32 size)->UINT32 {
        UINT32 newSize = size;
        UINT32 blankVal = 1;
        while (newSize > offsetof(AMD_EMBEDDED_FIRMWARE, NewPSP_Directory)) {
            UINT32 val = *(UINT32*)(ptr + newSize - sizeof(UINT32));
            if (val == 0 || val == 0xFFFFFFFF) {
                if (blankVal != UINT32_MAX && blankVal != 0) {
                    blankVal = val;
                    fetEndMarker = val;
                }
                if (val != blankVal)
                    break;
                newSize -= sizeof(UINT32);
            }
            else
                break;
        }
        return newSize;
    };
    const char* const fetPtr = amdImage.constData() + offset;
    const UINT32 fetHdrSize = sizeof(AMD_EMBEDDED_FIRMWARE::Signature);
    UINT32 fetRawSize = offset + sizeof(AMD_EMBEDDED_FIRMWARE) > amdImage.size() ? (UINT32)amdImage.size() - offset : sizeof(AMD_EMBEDDED_FIRMWARE);
    fetRawSize &= ~(UINT32)(sizeof(UINT32) - 1);
    fetRawSize = fetCut(fetPtr, fetRawSize);
    UINT32 fetNewSize = fetRawSize;
    UINT32 fetTailSize = 0;
    while (fetNewSize >= offsetof(AMD_EMBEDDED_FIRMWARE, PSP_Directory)) {
        UINT32 val = *(UINT32*)(fetPtr + fetNewSize - sizeof(UINT32));
        if (val == 0xFFFF5500 || val == 0x000E55AA) {
            fetEndMarker = val;
            fetTailSize = sizeof(UINT32);
            break;
        }
        fetNewSize -= sizeof(UINT32);
    }
    if (fetNewSize >= offsetof(AMD_EMBEDDED_FIRMWARE, PSP_Directory))
        fetRawSize = fetNewSize;
    if (fetRawSize - fetTailSize <= offsetof(AMD_EMBEDDED_FIRMWARE, PSP_Directory)) {
        msg(usprintf("%s: FET candidate found at offset %Xh, too small to contain at least one directory table pointer", __FUNCTION__, offset), parent);
        return U_INVALID_FLASH_DESCRIPTOR;
    }
    UINT32 endOffset = offset + fetRawSize - fetTailSize;

    // Get some info about root firmwares
    USTATUS result;
    struct ptrList { const char* name; const UINT32 ptrOffs; };
    if (!probe) {
        UModelIndex containerIndex = imageIndex(parent);
        result = insertByRange(model->base(parent) - model->base(containerIndex), Types::Image, Subtypes::AmdImage,
            UString("Embedded firmware structure"), UString(), UString(),
            0, (UINT32)amdImage.size(), 0,
            parent, index);
        if (result == U_DIR_ALREADY_EXIST) {
            msg(usprintf("%s: ", __FUNCTION__) + model->name(index) + usprintf(" at offset %Xh was already parsed",
                model->base(parent) - model->base(containerIndex)), index);
            return U_SUCCESS;
        }
        if (result != U_SUCCESS)
            return result;

        const struct ptrList firmwares[] = {
            { "IMC", offsetof(AMD_EMBEDDED_FIRMWARE, IMC_Firmware) }, { "GEC", offsetof(AMD_EMBEDDED_FIRMWARE, GEC_Firmware) },
            { "xHCI", offsetof(AMD_EMBEDDED_FIRMWARE, xHCI_Firmware) } };
        for (const auto& fw : firmwares) {
            const UINT32 fwPtrOffs = fw.ptrOffs + offset;
            const UINT32 fwOffs = pspDirectoryOffset(amdImage, *(UINT32*)(amdImage.constData() + fwPtrOffs));
            if (fwOffs == 0 || fwOffs == UINT32_MAX)
                msg(usprintf("%s: %s firmware is not provided", __FUNCTION__, fw.name), index);
            else {
                msg(usprintf("%s: %s firmware at offset %Xh", __FUNCTION__, fw.name, fwOffs), index);
            }
        }
    }

    // The specification between SoCs changed a lot, and at this point the
    // SoC/PSP ID isn't known. Attempt to decode all tables without assuming
    // to find a specific type
    UString fetStrippedBy;
    int foundDirs = 0;
    USTATUS overall = U_INVALID_STORE;
    UModelIndex childIndex;

    // At least, one PSP directory is mandatory (but on very ancient platforms
    // FET can be without any PSP or BIOS dirs, only firmwares)
    const struct ptrList pspDirs[] = {
        { "PSP", offsetof(AMD_EMBEDDED_FIRMWARE, PSP_Directory) }, { "NewPSP", offsetof(AMD_EMBEDDED_FIRMWARE, NewPSP_Directory) },
        { "BackupPSP",  offsetof(AMD_EMBEDDED_FIRMWARE, BackupPSP_Directory) } };
    for (const auto& dir : pspDirs) {
        const UINT32 dirPtrOffs = dir.ptrOffs + offset;
        if (dirPtrOffs < endOffset) {
            result = U_INVALID_PARAMETER;
            const UINT32 dirPtr = *(UINT32*)(amdImage.constData() + dirPtrOffs);
            const UINT32 dirOffs = pspDirectoryOffset(amdImage, dirPtr);
            if (dirOffs < UINT32_MAX)
                result = pspParseDirectory(amdImage, dirOffs, Subtypes::AnyDirectory, index, childIndex, probe);
            if (result == U_SUCCESS) {
                if (dirOffs > offset && dirOffs < endOffset) {
                    fetStrippedBy = usprintf("%s directory table at offset %Xh", dir.name, dirOffs);
                    endOffset = dirOffs;
                }
                if (!probe) {
                    msg(usprintf("%s: %s directory table at offset %Xh", __FUNCTION__, dir.name, dirOffs), childIndex);
                    model->setText(childIndex, usprintf("FET %s", dir.name));
                }
                foundDirs++;
            }
            else {
                if (!probe)
                    msg(usprintf("%s: %s directory table is invalid or not provided (%Xh)", __FUNCTION__, dir.name, dirPtr), index);
                overall = result;
            }
        }
    }
    if (foundDirs == 0)
        return overall;

    // BIOS directories is not mandatory for some ancient platforms, only count found dirs for now
    foundDirs = 0;
    const struct ptrList biosDirs[] = {
        { "BIOS0", offsetof(AMD_EMBEDDED_FIRMWARE, BIOS0_Entry) }, { "BIOS1", offsetof(AMD_EMBEDDED_FIRMWARE, BIOS1_Entry) },
        { "BIOS2", offsetof(AMD_EMBEDDED_FIRMWARE, BIOS2_Entry) }, { "BIOS3", offsetof(AMD_EMBEDDED_FIRMWARE, BIOS3_Entry) } };
    for (const auto& dir : biosDirs) {
        const UINT32 dirPtrOffs = dir.ptrOffs + offset;
        if (dirPtrOffs < endOffset) {
            result = U_INVALID_PARAMETER;
            const UINT32 dirPtr = *(UINT32*)(amdImage.constData() + dirPtrOffs);
            const UINT32 dirOffs = pspDirectoryOffset(amdImage, dirPtr);
            if (dirOffs < UINT32_MAX)
                result = pspParseDirectory(amdImage, dirOffs, Subtypes::AnyDirectory, index, childIndex, probe);
            if (result == U_SUCCESS) {
                if (dirOffs > offset && dirOffs < endOffset) {
                    fetStrippedBy = usprintf("%s directory table at offset %Xh", dir.name, dirOffs);
                    endOffset = dirOffs;
                }
                if (!probe) {
                    msg(usprintf("%s: %s directory table at offset %Xh", __FUNCTION__, dir.name, dirOffs), childIndex);
                    model->setText(childIndex, usprintf("FET %s", dir.name));
                }
                foundDirs++;
            }
            else {
                if (!probe)
                    msg(usprintf("%s: %s directory table is invalid or not provided (%Xh)", __FUNCTION__, dir.name, dirPtr), index);
                overall = result;
            }
        }
    }

    if (!probe) {
        // Sort files by offset, size, parent's base, etc.
        qsort(pspFilesList.data(), pspFilesList.size(), sizeof(PSP_FILE_SPEC),
            [](const void* pa, const void* pb)->int {
                const PSP_FILE_SPEC* a = static_cast<const PSP_FILE_SPEC*>(pa);
                const PSP_FILE_SPEC* b = static_cast<const PSP_FILE_SPEC*>(pb);
                if (a->offset != b->offset)
                    return (a->offset > b->offset) - (b->offset > a->offset);
                if (a->size != b->size)
                    return (b->size > a->size) - (a->size > b->size);
                if (a->dir != b->dir)
                    return (b->dir > a->dir) - (a->dir > b->dir);
                if (a->parent != b->parent)
                    return (a->parent > b->parent) - (b->parent > a->parent);
                return (a->flags > b->flags) - (b->flags > a->flags);
            });
        // Group identical binaries with same offset and size, drop with same parents
        UINT32 prevParentBase, prevOffset, prevSize;
        prevParentBase = prevOffset = prevSize = UINT32_MAX;
        std::vector<std::vector<PSP_FILE_SPEC*>*> quantiList;
        for (auto& f : pspFilesList) {
            if (prevParentBase == f.parent)
                continue;
            prevParentBase = f.parent;
            if (prevOffset != f.offset || prevSize != f.size)
                quantiList.push_back(new std::vector<PSP_FILE_SPEC*>);
            prevOffset = f.offset;
            prevSize = f.size;
            quantiList[quantiList.size() - 1]->push_back(&f);
        }
        // This complicated logic is only to get informed
        // about dublicated binaries properties are identical or not
        for (const auto* qf : quantiList) {
            int nameDiff, typeDiff, subDiff, instDiff, romDiff, dirDiff, wrDiff, flagsDiff,
                rstDiff, cpyDiff, roDiff, compDiff, regDiff, destDiff;
            bool first = true;
            PSP_FILE_SPEC ref;
            for (const auto* f : *qf) {
                if (first) {
                    ref = *f;
                    nameDiff = typeDiff = subDiff = instDiff = romDiff = dirDiff = wrDiff = flagsDiff
                        = rstDiff = cpyDiff = roDiff = compDiff = regDiff = destDiff = 0;
                    first = false;
                }
                else {
                    nameDiff += ref.name == f->name ? 0 : 1;
                    typeDiff += ref.type == f->type ? 0 : 1;
                    subDiff += ref.sub == f->sub ? 0 : 1;
                    instDiff += ref.inst == f->inst ? 0 : 1;
                    romDiff += ref.rom == f->rom ? 0 : 1;
                    dirDiff += ref.dir == f->dir ? 0 : 1;
                    wrDiff += ref.wr == f->wr ? 0 : 1;
                    flagsDiff += ref.flags == f->flags ? 0 : 1;
                    if (f->dir) {
                        rstDiff += ref.rst == f->rst ? 0 : 1;
                        cpyDiff += ref.cpy == f->cpy ? 0 : 1;
                        roDiff += ref.ro == f->ro ? 0 : 1;
                        compDiff += ref.comp == f->comp ? 0 : 1;
                        regDiff += ref.reg == f->reg ? 0 : 1;
                        destDiff += ref.dest == f->dest ? 0 : 1;
                    }
                }
            }
            UString nameStr = nameDiff ? "Different types from multiple parents" : ref.name;
            if ((subDiff || ref.sub || instDiff || ref.inst) && !(subDiff && instDiff)) {
                nameStr += " (" + UString(subDiff ? "*" : usprintf("%X", ref.sub)) + ":"
                    + UString(instDiff ? "*" : usprintf("%01X", ref.inst)) + ")";
            }
            if (ref.size == 0 || ref.size == UINT32_MAX) {
                msg(usprintf("%s: skipping %s directory regular file with no size: ",
                        __FUNCTION__, dirDiff ? "PSP/BIOS" : (ref.dir ? "BIOS" : "PSP"))
                    + nameStr, model->findByBase(ref.parent, index));
                continue;
            }
            UString typeStr = "Type: " + UString(typeDiff ? "*" : usprintf("%02Xh", ref.type));
            typeStr += dirDiff ? " (different directories types)" : usprintf(" (%s directory file)",
                ref.dir ? "BIOS" : "PSP");
            const UString subStr   = "SubProgram: " + UString(subDiff ? "*" : usprintf("%02Xh", ref.sub));
            const UString instStr  = "Instance: " + UString(instDiff ? "*" : usprintf("%01Xh", ref.inst));
            const UString romStr   = "RomId: " + UString(romDiff ? "*" : usprintf("%01Xh", ref.rom));
            const UString wrStr    = "Writable: " + UString(wrDiff ? "*" : ref.wr ? "true" : "false");
            const UString flagsStr = "Flags: " + UString(flagsDiff ? "*" : usprintf("%04Xh", ref.flags));
            UString infoStr = typeStr + "\n" + subStr + "\n" + instStr + "\n" + romStr + "\n" + wrStr + "\n";
            if (!dirDiff && ref.dir) {
                const UString rstStr  = "Reset-image: " + UString(rstDiff ? "*" : ref.rst ? "true" : "false");
                const UString cpyStr  = "Copy image: " + UString(cpyDiff ? "*" : ref.cpy ? "true" : "false");
                const UString roStr   = "Read only: " + UString(roDiff ? "*" : ref.ro ? "true" : "false");
                const UString compStr = "Compressed: " + UString(compDiff ? "*" : ref.comp ? "true" : "false");
                const UString regStr  = "Region type: " + UString(regDiff ? "*" : usprintf("%02Xh", ref.reg));
                const UString destStr = "Destination: " + UString(destDiff ? "*" : usprintf("%" PRIX64 "Xh", ref.dest));
                infoStr += rstStr + "\n" + cpyStr + "\n" + roStr + "\n" + compStr + "\n" + flagsStr + "\n" + regStr + "\n" + destStr + "\n";
            }
            else
                infoStr += flagsStr + "\n";
            UString textStr = "Type " + UString(typeDiff ? "*" : usprintf("%02Xh", ref.type));
            if (subDiff || ref.sub)
                textStr += ", SubProgram " + UString(subDiff ? "*" : usprintf("%Xh", ref.sub));
            if (instDiff || ref.inst)
                textStr += ", Instance " + UString(instDiff ? "*" : usprintf("%01Xh", ref.inst));
            first = true;
            for (const auto* f : *qf) {
                UByteArray bin, binUncompressed;
                bool compressed = false;
                // Preprocess special file types
                if (first) {
                    first = false;
                    switch (f->type) {
                        case AMD_BIOS_BIN:
                            bin = amdImage.mid(f->offset, f->size);
                            if (f->comp) {
                                result = decompressBios(bin, binUncompressed);
                                if (result == U_SUCCESS) {
                                    compressed = true;
                                    infoStr += usprintf(
                                        "Compression algorithm: Zlib\nDecompressed size: %Xh (%u)\n", (UINT32)bin.size(), (UINT32)bin.size());
                                }
                                else {
                                    infoStr += "Compression algorithm: unknown\n";
                                    msg(usprintf("%s: decompression failed with error: ", __FUNCTION__) + errorCodeToUString(result), childIndex);
                                }
                            }
                            break;
                    }
                }
                // Add file to tree
                result = insertByRange(f->offset, Types::Region, Subtypes::PspDirectoryFile,
                    nameStr, textStr, infoStr,
                    0, f->size, 0,
                    model->findByBase(f->parent, index), childIndex);
                if (result != U_SUCCESS && result != U_DIR_ALREADY_EXIST) {
                    msg(usprintf("%s: failed to create %s directory file: ",
                            __FUNCTION__, dirDiff ? "PSP/BIOS" : (ref.dir ? "BIOS" : "PSP"))
                        + nameStr, childIndex);
                    continue;
                }
                if (result == U_DIR_ALREADY_EXIST)
                    continue;
                // Postprocess special file types
                UModelIndex dumbIndex;
                switch (f->type) {
                    case AMD_EFS_BACKUP: {
                        auto pspMaxOffsetSave = pspMaxOffset;
                        auto pspFilesListSave = pspFilesList;
                        pspParseEFStructure(amdImage.mid(f->offset, f->size), 0, childIndex, dumbIndex);
                        pspMaxOffset = pspMaxOffsetSave;
                        pspFilesList = pspFilesListSave;
                    } break;
                    case AMD_BIOS_BIN:
                        if (compressed) {
                            model->setUncompressedData(childIndex, binUncompressed);
                            model->setCompressed(childIndex, true);
                            bin = binUncompressed;
                        }
                        parseGenericImage(bin, 0, childIndex, dumbIndex);
                        break;
                    }
            }
        }
        UINT32 fetUpdSize = endOffset - offset + fetTailSize;
        if (fetUpdSize < fetRawSize) {
            fetRawSize = fetUpdSize;
            fetTailSize = 0;
        }
        fetUpdSize = fetCut(fetPtr, fetRawSize);
        if (fetUpdSize < fetRawSize) {
            fetRawSize = fetUpdSize;
            fetTailSize = 0;
        }
        UString fetInfo = usprintf("Maximum PSP offset: %" PRIX64 "Xh\n", pspMaxOffset - 1);
        if (fetRawSize < sizeof(AMD_EMBEDDED_FIRMWARE)) {
            if (fetEndMarker == 1)
                fetInfo += "Stripped by " + fetStrippedBy;
            else {
                fetInfo += "End marker: ";
                if (fetEndMarker == 0 || fetEndMarker == 0xFFFFFFFF)
                    fetInfo += usprintf("%02Xh\n", (UINT8)fetEndMarker);
                else
                    fetInfo += usprintf("%08Xh\n", fetEndMarker);
            }
            fetInfo += "\n";
        }
        insertByRange(offset, Types::DirectoryTable, Subtypes::PSPDirectory,
            "Firmware entry table", UString(), fetInfo,
            fetHdrSize, fetRawSize - fetHdrSize - fetTailSize, fetTailSize,
            index, childIndex);
        if (fetRawSize - fetTailSize >= offsetof(AMD_EMBEDDED_FIRMWARE, BIOS3_Entry))
            msg(usprintf("%s: EFS generation is %Xh", __FUNCTION__, fet->EFS_Generation), childIndex);
        else
            msg(usprintf("%s: ancient FET without EFS generation", __FUNCTION__), childIndex);
    }

    return U_SUCCESS;
}


USTATUS FfsParser::parseAMDImage(const UByteArray& amdImage, const UINT32 localOffset, const UModelIndex& parent, UModelIndex& index)
{
    USTATUS result = U_INVALID_IMAGE;
    UINT32 probeOffset;
    UModelIndex efsIndex;
    struct efsDesc { UINT32 probe; UINT32 bank; UINT32 size; };
    std::vector<struct efsDesc> efsDescsList;

    // Probe all possible locations for the header
    const UINT32 bankSizeMin = 0x200000;
    UINT32 bankStep = bankSizeMin;
    UINT32 bankSize = bankStep, bankOffset = 0;
    for (probeOffset = AMD_EMBEDDED_FIRMWARE_OFFSET; (probeOffset + sizeof(AMD_EMBEDDED_FIRMWARE)) < amdImage.size(); probeOffset += 0x20000) {
        UINT32 bankOffsetTemp = bankOffset;
        while (bankOffsetTemp < probeOffset) {
            while (bankSize <= amdImage.size() - bankOffsetTemp) {
                const UByteArray bankImage = amdImage.mid(bankOffsetTemp, amdImage.size() - bankOffsetTemp);
                pspSpiRomBase = UINT32_MAX - bankSize + 1;
                pspMaxOffset = 0;
                result = pspParseEFStructure(bankImage, probeOffset - bankOffsetTemp, UModelIndex(), efsIndex, true);
                if (result == U_INVALID_FLASH_DESCRIPTOR)
                    break;
                if (result == U_SUCCESS) {
                    // if pspMaxOffset is too high then it's probably near 0xFFxxxxxx meaning that pspSpiRomBase is not valid
                    if (pspMaxOffset < INT32_MAX) {
                        if (pspMaxOffset > amdImage.size() - bankOffsetTemp)
                            pspMaxOffset = amdImage.size() - bankOffsetTemp;
                        UINT32 bankSizeTemp = (UINT32)(bitMaskFromValue(pspMaxOffset - 1) + 1);
                        // some files, such as BIOS binary, can be compressed, but it's size declared
                        // is for uncompressed data; so, because BIOS binary usually (if not always)
                        // is at the end of the bank, it's resulted end may be slightly ouside the bank
                        if (pspMaxOffset < bankSizeTemp / 2 + bankSizeTemp / 8)
                            bankSizeTemp /= 2;
                        if (bankSize < bankSizeTemp)
                            bankSize = bankSizeTemp;
                        efsDescsList.push_back({ probeOffset, bankOffsetTemp, bankSize });
                        break;
                    }
                }
                bankSize *= 2;
            }
            if (result == U_SUCCESS) {
                bankStep = bankSize;
                break;
            }
            bankOffsetTemp += bankStep;
            if (result == U_INVALID_FLASH_DESCRIPTOR) {
                bankOffset = bankOffsetTemp;
                break;
            }
        }
    }
    if (efsDescsList.empty()) {
        // This is not an error to be reported here, as this is the way to stop parsing non-AMD images
        return U_ITEM_NOT_FOUND;
    }

    // Add dummy bank if 1st detected bank is not at the beginning of the image
    if (efsDescsList.at(0).bank > 0)
        efsDescsList.insert(efsDescsList.begin(), { UINT32_MAX, 0, efsDescsList.at(0).bank });
    UINT32 bankOffsetLast = (UINT32)(efsDescsList.back().bank);
    UINT32 bankSizeLast = efsDescsList.back().size;
    // ...and add dummy bank if last detected bank is not at the end of the image
    if (bankOffsetLast + bankSizeLast < amdImage.size())
        efsDescsList.push_back({ UINT32_MAX, bankOffsetLast + bankSizeLast, (UINT32)amdImage.size() - bankOffsetLast - bankSizeLast });

    // Finally, try to detect/correct bank size
    bankSize = 1;
    for (int i = 0; i < efsDescsList.size(); i++) {
        UINT32 currentSize = efsDescsList.at(i).size;
        if (bankSize < currentSize)
            bankSize = currentSize;
    }
    bool singleImage = amdImage.size() <= bankSize;

    // Add AMD image tree item
    index = model->addItem(
        localOffset, Types::Image, Subtypes::AmdImage,
        "AMD image", UString(), usprintf("Full size: %Xh (%u)\n", (UINT32)amdImage.size(), (UINT32)amdImage.size()),
        UByteArray(), amdImage, UByteArray(),
        Fixed, parent);
    UModelIndex amdIndex = index;

    UINT32 efsInstance = 0;
    for (int i = 0; i < efsDescsList.size(); i++) {
        bankOffset = efsDescsList.at(i).bank;
        probeOffset = (UINT32)(efsDescsList.at(i).probe) - bankOffset;
        UString bankName = usprintf("Bank %u", bankOffset / bankSize);

        UModelIndex bankIndex = amdIndex;
        UByteArray bankImage = amdImage.mid(bankOffset, bankSize);
        if (efsDescsList.size() > 1) {
            bankIndex = model->addItem(
                bankOffset, Types::Image, Subtypes::AmdImage,
                bankName, UString(), usprintf("Full size: %Xh (%u)\n", (UINT32)bankImage.size(), (UINT32)bankImage.size()),
                UByteArray(), bankImage, UByteArray(),
                Fixed, bankIndex);
            efsInstance = 0;
        }
        bool noEFS = true;
        if (efsDescsList.at(i).probe != UINT32_MAX) {
            noEFS = false;
            pspSpiRomBase = UINT32_MAX - (UINT32)bitMaskFromValue(bankImage.size() - 1);
            result = pspParseEFStructure(bankImage, probeOffset, bankIndex, efsIndex);
            UString efsTitleSuffix = efsInstance > 0 ? usprintf(" #%u", efsInstance + 1) : UString();
            if (model->rowCount(efsIndex) > 0) {
                if (result != U_SUCCESS) {
                    msg(usprintf("%s: ", __FUNCTION__) + model->name(efsIndex) + UString(" was not fully parsed")
                        + (singleImage ? "" : usprintf(" (bank %u)", bankOffset / bankSize)), bankIndex);
                }
                else
                    model->setName(efsIndex, model->name(efsIndex) + efsTitleSuffix);
            }
        }
        UModelIndex uefiIndex;
        result = parseGenericImage(bankImage, 0, bankIndex, uefiIndex);
        if (noEFS && (U_STORES_NOT_FOUND == result || model->rowCount(uefiIndex) <= 0)) {
            model->setName(uefiIndex, "Padding");
            model->setType(uefiIndex, Types::Padding);
            model->setSubtype(uefiIndex, getPaddingType(bankImage));
            result = U_SUCCESS;
        }
        typename std::decay<decltype(indexesAddressDiffs)>::type::value_type p;
        p.first = uefiIndex;
        p.second = 0x100000000ULL - model->base(p.first) - model->entire(p.first).size();
        addressDiff = p.second;
        indexesAddressDiffs.push_back(p);
    }

    pspFilesList.clear();

    return result;
}