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
/*
 * COPYRIGHT:       See COPYING.ARM in the top level directory
 * PROJECT:         ReactOS UEFI Boot Manager
 * FILE:            boot/environ/app/bootmgr/bootmgr.cla
 * PURPOSE:         Boot Manager Entrypoint
 * PROGRAMMER:      Alex Ionescu (alex.ionescu@reactos.org)
 */

/* INCLUDES ******************************************************************/

#include "bootmgr.h"

/* DATA VARIABLES ************************************************************/

DEFINE_GUID(GUID_WINDOWS_BOOTMGR,
            0x9DEA862C,
            0x5CDD,
            0x4E70,
            0xAC, 0xC1, 0xF3, 0x2B, 0x34, 0x4D, 0x47, 0x95);

ULONGLONG ApplicationStartTime;
ULONGLONG PostTime;
GUID BmApplicationIdentifier;
PWCHAR BootDirectory;

BL_BOOT_ERROR BmpErrorBuffer;
PBL_BOOT_ERROR BmpInternalBootError;
BL_PACKED_BOOT_ERROR BmpPackedBootError;

BOOLEAN BmBootIniUsed;
WCHAR BmpFileNameBuffer[128];
PWCHAR ParentFileName = L"";

BOOLEAN BmDisplayStateCached;
PBL_LOADED_APPLICATION_ENTRY* BmpFailedBootEntries;
PBL_LOADED_APPLICATION_ENTRY BmpSelectedBootEntry;
BOOLEAN BmBootEntryOverridePresent;
BOOLEAN BmpDisplayBootMenu;

/* FUNCTIONS *****************************************************************/

NTSTATUS
BmGetOptionList (
    _In_ HANDLE BcdHandle,
    _In_ PGUID ObjectId,
    _In_ PBL_BCD_OPTION *OptionList
    )
{
    NTSTATUS Status;
    HANDLE ObjectHandle;
    ULONG ElementSize, ElementCount, i, OptionsSize;
    BcdElementType Type;
    PBCD_ELEMENT_HEADER Header;
    PBCD_ELEMENT BcdElements;
    PBL_BCD_OPTION Options, Option, PreviousOption, DeviceOptions;
    PBCD_DEVICE_OPTION DeviceOption;
    GUID DeviceId;
    PVOID DeviceData;

    /* Open the BCD object requested */
    ObjectHandle = NULL;
    BcdElements = NULL;
    Status = BcdOpenObject(BcdHandle, ObjectId, &ObjectHandle);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Do the initial enumeration to get the size needed */
    ElementSize = 0;
    Status = BcdEnumerateAndUnpackElements(BcdHandle,
                                           ObjectHandle,
                                           NULL,
                                           &ElementSize,
                                           &ElementCount);
    if (Status != STATUS_BUFFER_TOO_SMALL)
    {
        /* If we got success, that doesn't make any sense */
        if (NT_SUCCESS(Status))
        {
            Status = STATUS_INVALID_PARAMETER;
        }

        /* Bail out */
        goto Quickie;
    }

    /* Allocate a large-enough buffer */
    BcdElements = BlMmAllocateHeap(ElementSize);
    if (!BcdElements)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Now do the real enumeration to fill out the elements buffer */
    Status = BcdEnumerateAndUnpackElements(BcdHandle,
                                           ObjectHandle,
                                           BcdElements,
                                           &ElementSize,
                                           &ElementCount);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Go through each BCD option to add the sizes up */
    OptionsSize = 0;
    for (i = 0; i < ElementCount; i++)
    {
        OptionsSize += BcdElements[i].Header->Size + sizeof(BL_BCD_OPTION);
    }

    /* Allocate the required BCD option list */
    Options = BlMmAllocateHeap(OptionsSize);
    if (!Options)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Zero it out */
    RtlZeroMemory(Options, OptionsSize);

    /* Start going through each option */
    PreviousOption = NULL;
    Option = Options;
    for (i = 0; i < ElementCount; i++)
    {
        /* Read the header and type */
        Header = BcdElements[i].Header;
        Type.PackedValue = Header->Type;

        /* Check if this option isn't already present */
        if (!MiscGetBootOption(Options, Type.PackedValue))
        {
            /* It's a new option. Did we have an existing one? */
            if (PreviousOption)
            {
                /* Link it to this new one */
                PreviousOption->NextEntryOffset = (ULONG_PTR)Option -
                                                  (ULONG_PTR)Options;
            }

            /* Capture the type, size, data, and offset */
            Option->Type = Type.PackedValue;
            Option->DataSize = Header->Size;
            RtlCopyMemory(Option + 1, BcdElements[i].Body, Header->Size);
            Option->DataOffset = sizeof(BL_BCD_OPTION);

            /* Check if this was a device */
            if (Type.Format == BCD_TYPE_DEVICE)
            {
                /* Grab its GUID */
                DeviceOption = (PBCD_DEVICE_OPTION)(Option + 1);
                DeviceId = DeviceOption->AssociatedEntry;

                /* Look up the options for that GUID */
                Status = BmGetOptionList(BcdHandle, &DeviceId, &DeviceOptions);
                if (NT_SUCCESS(Status))
                {
                    /* Device data is after the device option */
                    DeviceData = (PVOID)((ULONG_PTR)DeviceOption + Header->Size);

                    /* Copy it */
                    RtlCopyMemory(DeviceData,
                                  DeviceOptions,
                                  BlGetBootOptionListSize(DeviceOptions));

                    /* Don't need this anymore */
                    BlMmFreeHeap(DeviceOptions);

                    /* Write the offset of the device options */
                    Option->ListOffset = (ULONG_PTR)DeviceData -
                                         (ULONG_PTR)Option;
                }
            }

            /* Save the previous option and go to the next one */
            PreviousOption = Option;
            Option = (PBL_BCD_OPTION)((ULONG_PTR)Option +
                                      BlGetBootOptionSize(Option));
        }
    }

    /* Return the pointer back, we've made it! */
    *OptionList = Options;
    Status = STATUS_SUCCESS;

Quickie:
    /* Did we allocate a local buffer? Free it if so */
    if (BcdElements)
    {
        BlMmFreeHeap(BcdElements);
    }

    /* Was the key open? Close it if so */
    if (ObjectHandle)
    {
        BiCloseKey(ObjectHandle);
    }

    /* Return the option list parsing status */
    return Status;
}

NTSTATUS
BmpUpdateApplicationOptions (
    _In_ HANDLE BcdHandle
    )
{
    NTSTATUS Status;
    PBL_BCD_OPTION Options;

    /* Get the boot option list */
    Status = BmGetOptionList(BcdHandle, &BmApplicationIdentifier, &Options);
    if (!NT_SUCCESS(Status))
    {
        return Status;
    }

    /* Append the options, free the local buffer, and return success */
    BlAppendBootOptions(&BlpApplicationEntry, Options);
    BlMmFreeHeap(Options);
    return STATUS_SUCCESS;
}

NTSTATUS
BmpFwGetApplicationDirectoryPath (
    _In_ PUNICODE_STRING ApplicationDirectoryPath
    )
{
    NTSTATUS Status;
    SIZE_T i, AppPathLength;
    PWCHAR ApplicationPath, PathCopy;

    /* Clear the incoming string */
    ApplicationDirectoryPath->Length = 0;
    ApplicationDirectoryPath->MaximumLength = 0;
    ApplicationDirectoryPath->Buffer = 0;

    /* Get the boot application path */
    ApplicationPath = NULL;
    Status = BlGetBootOptionString(BlpApplicationEntry.BcdData,
                                   BcdLibraryString_ApplicationPath,
                                   &ApplicationPath);
    if (NT_SUCCESS(Status))
    {
        /* Calculate the length of the application path */
        for (i = wcslen(ApplicationPath) - 1; i > 0; i--)
        {
            /* Keep going until the path separator */
            if (ApplicationPath[i] == OBJ_NAME_PATH_SEPARATOR)
            {
                break;
            }
        }

        /* Check if we have space for one more character */
        Status = RtlSIZETAdd(i, 1, &AppPathLength);
        if (NT_SUCCESS(Status))
        {
            /* Check if it's safe to multiply by two */
            Status = RtlSIZETMult(AppPathLength, sizeof(WCHAR), &AppPathLength);
            if (NT_SUCCESS(Status))
            {
                /* Allocate a copy for the string */
                PathCopy = BlMmAllocateHeap(AppPathLength);
                if (PathCopy)
                {
                    /* NULL-terminate it */
                    RtlCopyMemory(PathCopy,
                                  ApplicationPath,
                                  AppPathLength - sizeof(UNICODE_NULL));
                    PathCopy[AppPathLength] = UNICODE_NULL;

                    /* Finally, initialize the outgoing string */
                    RtlInitUnicodeString(ApplicationDirectoryPath, PathCopy);
                }
                else
                {
                    /* No memory, fail */
                    Status = STATUS_NO_MEMORY;
                }
            }
        }
    }

    /* Check if we had an application path */
    if (ApplicationPath)
    {
        /* No longer need this, free it */
        BlMmFreeHeap(ApplicationPath);
    }

    /* All done! */
    return Status;
}

NTSTATUS
BmFwInitializeBootDirectoryPath (
    VOID
    )
{
    PWCHAR FinalPath;
    NTSTATUS Status;
    PWCHAR BcdDirectory;
    UNICODE_STRING BcdPath;
    ULONG FinalSize;
    ULONG FileHandle, DeviceHandle;

    /* Initialize everything for failure */
    BcdPath.MaximumLength = 0;
    BcdPath.Buffer = NULL;
    BcdDirectory = NULL;
    FinalPath = NULL;
    FileHandle = -1;
    DeviceHandle = -1;

    /* Try to open the boot device */
    Status = BlpDeviceOpen(BlpBootDevice,
                           BL_DEVICE_READ_ACCESS,
                           0, 
                           &DeviceHandle);
    if (!NT_SUCCESS(Status))
    {
        EfiPrintf(L"Device open failed: %lx\r\n", Status);
        goto Quickie;
    }

    /* Get the directory path */
    Status = BmpFwGetApplicationDirectoryPath(&BcdPath);
    BcdDirectory = BcdPath.Buffer;
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Add the BCD file name to it */
    FinalSize = BcdPath.MaximumLength + sizeof(L"\\BCD") - sizeof(UNICODE_NULL);
    if (FinalSize < BcdPath.MaximumLength)
    {
        goto Quickie;
    }

    /* Allocate space for the final path */
    FinalPath = BlMmAllocateHeap(FinalSize);
    if (!FinalPath)
    {
        goto Quickie;
    }

    /* Build it */
    RtlZeroMemory(FinalPath, FinalSize);
    RtlCopyMemory(FinalPath, BcdDirectory, BcdPath.MaximumLength);
    wcsncat(FinalPath, L"\\BCD", FinalSize / sizeof(WCHAR));

    /* Try to open the file */
    Status = BlFileOpen(DeviceHandle,
                        FinalPath,
                        BL_FILE_READ_ACCESS,
                        &FileHandle);
    if (!NT_SUCCESS(Status))
    {
        BootDirectory = BcdDirectory;
        goto Quickie;
    }

    /* Save the boot directory */
    BootDirectory = L"\\EFI\\Boot"; /* Should be EFI\\ReactOS\\Boot */

Quickie:
    /* Free all the allocations we made */
    if (BcdDirectory)
    {
        Status = BlMmFreeHeap(BcdDirectory);
    }
    if (FinalPath)
    {
        Status = BlMmFreeHeap(FinalPath);
    }

    /* Close the BCD file */
    if (FileHandle != -1)
    {
        Status = BlFileClose(FileHandle);
    }

    /* Close the boot device */
    if (DeviceHandle != -1)
    {
        Status = BlDeviceClose(DeviceHandle);
    }

    /* Return back to the caller */
    return Status;
}

NTSTATUS
BmOpenBootIni (
    VOID
    )
{
    /* Don't yet handled boot.ini */
    return STATUS_NOT_FOUND;
}

ULONG
BmpFatalErrorMessageFilter (
    _In_ NTSTATUS ErrorStatus,
    _Out_ PULONG ErrorResourceId
    )
{
    ULONG Result;

    /* Assume no message for now, check for known status message */
    Result = 0;
    switch (ErrorStatus)
    {
        /* Convert each status to a resource ID */
        case STATUS_UNEXPECTED_IO_ERROR:
            *ErrorResourceId = 9017;
            Result = 1;
            break;
        case STATUS_IMAGE_CHECKSUM_MISMATCH:
            *ErrorResourceId = 9018;
            break;
        case STATUS_INVALID_IMAGE_WIN_64:
            *ErrorResourceId = 9016;
            break;
        case 0xC0000428:
            *ErrorResourceId = 9019;
            Result = 2;
            break;
        case 0xC0210000:
            *ErrorResourceId = 9013;
            break;
    }

    /* Return the type of message */
    return Result;
}

VOID
BmErrorPurge (
    VOID
    )
{
    /* Check if a boot error is present */
    if (BmpPackedBootError.BootError)
    {
        /* Purge it */
        BlMmFreeHeap(BmpPackedBootError.BootError);
        BmpPackedBootError.BootError = NULL;
    }

    /* Zero out the packed buffer */
    BmpPackedBootError.Size = 0;
    BmpInternalBootError = NULL;
    RtlZeroMemory(&BmpErrorBuffer, sizeof(BmpErrorBuffer));
}

VOID
BmpErrorLog (
    _In_ ULONG ErrorCode,
    _In_ NTSTATUS ErrorStatus,
    _In_ ULONG ErrorMsgId,
    _In_ PWCHAR FileName,
    _In_ ULONG HelpMsgId
    )
{
    PWCHAR ErrorMsgString;

    /* Check if we already had an error */
    if (BmpInternalBootError)
    {
        /* Purge it */
        BmErrorPurge();
    }

    /* Find the string for this error ID */
    ErrorMsgString = BlResourceFindMessage(ErrorMsgId);
    if (ErrorMsgString)
    {
        /* Fill out the error buffer */
        BmpErrorBuffer.Unknown1 = 0;
        BmpErrorBuffer.Unknown2 = 0;
        BmpErrorBuffer.ErrorString = ErrorMsgString;
        BmpErrorBuffer.FileName = FileName;
        BmpErrorBuffer.ErrorCode = ErrorCode;
        BmpErrorBuffer.ErrorStatus = ErrorStatus;
        BmpErrorBuffer.HelpMsgId = HelpMsgId;
        BmpInternalBootError = &BmpErrorBuffer;
    }
}

VOID
BmFatalErrorEx (
    _In_ ULONG ErrorCode,
    _In_ ULONG_PTR Parameter1,
    _In_ ULONG_PTR Parameter2,
    _In_ ULONG_PTR Parameter3,
    _In_ ULONG_PTR Parameter4
    )
{
    PWCHAR FileName, Buffer;
    NTSTATUS ErrorStatus;
    WCHAR FormatString[256];
    ULONG ErrorResourceId, ErrorHelpId;
    BOOLEAN Restart, NoError;

    /* Assume no buffer for now */
    Buffer = NULL;

    /* Check what error code is being raised */
    switch (ErrorCode)
    {
        /* Error reading the BCD */
        case BL_FATAL_ERROR_BCD_READ:

            /* Check if we have a name for the BCD file */
            if (Parameter1)
            {
                /* Check if the name fits into our buffer */
                FileName = (PWCHAR)Parameter1;
                if (wcslen(FileName) < sizeof(BmpFileNameBuffer))
                {
                    /* Copy it in there */
                    Buffer = BmpFileNameBuffer;
                    wcsncpy(BmpFileNameBuffer,
                            FileName,
                            RTL_NUMBER_OF(BmpFileNameBuffer));
                }
            }

            /* If we don't have a buffer, use an empty one */
            if (!Buffer)
            {
                Buffer = ParentFileName;
            }

            /* The NTSTATUS code is in parameter 2*/
            ErrorStatus = (NTSTATUS)Parameter2;

            /* Build the error string */
            swprintf(FormatString,
                     L"\nAn error occurred (%08x) while attempting "
                     L"to read the boot configuration data file %s\n",
                     ErrorStatus,
                     Buffer);

            /* Select the resource ID message */
            ErrorResourceId = 9002;
            break;

        case BL_FATAL_ERROR_BCD_ENTRIES:

            /* File name is in parameter 1 */
            FileName = (PWCHAR)Parameter1;

            /* The NTSTATUS code is in parameter 2*/
            ErrorStatus = (NTSTATUS)Parameter2;

            /* Build the error string */
            swprintf(FormatString,
                     L"\nNo valid entries found in the boot configuration data file %s\n",
                     FileName);

            /* Select the resource ID message */
            ErrorResourceId = 9007;
            break;

        case BL_FATAL_ERROR_BCD_PARSE:

            /* File name isin parameter 1 */
            FileName = (PWCHAR)Parameter1;

            /* The NTSTATUS code is in parameter 2*/
            ErrorStatus = (NTSTATUS)Parameter2;

            /* Build the error string */
            swprintf(FormatString,
                     L"\nThe boot configuration file %s is invalid (%08x).\n",
                     FileName,
                     ErrorStatus);

            /* Select the resource ID message */
            ErrorResourceId = 9015;
            break;

        case BL_FATAL_ERROR_GENERIC:

            /* The NTSTATUS code is in parameter 1*/
            ErrorStatus = (NTSTATUS)Parameter1;

            /* Build the error string */
            swprintf(FormatString,
                     L"\nThe boot manager experienced an error (%08x).\n",
                     ErrorStatus);

            /* Select the resource ID message */
            ErrorResourceId = 9005;
            break;

        default:

            /* The rest is not yet handled */
            EfiPrintf(L"Unexpected fatal error: %lx\r\n", ErrorCode);
            while (1);
            break;
    }

    /* Check if the BCD option for restart is set */
    BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                           BcdLibraryBoolean_RestartOnFailure,
                           &Restart);
    if (Restart)
    {
        /* Yes, so no error should be shown since we'll auto-restart */
        NoError = TRUE;
    }
    else
    {
        /* Check if the option for not showing errors is set in the BCD */
        BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                               BcdBootMgrBoolean_NoErrorDisplay,
                               &NoError);
    }

    /* Do we want an error? */
    if (!NoError)
    {
        /* Yep, print it and then raise an error */
        BlStatusPrint(FormatString);
        BlStatusError(1, ErrorCode, Parameter1, Parameter2, Parameter3);
    }

    /* Get the help message ID */
    ErrorHelpId = BmpFatalErrorMessageFilter(ErrorStatus, &ErrorResourceId);
    BmpErrorLog(ErrorCode, ErrorStatus, ErrorResourceId, Buffer, ErrorHelpId);
}

NTSTATUS
BmpFwGetFullPath (
    _In_ PWCHAR FileName,
    _Out_ PWCHAR* FullPath
    )
{
    NTSTATUS Status;
    SIZE_T BootDirLength, PathLength;

    /* Compute the length of the directory, and add a NUL */
    BootDirLength = wcslen(BootDirectory);
    Status = RtlSIZETAdd(BootDirLength, 1, &BootDirLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Add the length of the file, make sure it fits */
    PathLength = wcslen(FileName);
    Status = RtlSIZETAdd(PathLength, BootDirLength, &PathLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Convert to bytes */
    Status = RtlSIZETMult(PathLength, sizeof(WCHAR), &PathLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Allocate the full path */
    *FullPath = BlMmAllocateHeap(PathLength);
    if (*FullPath)
    {
        /* Copy the directory followed by the file name */
        wcsncpy(*FullPath, BootDirectory, PathLength / sizeof(WCHAR));
        wcsncat(*FullPath, FileName, PathLength / sizeof(WCHAR));
    }
    else
    {
        /* Bail out since we have no memory */
        Status = STATUS_NO_MEMORY;
    }

Quickie:
    /* Return to caller */
    return Status;
}

VOID
BmCloseDataStore (
    _In_ HANDLE Handle
    )
{
    /* Check if boot.ini data needs to be freed */
    if (BmBootIniUsed)
    {
        EfiPrintf(L"Boot.ini not handled\r\n");
    }

    /* Dereference the hive and close the key */
    BiDereferenceHive(Handle);
    BiCloseKey(Handle);
}

NTSTATUS
BmOpenDataStore (
    _Out_ PHANDLE Handle
    )
{
    NTSTATUS Status;
    PBL_DEVICE_DESCRIPTOR BcdDevice;
    PWCHAR BcdPath, FullPath, PathBuffer;
    BOOLEAN HavePath;
    SIZE_T PathLength, FullSize;
    PVOID FinalBuffer;
    UNICODE_STRING BcdString;

    /* Initialize variables */
    PathBuffer = NULL;
    BcdDevice = NULL;
    BcdPath = NULL;
    HavePath = FALSE;

    /* Check if a boot.ini file exists */
    Status = BmOpenBootIni();
    if (NT_SUCCESS(Status))
    {
        BmBootIniUsed = TRUE;
    }

    /* Check on which device the BCD is */
    Status = BlGetBootOptionDevice(BlpApplicationEntry.BcdData,
                                   BcdBootMgrDevice_BcdDevice,
                                   &BcdDevice,
                                   NULL);
    if (!NT_SUCCESS(Status))
    {
        /* It's not on a custom device, so it must be where we are */
        Status = BlGetBootOptionDevice(BlpApplicationEntry.BcdData,
                                       BcdLibraryDevice_ApplicationDevice,
                                       &BcdDevice,
                                       NULL);
        if (!NT_SUCCESS(Status))
        {
            /* This BCD option is required */
            goto Quickie;
        }
    }

    /* Next, check what file contains the BCD */
    Status = BlGetBootOptionString(BlpApplicationEntry.BcdData,
                                   BcdBootMgrString_BcdFilePath,
                                   &BcdPath);
    if (NT_SUCCESS(Status))
    {
        /* We don't handle custom BCDs yet */
        EfiPrintf(L"Custom BCD Not handled: %s\r\n", BcdPath);
        Status = STATUS_NOT_IMPLEMENTED;
        goto Quickie;
    }

    /* Now check if the BCD is on a remote share */
    if (BcdDevice->DeviceType == UdpDevice)
    {
        /* Nope. Nope. Nope */
        EfiPrintf(L"UDP device Not handled\r\n");
        Status = STATUS_NOT_IMPLEMENTED;
        goto Quickie;
    }

    /* Otherwise, compute the hardcoded path of the BCD */
    Status = BmpFwGetFullPath(L"\\BCD", &FullPath);
    if (!NT_SUCCESS(Status))
    {
        /* User the raw path */
        PathBuffer = BcdPath;
    }
    else
    {
        /* Use the path we got */
        PathBuffer = FullPath;
        HavePath = TRUE;
    }

    /* Check if we failed to get the BCD path */
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Add a NUL to the path, make sure it'll fit */
    PathLength = wcslen(PathBuffer);
    Status = RtlSIZETAdd(PathLength, 1, &PathLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Convert to bytes */
    Status = RtlSIZETMult(PathLength, sizeof(WCHAR), &PathLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Now add the size of the path to the device path, check if it fits */
    Status = RtlSIZETAdd(PathLength, BcdDevice->Size, &FullSize);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Allocate a final structure to hold both entities */
    FinalBuffer = BlMmAllocateHeap(FullSize);
    if (!FinalBuffer)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Copy the device path and file path into the final buffer */
    RtlCopyMemory(FinalBuffer, BcdDevice, BcdDevice->Size);
    RtlCopyMemory((PVOID)((ULONG_PTR)FinalBuffer + BcdDevice->Size),
                  PathBuffer,
                  PathLength);

    /* Now tell the BCD engine to open the store */
    BcdString.Length = FullSize;
    BcdString.MaximumLength = FullSize;
    BcdString.Buffer = FinalBuffer;
    Status = BcdOpenStoreFromFile(&BcdString, Handle);

    /* Free our final buffer */
    BlMmFreeHeap(FinalBuffer);

Quickie:
    /* Did we allocate a device? */
    if (BcdDevice)
    {
        /* Free it */
        BlMmFreeHeap(BcdDevice);
    }

    /* Is this the failure path? */
    if (!NT_SUCCESS(Status))
    {
        /* Raise a fatal error */
        BmFatalErrorEx(BL_FATAL_ERROR_BCD_READ,
                       (ULONG_PTR)PathBuffer,
                       Status,
                       0,
                       0);
    }

    /* Did we get an allocated path? */
    if ((PathBuffer) && (HavePath))
    {
        /* Free it */
        BlMmFreeHeap(PathBuffer);
    }

    /* Return back to the caller */
    return Status;
}

typedef struct _BL_BSD_LOG_OBJECT
{
    ULONG DeviceId;
    ULONG FileId;
    ULONG Unknown;
    ULONG Size;
    ULONG Flags;
} BL_BSD_LOG_OBJECT, *PBL_BSD_LOG_OBJECT;

BL_BSD_LOG_OBJECT BsdpLogObject;
BOOLEAN BsdpLogObjectInitialized;

VOID
BlBsdInitializeLog (
    _In_ PBL_DEVICE_DESCRIPTOR LogDevice,
    _In_ PWCHAR LogPath,
    _In_ ULONG Flags
    )
{
    NTSTATUS Status;

    /* Don't initialize twice */
    if (BsdpLogObjectInitialized)
    {
        return;
    }

    /* Set invalid IDs for now */
    BsdpLogObject.DeviceId = -1;
    BsdpLogObject.FileId = -1;

    /* Open the BSD device */
    Status = BlpDeviceOpen(LogDevice,
                           BL_DEVICE_READ_ACCESS | BL_DEVICE_WRITE_ACCESS,
                           0,
                           &BsdpLogObject.DeviceId);
    if (!NT_SUCCESS(Status))
    {
        /* Welp that didn't work */
        goto FailurePath;
    }

    /* Now open the BSD itself */
    Status = BlFileOpen(BsdpLogObject.DeviceId,
                        LogPath,
                        BL_FILE_READ_ACCESS | BL_FILE_WRITE_ACCESS,
                        &BsdpLogObject.FileId);
    if (!NT_SUCCESS(Status))
    {
        /* D'oh */
        goto FailurePath;
    }

    /* The BSD is open. Start doing stuff to it */
    EfiPrintf(L"Unimplemented BSD path\r\n");
    Status = STATUS_NOT_IMPLEMENTED;

FailurePath:
    /* Close the BSD if we had it open */
    if (BsdpLogObject.FileId != -1)
    {
        BlFileClose(BsdpLogObject.FileId);
    }

    /* Close the device if we had it open */
    if (BsdpLogObject.DeviceId != -1)
    {
        BlDeviceClose(BsdpLogObject.DeviceId);
    }

    /* Set BSD object to its uninitialized state */
    BsdpLogObjectInitialized = FALSE;
    BsdpLogObject.FileId = 0;
    BsdpLogObject.DeviceId = 0;
    BsdpLogObject.Flags = 0;
    BsdpLogObject.Unknown = 0;
    BsdpLogObject.Size = 0;
}

VOID
BmpInitializeBootStatusDataLog (
    VOID
    )
{
    NTSTATUS Status;
    PBL_DEVICE_DESCRIPTOR BsdDevice;
    PWCHAR BsdPath;
    ULONG Flags;
    BOOLEAN PreserveBsd;

    /* Initialize locals */
    BsdPath = NULL;
    BsdDevice = NULL;
    Flags = 0;

    /* Check if the BSD is stored in a custom device */
    Status = BlGetBootOptionDevice(BlpApplicationEntry.BcdData,
                                   BcdLibraryDevice_BsdLogDevice,
                                   &BsdDevice,
                                   NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Nope, use the boot device */
        BsdDevice = BlpBootDevice;
    }

    /* Check if the path is custom as well */
    Status = BlGetBootOptionString(BlpApplicationEntry.BcdData,
                                   BcdLibraryString_BsdLogPath,
                                   &BsdPath);
    if (!NT_SUCCESS(Status))
    {
        /* Nope, use our default path */
        Status = BmpFwGetFullPath(L"\\bootstat.dat", &BsdPath);
        if (!NT_SUCCESS(Status))
        {
            BsdPath = NULL;
        }

        /* Set preserve flag */
        Flags = 1;
    }
    else
    {
        /* Set preserve flag */
        Flags = 1;
    }

    /* Finally, check if the BSD should be preserved */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdLibraryBoolean_PreserveBsdLog,
                                    &PreserveBsd);
    if (!(NT_SUCCESS(Status)) || !(PreserveBsd))
    {
        /* We failed to read, or we were asked not to preserve it */
        Flags = 0;
    }

    /* Initialize the log */
    BlBsdInitializeLog(BsdDevice, BsdPath, Flags);

    /* Free the BSD device descriptor if we had one */
    if (BsdDevice)
    {
        BlMmFreeHeap(BsdDevice);
    }

    /* Free the BSD path if we had one */
    if ((Flags) && (BsdPath))
    {
        BlMmFreeHeap(BsdPath);
    }
}

VOID
BmFwMemoryInitialize (
    VOID
    )
{
    NTSTATUS Status;
    PHYSICAL_ADDRESS PhysicalAddress;
    BL_ADDRESS_RANGE AddressRange;

    /* Select the range below 1MB */
    AddressRange.Maximum = 0xFFFFF;
    AddressRange.Minimum = 0;

    /* Allocate one reserved page with the "below 1MB" attribute */
    Status = MmPapAllocatePhysicalPagesInRange(&PhysicalAddress,
                                               BlApplicationReserved,
                                               1,
                                               BlMemoryBelow1MB,
                                               0,
                                               &MmMdlUnmappedAllocated,
                                               &AddressRange,
                                               BL_MM_REQUEST_DEFAULT_TYPE);
    if (!NT_SUCCESS(Status))
    {
        /* Print a message on error, but keep going */
        BlStatusPrint(L"BmFwMemoryInitialize: Failed to allocate a page below 1MB. Status: 0x%08x\r\n",
                      Status);
    }
}

NTSTATUS
BmpBgDisplayClearScreen (
    _In_ ULONG Color
    )
{
    /* Not yet supported */
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
BlXmiWrite (
    _In_ PWCHAR XmlTag
    )
{
    /* Sigh */
    EfiPrintf(L"XML: %s\r\n", XmlTag);
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
BlXmiInitialize (
    _In_ PWCHAR Stylesheet
    )
{
    /* Reset the cursor type */
    BlDisplaySetCursorType(0);

    /* Nope, not doing any XML stuff */
    return STATUS_SUCCESS;
}

NTSTATUS
BmFwVerifySelfIntegrity (
    VOID
    )
{
    /* Check if we're booted by UEFI off the DVD directly */
    if ((BlpBootDevice->DeviceType == LocalDevice) &&
        (BlpBootDevice->Local.Type == CdRomDevice) &&
        (BlpApplicationFlags & BL_APPLICATION_FLAG_CONVERTED_FROM_EFI))
    {
        /* Windows actually bypasses integrity checks in this case. Works for us */
        return STATUS_SUCCESS;
    }

    /* Our binaries aren't signed, so always return failure */
    return 0xC0000428;
}

NTSTATUS
BmFwRegisterRevocationList (
    VOID
    )
{
    NTSTATUS Status;
    BOOLEAN SecureBootEnabled;

    /* Is SecureBoot enabled? */
    Status = BlSecureBootIsEnabled(&SecureBootEnabled);
    if ((NT_SUCCESS(Status)) && (SecureBootEnabled))
    {
        EfiPrintf(L"SB not implemented revok\r\n");
        return STATUS_NOT_IMPLEMENTED;
    }
    else
    {
        /* Nothing to do without SecureBoot */
        Status = STATUS_SUCCESS;
    }

    /* Return revocation result back to caller */
    return Status;
}

NTSTATUS
BmResumeFromHibernate (
    _Out_ PHANDLE BcdResumeHandle
    )
{
    NTSTATUS Status;
    BOOLEAN AttemptResume;

    /* Should we attempt to resume from hibernation? */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdBootMgrBoolean_AttemptResume,
                                    &AttemptResume);
    if (!NT_SUCCESS(Status))
    {
        /* Nope. Is automatic restart on crash enabled? */
        AttemptResume = FALSE;
        Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                        BcdOSLoaderBoolean_DisableCrashAutoReboot,
                                        &AttemptResume);
        AttemptResume = (NT_SUCCESS(Status) && (AttemptResume));
    }

    /* Don't do anything if there's no need to resume anything */
    if (!AttemptResume)
    {
        return STATUS_SUCCESS;
    }

    /* Not yet implemented */
    EfiPrintf(L"Resume not supported\r\n");
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
BmpProcessBadMemory (
    VOID
    )
{
    BL_PD_DATA_BLOB BadMemoryData;
    NTSTATUS Status;

    /* Try to get the memory data from the memtest application */
    BadMemoryData.BlobSize = 0;
    BadMemoryData.Data = NULL;
    BadMemoryData.DataSize = 0;
    Status = BlPdQueryData(&BadMemoryGuid, NULL, &BadMemoryData);
    if (Status != STATUS_BUFFER_TOO_SMALL)
    {
        /* No results, or some other error */
        return Status;
    }

    /* Not yet implemented */
    EfiPrintf(L"Bad page list persistence not implemented\r\n");
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
BmPurgeOption (
    _In_ HANDLE BcdHandle,
    _In_ PGUID ObjectId,
    _In_ ULONG Type
    )
{
    HANDLE ObjectHandle;
    NTSTATUS Status;

    /* Open the object */
    Status = BcdOpenObject(BcdHandle, ObjectId, &ObjectHandle);
    if (NT_SUCCESS(Status))
    {
        /* Delete the element */
        BcdDeleteElement(ObjectHandle, Type);

        /* Close the object and set success */
        BiCloseKey(ObjectHandle);
        Status = STATUS_SUCCESS;
    }

    /* Return the result */
    return Status;
}

NTSTATUS
BmGetEntryDescription (
    _In_ HANDLE BcdHandle,
    _In_ PGUID ObjectId,
    _Out_ PBCD_OBJECT_DESCRIPTION Description
    )
{
    NTSTATUS Status;
    HANDLE ObjectHandle;

    /* Open the BCD object */
    Status = BcdOpenObject(BcdHandle, ObjectId, &ObjectHandle);
    if (NT_SUCCESS(Status))
    {
        /* Make sure the caller passed this argument in */
        if (!Description)
        {
            /* Fail otherwise */
            Status = STATUS_INVALID_PARAMETER;
        }
        else
        {
            /* Query the description from the BCD interface */
            Status = BiGetObjectDescription(ObjectHandle, Description);
        }

        /* Close the object key */
        BiCloseKey(ObjectHandle);
    }

    /* Return the result back */
    return Status;
}

NTSTATUS
BmpPopulateBootEntryList (
    _In_ HANDLE BcdHandle,
    _In_ PGUID SequenceList,
    _In_ ULONG Flags,
    _Out_ PBL_LOADED_APPLICATION_ENTRY* BootSequence,
    _Out_ PULONG SequenceCount
    )
{
    NTSTATUS Status;
    ULONG BootIndex, i, OptionSize;
    PBL_LOADED_APPLICATION_ENTRY BootEntry;
    PBL_BCD_OPTION Options;
    BCD_OBJECT_DESCRIPTION Description;
    BcdObjectType ObjectType;
    BOOLEAN HavePath, IsWinPe, SoftReboot;
    PWCHAR LoaderPath;

    /* Initialize locals */
    Options = NULL;
    BootIndex = 0;
    Status = STATUS_NOT_FOUND;

    /* Loop through every element in the sequence */
    for (i = 0; i < *SequenceCount; i++)
    {
        /* Assume failure */
        BootEntry = NULL;

        /* Get the options for the sequence element */
        Status = BmGetOptionList(BcdHandle, SequenceList, &Options);
        if (!NT_SUCCESS(Status))
        {
            EfiPrintf(L"option list failed: %lx\r\n", Status);
            goto LoopQuickie;
        }

        /* Make sure there's at least a path and description */
        if (!(MiscGetBootOption(Options, BcdLibraryDevice_ApplicationDevice)) ||
            !(MiscGetBootOption(Options, BcdLibraryString_Description)))
        {
            Status = STATUS_UNSUCCESSFUL;
            EfiPrintf(L"missing list failed: %lx\r\n", Status);
            goto LoopQuickie;
        }

        /* Get the size of the BCD options and allocate a large enough entry */
        OptionSize = BlGetBootOptionListSize(Options);
        BootEntry = BlMmAllocateHeap(sizeof(*BootEntry) + OptionSize);
        if (!BootEntry)
        {
            Status = STATUS_NO_MEMORY;
            goto Quickie;
        }

        /* Save it as part of the sequence */
        BootSequence[BootIndex] = BootEntry;

        /* Initialize it, and copy the BCD data */
        RtlZeroMemory(BootEntry, sizeof(*BootEntry));
        BootEntry->Guid = *SequenceList;
        BootEntry->BcdData = (PBL_BCD_OPTION)(BootEntry + 1);
        BootEntry->Flags = Flags;
        RtlCopyMemory(BootEntry->BcdData, Options, OptionSize);

        /* Get the object descriptor to find out what kind of entry it is */
        Status = BmGetEntryDescription(BcdHandle,
                                       &BootEntry->Guid,
                                       &Description);
        if (!NT_SUCCESS(Status))
        {
            EfiPrintf(L"missing desc failed: %lx\r\n", Status);
            goto LoopQuickie;
        }

        /* Check if a path was given or not */
        HavePath = MiscGetBootOption(Options, BcdLibraryString_ApplicationPath) ?
                   TRUE : FALSE;

        /* Now select based on what type of object this is -- must be an app */
        ObjectType.PackedValue = Description.Type;
        if (ObjectType.Application.ObjectCode == BCD_OBJECT_TYPE_APPLICATION)
        {
            /* Then select based on what kind of app it is */
            switch (ObjectType.Application.ApplicationCode)
            {
                /* Another boot manager */
                case BCD_APPLICATION_TYPE_BOOTMGR:
                    BootEntry->Flags |= BCD_APPLICATION_TYPE_BOOTMGR;
                    break;

                /* An OS loader */
                case BCD_APPLICATION_TYPE_OSLOADER:
                    BootEntry->Flags |= BL_APPLICATION_ENTRY_WINLOAD;

                    /* Do we have a path for it? */
                    if (!HavePath)
                    {
                        /* We'll try to make one up. Is this WinPE? */
                        IsWinPe = FALSE;
                        Status = BlGetBootOptionBoolean(Options,
                                                        BcdOSLoaderBoolean_WinPEMode,
                                                        &IsWinPe);
                        if (!(NT_SUCCESS(Status)) && (Status != STATUS_NOT_FOUND))
                        {
                            goto Quickie;
                        }

                        /* Use the appropriate path for WinPE or local install */
                        LoaderPath = IsWinPe ?
                                     L"\\Windows\\System32\\boot\\winload.efi" :
                                     L"\\Windows\\System32\\winload.efi";

                        /* Add the path to the boot entry */
                        Status = BlAppendBootOptionString(BootEntry,
                                                          BcdLibraryString_ApplicationPath,
                                                          LoaderPath);
                        if (!NT_SUCCESS(Status))
                        {
                            goto Quickie;
                        }

                        /* We have a path now */
                        HavePath = TRUE;
                    }
                    break;

                /* A hibernate-resume application */
                case BCD_APPLICATION_TYPE_RESUME:
                    BootEntry->Flags |= BL_APPLICATION_ENTRY_WINRESUME;
                    break;

                /* An older OS NTLDR */
                case BCD_APPLICATION_TYPE_NTLDR:
                    BootEntry->Flags |= BL_APPLICATION_ENTRY_NTLDR;
                    break;

                /* An older OS SETUPLDR */
                case BCD_APPLICATION_TYPE_SETUPLDR:
                    BootEntry->Flags |= BL_APPLICATION_ENTRY_SETUPLDR;
                    break;

                /* A 3rd party/Win9x boot sector */
                case BCD_APPLICATION_TYPE_BOOTSECTOR:
                    BootEntry->Flags |= BL_APPLICATION_ENTRY_BOOTSECTOR;
                    break;

                /* Something else entirely */
                default:
                    break;
            }
        }

        /* We better have a path by now */
        if (!HavePath)
        {
            Status = STATUS_UNSUCCESSFUL;
            goto LoopQuickie;
        }

        /* Check if this is a real mode startup.com */
        if ((ObjectType.Application.ObjectCode == BCD_OBJECT_TYPE_APPLICATION) &&
            (ObjectType.Application.ImageCode == BCD_IMAGE_TYPE_REAL_MODE) &&
            (ObjectType.Application.ApplicationCode == BCD_APPLICATION_TYPE_STARTUPCOM))
        {
            /* Check if PXE soft reboot will occur */
            Status = BlGetBootOptionBoolean(Options,
                                            BcdStartupBoolean_PxeSoftReboot,
                                            &SoftReboot);
            if ((NT_SUCCESS(Status)) && (SoftReboot))
            {
                /* Then it's a valid startup.com entry */
                BootEntry->Flags |= BL_APPLICATION_ENTRY_STARTUP;
            }
        }

LoopQuickie:
        /* All done with this entry -- did we have BCD options? */
        if (Options)
        {
            /* Free them, they're part of the entry now */
            BlMmFreeHeap(Options);
            Options = NULL;
        }

        /* Did we fail anywhere? */
        if (!NT_SUCCESS(Status))
        {
            /* Yep -- did we fail with an active boot entry? */
            if (BootEntry)
            {
                /* Destroy it */
                BlDestroyBootEntry(BootEntry);
                BootSequence[BootIndex] = NULL;
            }
        }
        else
        {
            /* It worked, so populate the next index now */
            BootIndex++;
        }

        /* And move to the next GUID in the sequence list */
        SequenceList++;
    }

Quickie:
    /* All done now -- did we have any BCD options? */
    if (Options)
    {
        /* Free them */
        BlMmFreeHeap(Options);
    }

    /* Return the status */
    return Status;
}

NTSTATUS
BmGetBootSequence (
    _In_ HANDLE BcdHandle,
    _In_ PGUID SequenceList,
    _In_ ULONG SequenceListCount,
    _In_ ULONG Flags,
    _Out_ PBL_LOADED_APPLICATION_ENTRY** BootSequence,
    _Out_ PULONG SequenceCount
    )
{
    PBL_LOADED_APPLICATION_ENTRY* Sequence;
    ULONG Count = SequenceListCount;
    NTSTATUS Status;

    /* Allocate the sequence list */
    Sequence = BlMmAllocateHeap(SequenceListCount * sizeof(*Sequence));
    if (!Sequence)
    {
        return STATUS_NO_MEMORY;
    }

    /* Populate the sequence list */
    Status = BmpPopulateBootEntryList(BcdHandle,
                                      SequenceList,
                                      Flags,
                                      Sequence,
                                      &Count);
    if (!NT_SUCCESS(Status))
    {
        /* Free the list on failure */
        BlMmFreeHeap(Sequence);
    }
    else
    {
        /* Otherwise, set success and return the list and count */
        Status = STATUS_SUCCESS;
        *BootSequence = Sequence;
        *SequenceCount = Count;
    }

    /* All done */
    return Status;
}

NTSTATUS
BmEnumerateBootEntries (
    _In_ HANDLE BcdHandle,
    _Out_ PBL_LOADED_APPLICATION_ENTRY **BootSequence,
    _Out_ PULONG SequenceCount
    )
{
    NTSTATUS Status;
    ULONG BootIndex, BootIniCount, BootEntryCount, BcdCount;
    PBL_LOADED_APPLICATION_ENTRY* Sequence;
    PGUID DisplayOrder;
    GUID DefaultObject;
    BOOLEAN UseDisplayList;

    /* Initialize locals */
    BootIndex = 0;

    /* First try to get the display list, if any */
    UseDisplayList = TRUE;
    Status = BlGetBootOptionGuidList(BlpApplicationEntry.BcdData,
                                     BcdBootMgrObjectList_DisplayOrder,
                                     &DisplayOrder,
                                     &BcdCount);
    if (!NT_SUCCESS(Status))
    {
        /* No list, get the default entry instead */
        Status = BlGetBootOptionGuid(BlpApplicationEntry.BcdData,
                                     BcdBootMgrObject_DefaultObject,
                                     &DefaultObject);
        if (NT_SUCCESS(Status))
        {
            /* Set the array to just our entry */
            UseDisplayList = FALSE;
            BcdCount = 1;
            DisplayOrder = &DefaultObject;
        }
        else
        {
            /* No default list either, return success but no entries */
            *BootSequence = NULL;
            *SequenceCount = 0;
            Status = STATUS_SUCCESS;
            DisplayOrder = NULL;
            goto Quickie;
        }
    }

    /* Check if boot.ini was used */
    BootIniCount = 0;
    if (BmBootIniUsed)
    {
        /* Get the entries from it */
        EfiPrintf(L"Boot.ini not supported\r\n");
        BootIniCount = 0;//BmBootIniGetEntryCount();
    }

    /* Allocate an array large enough for the combined boot entries */
    BootEntryCount = BootIniCount + BcdCount;
    Sequence = BlMmAllocateHeap(BootEntryCount * sizeof(*Sequence));
    if (!Sequence)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Zero it out */
    RtlZeroMemory(Sequence, BootEntryCount * sizeof(*Sequence));

    /* Check if we had BCD entries */
    if (BcdCount)
    {
        /* Populate the list of bootable entries */
        Status = BmpPopulateBootEntryList(BcdHandle,
                                          DisplayOrder,
                                          BL_APPLICATION_ENTRY_DISPLAY_ORDER,
                                          Sequence,
                                          &BcdCount);
        if (!NT_SUCCESS(Status))
        {
            /* Bail out */
            goto Quickie;
        }
    }

    /* Check if we had boot.ini entries */
    if (BootIniCount)
    {
        /* TODO */
        EfiPrintf(L"Boot.ini not supported\r\n");
    }

    /* Return success and the sequence + count populated */
    Status = STATUS_SUCCESS;
    *BootSequence = Sequence;
    *SequenceCount = BootIniCount + BcdCount;

Quickie:
    /* Check if we had allocated a GUID list */
    if ((UseDisplayList) && (DisplayOrder))
    {
        /* Free it */
        BlMmFreeHeap(DisplayOrder);
    }

    /* Check if this is the failure path */
    if (!(NT_SUCCESS(Status)) && (Sequence))
    {
        /* Loop the remaining boot entries */
        while (BootIndex < BootEntryCount)
        {
            /* Check if it had been allocated */
            if (Sequence[BootIndex])
            {
                /* Free it */
                BlMmFreeHeap(Sequence[BootIndex]);
            }

            /* Next*/
            BootIndex++;
        }

        /* Free the whole sequence now */
        BlMmFreeHeap(Sequence);
    }

    /* All done, return the result */
    return Status;
}

VOID
BmpGetDefaultBootEntry (
    _In_ PBL_LOADED_APPLICATION_ENTRY* Sequence,
    _In_ ULONG Count,
    _Out_ PBL_LOADED_APPLICATION_ENTRY* DefaultEntry,
    _Out_ PULONG DefaultIndex
    )
{
    GUID DefaultObject;
    NTSTATUS Status;
    ULONG BootIndex;

    /* Assume no default */
    *DefaultEntry = *Sequence;
    *DefaultIndex = 0;

    /* Nothing to do if there's just one entry */
    if (Count == 1)
    {
        return;
    }

    /* Get the default object, bail out if there isn't one */
    Status = BlGetBootOptionGuid(BlpApplicationEntry.BcdData,
                                 BcdBootMgrObject_DefaultObject,
                                 &DefaultObject);
    if (!(NT_SUCCESS(Status)) || !(Count))
    {
        return;
    }

    /* Scan the boot sequence */
    for (BootIndex = 0; BootIndex < Count; BootIndex++)
    {
        /* Find one that matches the default */
        if (RtlEqualMemory(&Sequence[BootIndex]->Guid,
                           &DefaultObject,
                           sizeof(GUID)))
        {
            /* Return it */
            *DefaultEntry = Sequence[BootIndex];
            *DefaultIndex = BootIndex;
            return;
        }
    }
}

BL_MENU_POLICY
BmGetBootMenuPolicy (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry
    )
{
    NTSTATUS Status;
    BOOLEAN EmsEnabled;
    ULONGLONG BootMenuPolicy;
    ULONG OptionId;

    /* Check if EMS is enabled */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdOSLoaderBoolean_EmsEnabled,
                                    &EmsEnabled);
    if ((NT_SUCCESS(Status)) && (EmsEnabled))
    {
        /* No boot menu */
        return MenuPolicyLegacy;
    }

    /* Check what entry we are looking at */
    if (!BootEntry)
    {
        /* No entry, pick the selected one */
        BootEntry = BmpSelectedBootEntry;
    }

    /* Do we still not have an entry? */
    if (!BootEntry)
    {
        /* Show the menu */
        return MenuPolicyStandard;
    }

    /* Check if this is an OS loader */
    BootMenuPolicy = 0;
    if (BootEntry->Flags & BL_APPLICATION_ENTRY_WINLOAD)
    {
        /* Use the correct option ID */
        OptionId = BcdOSLoaderInteger_BootMenuPolicy;
    }
    else
    {
        /* Check if this is an OS resumer */
        if (!(BootEntry->Flags & BL_APPLICATION_ENTRY_WINRESUME))
        {
            /* Nope, so no reason for a menu */
            return MenuPolicyLegacy;
        }

        /* Use the correct option ID */
        OptionId = BcdResumeInteger_BootMenuPolicy;
    }

    /* Check the option ID for the boot menu policy */
    Status = BlGetBootOptionInteger(BootEntry->BcdData,
                                    OptionId,
                                    &BootMenuPolicy);
    if (NT_SUCCESS(Status))
    {
        /* We have one, return it */
        return BootMenuPolicy;
    }

    /* No policy, so assume no menu */
    return MenuPolicyLegacy;
}

VOID
BmDisplayGetBootMenuStatus (
    _Out_ PL_MENU_STATUS MenuStatus
    )
{
    /* For now, don't support key input at all */
    MenuStatus->AsULong = 0;
    MenuStatus->OemKey = UNICODE_NULL;
    MenuStatus->BootIndex = -1;
}

NTSTATUS
BmProcessCustomAction (
    _In_ HANDLE BcdHandle,
    _In_ PWCHAR ActionKey
    )
{
    EfiPrintf(L"Custom actions not yet handled\r\n");
    return STATUS_NOT_IMPLEMENTED;
}

VOID
BmpProcessBootEntry (
    _In_ HANDLE BcdHandle,
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry,
    _Out_ PBOOLEAN ExitBootManager
    )
{
    BL_MENU_STATUS MenuStatus;

    /* Don't exit */
    *ExitBootManager = FALSE;

    /* If the legacy menu must be shown, or if we have a boot entry */
    if ((BmGetBootMenuPolicy(BootEntry) != MenuPolicyStandard) || (BootEntry))
    {
        /* Check if any key has been pressed */
        BmDisplayGetBootMenuStatus(&MenuStatus);
        if (MenuStatus.AnyKey)
        {
            /* Was the exit key pressed? */
            if (MenuStatus.Exit)
            {
                /* Don't display a menu, and exit */
                *ExitBootManager = TRUE;
                BmpDisplayBootMenu = FALSE;
            }
            else if (MenuStatus.OemKey)
            {
                /* Process the OEM key action */
                BmProcessCustomAction(BcdHandle, &MenuStatus.KeyValue);
            }
            else
            {
                /* Process other keys */
                EfiPrintf(L"TODO\r\n");
            }
        }
    }
}

NTSTATUS
BmpGetSelectedBootEntry (
    _In_ HANDLE BcdHandle,
    _Out_ PBL_LOADED_APPLICATION_ENTRY* SelectedBootEntry,
    _Out_ PULONG EntryIndex,
    _Out_ PBOOLEAN ExitBootManager
    )
{
    NTSTATUS Status;
    PBL_LOADED_APPLICATION_ENTRY* Sequence;
    PBL_LOADED_APPLICATION_ENTRY Entry, SelectedEntry;
    ULONG Count, BootIndex, SelectedIndex;
  //  BOOLEAN FoundFailedEntry;
    ULONGLONG Timeout;

    /* Initialize locals */
    BootIndex = 0;
    Count = 0;
    Sequence = NULL;
    SelectedEntry = NULL;

    /* Enumerate all the boot entries */
    Status = BmEnumerateBootEntries(BcdHandle, &Sequence, &Count);
    if (!NT_SUCCESS(Status))
    {
        /* Bail out if we failed */
        goto Quickie;
    }

    /* Check if there are no entries */
    if (!Count)
    {
        /* This is fatal -- kill the system */
        Status = STATUS_FILE_INVALID;
        BmFatalErrorEx(BL_FATAL_ERROR_BCD_ENTRIES, (ULONG_PTR)L"\\BCD", Status, 0, 0);
        goto Quickie;
    }

    /* Check if we don't yet have an array of failed boot entries */
    if (!BmpFailedBootEntries)
    {
        /* Allocate it */
        BmpFailedBootEntries = BlMmAllocateHeap(Count);
        if (BmpFailedBootEntries)
        {
            /* Zero it out */
            RtlZeroMemory(BmpFailedBootEntries, Count);
        }
    }

    /* Check if we have a hardcoded boot override */
    if (BmBootEntryOverridePresent)
    {
        EfiPrintf(L"Hard-coded boot override mode not supported\r\n");
    }

    /* Log the OS count */
    //BlLogEtwWrite(BOOT_BOOTMGR_MULTI_OS_COUNT);

    /* Check if the display is already active and cached */
    if (!BmDisplayStateCached)
    {
        /* Check if we should display a boot menu */
        Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                        BcdBootMgrBoolean_DisplayBootMenu,
                                        &BmpDisplayBootMenu);
        if (!NT_SUCCESS(Status))
        {
            /* Assume not */
            BmpDisplayBootMenu = FALSE;
        }
    }

    /* Check if there's only one entry to boot anyway */
    if (Count == 1)
    {
        /* Read it */
        SelectedEntry = *Sequence;

        /* Process it */
        BmpProcessBootEntry(BcdHandle, SelectedEntry, ExitBootManager);

        /* Check if we're not displaying a boot menu */
        if (!BmpDisplayBootMenu)
        {
            /* Now we are */
            BmpDisplayBootMenu = TRUE;

            /* Return the entry and its index back */
            *EntryIndex = 0;
            *SelectedBootEntry = SelectedEntry;
            Status = STATUS_SUCCESS;
            goto Quickie;
        }
    }
    else
    {
        /* Get the default boot entry */
        BmpGetDefaultBootEntry(Sequence, Count, &SelectedEntry, &SelectedIndex);

        /* Check if we have a failed boot entry array allocated */
        //FoundFailedEntry = FALSE;
        if (BmpFailedBootEntries)
        {
            /* Check if the default entry failed to boot */
            if (BmpFailedBootEntries[SelectedIndex])
            {
                /* Loop through the current boot sequence */
                for (SelectedIndex = 0; SelectedIndex < Count; SelectedIndex++)
                {
                    /* Check if there's no sequence for this index, or it failed */
                    while (!(Sequence[SelectedIndex]) ||
                            (BmpFailedBootEntries[SelectedIndex]))
                    {
                        /* Remember that this is a failed entry */
                        SelectedEntry = Sequence[SelectedIndex];
                        //FoundFailedEntry = TRUE;
                        BmpDisplayBootMenu = FALSE;
                    }
                }
            }
        }

        /* Check if the entry is an OS loader */
        if (SelectedEntry->Flags & BL_APPLICATION_ENTRY_WINLOAD)
        {
            // todo
            EfiPrintf(L"todo path\r\n");
        }

        /* Check if there's no timeout */
        Status = BlGetBootOptionInteger(BlpApplicationEntry.BcdData,
                                        BcdBootMgrInteger_Timeout,
                                        &Timeout);
        if ((NT_SUCCESS(Status) && !(Timeout)))
        {
            /* There isn't, so just process the default entry right away */
            BmpProcessBootEntry(BcdHandle, SelectedEntry, ExitBootManager);

            /* Check if we're not displaying a boot menu */
            if (!BmpDisplayBootMenu)
            {
                /* Now we are */
                BmpDisplayBootMenu = TRUE;

                /* Return the entry and its index back */
                *EntryIndex = 0;
                *SelectedBootEntry = SelectedEntry;
                Status = STATUS_SUCCESS;
                goto Quickie;
            }

            /* Remove the timeout for this boot instance */
            BlRemoveBootOption(BlpApplicationEntry.BcdData,
                               BcdBootMgrInteger_Timeout);
        }
    }

    /* Here is where we display the menu and list of tools */
    EfiPrintf(L"Tool selection not yet implemented\r\n");
    EfiStall(10000000);
    *SelectedBootEntry = NULL;

Quickie:
    /* We are done -- did we have a sequence? */
    if (Sequence)
    {
        /* Do we have any boot entries we parsed? */
        while (BootIndex < Count)
        {
            /* Get the current boot entry */
            Entry = Sequence[BootIndex];

            /* Did we fail, or is is not the selected one? */
            if ((Entry) && ((Entry != SelectedEntry) || !(NT_SUCCESS(Status))))
            {
                /* Destroy it, as it won't be needed */
                BlDestroyBootEntry(Entry);
            }
            else if (Entry == SelectedEntry)
            {
                /* It's the selected one, return its index */
                *EntryIndex = BootIndex;
            }

            /* Move to the next entry */
            BootIndex++;
        }

        /* Free the sequence of entries */
        BlMmFreeHeap(Sequence);
    }

    /* Return the selection result */
    return Status;
}

NTSTATUS 
BmLaunchRecoverySequence (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry,
    _In_ ULONG LaunchCode
    )
{
    NTSTATUS Status;
    PBL_LOADED_APPLICATION_ENTRY RecoveryEntry;
    HANDLE BcdHandle;
    PGUID RecoverySequence;
    ULONG Count, i, RecoveryIndex, SequenceCount;
    PBL_LOADED_APPLICATION_ENTRY* Sequence;

    /* Initialize locals */
    RecoveryIndex = 0;
    Sequence = NULL;
    RecoverySequence = NULL;
    Count = 0;
    BcdHandle = NULL;

    /* Open the BCD*/
    Status = BmOpenDataStore(&BcdHandle);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Get the recovery sequence list */
    Status = BlGetBootOptionGuidList(BootEntry->BcdData,
                                     BcdLibraryObjectList_RecoverySequence,
                                     &RecoverySequence,
                                     &SequenceCount);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Get the sequence of boot entries out of it */
    Status = BmGetBootSequence(BcdHandle,
                               RecoverySequence,
                               SequenceCount,
                               BL_APPLICATION_ENTRY_RECOVERY,
                               &Sequence,
                               &Count);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Was the BCD open? */
    if (BcdHandle)
    {
        /* Close it */
        BmCloseDataStore(BcdHandle);
    }

    /* Now go over every entry in the sequence */
    for (i = 0; i < Count; ++i)
    {
        /* Check the code for this recovery launch */
        if (LaunchCode == 2 || LaunchCode == 5)
        {
            /* Remove the override if there is one, and set it to 4 */
            BlRemoveBootOption(Sequence[i]->BcdData, BcdLibraryInteger_DisplayMessageOverride);
            BlAppendBootOptionInteger(Sequence[i],
                                      BcdLibraryInteger_DisplayMessageOverride,
                                      4);
        }
        else if (LaunchCode == 3)
        {
            /* Remove the override if there is one, and set it to 10 */
            BlRemoveBootOption(Sequence[i]->BcdData, BcdLibraryInteger_DisplayMessageOverride);
            BlAppendBootOptionInteger(Sequence[i],
                                        BcdLibraryInteger_DisplayMessageOverride,
                                        10);
        }

        /* Launch the boot entry for this part of the recovery sequence */
        Status = BmpLaunchBootEntry(Sequence[i], NULL, LaunchCode, FALSE);
        if (!NT_SUCCESS(Status))
        {
            break;
        }
    }

Quickie:
    /* Did we have a sequence of entries? */
    if (Sequence)
    {   
        /* Loop through each one */
        for (RecoveryIndex = 0; RecoveryIndex < Count; RecoveryIndex++)
        {
            /* Does this index have an allocated boot entry? */
            RecoveryEntry = Sequence[RecoveryIndex];
            if (RecoveryEntry)
            {
                /* Destroy it */
                BlDestroyBootEntry(RecoveryEntry);
            }
        }

        /* Free the sequence itself */
        BlMmFreeHeap(Sequence);
    }

    /* Was there a sequence list? */
    if (RecoverySequence)
    {
        /* Free it */
        BlMmFreeHeap(RecoverySequence);
    }
  
    /* Return back to caller */
    return Status;
}

ULONG
BmDisplayDumpError (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry,
    _In_ ULONG LaunchCode
    )
{
    ULONG BootError;
    NTSTATUS Status;
    BOOLEAN Restart, NoError;

    /* Assume we'll just reboot */
    BootError = Reboot;

    /* Should we reboot? */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdLibraryBoolean_RestartOnFailure,
                                    &Restart);
    if ((NT_SUCCESS(Status)) && (Restart))
    {
        return BootError;
    }

    /* Should we not show errors, and thus, reboot? */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdBootMgrBoolean_NoErrorDisplay,
                                    &NoError);
    if ((NT_SUCCESS(Status)) && (NoError))
    {
        return BootError;
    }

    /* Is there an internal boot error? */
    if (BmpInternalBootError)
    {
        /* Return it -- but it's a pointer? */
        return (ULONG_PTR)BmpInternalBootError; // ???
    }

    /* Otherwise, show the menu to see what to do */
    EfiPrintf(L"Error menu not yet implemented\r\n");
    return BootError;
}

NTSTATUS
BmpCreateDevices (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry
    )
{
    ULONG NextOffset, DataOffset, ListOffset;
    PBL_BCD_OPTION Option, ListOption;
    BcdElementType ElementType;
    PBCD_DEVICE_OPTION BcdDevice;

    /* Starting at offset 0, loop every BCD option */
    NextOffset = 0;
    do
    {
        /* Get the current option, and its offset */
        Option = (PBL_BCD_OPTION)((ULONG_PTR)BootEntry->BcdData + NextOffset);
        NextOffset = Option->NextEntryOffset;

        /* If it's empty, ignore it */
        if (Option->Empty)
        {
            continue;
        }

        /* If it's not a device option, ignore it */
        ElementType.PackedValue = Option->Type;
        if (ElementType.Format != BCD_TYPE_DEVICE)
        {
            continue;
        }

        /* Get the data offset */
        DataOffset = Option->DataOffset;

        /* Extract the device out of it */
        BcdDevice = (PBCD_DEVICE_OPTION)((ULONG_PTR)BootEntry->BcdData + DataOffset);

        /* If the device is already fully specified, no need to build it */
        if (!(BcdDevice->DeviceDescriptor.Flags & 1))
        {
            continue;
        }

        /* Otherwise, check if there's any list options as well */
        ListOption = NULL;
        ListOffset = Option->ListOffset;
        if (Option->ListOffset)
        {
            ListOption = (PBL_BCD_OPTION)((ULONG_PTR)BootEntry->BcdData + ListOffset);
        }

        /* And now call BlCreateDevice to build the full device descriptor */
        EfiPrintf(L"Unspecified devices not yet supported: %p\r\n", ListOption);
        return STATUS_NOT_SUPPORTED;
    } while (NextOffset != 0);

    /* Devices created successfully */
    return STATUS_SUCCESS;
}

NTSTATUS
BmpTransferExecution (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry,
    _Out_ PULONG LaunchCode,
    _Out_ PBOOLEAN Recover
    )
{
    PWCHAR AppPath;
    NTSTATUS Status;
    PBL_DEVICE_DESCRIPTOR AppDevice;
    BL_RETURN_ARGUMENTS ReturnArgs;
    BOOLEAN AdvancedOptions;
    ULONG AppHandle;

    /* Get the application path */
    Status = BlGetBootOptionString(BootEntry->BcdData,
                                   BcdLibraryString_ApplicationPath,
                                   &AppPath);
    if (!NT_SUCCESS(Status))
    {
        /* If we couldn't find one, set this to NULL */
        AppPath = NULL;
    }

    /* Check if this is a PXE startup.com */
    if (BootEntry->Flags & BL_APPLICATION_ENTRY_STARTUP)
    {
#if BL_NET_SUPPORT
        /* Do soft reboot to launch it */
        Status = BlNetSoftReboot(BootEntry);
#else
        EfiPrintf(L"Net boot not supported\r\n");
        Status = STATUS_NOT_SUPPORTED;
#endif
        /* Nothing else for us to do */
        goto Quickie;
    }

    /* Loop as long as boot was not cancelled */
    do
    {
        /* Load the boot application */
        Status = BlImgLoadBootApplication(BootEntry, &AppHandle);

        /* Did we not find it? */
        if (Status == STATUS_NOT_FOUND)
        {
            /* Get the device for the boot application */
            Status = BlGetBootOptionDevice(BootEntry->BcdData,
                                           BcdLibraryDevice_ApplicationDevice,
                                           &AppDevice,
                                           NULL);
            if (!NT_SUCCESS(Status))
            {
                /* Force re-enumeration */
                Status = BlFwEnumerateDevice(AppDevice);
            }

            /* Did re-enumeration work? */
            if (!NT_SUCCESS(Status))
            {
                /* Nope, raise a fatal error */
                BmFatalErrorEx(BL_FATAL_ERROR_APP_LOAD,
                               (ULONG_PTR)AppPath,
                               Status,
                               0,
                               0);
                goto Quickie;
            }

            /* Yes, try booting it again */
            Status = BlImgLoadBootApplication(BootEntry, &AppHandle);
        }

        /* Was boot cancelled?*/
        if (Status == STATUS_CANCELLED)
        {
            /* Should we display the menu, or is there no launch sequence? */
            if ((BmGetBootMenuPolicy(BootEntry) != MenuPolicyStandard) ||
                !(MiscGetBootOption(BootEntry->BcdData,
                                    BcdLibraryObjectList_RecoverySequence)))
            {
                /* Bail out, the menu will take care of it */
                goto Quickie;
            }

            /* No menu and there's a sequence, launch it */
            *LaunchCode = 4;
            *Recover = TRUE;
            goto Quickie;
        }

        /* STATUS_FVE_LOCKED_VOLUME -- bitlocker volume is locked */
        if (Status == 0xC0210000)
        {
            /* Launch recovery mode */
            *LaunchCode = 4;
            *Recover = TRUE;
            goto Quickie;
        }

        /* Was there some other error launching the boot application? */
        if (!NT_SUCCESS(Status))
        {
            /* Raise a fatal error */
            BmFatalErrorEx(BL_FATAL_ERROR_APP_LOAD,
                           (ULONG_PTR)AppPath,
                           Status,
                           0,
                           0);
            goto Quickie;
        }

        /* Zero out the return arguments */
        RtlZeroMemory(&ReturnArgs, sizeof(ReturnArgs));

        /* Log to ETW this launch */
        //BmpLogApplicationLaunchEvent(&BootEntry->Guid, AppPath);

        /* Launch the boot application*/
        Status = BlImgStartBootApplication(AppHandle, &ReturnArgs);

#if BL_BITLOCKER_SUPPORT
        /* Bitlocker stuff */
        BlFveSecureBootCheckpointAppReturn(BootEntry, &ReturnArgs);
#endif

        /* Log in the boot status log the launch */
        //BlBsdLogEntry(1, 0x12, &BootEntry->Guid, 0x14);

        /* Unloac the boot application if we've returned */
        BlImgUnloadBootApplication(AppHandle);

        /* Keep going unless STATUS_RESTART_BOOT_APPLICATION */
    } while (Status != 0xC0000453);

    /* We've come back. Assume we need to launch the recovery sequence */
    *Recover = TRUE;

    /* Why did we get back? */
    if (ReturnArgs.Flags & 1)
    {
        /* Flag 1 -- should we display advanced options? */
        Status = BlGetBootOptionBoolean(BootEntry->BcdData,
                                        BcdLibraryBoolean_DisplayAdvancedOptions,
                                        &AdvancedOptions);
        if ((NT_SUCCESS(Status)) && (AdvancedOptions))
        {
            /* Yes, so return with code 2 */
            *LaunchCode = 2;
        }
        else
        {
            /* No, return with code 1 */
            *LaunchCode = 1;
        }
    }
    else if (ReturnArgs.Flags & 4)
    {
        /* Flag 4 -- unknown */
        *LaunchCode = 1;
    }
    else if (ReturnArgs.Flags & 8)
    {
        /* Flag 5 -- unknown */
        *LaunchCode = 5;
    }
    else if (ReturnArgs.Flags & 0x10)
    {
        /* Flag 6 -- unknown */
        *LaunchCode = 6;
    }
    else if (ReturnArgs.Flags & 0x20)
    {
        /* Flag 7 -- unknown */
        *LaunchCode = 7;
    }
    else if (ReturnArgs.Flags & BL_RETURN_ARGUMENTS_NO_PAE_FLAG)
    {
        /* PAE is not supported -- refuse to boot */
        *Recover = FALSE;
        BmFatalErrorEx(BL_FATAL_ERROR_NO_PAE, Status, 0, 0, 0);
    }

Quickie:
    /* All done, did we have an application path? */
    if (AppPath)
    {
        /* Free it */
        BlMmFreeHeap(AppPath);
    }

    /* Back to the caller now */
    return Status;
}

NTSTATUS
BmpLaunchBootEntry (
    _In_ PBL_LOADED_APPLICATION_ENTRY BootEntry,
    _Out_ PULONG EntryIndex,
    _In_ ULONG LaunchCode,
    _In_ BOOLEAN LaunchWinRe
    )
{
    HANDLE BcdHandle;
    NTSTATUS Status;
    GUID ObjectId;
    BOOLEAN DoRecovery, AutoRecovery, DoSequence, RestartOnFailure;
    ULONG ErrorCode;
    BOOLEAN AdvancedOneTime, EditOneTime;

    /* Check if this is the OS loader */
    if (BootEntry->Flags & BL_APPLICATION_ENTRY_WINLOAD)
    {
        /* Check if one-time advanced options should be shown */
        if (MiscGetBootOption(BootEntry->BcdData,
                              BcdOSLoaderBoolean_AdvancedOptionsOneTime))
        {
            /* Open the BCD */
            BcdHandle = NULL;
            Status = BmOpenDataStore(BcdHandle);
            if (NT_SUCCESS(Status))
            {
                /* Delete the option from the BCD, so it doesn't happen again */
                ObjectId = BootEntry->Guid;
                BmPurgeOption(BcdHandle,
                              &ObjectId,
                              BcdOSLoaderBoolean_AdvancedOptionsOneTime);
                BmCloseDataStore(BcdHandle);
            }
        }

        /* Check if one-time options editor should be shown */
        if (MiscGetBootOption(BootEntry->BcdData,
                              BcdOSLoaderBoolean_OptionsEditOneTime))
        {
            /* Open the BCD */
            BcdHandle = NULL;
            Status = BmOpenDataStore(BcdHandle);
            if (NT_SUCCESS(Status))
            {
                /* Delete the option from the BCD, so it doesn't happen again */
                ObjectId = BootEntry->Guid;
                BmPurgeOption(BcdHandle,
                              &ObjectId,
                              BcdOSLoaderBoolean_OptionsEditOneTime);
                BmCloseDataStore(BcdHandle);
            }
        }
    }

TryAgain:
    /* Disable recovery mode */
    DoRecovery = FALSE;

    /* Store globally which entry we are trying to boot */
    BmpSelectedBootEntry = BootEntry;

    /* Create any devices that aren't yet fully defined for this boot entry */
    Status = BmpCreateDevices(BootEntry);
    if (!NT_SUCCESS(Status))
    {
        /* That failed -- can we launch the recovery environment? */
        if (!LaunchWinRe)
        {
            return Status;
        }

        /* Yes, so return with the WinRe launch code */
        LaunchCode = 2;
        goto Quickie;
    }

    /* Is this an OS loader/ */
    if (BootEntry->Flags & BL_APPLICATION_ENTRY_WINLOAD)
    {
        /* Is the one-time advanced options menu option present? */
        Status = BlGetBootOptionBoolean(BootEntry->BcdData,
                                        BcdOSLoaderBoolean_AdvancedOptionsOneTime,
                                        &AdvancedOneTime);
        if (NT_SUCCESS(Status))
        {
            /* Is it turned on? */
            if (AdvancedOneTime)
            {
                /* Set the option this once */
                BlAppendBootOptionBoolean(BootEntry,
                                          BcdLibraryBoolean_DisplayAdvancedOptions,
                                          TRUE);
            }
            else
            {
                /* It's not, so disable the option if active */
                BlRemoveBootOption(BootEntry->BcdData,
                                   BcdLibraryBoolean_DisplayAdvancedOptions);
            }

            /* Remove the one-time option. We've already purged it earlier */
            BlRemoveBootOption(BootEntry->BcdData,
                               BcdOSLoaderBoolean_AdvancedOptionsOneTime);
        }

        /* Is the one-time options editor menu option present? */
        Status = BlGetBootOptionBoolean(BootEntry->BcdData,
                                        BcdOSLoaderBoolean_OptionsEditOneTime,
                                        &EditOneTime);
        if (NT_SUCCESS(Status))
        {
            /* Is it turned on? */
            if (EditOneTime)
            {
                /* Set the option this once */
                BlAppendBootOptionBoolean(BootEntry,
                                          BcdLibraryBoolean_DisplayOptionsEdit,
                                          TRUE);
            }
            else
            {
                /* It's not, so disable the option if active */
                BlRemoveBootOption(BootEntry->BcdData,
                                   BcdLibraryBoolean_DisplayOptionsEdit);
            }

            /* Remove the one-time option. We've already purged it earlier */
            BlRemoveBootOption(BootEntry->BcdData,
                               BcdOSLoaderBoolean_OptionsEditOneTime);
        }
    }

    /* BCD handling done, transfer execution to this entry */
    Status = BmpTransferExecution(BootEntry, &LaunchCode, &DoRecovery);
    if (!LaunchWinRe)
    {
        return Status;
    }

    /* Check if boot was successful, or  cancelled and we're not doing WinRE */
    if (((NT_SUCCESS(Status)) || (Status == STATUS_CANCELLED)) && !(DoRecovery))
    {
        return Status;
    }

    /* Boot failed -- are we doing recovery? */
    if (!DoRecovery)
    {
        /* Nope, bail out */
        LaunchCode = 2;
        goto Quickie;
    }

Quickie:
    /* Get the recovery sequence */
    if (MiscGetBootOption(BootEntry->BcdData, BcdLibraryObjectList_RecoverySequence))
    {
        /* Check if the launch depends on auto-recovery being enabled or not */
        if ((LaunchCode == 3) || (LaunchCode == 5) || (LaunchCode == 6))
        {
            Status = BlGetBootOptionBoolean(BootEntry->BcdData,
                                            BcdLibraryBoolean_AutoRecoveryEnabled,
                                            &AutoRecovery);
            if (NT_SUCCESS(Status))
            {
                /* Override the setting */
                DoRecovery = AutoRecovery;
            }
        }
    }
    else
    {
        /* There's no recovery setting */
        DoRecovery = FALSE;
    }

    /* Check if we should restart on failure */
    RestartOnFailure = FALSE;
    BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                           BcdLibraryBoolean_RestartOnFailure,
                           &RestartOnFailure);

    /* Do the sequence if recovery is on, unless we should restart instead */
    DoSequence = RestartOnFailure ? FALSE : DoRecovery;
    while (1)
    {
        /* Are we doing the recovery sequence? */
        if (DoSequence)
        {
            /* Because of automatic recovery? */
            if (AutoRecovery)
            {
#if BL_BITLOCKER_SUPPORT
                /* Do bitlocker stuff */
                BlFveRegisterBootEntryForTrustedWimBoot(BootEntry, TRUE);
#endif
            }

            /* Launch the recovery sequence*/
            Status = BmLaunchRecoverySequence(BootEntry, LaunchCode);

            /* Was it launched automatically? */
            if (AutoRecovery)
            {
#if BL_BITLOCKER_SUPPORT
                /* Do bitlocker stuff */
                BlFveRegisterBootEntryForTrustedWimBoot(BootEntry, FALSE);
#endif

                /* No need to do this again */
                AutoRecovery = FALSE;
            }

            /* Did the recovery sequence work? */
            if (NT_SUCCESS(Status))
            {
                /* All good */
                return STATUS_SUCCESS;
            }

            /* Remove the sequence, don't do it again */
            BlRemoveBootOption(BootEntry->BcdData, BcdLibraryObjectList_RecoverySequence);
        }

        /* Recovery sequence also failed, show fatal error */
        if (!BmpInternalBootError)
        {
            BmFatalErrorEx(BL_FATAL_ERROR_GENERIC, Status, 0, 0, 0);
        }

        /* Display the error menu */
        ErrorCode = BmDisplayDumpError(BootEntry, LaunchCode);
        BmErrorPurge();

        /* See what the user wants to do */
        switch (ErrorCode)
        {
            case TryAgain:
                /* Try again */
                goto TryAgain;

            case NextOs:
                /* Boot the next entry*/
                break;

            case OsSelection:
                /* Cancel the boot*/
                return STATUS_CANCELLED;

            case RecoverOem:
                /* Custom OEM recovery -- open the BCD */
                Status = BmOpenDataStore(BcdHandle);
                if (NT_SUCCESS(Status))
                {
                    /* See what the custom sequence is */
                    Status = BmProcessCustomAction(BcdHandle, NULL);
                }

                /* All done, close the BCD */
                if (BcdHandle)
                {
                    BmCloseDataStore(BcdHandle);
                }
                return Status;

            case AdvancedOptions:
                /* Show the advanced options next iteration */
                BlAppendBootOptionBoolean(BootEntry,
                                          BcdOSLoaderBoolean_AdvancedOptionsOneTime,
                                          TRUE);
                goto TryAgain;

            case BootOptions:
                /* Show the options editor next iteration */
                BlAppendBootOptionBoolean(BootEntry,
                                          BcdOSLoaderBoolean_OptionsEditOneTime,
                                          TRUE);
                goto TryAgain;

            case Recover:
                /* Try the recovery sequence next time*/
                DoSequence = TRUE;
                LaunchCode = 1;
                goto TryAgain;

            default:
                /* Something unknown */
                return STATUS_CANCELLED;
        }
    }

    /* We are booting the next OS, so return success as to not kill the boot */
    return STATUS_SUCCESS;
}

/*++
 * @name BmMain
 *
 *     The BmMain function implements the Windows Boot Application entrypoint for
 *     the Boot Manager.
 *
 * @param  BootParameters
 *         Pointer to the Boot Application Parameter Block.
 *
 * @return NT_SUCCESS if the image was loaded correctly, relevant error code
 *         otherwise.
 *
 *--*/
NTSTATUS
NTAPI
BmMain (
    _In_ PBOOT_APPLICATION_PARAMETER_BLOCK BootParameters
    )
{
    NTSTATUS Status, LibraryStatus;
    BL_LIBRARY_PARAMETERS LibraryParameters;
    PBL_RETURN_ARGUMENTS ReturnArguments;
    PGUID AppIdentifier;
    HANDLE BcdHandle, ResumeBcdHandle;
    PBL_BCD_OPTION EarlyOptions;
    PWCHAR Stylesheet;
    BOOLEAN XmlLoaded, DisableIntegrity, TestSigning, PersistBootSequence;
    BOOLEAN RebootOnError, CustomActions;
    ULONG SequenceId;
    PBL_LOADED_APPLICATION_ENTRY BootEntry;
    PGUID SequenceList;
    ULONG SequenceListCount;
    PBL_LOADED_APPLICATION_ENTRY* BootSequence;
    ULONG BootIndex;
    BOOLEAN ExitBootManager;
    BOOLEAN BootFailed;
    BOOLEAN BootOk;
    ULONG SequenceCount;
    BOOLEAN GetEntry;
    EfiPrintf(L"ReactOS UEFI Boot Manager Initializing...\r\n");

    /* Reading the BCD can change this later on */
    RebootOnError = FALSE;

    /* Save the start/end-of-POST time */
#if defined(_M_IX86) || defined(_M_X64)
    ApplicationStartTime = __rdtsc();
#else
    EfiPrintf(L"No time source defined for this platform\r\n");
    ApplicationStartTime = 0;
#endif
    PostTime = ApplicationStartTime;

    /* Setup the boot library parameters for this application */
    BlSetupDefaultParameters(&LibraryParameters);
    LibraryParameters.TranslationType = BlNone;
    LibraryParameters.LibraryFlags = 0x400 | 0x8;
    LibraryParameters.MinimumAllocationCount = 16;
    LibraryParameters.MinimumHeapSize = 512 * 1024;

    /* Initialize the boot library */
    Status = BlInitializeLibrary(BootParameters, &LibraryParameters);
    if (!NT_SUCCESS(Status))
    {
        /* Check for failure due to invalid application entry */
        if (Status != STATUS_INVALID_PARAMETER_9)
        {
            /* Specifically print out what happened */
            EfiPrintf(L"BlInitializeLibrary failed 0x%x\r\n", Status);
        }

        /* Go to exit path */
        goto Quickie;
    }

    /* Get the application identifier */
    AppIdentifier = BlGetApplicationIdentifier();
    if (!AppIdentifier)
    {
        /* None was given, so set our default one */
        AppIdentifier = (PGUID)&GUID_WINDOWS_BOOTMGR;
    }

    /* Save our identifier */
    BmApplicationIdentifier = *AppIdentifier;

    /* Initialize the file system to open a handle to our root boot directory */
    BmFwInitializeBootDirectoryPath();

    /* Load and initialize the boot configuration database (BCD) */
    Status = BmOpenDataStore(&BcdHandle);
    if (NT_SUCCESS(Status))
    {
        /* Copy the boot options */
        Status = BlCopyBootOptions(BlpApplicationEntry.BcdData, &EarlyOptions);
        if (NT_SUCCESS(Status))
        {
            /* Update them */
            Status = BmpUpdateApplicationOptions(BcdHandle);
            if (!NT_SUCCESS(Status))
            {
                /* Log a fatal error */
                BmFatalErrorEx(BL_FATAL_ERROR_BCD_PARSE,
                               (ULONG_PTR)L"\\BCD",
                               Status,
                               0,
                               0);
            }
        }
    }

#ifdef _SECURE_BOOT
    /* Initialize the secure boot machine policy */
    Status = BmSecureBootInitializeMachinePolicy();
    if (!NT_SUCCESS(Status))
    {
        BmFatalErrorEx(BL_FATAL_ERROR_SECURE_BOOT, Status, 0, 0, 0);
    }
#endif

    /* Copy the library parameters and add the re-initialization flag */
    RtlCopyMemory(&LibraryParameters,
                  &BlpLibraryParameters, 
                  sizeof(LibraryParameters));
    LibraryParameters.LibraryFlags |= (BL_LIBRARY_FLAG_REINITIALIZE_ALL |
                                       BL_LIBRARY_FLAG_REINITIALIZE);

    /* Now that we've parsed the BCD, re-initialize the library */
    LibraryStatus = BlInitializeLibrary(BootParameters, &LibraryParameters);
    if (!NT_SUCCESS(LibraryStatus) && (NT_SUCCESS(Status)))
    {
        Status = LibraryStatus;<--- Status is assigned
    }

    /* Initialize firmware-specific memory regions */
    BmFwMemoryInitialize();

    /* Initialize the boot status data log (BSD) */
    BmpInitializeBootStatusDataLog();

    /* Find our XSL stylesheet */
    Stylesheet = BlResourceFindHtml();
    if (!Stylesheet)
    {
        /* Awe, no XML. This is actually fatal lol. Can't boot without XML. */
        Status = STATUS_NOT_FOUND;
        EfiPrintf(L"BlResourceFindMessage failed 0x%x\r\n", STATUS_NOT_FOUND);
        goto Quickie;
    }

    /* Initialize the XML Engine (as a side-effect, resets cursor) */
    Status = BlXmiInitialize(Stylesheet);<--- Status is overwritten
    if (!NT_SUCCESS(Status))
    {
        EfiPrintf(L"\r\nBlXmiInitialize failed 0x%x\r\n", Status);
        goto Failure;
    }
    XmlLoaded = TRUE;

    /* Check if there's an active bitmap visible */
    if (!BlDisplayValidOemBitmap())
    {
        /* Nope, make the screen black using BGFX */
        if (!NT_SUCCESS(BmpBgDisplayClearScreen(0xFF000000)))
        {
            /* BGFX isn't active, use standard display */
            BlDisplayClearScreen();
        }
    }

#ifdef _BIT_LOCKER_
    /* Bitlocker will take over screen UI if enabled */
    FveDisplayScreen = BmFveDisplayScreen;
#endif

    /* Check if any bypass options are enabled */
    BlImgQueryCodeIntegrityBootOptions(&BlpApplicationEntry,
                                       &DisableIntegrity,
                                       &TestSigning);
    if (!DisableIntegrity)
    {
        /* Integrity checks are enabled, so validate our signature */
        Status = BmFwVerifySelfIntegrity();
        if (!NT_SUCCESS(Status))
        {
            /* Signature invalid, fail boot */
            goto Failure;
        }
    }


    /* TEST MODE */
    EfiPrintf(L"Performing memory allocator tests...\r\n");
    {
        NTSTATUS Status;
        PHYSICAL_ADDRESS PhysicalAddress, PhysicalAddress2;

        /* Allocate 1 physical page */
        PhysicalAddress.QuadPart = 0;
        Status = BlMmAllocatePhysicalPages(&PhysicalAddress, BlLoaderData, 1, 0, 1);
        if (Status != STATUS_SUCCESS)
        {
            EfiPrintf(L"FAIL: Allocation status: %lx at address: %llx\r\n", Status, PhysicalAddress.QuadPart);
            EfiStall(100000000);
        }

        /* Write some data */
        *(PULONG)((ULONG_PTR)PhysicalAddress.QuadPart) = 0x55555151;

        /* Free it */
        Status = BlMmFreePhysicalPages(PhysicalAddress);
        if (Status != STATUS_SUCCESS)
        {
            EfiPrintf(L"FAIL: Memory free status: %lx\r\n", Status);
            EfiStall(100000000);
        }

        /* Allocate a page again */
        PhysicalAddress2.QuadPart = 0;
        Status = BlMmAllocatePhysicalPages(&PhysicalAddress2, BlLoaderData, 1, 0, 1);
        if (Status != STATUS_SUCCESS)
        {
            EfiPrintf(L"FAIL: Allocation status: %lx at address: %llx\r\n", Status, PhysicalAddress2.QuadPart);
            EfiStall(100000000);
        }

        /* It should've given us the same page, since we freed it */
        if (PhysicalAddress.QuadPart != PhysicalAddress2.QuadPart)
        {
            EfiPrintf(L"FAIL: Non-matching addresses: %llx %llx\r\n", PhysicalAddress.QuadPart, PhysicalAddress2.QuadPart);
            EfiStall(100000000);
        }

        /* The data should still be there, since zero-ing is not on for bootmgr */
        if (*(PULONG)((ULONG_PTR)PhysicalAddress2.QuadPart) != 0x55555151)
        {
            EfiPrintf(L"FAIL: Non-matching data: %lx %lx\r\n", 0x55555151, *(PULONG)((ULONG_PTR)PhysicalAddress2.QuadPart));
            EfiStall(100000000);
        }

        /* And free the second page again */
        Status = BlMmFreePhysicalPages(PhysicalAddress);
        if (Status != STATUS_SUCCESS)
        {
            EfiPrintf(L"FAIL: Memory free status: %lx\r\n", Status);
            EfiStall(100000000);
        }
    }

    /* Write out the first XML tag */
    BlXmiWrite(L"<bootmgr/>");

    /* Check for factory reset */
    BlSecureBootCheckForFactoryReset();

    /* Load the revocation list */
    Status = BmFwRegisterRevocationList();
    if (!NT_SUCCESS(Status))
    {
        goto Failure;
    }

    /* Register our custom progress routine */
    BlUtlRegisterProgressRoutine();

    /* Display state is not currently cached */
    BmDisplayStateCached = FALSE;

    /* Check if we need to resume from hibernate */
    Status = BmResumeFromHibernate(&ResumeBcdHandle);
    if (!NT_SUCCESS(Status))
    {
        goto Failure;
    }

#ifdef BL_NET_SUPPORT
    /* Register multicast printing routine */
    BlUtlRegisterMulticastRoutine();
#endif

    /* Check if restart on failure is enabled */
    BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                           BcdLibraryBoolean_RestartOnFailure,
                           &RebootOnError);

    /* Check if the boot sequence is persisted */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdBootMgrBoolean_PersistBootSequence,
                                    &PersistBootSequence);
    if (!NT_SUCCESS(Status))
    {
        /* It usually is */
        PersistBootSequence = TRUE;
    }

    /* Check if there's custom actions to take */
    Status = BlGetBootOptionBoolean(BlpApplicationEntry.BcdData,
                                    BcdBootMgrBoolean_ProcessCustomActionsFirst,
                                    &CustomActions);
    if ((NT_SUCCESS(Status)) && (CustomActions))
    {
        /* We don't support this yet */
        EfiPrintf(L"Not implemented\r\n");
        Status = STATUS_NOT_IMPLEMENTED;
        goto Failure;
    }

    //BlResourceFindMessage(BM_MSG_TEST);

    /* At last, enter the boot selection stage */
    SequenceId = 0;
    GetEntry = FALSE;
    BootFailed = FALSE;
    SequenceList = NULL;
    BootSequence = NULL;
    SequenceCount = 0;
    while (1)
    {
        /* We don't have a boot entry nor a sequence ID */
        BootEntry = NULL;
        BootOk = FALSE;

        /* Do we have a hardcoded boot sequence set? */
        if (!(BootSequence) && !(GetEntry))
        {
            /* Not yet, read the BCD to see if one is there */
            Status = BlGetBootOptionGuidList(BlpApplicationEntry.BcdData,
                                             BcdBootMgrObjectList_BootSequence,
                                             &SequenceList,
                                             &SequenceListCount);
            if (NT_SUCCESS(Status))
            {
                /* A GUID list for the boot sequence is set. Extract it */
                Status = BmGetBootSequence(BcdHandle,
                                           SequenceList,
                                           SequenceListCount,
                                           BL_APPLICATION_ENTRY_FIXED_SEQUENCE,
                                           &BootSequence,
                                           &SequenceCount);
                if (NT_SUCCESS(Status))
                {
                    /* Don't get stuck in a loop repeating this sequence */
                    BlRemoveBootOption(BlpApplicationEntry.BcdData,
                                       BcdBootMgrObjectList_BootSequence);

                    /* But do check if we should persist it */
                    if (PersistBootSequence)
                    {
                        /* Yes -- so go select an entry now */
                        GetEntry = TRUE;
                    }
                    else
                    {
                        /* We shouldn't, so wipe it from the BCD too */
                        Status = BmPurgeOption(BcdHandle,
                                               &BmApplicationIdentifier,
                                               BcdBootMgrObjectList_BootSequence);
                        if (!NT_SUCCESS(Status))
                        {
                            /* Well that failed */
                            goto LoopQuickie;
                        }
                    }
                }
            }
            else
            {
                /* No boot entry sequence for us */
                BootSequence = NULL;
            }
        }

        /* Do we have a sequence active, and are we still processing it? */
        if ((BootSequence) && ((GetEntry) || (SequenceId < SequenceCount)))
        {
            /* Extract the next entry in the sequence */
            BootEntry = BootSequence[SequenceId];
            BootSequence[SequenceId] = NULL;

            /* Move to the next entry for next time */
            SequenceId++;

            /* Unless there won't be a a next time? */
            if (SequenceId == SequenceCount)
            {
                /* Clean up, it's the last entry */
                BlMmFreeHeap(BootSequence);
                BootSequence = NULL;
            }
        }
        else
        {
            /* Get the selected boot entry from the user */
            ExitBootManager = FALSE;
            Status = BmpGetSelectedBootEntry(BcdHandle,
                                             &BootEntry,
                                             &BootIndex,
                                             &ExitBootManager);
            if (!(NT_SUCCESS(Status)) || (ExitBootManager))
            {
                /* Selection failed, or user wants to exit */
                goto LoopQuickie;
            }
        }

        /* Did we have a BCD open? */
        if (BcdHandle)
        {
            /* Close it, we'll be opening a new one */
            BmCloseDataStore(BcdHandle);
            BcdHandle = NULL;
        }

        /* Launch the selected entry */
        Status = BmpLaunchBootEntry(BootEntry, &BootIndex, 0, TRUE);
        if (NT_SUCCESS(Status))
        {
            /* Boot worked, uncache display and process the bad memory list */
            BmDisplayStateCached = FALSE;
            BmpProcessBadMemory();
        }
        else
        {
            /* Boot failed -- was it user driven? */
            if (Status != STATUS_CANCELLED)
            {
                /* Nope, remember that booting failed */
                BootFailed = TRUE;
                goto LoopQuickie;
            }

            /* Yes -- the display is still valid */
            BmDisplayStateCached = TRUE;
        }

        /* Reopen the BCD */
        Status = BmOpenDataStore(&BcdHandle);
        if (!NT_SUCCESS(Status))
        {
            break;
        }

        /* Put the BCD options back into our entry */
        BlReplaceBootOptions(&BlpApplicationEntry, EarlyOptions);

        /* Update our options one more time */
        Status = BmpUpdateApplicationOptions(BcdHandle);
        if (NT_SUCCESS(Status))
        {
            /* Boot was 100% OK */
            BootOk = TRUE;
        }

LoopQuickie:
        /* Did we have a boot entry? */
        if (BootEntry)
        {
            /* We can destroy it now */
            BlDestroyBootEntry(BootEntry);
        }

        /* Is this the success path? */
        if (NT_SUCCESS(Status))
        {
            /* Did we actually boot something? */
            if (!BootOk)
            {
                /* Bope, fail out */
                break;
            }
        }

        /* This is the failure path... should we reboot? */
        if (RebootOnError)
        {
            break;
        }
    };

Failure:
    if (!BootFailed)
    {
        /* Check if we got here due to an internal error */
        if (BmpInternalBootError)
        {
            /* If XML is available, display the error */
            if (XmlLoaded)
            {
                //BmDisplayDumpError(0, 0);
                //BmErrorPurge();
            }

            /* Don't do a fatal error -- return back to firmware */
            goto Quickie;
        }
    }

    /* Log a general fatal error once we're here */
    BmFatalErrorEx(BL_FATAL_ERROR_GENERIC, Status, 0, 0, 0);

Quickie:
    /* Check if we should reboot */
    if ((RebootOnError) ||
        (BlpApplicationEntry.Flags & BL_APPLICATION_ENTRY_REBOOT_ON_ERROR))
    {
        /* Reboot the box */
        BlFwReboot();
        Status = STATUS_SUCCESS;
    }
    else
    {
        /* Return back to the caller with the error argument encoded */
        ReturnArguments = (PVOID)((ULONG_PTR)BootParameters + BootParameters->ReturnArgumentsOffset);
        ReturnArguments->Version = BL_RETURN_ARGUMENTS_VERSION;
        ReturnArguments->Status = Status;

        /* Tear down the boot library */
        BlDestroyLibrary();
    }

    /* Return back status */
    return Status;
}